Doxygen
Loading...
Searching...
No Matches
pre.l
Go to the documentation of this file.
1/******************************************************************************
2 *
3 * Copyright (C) 1997-2020 by Dimitri van Heesch.
4 *
5 * Permission to use, copy, modify, and distribute this software and its
6 * documentation under the terms of the GNU General Public License is hereby
7 * granted. No representations are made about the suitability of this software
8 * for any purpose. It is provided "as is" without express or implied warranty.
9 * See the GNU General Public License for more details.
10 *
11 * Documents produced by Doxygen are derivative works derived from the
12 * input used in their production; they are not affected by this license.
13 *
14 */
15%option never-interactive
16%option prefix="preYY"
17%option reentrant
18%option extra-type="struct preYY_state *"
19%top{
20#include <stdint.h>
21// forward declare yyscan_t to improve type safety
22#define YY_TYPEDEF_YY_SCANNER_T
23#define yyguts_t preYYguts_t
24struct yyguts_t;
yyguts_t * yyscan_t
Definition code.l:25
#define yyguts_t
Definition code.l:23
26}
27
28%{
29
30/*
31 * includes
32 */
33
34// own header
35#include "pre.h"
36
37// standard includes
38#include <algorithm>
39#include <deque>
40#include <map>
41#include <memory>
42#include <mutex>
43#include <stack>
44#include <utility>
45
46// other includes
47#include "arguments.h"
48#include "condparser.h"
49#include "config.h"
50#include "constexp.h"
51#include "containers.h"
52#include "debug.h"
53#include "defargs.h"
54#include "define.h"
55#include "doxygen.h"
56#include "dstring.h"
57#include "entry.h"
58#include "filedef.h"
59#include "fileinfo.h"
60#include "filename.h"
61#include "fortranscanner.h"
62#include "message.h"
63#include "portable.h"
64#include "regex.h"
65#include "stringutil.h"
66#include "trace.h"
67#include "util.h"
68
69#define YY_NO_UNISTD_H 1
70
71[[maybe_unused]] static const char *stateToString(int state);
72
74{
75 preYY_CondCtx(const DString &file,int line,const DString &id,bool b)
76 : fileName(file), lineNr(line), sectionId(id), skip(b) {}
78 int lineNr;
80 bool skip;
81};
82
84{
85 int lineNr = 1;
86 int curlyCount = 0;
87 std::string fileBuf;
88 const std::string *oldFileBuf = nullptr;
90 YY_BUFFER_STATE bufState = 0;
92 bool lexRulesPart = false;
94};
95
97{
98 PreIncludeInfo(const DString &fn,FileDef *srcFd, FileDef *dstFd,const DString &iName,bool loc, bool imp)
99 : fileName(fn), fromFileDef(srcFd), toFileDef(dstFd), includeName(iName), local(loc), imported(imp)
100 {
101 }
102 DString fileName; // file name in which the include statement was found
103 FileDef *fromFileDef; // filedef in which the include statement was found
104 FileDef *toFileDef; // filedef to which the include is pointing
105 DString includeName; // name used in the #include statement
106 bool local; // is it a "local" or <global> include
107 bool imported; // include via "import" keyword (Objective-C)
108};
109
110/** A dictionary of managed Define objects. */
111typedef std::map< std::string, Define > DefineMap;
112
113/** @brief Class that manages the defines available while
114 * preprocessing files.
115 */
117{
118 private:
119 /** Local class used to hold the defines for a single file */
121 {
122 public:
123 /** Creates an empty container for defines */
128 void addInclude(const std::string &fileName)
129 {
130 m_includedFiles.insert(fileName);
131 }
132 void store(const DefineMap &fromMap)
133 {
134 for (auto &[name,define] : fromMap)
135 {
136 m_defines.emplace(name,define);
137 }
138 //printf(" m_defines.size()=%zu\n",m_defines.size());
139 m_stored=true;
140 }
141 void retrieve(DefineMap &toMap)
142 {
143 StringUnorderedSet includeStack;
144 retrieveRec(toMap,includeStack);
145 }
146 void retrieveRec(DefineMap &toMap,StringUnorderedSet &includeStack)
147 {
148 //printf(" retrieveRec #includedFiles=%zu\n",m_includedFiles.size());
149 for (auto incFile : m_includedFiles)
150 {
151 DefinesPerFile *dpf = m_parent->find(incFile);
152 if (dpf && includeStack.find(incFile)==includeStack.end())
153 {
154 includeStack.insert(incFile);
155 dpf->retrieveRec(toMap,includeStack);
156 //printf(" retrieveRec: processing include %s: #toMap=%zu\n",qPrint(incFile),toMap.size());
157 }
158 }
159 for (auto &[name,define] : m_defines)
160 {
161 toMap.emplace(name,define);
162 }
163 }
164 bool stored() const { return m_stored; }
165 private:
169 bool m_stored = false;
170 };
171
172 friend class DefinesPerFile;
173 public:
174
175 void addInclude(const std::string &fromFileName,const std::string &toFileName)
176 {
177 //printf("DefineManager::addInclude('%s'->'%s')\n",qPrint(fromFileName),qPrint(toFileName));
178 auto it = m_fileMap.find(fromFileName);
179 if (it==m_fileMap.end())
180 {
181 it = m_fileMap.emplace(fromFileName,std::make_unique<DefinesPerFile>(this)).first;
182 }
183 auto &dpf = it->second;
184 dpf->addInclude(toFileName);
185 }
186
187 void store(const std::string &fileName,const DefineMap &fromMap)
188 {
189 //printf("DefineManager::store(%s,#=%zu)\n",qPrint(fileName),fromMap.size());
190 auto it = m_fileMap.find(fileName);
191 if (it==m_fileMap.end())
192 {
193 it = m_fileMap.emplace(fileName,std::make_unique<DefinesPerFile>(this)).first;
194 }
195 it->second->store(fromMap);
196 }
197
198 void retrieve(const std::string &fileName,DefineMap &toMap)
199 {
200 auto it = m_fileMap.find(fileName);
201 if (it!=m_fileMap.end())
202 {
203 auto &dpf = it->second;
204 dpf->retrieve(toMap);
205 }
206 //printf("DefineManager::retrieve(%s,#=%zu)\n",qPrint(fileName),toMap.size());
207 }
208
209 bool alreadyProcessed(const std::string &fileName) const
210 {
211 auto it = m_fileMap.find(fileName);
212 if (it!=m_fileMap.end())
213 {
214 return it->second->stored();
215 }
216 return false;
217 }
218
219 private:
220 /** Helper function to return the DefinesPerFile object for a given file name. */
221 DefinesPerFile *find(const std::string &fileName) const
222 {
223 auto it = m_fileMap.find(fileName);
224 return it!=m_fileMap.end() ? it->second.get() : nullptr;
225 }
226
227 std::unordered_map< std::string, std::unique_ptr<DefinesPerFile> > m_fileMap;
228};
229
230
231/* -----------------------------------------------------------------
232 *
233 * global state
234 */
235static std::mutex g_debugMutex;
236static std::mutex g_globalDefineMutex;
237static std::mutex g_updateGlobals;
239
240
241/* -----------------------------------------------------------------
242 *
243 * scanner's state
244 */
245
247{
248 int yyLineNr = 1;
249 int yyMLines = 1;
250 size_t yyColNr = 1;
252 FileDef *yyFileDef = nullptr;
254 int ifcount = 0;
255 int defArgs = -1;
261 bool defContinue = false;
262 bool defVarArgs = false;
265 const std::string *inputBuf = nullptr;
266 int inputBufPos = 0;
267 std::string *outputBuf = nullptr;
268 int roundCount = 0;
269 bool quoteArg = false;
270 bool idStart = false;
272 bool expectGuard = false;
277 int curlyCount = 0;
278 bool nospaces = false; // add extra spaces during macro expansion
279 bool boundedExpansion = false;
280 int javaBlock = 0;
281
282 bool macroExpansion = false; // from the configuration
283 bool expandOnlyPredef = false; // from the configuration
286 bool insideComment = false;
287 bool isImported = false;
289 int condCtx = 0;
290 bool skip = false;
291 bool insideIDL = false;
292 bool insideCS = false; // C# has simpler preprocessor
293 bool insideFtn = false;
294 bool isSource = false;
295 bool isFixedFormFtn = false;
296
297 yy_size_t fenceSize = 0;
298 char fenceChar = ' ';
299 bool ccomment = false;
301 bool isSpecialComment = false;
305 std::stack< std::unique_ptr<preYY_CondCtx> > condStack;
310 std::deque< std::unique_ptr<FileState> > includeStack;
311 std::unordered_map<std::string,Define*> expandedDict;
314 DefineMap contextDefines; // macros imported from other files
315 DefineMap localDefines; // macros defined in this file
319
320 int lastContext = 0;
321 bool lexRulesPart = false;
322 char prevChar=0;
323};
324
325// stateless functions
326static DString escapeAt(const DString &text);
327static DString extractTrailingComment(const DString &s);
328static char resolveTrigraph(char c);
329
330// stateful functions
331static inline void outputArray(yyscan_t yyscanner,const char *a,yy_size_t len);
332static inline void outputString(yyscan_t yyscanner,const DString &s);
333static inline void outputChar(yyscan_t yyscanner,char c);
334static inline void outputSpaces(yyscan_t yyscanner,char *s);
335static inline void outputSpace(yyscan_t yyscanner,char c);
336static inline void extraSpacing(yyscan_t yyscanner);
337static DString expandMacro(yyscan_t yyscanner,const DString &name);
338static DString expandStandardMacro(yyscan_t yyscanner,const DString &name);
339static void readIncludeFile(yyscan_t yyscanner,const DString &inc);
340static void incrLevel(yyscan_t yyscanner);
341static void decrLevel(yyscan_t yyscanner);
342static void setCaseDone(yyscan_t yyscanner,bool value);
343static bool otherCaseDone(yyscan_t yyscanner);
344static bool computeExpression(yyscan_t yyscanner,const DString &expr);
345static void startCondSection(yyscan_t yyscanner,const DString &sectId);
346static void endCondSection(yyscan_t yyscanner);
347static void addMacroDefinition(yyscan_t yyscanner);
348static void addDefine(yyscan_t yyscanner);
349static void setFileName(yyscan_t yyscanner,const DString &name);
350static int yyread(yyscan_t yyscanner,char *buf,int max_size);
351static Define * isDefined(yyscan_t yyscanner,const DString &name);
352static void determineBlockName(yyscan_t yyscanner);
353static yy_size_t getFenceSize(char *txt, yy_size_t leng);
354
355/* ----------------------------------------------------------------- */
356
357#undef YY_INPUT
358#define YY_INPUT(buf,result,max_size) result=yyread(yyscanner,buf,max_size);
359
360// otherwise the filename would be the name of the converted file (*.cpp instead of *.l)
361static inline const char *getLexerFILE() {return __FILE__;}
362#include "doxygen_lex.h"
363
364/* ----------------------------------------------------------------- */
365
constant expression parser used for the C preprocessor
Definition constexp.h:26
A String class for use with Doxygen wrapping std::string and adding some additional functionality off...
Definition dstring.h:84
A class representing a macro definition.
Definition define.h:31
Local class used to hold the defines for a single file.
Definition pre.l:121
void addInclude(const std::string &fileName)
Definition pre.l:128
DefinesPerFile(DefineManager *parent)
Creates an empty container for defines.
Definition pre.l:124
DefineManager * m_parent
Definition pre.l:166
void retrieveRec(DefineMap &toMap, StringUnorderedSet &includeStack)
Definition pre.l:146
void store(const DefineMap &fromMap)
Definition pre.l:132
StringUnorderedSet m_includedFiles
Definition pre.l:168
void retrieve(DefineMap &toMap)
Definition pre.l:141
Class that manages the defines available while preprocessing files.
Definition pre.l:117
bool alreadyProcessed(const std::string &fileName) const
Definition pre.l:209
void addInclude(const std::string &fromFileName, const std::string &toFileName)
Definition pre.l:175
void store(const std::string &fileName, const DefineMap &fromMap)
Definition pre.l:187
std::unordered_map< std::string, std::unique_ptr< DefinesPerFile > > m_fileMap
Definition pre.l:227
void retrieve(const std::string &fileName, DefineMap &toMap)
Definition pre.l:198
DefinesPerFile * find(const std::string &fileName) const
Helper function to return the DefinesPerFile object for a given file name.
Definition pre.l:221
A model of a file symbol.
Definition filedef.h:97
Container class representing a vector of objects with keys.
Definition linkedmap.h:36
std::stack< bool > BoolStack
Definition containers.h:35
std::unordered_set< std::string > StringUnorderedSet
Definition containers.h:29
std::vector< std::string > StringVector
Definition containers.h:33
std::map< std::string, int > IntMap
Definition containers.h:37
std::vector< Define > DefineList
List of all macro definitions.
Definition define.h:49
constexpr DocNodeVariant * parent(DocNodeVariant *n)
returns the parent node of a given node n or nullptr if the node has no parent.
Definition docnode.h:1335
Portable versions of functions that are platform dependent.
static DString expandMacro(yyscan_t yyscanner, const DString &name)
Definition pre.l:3720
static DString extractTrailingComment(const DString &s)
Definition pre.l:2488
std::map< std::string, Define > DefineMap
A dictionary of managed Define objects.
Definition pre.l:111
static void setCaseDone(yyscan_t yyscanner, bool value)
Definition pre.l:2350
static void addMacroDefinition(yyscan_t yyscanner)
Definition pre.l:3792
static void decrLevel(yyscan_t yyscanner)
Definition pre.l:2315
static void addDefine(yyscan_t yyscanner)
Definition pre.l:3763
static void determineBlockName(yyscan_t yyscanner)
Definition pre.l:3884
static DString expandStandardMacro(yyscan_t yyscanner, const DString &name)
Definition pre.l:3734
static bool computeExpression(yyscan_t yyscanner, const DString &expr)
Definition pre.l:3701
static void incrLevel(yyscan_t yyscanner)
Definition pre.l:2308
static void outputSpaces(yyscan_t yyscanner, char *s)
Definition pre.l:3860
static void endCondSection(yyscan_t yyscanner)
Definition pre.l:4086
static DString escapeAt(const DString &text)
Definition pre.l:4129
static std::mutex g_globalDefineMutex
Definition pre.l:236
static void outputChar(yyscan_t yyscanner, char c)
Definition pre.l:3836
static int yyread(yyscan_t yyscanner, char *buf, int max_size)
Definition pre.l:2260
static char resolveTrigraph(char c)
Definition pre.l:4144
static const char * stateToString(int state)
static void outputString(yyscan_t yyscanner, const DString &s)
Definition pre.l:3848
static void setFileName(yyscan_t yyscanner, const DString &name)
Definition pre.l:2281
static DefineManager g_defineManager
Definition pre.l:238
static void startCondSection(yyscan_t yyscanner, const DString &sectId)
Definition pre.l:4072
static yy_size_t getFenceSize(char *txt, yy_size_t leng)
Definition pre.l:2270
static std::mutex g_updateGlobals
Definition pre.l:237
static bool otherCaseDone(yyscan_t yyscanner)
Definition pre.l:2336
static void outputArray(yyscan_t yyscanner, const char *a, yy_size_t len)
Definition pre.l:3842
static void extraSpacing(yyscan_t yyscanner)
Definition pre.l:3871
static const char * getLexerFILE()
Definition pre.l:361
static void outputSpace(yyscan_t yyscanner, char c)
Definition pre.l:3854
static Define * isDefined(yyscan_t yyscanner, const DString &name)
Returns a reference to a Define object given its name or 0 if the Define does not exist.
Definition pre.l:4236
static std::mutex g_debugMutex
Definition pre.l:235
static void readIncludeFile(yyscan_t yyscanner, const DString &inc)
Definition pre.l:3917
Some helper functions for std::string.
std::string fileBuf
Definition pre.l:87
BoolStack levelGuard
Definition pre.l:93
YY_BUFFER_STATE bufState
Definition pre.l:90
int lineNr
Definition pre.l:85
DString fileName
Definition pre.l:91
bool lexRulesPart
Definition pre.l:92
int curlyCount
Definition pre.l:86
const std::string * oldFileBuf
Definition pre.l:88
int oldFileBufPos
Definition pre.l:89
FileDef * toFileDef
Definition pre.l:104
bool local
Definition pre.l:106
DString includeName
Definition pre.l:105
bool imported
Definition pre.l:107
DString fileName
Definition pre.l:102
FileDef * fromFileDef
Definition pre.l:103
PreIncludeInfo(const DString &fn, FileDef *srcFd, FileDef *dstFd, const DString &iName, bool loc, bool imp)
Definition pre.l:98
DString sectionId
Definition pre.l:79
bool skip
Definition pre.l:80
DString fileName
Definition pre.l:77
preYY_CondCtx(const DString &file, int line, const DString &id, bool b)
Definition pre.l:75
int lineNr
Definition pre.l:78
DString defExtraSpacing
Definition pre.l:260
bool expectGuard
Definition pre.l:272
int commentCount
Definition pre.l:285
size_t yyColNr
Definition pre.l:250
BoolStack levelGuard
Definition pre.l:304
bool macroExpansion
Definition pre.l:282
FileDef * inputFileDef
Definition pre.l:253
DString guardExpr
Definition pre.l:276
bool isFixedFormFtn
Definition pre.l:295
char prevChar
Definition pre.l:322
bool defContinue
Definition pre.l:261
bool insideFtn
Definition pre.l:293
StringUnorderedSet expanded
Definition pre.l:312
LinkedMap< PreIncludeInfo > includeRelations
Definition pre.l:317
DString condGuardErrorMessage
Definition pre.l:309
int condGuardCount
Definition pre.l:306
int lastContext
Definition pre.l:320
bool isSource
Definition pre.l:294
StringUnorderedSet pragmaSet
Definition pre.l:318
bool lexRulesPart
Definition pre.l:321
char fenceChar
Definition pre.l:298
bool skip
Definition pre.l:290
yy_size_t fenceSize
Definition pre.l:297
IntMap argMap
Definition pre.l:303
bool expandOnlyPredef
Definition pre.l:283
DString delimiter
Definition pre.l:300
ConstExpressionParser constExpParser
Definition pre.l:313
DString blockName
Definition pre.l:288
int roundCount
Definition pre.l:268
bool idStart
Definition pre.l:270
int curlyCount
Definition pre.l:277
int lastCContext
Definition pre.l:263
std::unordered_map< std::string, Define * > expandedDict
Definition pre.l:311
bool insideCS
Definition pre.l:292
bool isSpecialComment
Definition pre.l:301
int yyLineNr
Definition pre.l:248
FileDef * yyFileDef
Definition pre.l:252
DString fileName
Definition pre.l:251
int javaBlock
Definition pre.l:280
bool nospaces
Definition pre.l:278
std::deque< std::unique_ptr< FileState > > includeStack
Definition pre.l:310
bool quoteArg
Definition pre.l:269
int yyMLines
Definition pre.l:249
int defArgs
Definition pre.l:255
bool isImported
Definition pre.l:287
DefineMap localDefines
Definition pre.l:315
DString incName
Definition pre.l:275
DefineMap contextDefines
Definition pre.l:314
StringVector pathList
Definition pre.l:302
DString defName
Definition pre.l:256
int ifcount
Definition pre.l:254
std::stack< std::unique_ptr< preYY_CondCtx > > condStack
Definition pre.l:305
DString potentialDefine
Definition pre.l:284
int lastCPPContext
Definition pre.l:264
DString lastGuardName
Definition pre.l:274
bool ccomment
Definition pre.l:299
const std::string * inputBuf
Definition pre.l:265
DString guardName
Definition pre.l:273
bool insideComment
Definition pre.l:286
DString defLitText
Definition pre.l:258
std::string * outputBuf
Definition pre.l:267
DString defText
Definition pre.l:257
bool boundedExpansion
Definition pre.l:279
int condGuardErrorLine
Definition pre.l:308
DString defArgsStr
Definition pre.l:259
int findDefArgContext
Definition pre.l:271
int inputBufPos
Definition pre.l:266
int condCtx
Definition pre.l:289
DString condGuardErrorFileName
Definition pre.l:307
bool insideIDL
Definition pre.l:291
bool defVarArgs
Definition pre.l:262
DefineList macroDefinitions
Definition pre.l:316
A bunch of utility functions.
366%}
367
368IDSTART [a-z_A-Z\x80-\xFF]
369ID {IDSTART}[a-z_A-Z0-9\x80-\xFF]*
370B [ \t]
371Bopt {B}*
372BN [ \t\r\n]
373RAWBEGIN (u|U|L|u8)?R\"[^ \t\‍(\‍)\\‍]{0,16}"("
374RAWEND ")"[^ \t\‍(\‍)\\‍]{0,16}\"
375CHARLIT (("'"\\‍[0-7]{1,3}"'")|("'"\\."'")|("'"[^'\\\n]{1,4}"'"))
376
377CMD [\\@]
378FORMULA_START {CMD}("f{"|"f$"|"f["|"f(")
379FORMULA_END {CMD}("f}"|"f$"|"f]"|"f)")
380VERBATIM_START {CMD}("verbatim"|"iliteral"|"latexonly"|"htmlonly"|"xmlonly"|"docbookonly"|"rtfonly"|"manonly"|"dot"|"msc"|"mermaid"|"startuml"|"code"("{"[^}]*"}")?){BN}+
381VERBATIM_END {CMD}("endverbatim"|"endiliteral"|"endlatexonly"|"endhtmlonly"|"endxmlonly"|"enddocbookonly"|"endrtfonly"|"endmanonly"|"enddot"|"endmsc"|"endmermaid"|"enduml"|"endcode")
382VERBATIM_LINE {CMD}"noop"{B}+
383LITERAL_BLOCK {FORMULA_START}|{VERBATIM_START}
384LITERAL_BLOCK_END {FORMULA_END}|{VERBATIM_END}
385
386 // some rule pattern information for rules to handle lex files
387nl (\r\n|\r|\n)
388RulesDelim "%%"{nl}
389RulesSharp "<"[^>\n]*">"
390RulesCurly "{"[^{}\n]*"}"
391StartSquare "["
392StartDouble "\""
393StartRound "("
394StartRoundQuest "(?"
395EscapeRulesCharOpen "\\‍["|"\<"|"\\{"|"\\‍("|"\\\""|"\\ "|"\\\\"
396EscapeRulesCharClose "\\‍]"|"\>"|"\\}"|"\\‍)"
397EscapeRulesChar {EscapeRulesCharOpen}|{EscapeRulesCharClose}
398CHARCE "[:"[^:]*":]"
399DOXYCFG [A-Z][A-Z_0-9]*
400
401 // C start comment
402CCS "/\*"
403 // C end comment
404CCE "*\/"
405 // Cpp comment
406CPPC "/\/"
407 // optional characters after import
408ENDIMPORTopt [^\\\n]*
409 // Optional white space
410WSopt [ \t\r]*
411
412 //- begin: NUMBER
413 // Note same defines in commentcnv.l: keep in sync
414DECIMAL_INTEGER [1-9][0-9']*[0-9]?[uU]?[lL]?[lL]?
415HEXADECIMAL_INTEGER "0"[xX][0-9a-zA-Z']+[0-9a-zA-Z]?
416OCTAL_INTEGER "0"[0-7][0-7']+[0-7]?
417BINARY_INTEGER "0"[bB][01][01']*[01]?
418INTEGER_NUMBER {DECIMAL_INTEGER}|{HEXADECIMAL_INTEGER}|{OCTAL_INTEGER}|{BINARY_INTEGER}
419
420FP_SUF [fFlL]
421
422DIGIT_SEQ [0-9][0-9']*[0-9]?
423FRAC_CONST {DIGIT_SEQ}"."|{DIGIT_SEQ}?"."{DIGIT_SEQ}
424FP_EXP [eE][+-]?{DIGIT_SEQ}
425DEC_FP1 {FRAC_CONST}{FP_EXP}?{FP_SUF}?
426DEC_FP2 {DIGIT_SEQ}{FP_EXP}{FP_SUF}
427
428HEX_DIGIT_SEQ [0-9a-fA-F][0-9a-fA-F']*[0-9a-fA-F]?
429HEX_FRAC_CONST {HEX_DIGIT_SEQ}"."|{HEX_DIGIT_SEQ}?"."{HEX_DIGIT_SEQ}
430BIN_EXP [pP][+-]?{DIGIT_SEQ}
431HEX_FP1 "0"[xX]{HEX_FRAC_CONST}{BIN_EXP}{FP_SUF}?
432HEX_FP2 "0"[xX]{HEX_DIGIT_SEQ}{BIN_EXP}{FP_SUF}?
433
434FLOAT_DECIMAL {DEC_FP1}|{DEC_FP2}
435FLOAT_HEXADECIMAL {HEX_FP1}|{HEX_FP2}
436FLOAT_NUMBER {FLOAT_DECIMAL}|{FLOAT_HEXADECIMAL}
437NUMBER {INTEGER_NUMBER}|{FLOAT_NUMBER}
438 //- end: NUMBER ---------------------------------------------------------------------------
439
440
441%option noyywrap
442
443%x Start
444%x Command
445%x SkipCommand
446%x SkipLine
447%x SkipString
448%x CopyLine
449%x LexCopyLine
450%x CopyString
451%x CopyStringCs
452%x CopyStringFtn
453%x CopyStringFtnDouble
454%x CopyRawString
455%x Include
456%x IncludeID
457%x EndImport
458%x DefName
459%x DefineArg
460%x DefineText
461%x CmakeDefName01
462%x SkipCPPBlock
463%x SkipCComment
464%x ArgCopyCComment
465%x ArgCopyCppComment
466%x CopyCComment
467%x SkipVerbatim
468%x SkipCondVerbatim
469%x SkipCPPComment
470%x JavaDocVerbatimCode
471%x RemoveCComment
472%x RemoveCPPComment
473%x Guard
474%x DefinedExpr1
475%x DefinedExpr2
476%x SkipDoubleQuote
477%x SkipSingleQuote
478%x UndefName
479%x IgnoreLine
480%x FindDefineArgs
481%x ReadString
482%x CondLineC
483%x CondLineCpp
484%x SkipCond
485%x IDLquote
486%x RulesPattern
487%x RulesDouble
488%x RulesRoundDouble
489%x RulesSquare
490%x RulesRoundSquare
491%x RulesRound
492%x RulesRoundQuest
493%x PragmaOnce
494
496
497<*>\x06
498<*>\x00
499<*>\r
500<*>"??"[=/'()!<>-] { // Trigraph
501 unput(resolveTrigraph(yytext[2]));
502 }
503<Start>^{B}*"#" {
504 yyextra->yyColNr+=(int)yyleng;
505 yyextra->yyMLines=0;
506 yyextra->potentialDefine=yytext;
507 BEGIN(Command);
508 }
509<Start>^("%top{"|"%{") {
510 if (getLanguageFromFileName(yyextra->fileName)!=SrcLangExt::Lex) REJECT
511 outputArray(yyscanner,yytext,yyleng);
512 BEGIN(LexCopyLine);
513 }
SrcLangExt getLanguageFromFileName(const DString &fileName, SrcLangExt defLang)
Definition util.cpp:4300
514<Start>^{Bopt}"cpp_quote"{Bopt}"("{Bopt}\" {
515 if (yyextra->insideIDL)
516 {
517 BEGIN(IDLquote);
518 }
519 else
520 {
521 REJECT;
522 }
523 }
524<IDLquote>"\\\\" {
525 outputArray(yyscanner,"\\",1);
526 }
527<IDLquote>"\\\"" {
528 outputArray(yyscanner,"\"",1);
529 }
530<IDLquote>"\""{Bopt}")" {
531 BEGIN(Start);
532 }
533<IDLquote>\n {
534 outputChar(yyscanner,'\n');
535 yyextra->yyLineNr++;
536 }
537<IDLquote>. {
538 outputArray(yyscanner,yytext,yyleng);
539 }
540<Start>^[Cc*].* {
541 if (getLanguageFromFileName(yyextra->fileName)!=SrcLangExt::Fortran) REJECT;
542 if (!yyextra->isFixedFormFtn) REJECT;
543 outputArray(yyscanner,yytext,yyleng);
544 }
545<Start>^{Bopt}"!".* {
546 if (getLanguageFromFileName(yyextra->fileName)!=SrcLangExt::Fortran) REJECT;
547 outputArray(yyscanner,yytext,yyleng);
548 }
549<Start>^{Bopt}/[^#] {
550 outputArray(yyscanner,yytext,yyleng);
551 BEGIN(CopyLine);
552 }
553<Start>^{B}*[a-z_A-Z\x80-\xFF][a-z_A-Z0-9\x80-\xFF]+{B}*"("[^\‍)\n]*")"/{BN}{1,10}*[:{] { // constructors?
554 int i;
555 for (i=(int)yyleng-1;i>=0;i--)
556 {
557 unput(yytext[i]);
558 }
559 BEGIN(CopyLine);
560 }
561<Start>^{B}*[_A-Z][_A-Z0-9]+{B}*"("[^\‍(\‍)\n]*"("[^\‍)\n]*")"[^\‍)\n]*")"{B}*\n | // function list macro with one (...) argument, e.g. for K_GLOBAL_STATIC_WITH_ARGS
562<Start>^{B}*[_A-Z][_A-Z0-9]+{B}*"("[^\‍)\n]*")"{B}*\n | // function like macro
563<Start>^{B}*[_A-Z][_A-Z0-9]+{B}*"("[^\‍(\‍)\n]*"("[^\‍)\n]*")"[^\‍)\n]*")"/{B}*("//"|"/\*") | // function list macro with one (...) argument followed by comment
564<Start>^{B}*[_A-Z][_A-Z0-9]+{B}*"("[^\‍)\n]*")"/{B}*("//"|"/\*") { // function like macro followed by comment
565 bool skipFuncMacros = Config_getBool(SKIP_FUNCTION_MACROS);
566 DString name(yytext);
567 size_t pos = name.find('(');
568 if (pos==DString::npos) pos=0; // should never happen
569 name=name.left(pos).stripWhiteSpace();
570
571 Define *def=nullptr;
572 if (skipFuncMacros && !yyextra->insideFtn &&
573 name!="Q_PROPERTY" &&
574 !(
575 (yyextra->includeStack.empty() || yyextra->curlyCount>0) &&
576 yyextra->macroExpansion &&
577 (def=isDefined(yyscanner,name)) &&
578 /*macroIsAccessible(def) &&*/
579 (!yyextra->expandOnlyPredef || def->isPredefined)
580 )
581 )
582 {
583 // Only when ends on \n
584 if (yytext[yyleng-1] == '\n')
585 {
586 outputChar(yyscanner,'\n');
587 yyextra->yyLineNr++;
588 }
589 }
590 else // don't skip
591 {
592 int i;
593 for (i=(int)yyleng-1;i>=0;i--)
594 {
595 unput(yytext[i]);
596 }
597 BEGIN(CopyLine);
598 }
599 }
static constexpr size_t npos
value used to indicate 'not found' or 'to the end of the string', matching std::string::npos
Definition dstring.h:178
bool isPredefined
Definition define.h:43
#define Config_getBool(name)
Definition config.h:33
const char * name(int level)
Definition latexgen.h:368
600<CopyLine,LexCopyLine>"extern"{BN}*"\""[^\"]+"\""{BN}*("{")? {
601 DString text=yytext;
602 yyextra->yyLineNr+=text.contains('\n');
603 outputArray(yyscanner,yytext,yyleng);
604 }
int contains(char c, bool cs=true) const
Definition dstring.cpp:85
605<CopyLine,LexCopyLine>{RAWBEGIN} {
606 yyextra->delimiter = extractBeginRawStringDelimiter(yytext);
607 outputArray(yyscanner,yytext,yyleng);
608 BEGIN(CopyRawString);
609 }
DString extractBeginRawStringDelimiter(const char *rawStart)
Definition util.cpp:5514
610<CopyLine,LexCopyLine>"{" { // count brackets inside the main file
611 if (yyextra->includeStack.empty())
612 {
613 yyextra->curlyCount++;
614 }
615 outputChar(yyscanner,*yytext);
616 }
617<LexCopyLine>^"%}" {
618 outputArray(yyscanner,yytext,yyleng);
619 }
620<CopyLine,LexCopyLine>"}" { // count brackets inside the main file
621 if (yyextra->includeStack.empty() && yyextra->curlyCount>0)
622 {
623 yyextra->curlyCount--;
624 }
625 outputChar(yyscanner,*yytext);
626 }
627<CopyLine,LexCopyLine>"'"\\‍[0-7]{1,3}"'" {
628 outputArray(yyscanner,yytext,yyleng);
629 }
630<CopyLine,LexCopyLine>"'"\\."'" {
631 outputArray(yyscanner,yytext,yyleng);
632 }
633<CopyLine,LexCopyLine>"'"."'" {
634 outputArray(yyscanner,yytext,yyleng);
635 }
636<CopyLine,LexCopyLine>[$]?@\" {
637 if (getLanguageFromFileName(yyextra->fileName)!=SrcLangExt::CSharp) REJECT;
638 outputArray(yyscanner,yytext,yyleng);
639 BEGIN( CopyStringCs );
640 }
641<CopyLine,LexCopyLine>"!".* {
642 if (getLanguageFromFileName(yyextra->fileName)!=SrcLangExt::Fortran) REJECT;
643 outputArray(yyscanner,yytext,yyleng);
644 }
645<CopyLine,LexCopyLine>\" {
646 outputChar(yyscanner,*yytext);
647 if (getLanguageFromFileName(yyextra->fileName)!=SrcLangExt::Fortran)
648 {
649 BEGIN( CopyString );
650 }
651 else
652 {
653 BEGIN( CopyStringFtnDouble );
654 }
655 }
656<CopyLine,LexCopyLine>\' {
657 if (getLanguageFromFileName(yyextra->fileName)!=SrcLangExt::Fortran) REJECT;
658 outputChar(yyscanner,*yytext);
659 BEGIN( CopyStringFtn );
660 }
661<CopyString>[^\"\\\r\n]{1,1000} {
662 outputArray(yyscanner,yytext,yyleng);
663 }
664<CopyStringCs>[^\"\r\n]{1,1000} {
665 outputArray(yyscanner,yytext,yyleng);
666 }
667<CopyStringCs>\"\" {
668 outputArray(yyscanner,yytext,yyleng);
669 }
670<CopyString>\\. {
671 outputArray(yyscanner,yytext,yyleng);
672 }
673<CopyString,CopyStringCs>\" {
674 outputChar(yyscanner,*yytext);
675 BEGIN( CopyLine );
676 }
677<CopyStringFtnDouble>[^\"\\\r\n]{1,1000} {
678 outputArray(yyscanner,yytext,yyleng);
679 }
680<CopyStringFtnDouble>\\. {
681 outputArray(yyscanner,yytext,yyleng);
682 }
683<CopyStringFtnDouble>\" {
684 outputChar(yyscanner,*yytext);
685 BEGIN( CopyLine );
686 }
687<CopyStringFtn>[^\'\\\r\n]{1,1000} {
688 outputArray(yyscanner,yytext,yyleng);
689 }
690<CopyStringFtn>\\. {
691 outputArray(yyscanner,yytext,yyleng);
692 }
693<CopyStringFtn>\' {
694 outputChar(yyscanner,*yytext);
695 BEGIN( CopyLine );
696 }
697<CopyRawString>{RAWEND} {
698 outputArray(yyscanner,yytext,yyleng);
699 if (extractEndRawStringDelimiter(yytext)==yyextra->delimiter)
700 {
701 BEGIN( CopyLine );
702 }
703 }
DString extractEndRawStringDelimiter(const char *rawEnd)
Definition util.cpp:5522
704<CopyRawString>[^)]{1,1000} {
705 outputArray(yyscanner,yytext,yyleng);
706 }
707<CopyRawString>. {
708 outputChar(yyscanner,*yytext);
709 }
710<CopyLine,LexCopyLine>{ID}/{BN}{0,80}"(" {
711 yyextra->expectGuard = false;
712 Define *def=nullptr;
713 //def=yyextra->globalDefineDict->find(yytext);
714 //def=isDefined(yyscanner,yytext);
715 //printf("Search for define %s found=%d yyextra->includeStack.empty()=%d "
716 // "yyextra->curlyCount=%d yyextra->macroExpansion=%d yyextra->expandOnlyPredef=%d "
717 // "isPreDefined=%d\n",yytext,def ? 1 : 0,
718 // yyextra->includeStack.empty(),yyextra->curlyCount,yyextra->macroExpansion,yyextra->expandOnlyPredef,
719 // def ? def->isPredefined : -1
720 // );
721 if ((yyextra->includeStack.empty() || yyextra->curlyCount>0) &&
722 yyextra->macroExpansion &&
723 (def=isDefined(yyscanner,yytext)) &&
724 (!yyextra->expandOnlyPredef || def->isPredefined)
725 )
726 {
727 //printf("Found it! #args=%d\n",def->nargs);
728 yyextra->roundCount=0;
729 yyextra->defArgsStr=yytext;
730 DString resultExpr;
731 if (def->nargs==-1) // no function macro
732 {
733 DString result = def->isPredefined && !def->expandAsDefined ?
734 def->definition :
735 expandMacro(yyscanner,yyextra->defArgsStr);
736 outputString(yyscanner,result);
737 }
738 else // zero or more arguments
739 {
740 yyextra->findDefArgContext = CopyLine;
741 BEGIN(FindDefineArgs);
742 }
743 }
744 else
745 {
746 outputArray(yyscanner,yytext,yyleng);
747 }
748 }
int nargs
Definition define.h:40
bool expandAsDefined
Definition define.h:45
DString definition
Definition define.h:34
749<CopyLine>{RulesDelim} {
750 if (getLanguageFromFileName(yyextra->fileName)!=SrcLangExt::Lex) REJECT;
751 yyextra->lexRulesPart = !yyextra->lexRulesPart;
752 outputArray(yyscanner,yytext,yyleng);
753 }
754 /* start lex rule handling */
755<CopyLine>{RulesSharp} {
756 if (!yyextra->lexRulesPart) REJECT;
757 if (yyextra->curlyCount) REJECT;
758 outputArray(yyscanner,yytext,yyleng);
759 BEGIN(RulesPattern);
760 }
761<RulesPattern>{EscapeRulesChar} {
762 outputArray(yyscanner,yytext,yyleng);
763 }
764<RulesPattern>{RulesCurly} {
765 outputArray(yyscanner,yytext,yyleng);
766 }
767<RulesPattern>{StartDouble} {
768 outputArray(yyscanner,yytext,yyleng);
769 yyextra->lastContext = YY_START;
770 BEGIN(RulesDouble);
771 }
772<RulesDouble,RulesRoundDouble>"\\\\" {
773 outputArray(yyscanner,yytext,yyleng);
774 }
775<RulesDouble,RulesRoundDouble>"\\\"" {
776 outputArray(yyscanner,yytext,yyleng);
777 }
778<RulesDouble>"\"" {
779 outputArray(yyscanner,yytext,yyleng);
780 BEGIN( yyextra->lastContext ) ;
781 }
782<RulesRoundDouble>"\"" {
783 outputArray(yyscanner,yytext,yyleng);
784 BEGIN(RulesRound) ;
785 }
786<RulesDouble,RulesRoundDouble>. {
787 outputArray(yyscanner,yytext,yyleng);
788 }
789<RulesPattern>{StartSquare} {
790 outputArray(yyscanner,yytext,yyleng);
791 yyextra->lastContext = YY_START;
792 BEGIN(RulesSquare);
793 }
794<RulesSquare,RulesRoundSquare>{CHARCE} {
795 outputArray(yyscanner,yytext,yyleng);
796 }
797<RulesSquare,RulesRoundSquare>"\\‍[" |
798<RulesSquare,RulesRoundSquare>"\\‍]" {
799 outputArray(yyscanner,yytext,yyleng);
800 }
801<RulesSquare>"]" {
802 outputArray(yyscanner,yytext,yyleng);
803 BEGIN(RulesPattern);
804 }
805<RulesRoundSquare>"]" {
806 outputArray(yyscanner,yytext,yyleng);
807 BEGIN(RulesRound) ;
808 }
809<RulesSquare,RulesRoundSquare>"\\\\" {
810 outputArray(yyscanner,yytext,yyleng);
811 }
812<RulesSquare,RulesRoundSquare>. {
813 outputArray(yyscanner,yytext,yyleng);
814 }
815<RulesPattern>{StartRoundQuest} {
816 outputArray(yyscanner,yytext,yyleng);
817 yyextra->lastContext = YY_START;
818 BEGIN(RulesRoundQuest);
819 }
820<RulesRoundQuest>{nl} {
821 outputArray(yyscanner,yytext,yyleng);
822 }
823<RulesRoundQuest>[^)] {
824 outputArray(yyscanner,yytext,yyleng);
825 }
826<RulesRoundQuest>")" {
827 outputArray(yyscanner,yytext,yyleng);
828 BEGIN(yyextra->lastContext);
829 }
830<RulesPattern>{StartRound} {
831 yyextra->roundCount++;
832 outputArray(yyscanner,yytext,yyleng);
833 yyextra->lastContext = YY_START;
834 BEGIN(RulesRound);
835 }
836<RulesRound>{RulesCurly} {
837 outputArray(yyscanner,yytext,yyleng);
838 }
839<RulesRound>{StartSquare} {
840 outputArray(yyscanner,yytext,yyleng);
841 BEGIN(RulesRoundSquare);
842 }
843<RulesRound>{StartDouble} {
844 outputArray(yyscanner,yytext,yyleng);
845 BEGIN(RulesRoundDouble);
846 }
847<RulesRound>{EscapeRulesChar} {
848 outputArray(yyscanner,yytext,yyleng);
849 }
850<RulesRound>"(" {
851 yyextra->roundCount++;
852 outputArray(yyscanner,yytext,yyleng);
853 }
854<RulesRound>")" {
855 yyextra->roundCount--;
856 outputArray(yyscanner,yytext,yyleng);
857 if (!yyextra->roundCount) BEGIN( yyextra->lastContext ) ;
858 }
859<RulesRound>{nl} {
860 outputArray(yyscanner,yytext,yyleng);
861 }
862<RulesRound>{B} {
863 outputArray(yyscanner,yytext,yyleng);
864 }
865<RulesRound>. {
866 outputArray(yyscanner,yytext,yyleng);
867 }
868<RulesPattern>{B} {
869 outputArray(yyscanner,yytext,yyleng);
870 BEGIN(CopyLine);
871 }
872<RulesPattern>. {
873 outputArray(yyscanner,yytext,yyleng);
874 }
875 /* end lex rule handling */
876<CopyLine,LexCopyLine>{ID} {
877 Define *def=nullptr;
878 DString result;
879 if ((yyextra->includeStack.empty() || yyextra->curlyCount>0) &&
880 yyextra->macroExpansion &&
881 (def=isDefined(yyscanner,yytext)) &&
882 def->nargs==-1 &&
883 (!yyextra->expandOnlyPredef || def->isPredefined)
884 )
885 {
886 result=def->isPredefined && !def->expandAsDefined ?
887 def->definition :
888 expandMacro(yyscanner,yytext);
889 outputString(yyscanner,result);
890 }
891 else if (!(result = expandStandardMacro(yyscanner,yytext)).empty())
892 {
893 outputString(yyscanner,result);
894 }
895 else
896 {
897 outputArray(yyscanner,yytext,yyleng);
898 }
899 }
900<CopyLine,LexCopyLine>"\\"\r?/\n { // strip line continuation characters
901 if (getLanguageFromFileName(yyextra->fileName)==SrcLangExt::Fortran) outputChar(yyscanner,*yytext);
902 }
903<CopyLine,LexCopyLine>\\. {
904 outputArray(yyscanner,yytext,(int)yyleng);
905 }
906<CopyLine,LexCopyLine>. {
907 outputChar(yyscanner,*yytext);
908 }
909<CopyLine,LexCopyLine>\n {
910 outputChar(yyscanner,'\n');
911 BEGIN(Start);
912 yyextra->yyLineNr++;
913 yyextra->yyColNr=1;
914 }
915<FindDefineArgs>"(" {
916 yyextra->defArgsStr+='(';
917 yyextra->roundCount++;
918 }
919<FindDefineArgs>")" {
920 yyextra->defArgsStr+=')';
921 yyextra->roundCount--;
922 if (yyextra->roundCount==0)
923 {
924 DString result=expandMacro(yyscanner,yyextra->defArgsStr);
925 //printf("yyextra->defArgsStr='%s'->'%s'\n",qPrint(yyextra->defArgsStr),qPrint(result));
926 if (yyextra->findDefArgContext==CopyLine)
927 {
928 outputString(yyscanner,result);
929 BEGIN(yyextra->findDefArgContext);
930 }
931 else // yyextra->findDefArgContext==IncludeID
932 {
933 readIncludeFile(yyscanner,result);
934 yyextra->nospaces=false;
935 BEGIN(Start);
936 }
937 }
938 }
939 /*
940<FindDefineArgs>")"{B}*"(" {
941 yyextra->defArgsStr+=yytext;
942 }
943 */
944<FindDefineArgs>{CHARLIT} {
945 yyextra->defArgsStr+=yytext;
946 }
947<FindDefineArgs>{CCS}[*!]? {
948 yyextra->defArgsStr+=yytext;
949 BEGIN(ArgCopyCComment);
950 }
951<FindDefineArgs>{CPPC}[/!].*\n/{B}*{CPPC}[/!] { // replace multi line C++ style comment by C style comment
952 if (Config_getBool(MULTILINE_CPP_IS_BRIEF) && !Config_getBool(QT_AUTOBRIEF))
953 {
954 if (yytext[3]=='<') // preserve < before @brief
955 {
956 yyextra->defArgsStr+=DString("/**< @brief ")+&yytext[4];
957 }
958 else
959 {
960 yyextra->defArgsStr+=DString("/** @brief ")+&yytext[3];
961 }
962 }
963 else
964 {
965 yyextra->defArgsStr+=DString("/**")+&yytext[3];
966 }
967 BEGIN(ArgCopyCppComment);
968 }
969<FindDefineArgs>{CPPC}[/!].*\n { // replace C++ single line style comment by C style comment
970 if (Config_getBool(QT_AUTOBRIEF))
971 {
972 yyextra->defArgsStr+=DString("/**")+&yytext[3]+" */";
973 }
974 else // add brief command explicitly when translating C++ to C comment style
975 {
976 if (yytext[3]=='<') // preserve < before @brief
977 {
978 yyextra->defArgsStr+=DString("/**< @brief ")+&yytext[4]+" */";
979 }
980 else
981 {
982 yyextra->defArgsStr+=DString("/** @brief ")+&yytext[3]+" */";
983 }
984 }
985 }
986<FindDefineArgs>{CPPC}.*\n { // replace C++ single line style comment by C style comment
987 if (getLanguageFromFileName(yyextra->fileName)==SrcLangExt::Fortran) REJECT;
988 yyextra->defArgsStr+=DString("/*")+&yytext[2]+" */";
989 }
990<FindDefineArgs>\" {
991 yyextra->defArgsStr+=*yytext;
992 BEGIN(ReadString);
993 }
994<FindDefineArgs>' {
995 if (getLanguageFromFileName(yyextra->fileName)!=SrcLangExt::Fortran) REJECT;
996 yyextra->defArgsStr+=*yytext;
997 BEGIN(ReadString);
998 }
999<FindDefineArgs>\n {
1000 yyextra->defArgsStr+=' ';
1001 yyextra->yyLineNr++;
1002 outputChar(yyscanner,'\n');
1003 }
1004<FindDefineArgs>"@" {
1005 yyextra->defArgsStr+="@@";
1006 }
1007<FindDefineArgs>. {
1008 yyextra->defArgsStr+=*yytext;
1009 }
1010<ArgCopyCComment>[^*\n]+ {
1011 yyextra->defArgsStr+=yytext;
1012 }
1013<ArgCopyCComment>{CCE} {
1014 yyextra->defArgsStr+=yytext;
1015 BEGIN(FindDefineArgs);
1016 }
1017<ArgCopyCComment>\n {
1018 yyextra->defArgsStr+=yytext;
1019 yyextra->yyLineNr++;
1020 }
1021<ArgCopyCComment>. {
1022 yyextra->defArgsStr+=yytext;
1023 }
1024<ArgCopyCppComment>^{B}*
1025<ArgCopyCppComment>{CPPC}[/!].*\n/{B}*{CPPC}[/!] { // replace multi line C++ style comment by C style comment
1026 const char *startContent = &yytext[3];
1027 if (startContent[0]=='<') startContent++;
1028 yyextra->defArgsStr+=startContent;
1029 }
1030<ArgCopyCppComment>{CPPC}[/!].*\n { // replace C++ multie line style comment by C style comment
1031 const char *startContent = &yytext[3];
1032 if (startContent[0]=='<') startContent++;
1033 yyextra->defArgsStr+=DString(startContent)+" */";
1034 BEGIN(FindDefineArgs);
1035 }
1036<ArgCopyCppComment>. { // unexpected character
1037 unput(*yytext);
1038 yyextra->defArgsStr+=" */";
1039 BEGIN(FindDefineArgs);
1040 }
1041<ReadString>"\"" {
1042 yyextra->defArgsStr+=*yytext;
1043 BEGIN(FindDefineArgs);
1044 }
1045<ReadString>"'" {
1046 if (getLanguageFromFileName(yyextra->fileName)!=SrcLangExt::Fortran) REJECT;
1047 yyextra->defArgsStr+=*yytext;
1048 BEGIN(FindDefineArgs);
1049 }
1050
1051<ReadString>{CPPC}|{CCS} {
1052 yyextra->defArgsStr+=yytext;
1053 }
1054<ReadString>\\/\r?\n { // line continuation
1055 }
1056<ReadString>\\. {
1057 yyextra->defArgsStr+=yytext;
1058 }
1059<ReadString>. {
1060 yyextra->defArgsStr+=*yytext;
1061 }
1062<Command>("include"|"import"){B}+/{ID} {
1063 yyextra->isImported = yytext[1]=='m';
1064 if (yyextra->macroExpansion)
1065 BEGIN(IncludeID);
1066 }
1067<Command>("include"|"import"){B}*[<"] {
1068 yyextra->isImported = yytext[1]=='m';
1069 char c[2];
1070 c[0]=yytext[yyleng-1];c[1]='\0';
1071 yyextra->incName=c;
1072 BEGIN(Include);
1073 }
1074<Command>("cmake")?"define"{B}+ {
1075 yyextra->potentialDefine += substitute(yytext,"cmake"," ");
1076 //printf("!!!DefName\n");
1077 yyextra->yyColNr+=(int)yyleng;
1078 BEGIN(DefName);
1079 }
DString substitute(const DString &s, const DString &src, const DString &dst)
substitute all occurrences of src in s by dst
Definition dstring.cpp:485
1080<Command>"cmakedefine01"{B}+ {
1081 yyextra->potentialDefine += substitute(yytext,"cmakedefine01"," define ");
1082 //printf("!!!DefName\n");
1083 yyextra->yyColNr+=(int)yyleng;
1084 BEGIN(CmakeDefName01);
1085 }
1086<Command>"ifdef"/{B}*"(" {
1087 incrLevel(yyscanner);
1088 yyextra->guardExpr.clear();
1089 BEGIN(DefinedExpr2);
1090 }
1091<Command>"ifdef"/{B}+ {
1092 //printf("Pre.l: ifdef\n");
1093 incrLevel(yyscanner);
1094 yyextra->guardExpr.clear();
1095 BEGIN(DefinedExpr1);
1096 }
1097<Command>"ifndef"/{B}*"(" {
1098 incrLevel(yyscanner);
1099 yyextra->guardExpr="! ";
1100 BEGIN(DefinedExpr2);
1101 }
1102<Command>"ifndef"/{B}+ {
1103 incrLevel(yyscanner);
1104 yyextra->guardExpr="! ";
1105 BEGIN(DefinedExpr1);
1106 }
1107<Command>"if"/[ \t(!] {
1108 incrLevel(yyscanner);
1109 yyextra->guardExpr.clear();
1110 BEGIN(Guard);
1111 }
1112<Command>("elif"|"else"{B}*"if")/[ \t(!] {
1113 if (!otherCaseDone(yyscanner))
1114 {
1115 yyextra->guardExpr.clear();
1116 BEGIN(Guard);
1117 }
1118 else
1119 {
1120 yyextra->ifcount=0;
1121 BEGIN(SkipCPPBlock);
1122 }
1123 }
1124<Command>"else"/[^a-z_A-Z0-9\x80-\xFF] {
1125 if (otherCaseDone(yyscanner))
1126 {
1127 yyextra->ifcount=0;
1128 BEGIN(SkipCPPBlock);
1129 }
1130 else
1131 {
1132 setCaseDone(yyscanner,true);
1133 }
1134 }
1135<Command>"undef"{B}+ {
1136 BEGIN(UndefName);
1137 }
1138<Command>("elif"|"else"{B}*"if")/[ \t(!] {
1139 if (!otherCaseDone(yyscanner))
1140 {
1141 yyextra->guardExpr.clear();
1142 BEGIN(Guard);
1143 }
1144 }
1145<Command>"endif"/[^a-z_A-Z0-9\x80-\xFF] {
1146 //printf("Pre.l: #endif\n");
1147 decrLevel(yyscanner);
1148 }
1149<Command,IgnoreLine>\n {
1150 outputChar(yyscanner,'\n');
1151 BEGIN(Start);
1152 yyextra->yyLineNr++;
1153 }
1154<Command>"pragma"{B}+"once" {
1155 yyextra->expectGuard = false;
1156 if (yyextra->pragmaSet.find(yyextra->fileName.str())!=yyextra->pragmaSet.end())
1157 {
1158 outputChar(yyscanner,'\n');
1159 BEGIN(PragmaOnce);
1160 }
1161 else
1162 {
1163 yyextra->pragmaSet.insert(yyextra->fileName.data());
1164 }
1165 }
1166<PragmaOnce>. {}
1167<PragmaOnce>\n {}
1168<PragmaOnce><<EOF>> {
1169 yyextra->expectGuard = false;
1170 BEGIN(Start);
1171 }
1172<Command>{ID} { // unknown directive
1173 BEGIN(IgnoreLine);
1174 }
1175<IgnoreLine>\\‍[\r]?\n {
1176 outputChar(yyscanner,'\n');
1177 yyextra->yyLineNr++;
1178 }
1179<IgnoreLine>.
1180<Command>. { yyextra->potentialDefine += yytext[0]=='\t' ? '\t' : ' ';
1181 yyextra->yyColNr+=(int)yyleng;
1182 }
1183<UndefName>{ID} {
1184 Define *def;
1185 if ((def=isDefined(yyscanner,yytext))
1186 /*&& !def->isPredefined*/
1187 && !def->nonRecursive
1188 )
1189 {
1190 //printf("undefining %s\n",yytext);
1191 def->undef=true;
1192 }
1193 BEGIN(Start);
1194 }
bool nonRecursive
Definition define.h:44
bool undef
Definition define.h:41
1195<Guard>\\‍[\r]?\n {
1196 outputChar(yyscanner,'\n');
1197 yyextra->guardExpr+=' ';
1198 yyextra->yyLineNr++;
1199 }
1200<Guard>"defined"/{B}*"(" {
1201 BEGIN(DefinedExpr2);
1202 }
1203<Guard>"defined"/{B}+ {
1204 BEGIN(DefinedExpr1);
1205 }
1206<Guard>"true"/{B}|{B}*[\r]?\n { yyextra->guardExpr+="1L"; }
1207<Guard>"false"/{B}|{B}*[\r]?\n { yyextra->guardExpr+="0L"; }
1208<Guard>"not"/{B} { yyextra->guardExpr+='!'; }
1209<Guard>"not_eq"/{B} { yyextra->guardExpr+="!="; }
1210<Guard>"and"/{B} { yyextra->guardExpr+="&&"; }
1211<Guard>"or"/{B} { yyextra->guardExpr+="||"; }
1212<Guard>"bitand"/{B} { yyextra->guardExpr+="&"; }
1213<Guard>"bitor"/{B} { yyextra->guardExpr+="|"; }
1214<Guard>"xor"/{B} { yyextra->guardExpr+="^"; }
1215<Guard>"compl"/{B} { yyextra->guardExpr+="~"; }
1216<Guard>{ID} { yyextra->guardExpr+=yytext; }
1217<Guard>"@" { yyextra->guardExpr+="@@"; }
1218<Guard>. { yyextra->guardExpr+=*yytext; }
1219<Guard>\n {
1220 unput(*yytext);
1221 //printf("Guard: '%s'\n",
1222 // qPrint(yyextra->guardExpr));
1223 bool guard=computeExpression(yyscanner,yyextra->guardExpr);
1224 setCaseDone(yyscanner,guard);
1225 if (guard)
1226 {
1227 BEGIN(Start);
1228 }
1229 else
1230 {
1231 yyextra->ifcount=0;
1232 BEGIN(SkipCPPBlock);
1233 }
1234 }
1235<DefinedExpr1,DefinedExpr2>\\\n { yyextra->yyLineNr++; outputChar(yyscanner,'\n'); }
1236<DefinedExpr1>{ID} {
1237 if (isDefined(yyscanner,yytext) || yyextra->guardName==yytext)
1238 yyextra->guardExpr+=" 1L ";
1239 else
1240 yyextra->guardExpr+=" 0L ";
1241 yyextra->lastGuardName=yytext;
1242 BEGIN(Guard);
1243 }
1244<DefinedExpr2>{ID} {
1245 if (isDefined(yyscanner,yytext) || yyextra->guardName==yytext)
1246 yyextra->guardExpr+=" 1L ";
1247 else
1248 yyextra->guardExpr+=" 0L ";
1249 yyextra->lastGuardName=yytext;
1250 }
1251<DefinedExpr1,DefinedExpr2>\n { // should not happen, handle anyway
1252 yyextra->yyLineNr++;
1253 yyextra->ifcount=0;
1254 BEGIN(SkipCPPBlock);
1255 }
1256<DefinedExpr2>")" {
1257 BEGIN(Guard);
1258 }
1259<DefinedExpr1,DefinedExpr2>.
1260<SkipCPPBlock>^{B}*"#" { BEGIN(SkipCommand); }
1261<SkipCPPBlock>^{Bopt}/[^#] { BEGIN(SkipLine); }
1262<SkipCPPBlock>\n { yyextra->yyLineNr++; outputChar(yyscanner,'\n'); }
1263<SkipCPPBlock>.
1264<SkipCommand>"if"(("n")?("def"))?/[ \t(!] {
1265 incrLevel(yyscanner);
1266 yyextra->ifcount++;
1267 //printf("#if... depth=%d\n",yyextra->ifcount);
1268 }
1269<SkipCommand>"else" {
1270 //printf("Else! yyextra->ifcount=%d otherCaseDone=%d\n",yyextra->ifcount,otherCaseDone());
1271 if (yyextra->ifcount==0 && !otherCaseDone(yyscanner))
1272 {
1273 setCaseDone(yyscanner,true);
1274 //outputChar(yyscanner,'\n');
1275 BEGIN(Start);
1276 }
1277 }
1278<SkipCommand>("elif"|"else"{B}*"if")/[ \t(!] {
1279 if (yyextra->ifcount==0)
1280 {
1281 if (!otherCaseDone(yyscanner))
1282 {
1283 yyextra->guardExpr.clear();
1284 yyextra->lastGuardName.clear();
1285 BEGIN(Guard);
1286 }
1287 else
1288 {
1289 BEGIN(SkipCPPBlock);
1290 }
1291 }
1292 }
1293<SkipCommand>"endif" {
1294 yyextra->expectGuard = false;
1295 decrLevel(yyscanner);
1296 if (--yyextra->ifcount<0)
1297 {
1298 //outputChar(yyscanner,'\n');
1299 BEGIN(Start);
1300 }
1301 }
1302<SkipCommand>\n {
1303 outputChar(yyscanner,'\n');
1304 yyextra->yyLineNr++;
1305 BEGIN(SkipCPPBlock);
1306 }
1307<SkipCommand>{ID} { // unknown directive
1308 BEGIN(SkipLine);
1309 }
1310<SkipCommand>.
1311<SkipLine>[^'"/\n]+
1312<SkipLine>{CHARLIT} { }
1313<SkipLine>\" {
1314 BEGIN(SkipString);
1315 }
1316<SkipLine>.
1317<SkipString>{CPPC}/[^\n]* {
1318 }
1319<SkipLine,SkipCommand,SkipCPPBlock>{CPPC}[^\n]* {
1320 yyextra->lastCPPContext=YY_START;
1321 BEGIN(RemoveCPPComment);
1322 }
1323<SkipString>{CCS}/[^\n]* {
1324 }
1325<SkipLine,SkipCommand,SkipCPPBlock>{CCS}/[^\n]* {
1326 yyextra->lastCContext=YY_START;
1327 BEGIN(RemoveCComment);
1328 }
1329<SkipLine>\n {
1330 outputChar(yyscanner,'\n');
1331 yyextra->yyLineNr++;
1332 BEGIN(SkipCPPBlock);
1333 }
1334<SkipString>[^"\\\n]+ { }
1335<SkipString>\\. { }
1336<SkipString>\" {
1337 BEGIN(SkipLine);
1338 }
1339<SkipString>. { }
1340<IncludeID>{ID}{Bopt}/"(" {
1341 yyextra->nospaces=true;
1342 yyextra->roundCount=0;
1343 yyextra->defArgsStr=yytext;
1344 yyextra->findDefArgContext = IncludeID;
1345 BEGIN(FindDefineArgs);
1346 }
1347<IncludeID>{ID} {
1348 yyextra->nospaces=true;
1349 readIncludeFile(yyscanner,expandMacro(yyscanner,yytext));
1350 BEGIN(Start);
1351 }
1352<Include>[^\">\n]+[\">] {
1353 yyextra->incName+=yytext;
1354 if (yyextra->isImported)
1355 {
1356 BEGIN(EndImport);
1357 }
1358 else
1359 {
1360 readIncludeFile(yyscanner,yyextra->incName);
1361 BEGIN(Start);
1362 }
1363 }
1364<EndImport>{ENDIMPORTopt}/\n {
1365 readIncludeFile(yyscanner,yyextra->incName);
1366 BEGIN(Start);
1367 }
1368<EndImport>\\‍[\r]?"\n" {
1369 outputChar(yyscanner,'\n');
1370 yyextra->yyLineNr++;
1371 }
1372<EndImport>. {
1373 }
1374<DefName>{ID}/("\\\n")*"(" { // define with argument
1375 //printf("Define() '%s'\n",yytext);
1376 yyextra->argMap.clear();
1377 yyextra->defArgs = 0;
1378 yyextra->defArgsStr.clear();
1379 yyextra->defText.clear();
1380 yyextra->defLitText.clear();
1381 yyextra->defName = yytext;
1382 yyextra->defVarArgs = false;
1383 yyextra->defExtraSpacing.clear();
1384 yyextra->defContinue = false;
1385 BEGIN(DefineArg);
1386 }
1387<DefName>{ID}{B}+"1"/[ \r\t\n] { // special case: define with 1 -> can be "guard"
1388 //printf("Define '%s'\n",yytext);
1389 yyextra->argMap.clear();
1390 yyextra->defArgs = -1;
1391 yyextra->defArgsStr.clear();
1392 yyextra->defName = DString(yytext).left(yyleng-1).stripWhiteSpace();
1393 yyextra->defVarArgs = false;
1394 //printf("Guard check: %s!=%s || %d\n",
1395 // qPrint(yyextra->defName),qPrint(yyextra->lastGuardName),yyextra->expectGuard);
1396 if (yyextra->curlyCount>0 || yyextra->defName!=yyextra->lastGuardName || !yyextra->expectGuard)
1397 { // define may appear in the output
1398 DString def = yyextra->potentialDefine +
1399 yyextra->defName ;
1400 outputString(yyscanner,def);
1401 outputSpaces(yyscanner,yytext+yyextra->defName.length());
1402 yyextra->quoteArg=false;
1403 yyextra->insideComment=false;
1404 yyextra->lastGuardName.clear();
1405 yyextra->defText="1";
1406 yyextra->defLitText="1";
1407 BEGIN(DefineText);
1408 }
1409 else // define is a guard => hide
1410 {
1411 //printf("Found a guard %s\n",yytext);
1412 yyextra->defText.clear();
1413 yyextra->defLitText.clear();
1414 BEGIN(Start);
1415 }
1416 yyextra->expectGuard=false;
1417 }
DString stripWhiteSpace() const
returns a copy of this string with leading and trailing whitespace removed
Definition dstring.h:337
DString left(size_t len) const
Definition dstring.h:306
1418<DefName,CmakeDefName01>{ID}/{B}*"\n" { // empty define
1419 yyextra->argMap.clear();
1420 yyextra->defArgs = -1;
1421 yyextra->defName = yytext;
1422 yyextra->defArgsStr.clear();
1423 yyextra->defText.clear();
1424 yyextra->defLitText.clear();
1425 yyextra->defVarArgs = false;
1426 //printf("Guard check: %s!=%s || %d\n",
1427 // qPrint(yyextra->defName),qPrint(yyextra->lastGuardName),yyextra->expectGuard);
1428 if (yyextra->curlyCount>0 || yyextra->defName!=yyextra->lastGuardName || !yyextra->expectGuard)
1429 { // define may appear in the output
1430 DString def = yyextra->potentialDefine + yyextra->defName;
1431 outputString(yyscanner,def);
1432 yyextra->quoteArg=false;
1433 yyextra->insideComment=false;
1434 if (YY_START == CmakeDefName01) yyextra->defText = "0";
1435 else if (yyextra->insideCS) yyextra->defText="1"; // for C#, use "1" as define text
1436 BEGIN(DefineText);
1437 }
1438 else // define is a guard => hide
1439 {
1440 //printf("Found a guard %s\n",yytext);
1441 yyextra->guardName = yytext;
1442 yyextra->lastGuardName.clear();
1443 BEGIN(Start);
1444 }
1445 yyextra->expectGuard=false;
1446 }
1447<DefName>{ID}/{B}* { // define with content
1448 //printf("Define '%s'\n",yytext);
1449 yyextra->argMap.clear();
1450 yyextra->defArgs = -1;
1451 yyextra->defArgsStr.clear();
1452 yyextra->defText.clear();
1453 yyextra->defLitText.clear();
1454 yyextra->defName = yytext;
1455 yyextra->defVarArgs = false;
1456 DString def = yyextra->potentialDefine +
1457 yyextra->defName +
1458 yyextra->defArgsStr ;
1459 outputString(yyscanner,def);
1460 yyextra->quoteArg=false;
1461 yyextra->insideComment=false;
1462 BEGIN(DefineText);
1463 }
1464<DefineArg>"\\\n" {
1465 yyextra->defExtraSpacing+="\n";
1466 yyextra->defContinue = true;
1467 yyextra->yyLineNr++;
1468 }
1469<DefineArg>{B}* { yyextra->defExtraSpacing+=yytext; }
1470<DefineArg>","{B}* { yyextra->defArgsStr+=yytext; }
1471<DefineArg>"("{B}* { yyextra->defArgsStr+=yytext; }
1472<DefineArg>{B}*")"{B}* {
1473 extraSpacing(yyscanner);
1474 yyextra->defArgsStr+=yytext;
1475 DString def = yyextra->potentialDefine +
1476 yyextra->defName +
1477 yyextra->defArgsStr +
1478 yyextra->defExtraSpacing ;
1479 outputString(yyscanner,def);
1480 yyextra->quoteArg=false;
1481 yyextra->insideComment=false;
1482 BEGIN(DefineText);
1483 }
1484<DefineArg>"..." { // Variadic macro
1485 yyextra->defVarArgs = true;
1486 yyextra->defArgsStr+=yytext;
1487 yyextra->argMap.emplace(std::string("__VA_ARGS__"),yyextra->defArgs);
1488 yyextra->defArgs++;
1489 }
1490<DefineArg>{ID}{B}*("..."?) {
1491 //printf("Define addArg(%s)\n",yytext);
1492 DString argName=yytext;
1493 yyextra->defVarArgs = yytext[yyleng-1]=='.';
1494 if (yyextra->defVarArgs) // strip ellipsis
1495 {
1496 argName=argName.left(argName.length()-3);
1497 }
1498 argName = argName.stripWhiteSpace();
1499 yyextra->defArgsStr+=yytext;
1500 yyextra->argMap.emplace(toStdString(argName),yyextra->defArgs);
1501 yyextra->defArgs++;
1502 extraSpacing(yyscanner);
1503 }
size_t length() const
Returns the length of the string, not counting the 0-terminator.
Definition dstring.h:151
std::string toStdString(const DString &s)
Definition dstring.h:798
1504 /*
1505<DefineText>"/ **"|"/ *!" {
1506 yyextra->defText+=yytext;
1507 yyextra->defLitText+=yytext;
1508 yyextra->insideComment=true;
1509 }
1510<DefineText>"* /" {
1511 yyextra->defText+=yytext;
1512 yyextra->defLitText+=yytext;
1513 yyextra->insideComment=false;
1514 }
1515 */
1516<DefineText>{CCS}[^!*] {
1517 yyextra->defLitText+=' ';
1518 outputArray(yyscanner,yytext,yyleng);
1519 yyextra->lastCContext=YY_START;
1520 yyextra->commentCount=1;
1521 BEGIN(SkipCComment);
1522 }
1523<DefineText>{CCS}[!*] {
1524 yyextra->defText+=yytext;
1525 yyextra->defLitText+=yytext;
1526 yyextra->lastCContext=YY_START;
1527 yyextra->commentCount=1;
1528 BEGIN(CopyCComment);
1529 }
1530<DefineText>{CPPC}[!/]? {
1531 outputArray(yyscanner,yytext,yyleng);
1532 yyextra->lastCPPContext=YY_START;
1533 yyextra->defLitText+=' ';
1534 BEGIN(SkipCPPComment);
1535 }
1536<SkipCComment>[/]?{CCE} {
1537 if (yytext[0]=='/') outputChar(yyscanner,'/');
1538 outputChar(yyscanner,'*');outputChar(yyscanner,'/');
1539 if (--yyextra->commentCount<=0)
1540 {
1541 if (yyextra->lastCContext==Start)
1542 // small hack to make sure that ^... rule will
1543 // match when going to Start... Example: "/*...*/ some stuff..."
1544 {
1545 YY_CURRENT_BUFFER->yy_at_bol=1;
1546 }
1547 BEGIN(yyextra->lastCContext);
1548 }
1549 }
1550<SkipCComment>{CPPC}("/")* {
1551 outputArray(yyscanner,yytext,yyleng);
1552 }
1553<SkipCComment>{CCS} {
1554 outputChar(yyscanner,'/');outputChar(yyscanner,'*');
1555 //yyextra->commentCount++;
1556 }
1557<SkipCond>{CMD}{CMD} { }
1558<SkipCond>^({B}*"*"+)?{B}{0,3}"~~~"[~]* {
1559 bool markdownSupport = Config_getBool(MARKDOWN_SUPPORT);
1560 if (!markdownSupport || !yyextra->isSpecialComment)
1561 {
1562 REJECT;
1563 }
1564 else
1565 {
1566 yyextra->fenceChar='~';
1567 yyextra->fenceSize=(int)getFenceSize(yytext,yyleng);
1568 BEGIN(SkipCondVerbatim);
1569 }
1570 }
1571<SkipCond>^({B}*"*"+)?{B}{0,3}"```"[`]* {
1572 bool markdownSupport = Config_getBool(MARKDOWN_SUPPORT);
1573 if (!markdownSupport || !yyextra->isSpecialComment)
1574 {
1575 REJECT;
1576 }
1577 else
1578 {
1579 yyextra->fenceChar='`';
1580 yyextra->fenceSize=(int)getFenceSize(yytext,yyleng);
1581 BEGIN(SkipCondVerbatim);
1582 }
1583 }
1584<SkipCComment>^({B}*"*"+)?{B}{0,3}"~~~"[~]* {
1585 bool markdownSupport = Config_getBool(MARKDOWN_SUPPORT);
1586 if (!markdownSupport || !yyextra->isSpecialComment)
1587 {
1588 REJECT;
1589 }
1590 else
1591 {
1592 outputArray(yyscanner,yytext,yyleng);
1593 yyextra->fenceChar='~';
1594 yyextra->fenceSize=(int)getFenceSize(yytext,yyleng);
1595 BEGIN(SkipVerbatim);
1596 }
1597 }
1598<SkipCComment>^({B}*"*"+)?{B}{0,3}"```"[`]* {
1599 bool markdownSupport = Config_getBool(MARKDOWN_SUPPORT);
1600 if (!markdownSupport || !yyextra->isSpecialComment)
1601 {
1602 REJECT;
1603 }
1604 else
1605 {
1606 outputArray(yyscanner,yytext,yyleng);
1607 yyextra->fenceChar='`';
1608 yyextra->fenceSize=(int)getFenceSize(yytext,yyleng);
1609 BEGIN(SkipVerbatim);
1610 }
1611 }
1612<SkipCComment>{CMD}{VERBATIM_LINE} |
1613<SkipCComment>{CMD}{LITERAL_BLOCK} { // escaped command
1614 outputArray(yyscanner,yytext,yyleng);
1615 yyextra->yyLineNr+=DString(yytext).contains('\n');
1616 }
1617<SkipCComment>{VERBATIM_LINE}.*/\n { // normal command
1618 outputArray(yyscanner,yytext,yyleng);
1619 }
1620<SkipCComment>{LITERAL_BLOCK} { // normal block command
1621 outputArray(yyscanner,yytext,yyleng);
1622 yyextra->yyLineNr+=DString(yytext).contains('\n');
1623 if (yyextra->isSpecialComment)
1624 {
1625 determineBlockName(yyscanner);
1626 BEGIN(SkipVerbatim);
1627 }
1628 }
1629<SkipCond>{CMD}{CMD}"cond"[ \t]+ {}// escaped cond command
1630<SkipCond>{CMD}"cond"/\n |
1631<SkipCond>{CMD}"cond"[ \t]+ { // cond command in a skipped cond section, this section has to be skipped as well
1632 // but has to be recorded to match the endcond command
1633 startCondSection(yyscanner," ");
1634 }
1635<SkipCComment>"{"[ \t]*"@code"/[ \t\n] {
1636 outputArray(yyscanner,"@iliteral{code}",15);
1637 yyextra->javaBlock=1;
1638 BEGIN(JavaDocVerbatimCode);
1639 }
1640<SkipCComment>"{"[ \t]*"@literal"/[ \t\n] {
1641 outputArray(yyscanner,"@iliteral",9);
1642 yyextra->javaBlock=1;
1643 BEGIN(JavaDocVerbatimCode);
1644 }
1645<SkipCComment,SkipCPPComment>{CMD}{CMD}"cond"[ \t\n]+ { // escaped cond command
1646 outputArray(yyscanner,yytext,yyleng);
1647 }
1648<SkipCPPComment>{CMD}"cond"[ \t]+ { // conditional section
1649 yyextra->ccomment=true;
1650 yyextra->condCtx=YY_START;
1651 BEGIN(CondLineCpp);
1652 }
1653<SkipCComment>{CMD}"cond"[ \t]+ { // conditional section
1654 yyextra->ccomment=false;
1655 yyextra->condCtx=YY_START;
1656 BEGIN(CondLineC);
1657 }
1658<CondLineC,CondLineCpp>([!()&| \ta-z_A-Z0-9\x80-\xFF.\-]|{CMD}"doxyconfig")+ {
1659 startCondSection(yyscanner,yytext);
1660 if (yyextra->skip)
1661 {
1662 if (YY_START==CondLineC)
1663 {
1664 // end C comment
1665 outputArray(yyscanner,"*/",2);
1666 yyextra->ccomment=true;
1667 }
1668 else
1669 {
1670 yyextra->ccomment=false;
1671 }
1672 BEGIN(SkipCond);
1673 }
1674 else
1675 {
1676 BEGIN(yyextra->condCtx);
1677 }
1678 }
1679CondLine>{B}*{CMD}doxyconfig{B}+{DOXYCFG} {
1680 startCondSection(yyscanner,yytext);
1681 }
1682<CondLineC,CondLineCpp>. { // non-guard character
1683 unput(*yytext);
1684 startCondSection(yyscanner," ");
1685 if (yyextra->skip)
1686 {
1687 if (YY_START==CondLineC)
1688 {
1689 // end C comment
1690 outputArray(yyscanner,"*/",2);
1691 yyextra->ccomment=true;
1692 }
1693 else
1694 {
1695 yyextra->ccomment=false;
1696 }
1697 BEGIN(SkipCond);
1698 }
1699 else
1700 {
1701 BEGIN(yyextra->condCtx);
1702 }
1703 }
1704<SkipCComment,SkipCPPComment>{CMD}"cond"{WSopt}/\n { // no guard
1705 if (YY_START==SkipCComment)
1706 {
1707 yyextra->ccomment=true;
1708 // end C comment
1709 outputArray(yyscanner,"*/",2);
1710 }
1711 else
1712 {
1713 yyextra->ccomment=false;
1714 }
1715 yyextra->condCtx=YY_START;
1716 yyextra->condGuardCount=0;
1717 startCondSection(yyscanner," ");
1718 BEGIN(SkipCond);
1719 }
1720<SkipCond>\n { yyextra->yyLineNr++; outputChar(yyscanner,'\n'); }
1721<SkipCond>{VERBATIM_LINE}.*/\n { }
1722<SkipCond>{LITERAL_BLOCK} {
1723 auto numNLs = DString(yytext).contains('\n');
1724 yyextra->yyLineNr+=numNLs;
1725 for (int i = 0; i < numNLs; i++) outputChar(yyscanner,'\n');
1726 determineBlockName(yyscanner);
1727 BEGIN(SkipCondVerbatim);
1728 }
1729
1730<SkipCond>. { }
1731<SkipCond>"#if"("def")? { yyextra->condGuardCount++; }
1732<SkipCond>"#endif" { yyextra->condGuardCount--; }
1733<SkipCond>[^\/\!*\\@\n#]+ { }
1734<SkipCond>{CPPC}[/!] { yyextra->ccomment=false; }
1735<SkipCond>{CCS}[*!] { yyextra->ccomment=true; }
1736<SkipCond,SkipCComment,SkipCPPComment>{CMD}{CMD}"endcond"/[^a-z_A-Z0-9\x80-\xFF] {
1737 if (!yyextra->skip)
1738 {
1739 outputArray(yyscanner,yytext,yyleng);
1740 }
1741 }
1742<SkipCond>{CMD}"endcond"/[^a-z_A-Z0-9\x80-\xFF] {
1743 bool oldSkip = yyextra->skip;
1744 endCondSection(yyscanner);
1745 if (oldSkip && !yyextra->skip)
1746 {
1747 if (yyextra->ccomment)
1748 {
1749 outputArray(yyscanner,"/** ",4); // */
1750 }
1751 BEGIN(yyextra->condCtx);
1752 }
1753 }
1754<SkipCComment,SkipCPPComment>{CMD}"endcond"/[^a-z_A-Z0-9\x80-\xFF] {
1755 bool oldSkip = yyextra->skip;
1756 endCondSection(yyscanner);
1757 if (oldSkip && !yyextra->skip)
1758 {
1759 BEGIN(yyextra->condCtx);
1760 }
1761 }
1762<SkipCondVerbatim>{LITERAL_BLOCK_END} { /* end of verbatim block */
1763 if (yytext[1]=='f' && yyextra->blockName==&yytext[2])
1764 {
1765 BEGIN(SkipCond);
1766 }
1767 else if (&yytext[4]==yyextra->blockName)
1768 {
1769 BEGIN(SkipCond);
1770 }
1771 }
1772<SkipVerbatim>{LITERAL_BLOCK_END} { /* end of verbatim block */
1773 outputArray(yyscanner,yytext,yyleng);
1774 if (yytext[1]=='f' && yyextra->blockName==&yytext[2])
1775 {
1776 BEGIN(SkipCComment);
1777 }
1778 else if (&yytext[4]==yyextra->blockName)
1779 {
1780 BEGIN(SkipCComment);
1781 }
1782 }
1783<SkipCondVerbatim>^({B}*"*"+)?{B}{0,3}"~~~"[~]* {
1784 if (yyextra->fenceSize==getFenceSize(yytext,yyleng) && yyextra->fenceChar=='~')
1785 {
1786 BEGIN(SkipCond);
1787 }
1788 }
1789<SkipCondVerbatim>^({B}*"*"+)?{B}{0,3}"```"[`]* {
1790 if (yyextra->fenceSize==getFenceSize(yytext,yyleng) && yyextra->fenceChar=='`')
1791 {
1792 BEGIN(SkipCond);
1793 }
1794 }
1795<SkipVerbatim>^({B}*"*"+)?{B}{0,3}"~~~"[~]* {
1796 outputArray(yyscanner,yytext,yyleng);
1797 if (yyextra->fenceSize==getFenceSize(yytext,yyleng) && yyextra->fenceChar=='~')
1798 {
1799 BEGIN(SkipCComment);
1800 }
1801 }
1802<SkipVerbatim>^({B}*"*"+)?{B}{0,3}"```"[`]* {
1803 outputArray(yyscanner,yytext,yyleng);
1804 if (yyextra->fenceSize==getFenceSize(yytext,yyleng) && yyextra->fenceChar=='`')
1805 {
1806 BEGIN(SkipCComment);
1807 }
1808 }
1809<SkipCondVerbatim>{CCE}|{CCS} { }
1810<SkipVerbatim>{CCE}|{CCS} {
1811 outputArray(yyscanner,yytext,yyleng);
1812 }
1813<JavaDocVerbatimCode>"{" {
1814 if (yyextra->javaBlock==0)
1815 {
1816 REJECT;
1817 }
1818 else
1819 {
1820 yyextra->javaBlock++;
1821 outputArray(yyscanner,yytext,(int)yyleng);
1822 }
1823 }
1824<JavaDocVerbatimCode>"}" {
1825 if (yyextra->javaBlock==0)
1826 {
1827 REJECT;
1828 }
1829 else
1830 {
1831 yyextra->javaBlock--;
1832 if (yyextra->javaBlock==0)
1833 {
1834 outputArray(yyscanner," @endiliteral ",14);
1835 BEGIN(SkipCComment);
1836 }
1837 else
1838 {
1839 outputArray(yyscanner,yytext,(int)yyleng);
1840 }
1841 }
1842 }
1843<JavaDocVerbatimCode>\n { /* new line in verbatim block */
1844 outputArray(yyscanner,yytext,(int)yyleng);
1845 }
1846<JavaDocVerbatimCode>. { /* any other character */
1847 outputArray(yyscanner,yytext,(int)yyleng);
1848 }
1849<SkipCondVerbatim>[^{*\\@\x06~`\n\/]+ { }
1850<SkipCComment,SkipVerbatim>[^{*\\@\x06~`\n\/]+ {
1851 outputArray(yyscanner,yytext,yyleng);
1852 }
1853<SkipCComment,SkipVerbatim,SkipCondVerbatim>\n {
1854 yyextra->yyLineNr++;
1855 outputChar(yyscanner,'\n');
1856 }
1857<SkipCondVerbatim>. { }
1858<SkipCComment,SkipVerbatim>. {
1859 outputChar(yyscanner,*yytext);
1860 }
1861<CopyCComment>[^*a-z_A-Z\x80-\xFF\n]*[^*a-z_A-Z\x80-\xFF\\\n] {
1862 yyextra->defLitText+=yytext;
1863 yyextra->defText+=escapeAt(yytext);
1864 }
1865<CopyCComment>\\‍[\r]?\n {
1866 yyextra->defLitText+=yytext;
1867 yyextra->defText+=" ";
1868 yyextra->yyLineNr++;
1869 yyextra->yyMLines++;
1870 }
1871<CopyCComment>{CCE} {
1872 yyextra->defLitText+=yytext;
1873 yyextra->defText+=yytext;
1874 BEGIN(yyextra->lastCContext);
1875 }
1876<CopyCComment>\n {
1877 yyextra->yyLineNr++;
1878 yyextra->defLitText+=yytext;
1879 yyextra->defText+=' ';
1880 }
1881<RemoveCComment>{CCE}{B}*"#" { // see bug 594021 for a usecase for this rule
1882 if (yyextra->lastCContext==SkipCPPBlock)
1883 {
1884 BEGIN(SkipCommand);
1885 }
1886 else
1887 {
1888 REJECT;
1889 }
1890 }
1891<RemoveCComment>{CCE} { BEGIN(yyextra->lastCContext); }
1892<RemoveCComment>{CPPC}
1893<RemoveCComment>{CCS}
1894<RemoveCComment>[^*\x06\n]+
1895<RemoveCComment>\n { yyextra->yyLineNr++; outputChar(yyscanner,'\n'); }
1896<RemoveCComment>.
1897<SkipCPPComment>[^\n\/\\@]+ {
1898 outputArray(yyscanner,yytext,yyleng);
1899 }
1900<SkipCPPComment,RemoveCPPComment>\n {
1901 unput(*yytext);
1902 BEGIN(yyextra->lastCPPContext);
1903 }
1904<SkipCPPComment>{CCS} {
1905 outputChar(yyscanner,'/');outputChar(yyscanner,'*');
1906 }
1907<SkipCPPComment>{CPPC} {
1908 outputChar(yyscanner,'/');outputChar(yyscanner,'/');
1909 }
1910<SkipCPPComment>[^\x06\@\\\n]+ {
1911 outputArray(yyscanner,yytext,yyleng);
1912 }
1913<SkipCPPComment>. {
1914 outputChar(yyscanner,*yytext);
1915 }
1916<RemoveCPPComment>{CCS}
1917<RemoveCPPComment>{CPPC}
1918<RemoveCPPComment>[^\x06\n]+
1919<RemoveCPPComment>.
1920<DefineText>"__VA_OPT__("{B}*"##" {
1921 warn(yyextra->fileName,yyextra->yyLineNr,
1922 "'##' may not appear at the beginning of a __VA_OPT__()",
1923 yyextra->defName,yyextra->defLitText.stripWhiteSpace());
1924 yyextra->defText+="__VA_OPT__(";
1925 yyextra->defLitText+="__VA_OPT__(";
1926 }
#define warn(file, line, fmt,...)
Definition message.h:97
1927<DefineText>"#"/"__VA_OPT__" {
1928 yyextra->defText+=yytext;
1929 yyextra->defLitText+=yytext;
1930 }
1931<DefineText>"#"/{IDSTART} {
1932 outputChar(yyscanner,' ');
1933 yyextra->quoteArg=true;
1934 yyextra->idStart=true;
1935 yyextra->defLitText+=yytext;
1936 }
1937<DefineText,CopyCComment>{ID} {
1938 yyextra->defLitText+=yytext;
1939 if (YY_START == DefineText) outputSpaces(yyscanner,yytext);
1940 if (yyextra->quoteArg)
1941 {
1942 yyextra->defText+="\"";
1943 }
1944 if (yyextra->defArgs>0)
1945 {
1946 auto it = yyextra->argMap.find(yytext);
1947 if (it!=yyextra->argMap.end())
1948 {
1949 int n = it->second;
1950 yyextra->defText+='@';
1951 yyextra->defText+=DString().setNum(n);
1952 }
1953 else
1954 {
1955 if (yyextra->idStart)
1956 {
1957 warn(yyextra->fileName,yyextra->yyLineNr,
1958 "'#' is not followed by a macro parameter '{}': '{}'",
1959 yyextra->defName,yyextra->defLitText.stripWhiteSpace());
1960 }
1961 yyextra->defText+=yytext;
1962 }
1963 }
1964 else
1965 {
1966 yyextra->defText+=yytext;
1967 }
1968 if (yyextra->quoteArg)
1969 {
1970 yyextra->defText+="\"";
1971 }
1972 yyextra->quoteArg=false;
1973 yyextra->idStart=false;
1974 }
DString & setNum(short n)
Definition dstring.h:552
1975<CopyCComment>. {
1976 yyextra->defLitText+=yytext;
1977 yyextra->defText+=yytext;
1978 }
1979<DefineText>\\‍[\r]?\n {
1980 yyextra->defLitText+=yytext;
1981 outputChar(yyscanner,'\\');
1982 outputChar(yyscanner,'\n');
1983 yyextra->defText += ' ';
1984 yyextra->yyLineNr++;
1985 yyextra->yyMLines++;
1986 }
1987<DefineText>\n {
1988 DString comment=extractTrailingComment(yyextra->defLitText);
1989 yyextra->defText = yyextra->defText.stripWhiteSpace();
1990 if (yyextra->defText.startsWith("##"))
1991 {
1992 warn(yyextra->fileName,yyextra->yyLineNr,
1993 "'##' cannot occur at the beginning of a macro definition '{}': '{}'",
1994 yyextra->defName,yyextra->defLitText.stripWhiteSpace());
1995 }
1996 else if (yyextra->defText.endsWith("##"))
1997 {
1998 warn(yyextra->fileName,yyextra->yyLineNr,
1999 "'##' cannot occur at the end of a macro definition '{}': '{}'",
2000 yyextra->defName,yyextra->defLitText.stripWhiteSpace());
2001 }
2002 else if (yyextra->defText.endsWith("#"))
2003 {
2004 warn(yyextra->fileName,yyextra->yyLineNr,
2005 "expected formal parameter after # in macro definition '{}': '{}'",
2006 yyextra->defName,yyextra->defLitText.stripWhiteSpace());
2007 }
2008 if (!comment.empty())
2009 {
2010 outputString(yyscanner,comment);
2011 yyextra->defLitText=yyextra->defLitText.left(yyextra->defLitText.length()-comment.length()-1);
2012 }
2013 outputChar(yyscanner,'\n');
2014 yyextra->defLitText+=yytext;
2015 Define *def=nullptr;
2016 //printf("Define name='%s' text='%s' litTexti='%s'\n",qPrint(yyextra->defName),qPrint(yyextra->defText),qPrint(yyextra->defLitText));
2017 if (yyextra->includeStack.empty() || yyextra->curlyCount>0)
2018 {
2019 addMacroDefinition(yyscanner);
2020 }
2021 def=isDefined(yyscanner,yyextra->defName);
2022 if (def==0) // new define
2023 {
2024 //printf("new define '%s'!\n",qPrint(yyextra->defName));
2025 addDefine(yyscanner);
2026 }
2027 else if (def /*&& macroIsAccessible(def)*/)
2028 // name already exists
2029 {
2030 //printf("existing define!\n");
2031 //printf("define found\n");
2032 if (def->undef) // undefined name
2033 {
2034 def->undef = false;
2035 def->name = yyextra->defName;
2036 def->definition = yyextra->defText.stripWhiteSpace();
2037 def->nargs = yyextra->defArgs;
2038 def->fileName = yyextra->fileName;
2039 def->lineNr = yyextra->yyLineNr-yyextra->yyMLines;
2040 def->columnNr = yyextra->yyColNr;
2041 }
2042 else
2043 {
2044 if (def->fileName != yyextra->fileName && !yyextra->expandOnlyPredef) addDefine(yyscanner);
2045 //printf("error: define %s is defined more than once!\n",qPrint(yyextra->defName));
2046 }
2047 }
2048 yyextra->argMap.clear();
2049 yyextra->yyLineNr++;
2050 yyextra->yyColNr=1;
2051 yyextra->lastGuardName.clear();
2052 BEGIN(Start);
2053 }
bool empty() const
Returns true iff the string is empty (std::string compatible alias for isEmpty()).
Definition dstring.h:148
int lineNr
Definition define.h:38
DString name
Definition define.h:33
DString fileName
Definition define.h:35
size_t columnNr
Definition define.h:39
2054<DefineText>{B}* { outputString(yyscanner,yytext);
2055 yyextra->defText += ' ';
2056 yyextra->defLitText+=yytext;
2057 }
2058<DefineText>{B}*"##"{B}* { outputString(yyscanner,substitute(yytext,"##"," "));
2059 yyextra->defText += "##";
2060 yyextra->defLitText+=yytext;
2061 }
2062<DefineText>"@" { outputString(yyscanner,substitute(yytext,"@@"," "));
2063 yyextra->defText += "@@";
2064 yyextra->defLitText+=yytext;
2065 }
2066<DefineText>\" {
2067 outputChar(yyscanner,' ');
2068 yyextra->defText += *yytext;
2069 yyextra->defLitText+=yytext;
2070 if (!yyextra->insideComment)
2071 {
2072 BEGIN(SkipDoubleQuote);
2073 }
2074 }
2075<DefineText>{NUMBER} {
2076 outputSpaces(yyscanner,yytext);
2077 yyextra->defText += yytext;
2078 yyextra->defLitText+=yytext;
2079 }
2080<DefineText>\' {
2081 outputChar(yyscanner,' ');
2082 yyextra->defText += *yytext;
2083 yyextra->defLitText+=yytext;
2084 if (!yyextra->insideComment)
2085 {
2086 BEGIN(SkipSingleQuote);
2087 }
2088 }
2089<SkipDoubleQuote>{CPPC}[/]? { outputSpaces(yyscanner,yytext);
2090 yyextra->defText += yytext;
2091 yyextra->defLitText+=yytext;
2092 }
2093<SkipDoubleQuote>{CCS}[*]? { outputSpaces(yyscanner,yytext);
2094 yyextra->defText += yytext;
2095 yyextra->defLitText+=yytext;
2096 }
2097<SkipDoubleQuote>\" {
2098 outputChar(yyscanner,' ');
2099 yyextra->defText += *yytext;
2100 yyextra->defLitText+=yytext;
2101 BEGIN(DefineText);
2102 }
2103<SkipSingleQuote,SkipDoubleQuote>\\. {
2104 outputSpaces(yyscanner,yytext);
2105 yyextra->defText += yytext;
2106 yyextra->defLitText+=yytext;
2107 }
2108<SkipSingleQuote>\' {
2109 outputChar(yyscanner,' ');
2110 yyextra->defText += *yytext;
2111 yyextra->defLitText+=yytext;
2112 BEGIN(DefineText);
2113 }
2114<SkipDoubleQuote,SkipSingleQuote>. { outputSpace(yyscanner,yytext[0]);
2115 yyextra->defText += *yytext;
2116 yyextra->defLitText += *yytext;
2117 }
2118<DefineText>. { outputSpace(yyscanner,yytext[0]);
2119 yyextra->defText += *yytext;
2120 yyextra->defLitText += *yytext;
2121 }
2122<<EOF>> {
2123 TRACE("End of include file");
2124 //printf("Include stack depth=%d\n",yyextra->includeStack.size());
2125 if (yyextra->includeStack.empty())
2126 {
2127 TRACE("Terminating scanner");
2128 yyterminate();
2129 }
2130 else
2131 {
2132 if (!yyextra->levelGuard.empty())
2133 {
2134 if (yyextra->condGuardErrorLine!=0)
2135 {
2136 warn(yyextra->condGuardErrorFileName,yyextra->condGuardErrorLine,"{}",yyextra->condGuardErrorMessage);
2137 }
2138 else
2139 {
2140 warn(yyextra->fileName,yyextra->yyLineNr,"More #endif's than #if's found.");
2141 }
2142 }
2143 DString toFileName = yyextra->fileName;
2144 const std::unique_ptr<FileState> &fs=yyextra->includeStack.back();
2145 //fileDefineCache->merge(yyextra->fileName,fs->fileName);
2146 YY_BUFFER_STATE oldBuf = YY_CURRENT_BUFFER;
2147 yy_switch_to_buffer( fs->bufState, yyscanner );
2148 yy_delete_buffer( oldBuf, yyscanner );
2149 yyextra->yyLineNr = fs->lineNr;
2150 //preYYin = fs->oldYYin;
2151 yyextra->inputBuf = fs->oldFileBuf;
2152 yyextra->inputBufPos = fs->oldFileBufPos;
2153 yyextra->curlyCount = fs->curlyCount;
2154 yyextra->levelGuard = fs->levelGuard;
2155 setFileName(yyscanner,fs->fileName);
2156 TRACE("switching to {}",yyextra->fileName);
2157
2158 // Deal with file changes due to
2159 // #include's within { .. } blocks
2160 DString lineStr(15+yyextra->fileName.length(), DString::ExplicitSize);
2161 lineStr.sprintf("# %d \"%s\" 2",yyextra->yyLineNr,qPrint(yyextra->fileName));
2162 outputString(yyscanner,lineStr);
2163
2164 yyextra->includeStack.pop_back();
2165
2166 {
2167 std::lock_guard<std::mutex> lock(g_globalDefineMutex);
2168 // to avoid deadlocks we allow multiple threads to process the same header file.
2169 // The first one to finish will store the results globally. After that the
2170 // next time the same file is encountered, the stored data is used and the file
2171 // is not processed again.
2172 if (!g_defineManager.alreadyProcessed(toFileName.str()))
2173 {
2174 // now that the file is completely processed, prevent it from processing it again
2175 g_defineManager.addInclude(yyextra->fileName.str(),toFileName.str());
2176 g_defineManager.store(toFileName.str(),yyextra->localDefines);
2177 }
2178 else
2179 {
2181 {
2182 Debug::print(Debug::Preprocessor,0,"#include {}: was already processed by another thread! not storing data...\n",toFileName);
2183 }
2184 }
2185 }
2186 // move the local macros definitions for in this file to the translation unit context
2187 for (const auto &kv : yyextra->localDefines)
2188 {
2189 auto pair = yyextra->contextDefines.insert(kv);
2190 if (!pair.second) // define already in context -> replace with local version
2191 {
2192 yyextra->contextDefines.erase(pair.first);
2193 yyextra->contextDefines.insert(kv);
2194 }
2195 }
2196 yyextra->localDefines.clear();
2197 }
2198 }
char & back()
Returns a reference to the last character.
Definition dstring.h:199
@ ExplicitSize
Definition dstring.h:131
const std::string & str() const
Definition dstring.h:645
@ Preprocessor
Definition debug.h:31
static bool isFlagSet(const DebugMask mask)
Definition debug.cpp:132
static void print(DebugMask mask, int prio, fmt::format_string< Args... > fmt, Args &&... args)
Definition debug.h:78
#define yyterminate()
const char * qPrint(const char *s)
Definition dstring.h:783
#define TRACE(...)
Definition trace.h:77
2199<*>{CCS}/{CCE} |
2200<*>{CCS}[*!]? {
2201 if (YY_START==SkipVerbatim || YY_START == SkipCondVerbatim || YY_START==SkipCond || YY_START==IDLquote || YY_START == PragmaOnce)
2202 {
2203 REJECT;
2204 }
2205 else
2206 {
2207 outputArray(yyscanner,yytext,yyleng);
2208 yyextra->lastCContext=YY_START;
2209 yyextra->commentCount=1;
2210 if (yyleng==3)
2211 {
2212 yyextra->isSpecialComment = true;
2213 yyextra->lastGuardName.clear(); // reset guard in case the #define is documented!
2214 }
2215 else
2216 {
2217 yyextra->isSpecialComment = false;
2218 }
2219 BEGIN(SkipCComment);
2220 }
2221 }
2222<*>{CPPC}[/!]? {
2223 if (YY_START==SkipVerbatim || YY_START == SkipCondVerbatim || YY_START==SkipCond || getLanguageFromFileName(yyextra->fileName)==SrcLangExt::Fortran || YY_START==IDLquote || YY_START == PragmaOnce)
2224 {
2225 REJECT;
2226 }
2227 else if (YY_START==RulesRoundDouble)
2228 {
2229 REJECT;
2230 }
2231 else
2232 {
2233 outputArray(yyscanner,yytext,yyleng);
2234 yyextra->lastCPPContext=YY_START;
2235 if (yyleng==3)
2236 {
2237 yyextra->isSpecialComment = true;
2238 yyextra->lastGuardName.clear(); // reset guard in case the #define is documented!
2239 }
2240 else
2241 {
2242 yyextra->isSpecialComment = false;
2243 }
2244 BEGIN(SkipCPPComment);
2245 }
2246 }
2247<*>\n {
2248 outputChar(yyscanner,'\n');
2249 yyextra->yyLineNr++;
2250 }
2251<*>. {
2252 yyextra->expectGuard = false;
2253 outputChar(yyscanner,*yytext);
2254 }
2255
2256%%
2257
2258/////////////////////////////////////////////////////////////////////////////////////
2259
2260static int yyread(yyscan_t yyscanner,char *buf,int max_size)
2261{
2262 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
2263 int bytesInBuf = static_cast<int>(state->inputBuf->size())-state->inputBufPos;
2264 int bytesToCopy = std::min(max_size,bytesInBuf);
2265 memcpy(buf,state->inputBuf->data()+state->inputBufPos,bytesToCopy);
2266 state->inputBufPos+=bytesToCopy;
2267 return bytesToCopy;
2268}
2269
2270static yy_size_t getFenceSize(char *txt, yy_size_t leng)
2271{
2272 yy_size_t fenceSize = 0;
2273 for (size_t i = 0; i < leng; i++)
2274 {
2275 if (txt[i] != ' ' && txt[i] != '*' && txt[i] != '\t') break;
2276 fenceSize++;
2277 }
2278 return leng-fenceSize;
2279}
2280
2281static void setFileName(yyscan_t yyscanner,const DString &name)
2282{
2283 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
2284 bool ambig = false;
2285 FileInfo fi(name.str());
2286 state->fileName=fi.absFilePath();
2287 state->yyFileDef=Doxygen::inputNameLinkedMap->findFileDef(state->fileName,ambig);
2288 if (state->yyFileDef==nullptr) // if this is not an input file check if it is an include file
2289 {
2290 state->yyFileDef=Doxygen::includeNameLinkedMap->findFileDef(state->fileName,ambig);
2291 }
2292 //printf("setFileName(%s) state->fileName=%s state->yyFileDef=%p\n",
2293 // name,qPrint(state->fileName),state->yyFileDef);
2294 if (state->yyFileDef && state->yyFileDef->isReference()) state->yyFileDef=nullptr;
2295 state->insideIDL = getLanguageFromFileName(state->fileName)==SrcLangExt::IDL;
2296 state->insideCS = getLanguageFromFileName(state->fileName)==SrcLangExt::CSharp;
2297 state->insideFtn = getLanguageFromFileName(state->fileName)==SrcLangExt::Fortran;
2298 state->isFixedFormFtn = false;
2299 if (state->insideFtn)
2300 {
2302 state->isFixedFormFtn = recognizeFixedForm(DString(state->inputBuf->data()),fmt);
2303 }
2304 EntryType section = EntryType::guessSection(state->fileName);
2305 state->isSource = section.isHeader() || section.isSource();
2306}
2307
2308static void incrLevel(yyscan_t yyscanner)
2309{
2310 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
2311 state->levelGuard.push(false);
2312 //printf("%s line %d: incrLevel %zu\n",qPrint(state->fileName),state->yyLineNr,state->levelGuard.size());
2313}
2314
2315static void decrLevel(yyscan_t yyscanner)
2316{
2317 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
2318 //printf("%s line %d: decrLevel %zu\n",qPrint(state->fileName),state->yyLineNr,state->levelGuard.size());
2319 if (!state->levelGuard.empty())
2320 {
2321 state->levelGuard.pop();
2322 }
2323 else
2324 {
2325 if (state->condGuardErrorLine!=0)
2326 {
2327 warn(state->condGuardErrorFileName,state->condGuardErrorLine,"{}",state->condGuardErrorMessage);
2328 }
2329 else
2330 {
2331 warn(state->fileName,state->yyLineNr,"More #endif's than #if's found.");
2332 }
2333 }
2334}
2335
2336static bool otherCaseDone(yyscan_t yyscanner)
2337{
2338 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
2339 if (state->levelGuard.empty())
2340 {
2341 warn(state->fileName,state->yyLineNr,"Found an #else without a preceding #if.");
2342 return true;
2343 }
2344 else
2345 {
2346 return state->levelGuard.top();
2347 }
2348}
2349
2350static void setCaseDone(yyscan_t yyscanner,bool value)
2351{
2352 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
2353 state->levelGuard.top()=value;
2354}
2355
2356
2357static std::unique_ptr<FileState> checkAndOpenFile(yyscan_t yyscanner,const DString &fileName,bool &alreadyProcessed)
2358{
2359 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
2360 alreadyProcessed = false;
2361 std::unique_ptr<FileState> fs;
2362 //printf("checkAndOpenFile(%s)\n",qPrint(fileName));
2363 FileInfo fi(fileName.str());
2364 if (fi.exists() && fi.isFile())
2365 {
2366 StringVector exclPatterns = Config_getList(EXCLUDE_PATTERNS);
2367 if (fi.match(exclPatterns,useCaseSenseNames())) return nullptr;
2368
2369 DString absName = fi.absFilePath();
2370
2371 // global guard
2372 if (state->curlyCount==0) // not #include inside { ... }
2373 {
2374 std::lock_guard<std::mutex> lock(g_globalDefineMutex);
2375 if (g_defineManager.alreadyProcessed(absName.str()))
2376 {
2377 alreadyProcessed = true;
2378 //printf(" already included 1\n");
2379 return 0; // already done
2380 }
2381 }
2382 // check include stack for absName
2383
2384 alreadyProcessed = std::any_of(
2385 state->includeStack.begin(),
2386 state->includeStack.end(),
2387 [absName](const std::unique_ptr<FileState> &lfs)
2388 { return lfs->fileName==absName; }
2389 );
2390
2391 if (alreadyProcessed)
2392 {
2393 //printf(" already included 2\n");
2394 return nullptr;
2395 }
2396 //printf("#include %s\n",qPrint(absName));
2397
2398 fs = std::make_unique<FileState>();
2399 if (!readInputFile(absName,fs->fileBuf))
2400 { // error
2401 //printf(" error reading\n");
2402 fs.reset();
2403 }
2404 else
2405 {
2406 addTerminalCharIfMissing(fs->fileBuf,'\n');
2407 fs->oldFileBuf = state->inputBuf;
2408 fs->oldFileBufPos = state->inputBufPos;
2409 }
2410 }
2411 return fs;
2412}
2413
2414static std::unique_ptr<FileState> findFile(yyscan_t yyscanner, const DString &fileName,bool localInclude,bool &alreadyProcessed)
2415{
2416 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
2417 //printf("** findFile(%s,%d) state->fileName=%s\n",qPrint(fileName),localInclude,qPrint(state->fileName));
2418 if (Portable::isAbsolutePath(fileName))
2419 {
2420 auto fs = checkAndOpenFile(yyscanner,fileName,alreadyProcessed);
2421 if (fs)
2422 {
2423 setFileName(yyscanner,fileName);
2424 state->yyLineNr=1;
2425 return fs;
2426 }
2427 else if (alreadyProcessed)
2428 {
2429 return nullptr;
2430 }
2431 }
2432 if (localInclude && !state->fileName.empty())
2433 {
2434 FileInfo fi(state->fileName.str());
2435 if (fi.exists())
2436 {
2437 DString absName = DString(fi.dirPath(true))+"/"+fileName;
2438 auto fs = checkAndOpenFile(yyscanner,absName,alreadyProcessed);
2439 if (fs)
2440 {
2441 setFileName(yyscanner,absName);
2442 state->yyLineNr=1;
2443 return fs;
2444 }
2445 else if (alreadyProcessed)
2446 {
2447 return nullptr;
2448 }
2449 }
2450 }
2451 if (state->pathList.empty())
2452 {
2453 return nullptr;
2454 }
2455 for (auto path : state->pathList)
2456 {
2457 DString absName = path+"/"+fileName;
2458 //printf(" Looking for %s in %s\n",fileName,qPrint(path));
2459 auto fs = checkAndOpenFile(yyscanner,absName,alreadyProcessed);
2460 if (fs)
2461 {
2462 setFileName(yyscanner,absName);
2463 state->yyLineNr=1;
2464 //printf(" -> found it\n");
2465 return fs;
2466 }
2467 else if (alreadyProcessed)
2468 {
2469 return nullptr;
2470 }
2471 }
2472 bool ambig = false;
2473 FileDef *fd=Doxygen::inputNameLinkedMap->findFileDef(fileName,ambig);
2474 if (fd && !ambig) // fallback in case the file is uniquely named in the input, use that one
2475 {
2476 auto fs = checkAndOpenFile(yyscanner,fd->absFilePath(),alreadyProcessed);
2477 if (fs)
2478 {
2479 setFileName(yyscanner,fd->absFilePath());
2480 state->yyLineNr=1;
2481 //printf(" -> found it\n");
2482 return fs;
2483 }
2484 }
2485 return nullptr;
2486}
2487
2489{
2490 if (s.empty()) return "";
2491 int i=(int)s.length()-1;
2492 while (i>=0)
2493 {
2494 char c=s[i];
2495 switch (c)
2496 {
2497 case '/':
2498 {
2499 i--;
2500 if (i>=0 && s[i]=='*') // end of a comment block
2501 {
2502 i--;
2503 while (i>0 && !(s[i-1]=='/' && s[i]=='*')) i--;
2504 if (i==0)
2505 {
2506 i++;
2507 }
2508 // only /*!< ... */ or /**< ... */ are treated as a comment for the macro name,
2509 // otherwise the comment is treated as part of the macro definition
2510 return ((s[i+1]=='*' || s[i+1]=='!') && s[i+2]=='<') ? &s[i-1] : "";
2511 }
2512 else
2513 {
2514 return "";
2515 }
2516 }
2517 break;
2518 // whitespace or line-continuation
2519 case ' ':
2520 case '\t':
2521 case '\r':
2522 case '\n':
2523 case '\\':
2524 break;
2525 default:
2526 return "";
2527 }
2528 i--;
2529 }
2530 return "";
2531}
2532
2533static int getNextChar(yyscan_t yyscanner,const DString &expr,DString *rest,uint32_t &pos);
2534static int getCurrentChar(yyscan_t yyscanner,const DString &expr,DString *rest,uint32_t pos);
2535static void unputChar(yyscan_t yyscanner,const DString &expr,DString *rest,uint32_t &pos,char c);
2536static bool expandExpression(yyscan_t yyscanner,DString &expr,DString *rest,int pos,int level);
2537static DString removeMarkers(const DString &s);
2538
2539static void expandArgument(yyscan_t yyscanner,DString &arg,int level)
2540{
2541 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
2542 // Argument prescan cannot consume tokens from the enclosing input stream.
2543 bool previous = state->boundedExpansion;
2544 state->boundedExpansion = true;
2545 expandExpression(yyscanner,arg,nullptr,0,level);
2546 state->boundedExpansion = previous;
2547}
2548
2549static DString stringize(const DString &s)
2550{
2551 DString result;
2552 uint32_t i=0;
2553 bool inString=false;
2554 bool inChar=false;
2555 char c,pc;
2556 while (i<s.length())
2557 {
2558 if (!inString && !inChar)
2559 {
2560 while (i<s.length() && !inString && !inChar)
2561 {
2562 c=s.at(i++);
2563 if (c=='"')
2564 {
2565 result+="\\\"";
2566 inString=true;
2567 }
2568 else if (c=='\'')
2569 {
2570 result+=c;
2571 inChar=true;
2572 }
2573 else
2574 {
2575 result+=c;
2576 }
2577 }
2578 }
2579 else if (inChar)
2580 {
2581 while (i<s.length() && inChar)
2582 {
2583 c=s.at(i++);
2584 if (c=='\'')
2585 {
2586 result+='\'';
2587 inChar=false;
2588 }
2589 else if (c=='\\')
2590 {
2591 result+="\\\\";
2592 }
2593 else
2594 {
2595 result+=c;
2596 }
2597 }
2598 }
2599 else
2600 {
2601 pc=0;
2602 while (i<s.length() && inString)
2603 {
2604 c=s.at(i++);
2605 if (c=='"')
2606 {
2607 result+="\\\"";
2608 inString= pc=='\\';
2609 }
2610 else if (c=='\\')
2611 result+="\\\\";
2612 else
2613 result+=c;
2614 pc=c;
2615 }
2616 }
2617 }
2618 //printf("stringize '%s'->'%s'\n",qPrint(s),qPrint(result));
2619 return result;
2620}
2621
2622/*! Execute all ## operators in expr.
2623 * If the macro name before or after the operator contains a no-rescan
2624 * marker (@-) then this is removed (before the concatenated macro name
2625 * may be expanded again.
2626 */
2628{
2629 if (expr.empty()) return;
2630 //printf("processConcatOperators: in='%s'\n",qPrint(expr));
2631 std::string e = expr.str();
2632 static const reg::Ex r(R"(\s*##\s*)");
2634
2635 size_t i=0;
2636 for (;;)
2637 {
2638 reg::Iterator it(e,r,i);
2639 if (it!=end)
2640 {
2641 const auto &match = *it;
2642 size_t n = match.position();
2643 size_t l = match.length();
2644 //printf("Match: '%s'\n",qPrint(expr.mid(i)));
2645 // A pasted placemarker disappears, but must not join neighboring tokens.
2646 bool leftEmpty = n>=2 && e.compare(n-2,2,"@E")==0 && (n<3 || e[n-3]!='@');
2647 bool rightEmpty = e.compare(n+l,2,"@E")==0;
2648 if (leftEmpty && rightEmpty)
2649 {
2650 e.erase(n,l+2);
2651 i=n-2;
2652 continue;
2653 }
2654 if (leftEmpty)
2655 {
2656 if (e.compare(n+l,2,"@-")==0) e.erase(n+l,2);
2657 e.replace(n-2,l+2," ");
2658 i=n-1;
2659 continue;
2660 }
2661 if (rightEmpty)
2662 {
2663 int k=static_cast<int>(n)-1;
2664 while (k>=0 && isId(e[k])) k--;
2665 if (k>0 && e[k]=='-' && e[k-1]=='@')
2666 {
2667 e.erase(k-1,2);
2668 n-=2;
2669 }
2670 size_t next=e.find_first_not_of(" \t\r\n",n+l+2);
2671 if (next!=std::string::npos && e.compare(next,2,"##")==0)
2672 {
2673 // Keep the remaining paste operator for chains such as a##empty##b.
2674 e.erase(n,l+2);
2675 i=n;
2676 }
2677 else
2678 {
2679 e.replace(n,l+2," ");
2680 i=n+1;
2681 }
2682 continue;
2683 }
2684 if (n+l+1<e.length() && e[static_cast<int>(n+l)]=='@' && expr[static_cast<int>(n+l+1)]=='-')
2685 {
2686 // remove no-rescan marker after ID
2687 l+=2;
2688 }
2689 //printf("found '%s'\n",qPrint(expr.mid(n,l)));
2690 // remove the ## operator and the surrounding whitespace
2691 e=e.substr(0,n)+e.substr(n+l);
2692 int k=static_cast<int>(n)-1;
2693 while (k>=0 && isId(e[k])) k--;
2694 if (k>0 && e[k]=='-' && e[k-1]=='@')
2695 {
2696 // remove no-rescan marker before ID
2697 e=e.substr(0,k-1)+e.substr(k+1);
2698 n-=2;
2699 }
2700 i=n;
2701 }
2702 else
2703 {
2704 break;
2705 }
2706 }
2707
2708 expr = e;
2709
2710 //printf("processConcatOperators: out='%s'\n",qPrint(expr));
2711}
2712
2713static void returnCharToStream(yyscan_t yyscanner,char c)
2714{
2715 struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
2716 unput(c);
2717}
2718
2719static inline void addTillEndOfString(yyscan_t yyscanner,const DString &expr,DString *rest,
2720 uint32_t &pos,char term,DString &arg)
2721{
2722 int cc;
2723 while ((cc=getNextChar(yyscanner,expr,rest,pos))!=EOF && cc!=0)
2724 {
2725 if (cc=='\\')
2726 {
2727 arg+=(char)cc;
2728 cc=getNextChar(yyscanner,expr,rest,pos);
2729 }
2730 else if (cc==term)
2731 {
2732 return;
2733 }
2734 arg+=(char)cc;
2735 }
2736}
2737
2738static inline void addTillEndOfComment(yyscan_t yyscanner,const DString &expr,DString *rest,
2739 uint32_t &pos,char term,DString &arg)
2740{
2741 int cc;
2742 while ((cc=getNextChar(yyscanner,expr,rest,pos))!=EOF && cc!=0)
2743 {
2744 if (cc=='*' && getCurrentChar(yyscanner,expr,rest,pos)=='/')
2745 {
2746 arg+=(char)cc;
2747 cc = getNextChar(yyscanner,expr,rest,pos);
2748 return;
2749 }
2750 arg+=(char)cc;
2751 }
2752}
2753
2754static void skipCommentMacroName(yyscan_t yyscanner, const DString &expr, DString *rest,
2755 int &cc, uint32_t &j, int &len)
2756{
2757 bool changed = false;
2758
2759 do
2760 {
2761 changed = false;
2762 while ((cc=getCurrentChar(yyscanner,expr,rest,j))!=EOF && cc!='\n' && isspace(cc))
2763 {
2764 len++;
2765 getNextChar(yyscanner,expr,rest,j);
2766 }
2767
2768 if (cc=='/') // possible start of a comment
2769 {
2770 int prevChar = '\0';
2771 getNextChar(yyscanner,expr,rest,j);
2772 if ((cc=getCurrentChar(yyscanner,expr,rest,j))!=EOF && cc == '*') // we have a comment
2773 {
2774 while ((cc=getNextChar(yyscanner,expr,rest,j))!=EOF && cc!=0)
2775 {
2776 if (cc == '/' && prevChar == '*') break; // we have an end of comment
2777 prevChar = cc;
2778 }
2779 if (cc != EOF) changed = true;
2780 }
2781 }
2782 } while (changed);
2783}
2784
2785static bool isFunctionMacroCall(yyscan_t yyscanner,const DString &expr,DString *rest,int pos)
2786{
2787 DString remaining=expr.mid(pos);
2788 if (rest) remaining+=*rest;
2789 uint32_t cursor=0;
2790 std::string readAhead;
2791 auto next = [&]() -> int
2792 {
2793 bool fromStream=cursor>=remaining.length() && !preYYget_extra(yyscanner)->boundedExpansion;
2794 int c=getNextChar(yyscanner,remaining,nullptr,cursor);
2795 if (fromStream && c!=EOF && c!=0) readAhead+=static_cast<char>(c);
2796 return c;
2797 };
2798 int c=next();
2799 for (;;)
2800 {
2801 while (c!=EOF && c!=0 && c!='\n' && isspace(static_cast<unsigned char>(c))) c=next();
2802 if (c!='/') break;
2803 c=next();
2804 if (c!='*') break;
2805 int previous=0;
2806 while ((c=next())!=EOF && c!=0 && !(previous=='*' && c=='/')) previous=c;
2807 if (c==EOF || c==0) break;
2808 c=next();
2809 }
2810 // Lookahead must not consume characters from the enclosing scanner.
2811 for (auto it=readAhead.rbegin();it!=readAhead.rend();++it) returnCharToStream(yyscanner,*it);
2812 return c=='(';
2813}
2814
2815// Expand C++20's __VA_OPT__(x) to either x if hasOptionalArgs==true or to the empty string if false
2816static DString expandVAOpt(const DString &vaStr,bool hasOptionalArgs)
2817{
2818 //printf("expandVAOpt(vaStr=%s,hasOptionalArgs=%d)\n",qPrint(vaStr),hasOptionalArgs);
2819 DString result;
2820 size_t vo=0, vp=0;
2821 result.clear();
2822 size_t vl = vaStr.length();
2823 while ((vo = vaStr.find("__VA_OPT__(",vp))!=DString::npos)
2824 {
2825 bool hasHash = vo>0 && vaStr.at(vo-1)=='#';
2826 if (hasHash)
2827 {
2828 result+=vaStr.mid(vp,vo-vp-1); // don't copy #
2829 result+="\"";
2830 }
2831 else
2832 {
2833 result+=vaStr.mid(vp,vo-vp);
2834 }
2835 size_t ve=vo+11; // skip over '__VA_OPT__(' part
2836 int bc=1;
2837 while (bc>0 && ve<vl)
2838 {
2839 if (vaStr[ve]==')') bc--;
2840 else if (vaStr[ve]=='(') bc++;
2841 ve++;
2842 }
2843 // ve points to end of __VA_OPT__(....)
2844 if (bc==0 && hasOptionalArgs)
2845 {
2846 DString voStr = vaStr.mid(vo+11,ve-vo-12);
2847 //printf("vo=%d ve=%d voStr=%s\n",vo,ve,qPrint(voStr));
2848 result+=voStr; // take 'x' from __VA_OPT__(x)
2849 }
2850 if (hasHash)
2851 {
2852 result+="\"";
2853 }
2854 vp=ve;
2855 }
2856 result+=vaStr.mid(vp);
2857 //printf("vaStr='%s'\n -> '%s'\n",qPrint(vaStr),qPrint(result));
2858 return result;
2859}
2860
2861/*! replaces the function macro \a def whose argument list starts at
2862 * \a pos in expression \a expr.
2863 * Notice that this routine may scan beyond the \a expr string if needed.
2864 * In that case the characters will be read from the input file.
2865 * The replacement string will be returned in \a result and the
2866 * length of the (unexpanded) argument list is stored in \a len.
2867 */
2868static bool replaceFunctionMacro(yyscan_t yyscanner,const DString &expr,DString *rest,int pos,int &len,const Define *def,DString &result,int level)
2869{
2870 //printf(">replaceFunctionMacro(expr='%s',rest='%s',pos=%d,def='%s') level=%zu\n",qPrint(expr),rest ? qPrint(*rest) : 0,pos,qPrint(def->name),preYYget_extra(yyscanner)->levelGuard.size());
2871 uint32_t j=pos;
2872 len=0;
2873 result.clear();
2874 int cc;
2875
2876 skipCommentMacroName(yyscanner, expr, rest, cc, j, len);
2877
2878 if (cc!='(')
2879 {
2880 if (cc!=':') // don't add spaces for colons
2881 {
2882 unputChar(yyscanner,expr,rest,j,' ');
2883 }
2884 return false;
2885 }
2886 getNextChar(yyscanner,expr,rest,j); // eat the '(' character
2887
2888 struct MacroArgument
2889 {
2890 DString raw;
2891 DString expanded;
2892 };
2893 std::map<std::string,MacroArgument> argTable;
2894 DString arg;
2895 DString rawArg;
2896 // The variadic argument may contain an already-expanded prefix.
2897 size_t expandedPrefixLength=0;
2898 int argCount=0;
2899 int argCountNonEmpty=0;
2900 bool done=false;
2901
2902 // PHASE 1: read the macro arguments
2903 if (def->nargs==0)
2904 {
2905 while ((cc=getNextChar(yyscanner,expr,rest,j))!=EOF && cc!=0)
2906 {
2907 char c = (char)cc;
2908 if (c==')') break;
2909 }
2910 }
2911 else
2912 {
2913 while (!done && (argCount<def->nargs || def->varArgs) &&
2914 ((cc=getNextChar(yyscanner,expr,rest,j))!=EOF && cc!=0)
2915 )
2916 {
2917 char c=(char)cc;
2918 if (c=='(') // argument is a function => search for matching )
2919 {
2920 int lvl=1;
2921 arg+=c;
2922 //char term='\0';
2923 while ((cc=getNextChar(yyscanner,expr,rest,j))!=EOF && cc!=0)
2924 {
2925 c=(char)cc;
2926 //printf("processing %c: term=%c (%d)\n",c,term,term);
2927 if (c=='\'' || c=='\"') // skip ('s and )'s inside strings
2928 {
2929 arg+=c;
2930 addTillEndOfString(yyscanner,expr,rest,j,c,arg);
2931 }
2932 else if (c=='/')
2933 {
2934 int nxtChar = getCurrentChar(yyscanner,expr,rest,j);
2935 if (nxtChar == '*')
2936 {
2937 arg+=c;
2938 addTillEndOfComment(yyscanner,expr,rest,j,c,arg);
2939 }
2940 // We don't need to handle the // case as this has already been converted into a /* .. */ comment.
2941 }
2942
2943 if (c==')')
2944 {
2945 lvl--;
2946 arg+=c;
2947 if (lvl==0) break;
2948 }
2949 else if (c=='(')
2950 {
2951 lvl++;
2952 arg+=c;
2953 }
2954 else
2955 {
2956 arg+=c;
2957 }
2958 }
2959 }
2960 else if (c==')' || c==',') // last or next argument found
2961 {
2962 if (c==',' && argCount==def->nargs-1 && def->varArgs)
2963 {
2964 rawArg+=arg.mid(expandedPrefixLength);
2965 rawArg+=',';
2966 expandArgument(yyscanner,arg,level+1);
2967 arg=arg.stripWhiteSpace();
2968 arg+=',';
2969 expandedPrefixLength=arg.length();
2970 }
2971 else
2972 {
2973 rawArg+=arg.mid(expandedPrefixLength);
2974 rawArg=rawArg.stripWhiteSpace();
2975 DString expandedArg=arg;
2976 expandArgument(yyscanner,expandedArg,level+1);
2977 expandedArg=expandedArg.stripWhiteSpace();
2978 DString argKey;
2979 argKey.sprintf("@%d",argCount++); // key name
2980 if (c==',' || !expandedArg.empty()) argCountNonEmpty++;
2981 // add argument to the lookup table
2982 argTable.emplace(toStdString(argKey), MacroArgument{rawArg,expandedArg});
2983 arg.clear();
2984 rawArg.clear();
2985 expandedPrefixLength=0;
2986 if (c==')') // end of the argument list
2987 {
2988 done=true;
2989 }
2990 }
2991 }
2992 else if (c=='\"') // append literal strings
2993 {
2994 arg+=c;
2995 bool found=false;
2996 while (!found && (cc=getNextChar(yyscanner,expr,rest,j))!=EOF && cc!=0)
2997 {
2998 found = cc=='"';
2999 if (cc=='\\')
3000 {
3001 c=(char)cc;
3002 arg+=c;
3003 if ((cc=getNextChar(yyscanner,expr,rest,j))==EOF || cc==0) break;
3004 }
3005 c=(char)cc;
3006 arg+=c;
3007 }
3008 }
3009 else if (c=='\'') // append literal characters
3010 {
3011 arg+=c;
3012 bool found=false;
3013 while (!found && (cc=getNextChar(yyscanner,expr,rest,j))!=EOF && cc!=0)
3014 {
3015 found = cc=='\'';
3016 if (cc=='\\')
3017 {
3018 c=(char)cc;
3019 arg+=c;
3020 if ((cc=getNextChar(yyscanner,expr,rest,j))==EOF || cc==0) break;
3021 }
3022 c=(char)cc;
3023 arg+=c;
3024 }
3025 }
3026 else if (c=='/') // possible start of a comment
3027 {
3028 char prevChar = '\0';
3029 arg+=c;
3030 if ((cc=getCurrentChar(yyscanner,expr,rest,j)) == '*') // we have a comment
3031 {
3032 while ((cc=getNextChar(yyscanner,expr,rest,j))!=EOF && cc!=0)
3033 {
3034 c=(char)cc;
3035 arg+=c;
3036 if (c == '/' && prevChar == '*') break; // we have an end of comment
3037 prevChar = c;
3038 }
3039 }
3040 }
3041 else // append other characters
3042 {
3043 arg+=c;
3044 }
3045 }
3046 }
3047
3048 // PHASE 2: apply the macro function
3049 if (argCount==def->nargs || // same number of arguments
3050 (argCount>=def->nargs-1 && def->varArgs)) // variadic macro with at least as many
3051 // params as the non-variadic part (see bug731985)
3052 {
3053 size_t k=0;
3054 // substitution of all formal arguments
3055 DString resExpr;
3057 //printf("varArgs=%d argCount=%d def->nargs=%d d=%s\n",def->varArgs,argCount,def->nargs,qPrint(d));
3058 if (def->varArgs) d = expandVAOpt(d,argCountNonEmpty!=def->nargs-1);
3059 //printf("Macro definition: '%s'\n",qPrint(d));
3060 bool inString=false;
3061 while (k<d.length())
3062 {
3063 if (d.at(k)=='@') // maybe a marker, otherwise an escaped @
3064 {
3065 if (d.at(k+1)=='@') // escaped @ => copy it (is unescaped later)
3066 {
3067 k+=2;
3068 resExpr+="@@"; // we unescape these later
3069 }
3070 else if (d.at(k+1)=='-') // no-rescan marker
3071 {
3072 k+=2;
3073 resExpr+="@-";
3074 }
3075 else // argument marker => read the argument number
3076 {
3077 DString key="@";
3078 bool hash=false;
3079 int l=static_cast<int>(k)-1;
3080 // search for ## backward
3081 if (l>=0 && d.at(l)=='"') l--;
3082 while (l>=0 && d.at(l)==' ') l--;
3083 if (l>0 && d.at(l)=='#' && d.at(l-1)=='#') hash=true;
3084 k++;
3085 // scan the number
3086 while (k<d.length() && d.at(k)>='0' && d.at(k)<='9') key+=d.at(k++);
3087 if (!hash)
3088 {
3089 // search for ## forward
3090 l=static_cast<int>(k);
3091 if (l<(int)d.length() && d.at(l)=='"') l++;
3092 while (l<(int)d.length() && d.at(l)==' ') l++;
3093 if (l<(int)d.length()-1 && d.at(l)=='#' && d.at(l+1)=='#') hash=true;
3094 }
3095 //printf("request key %s result %s\n",qPrint(key),argTable[key]->data());
3096 auto it = argTable.find(key.str());
3097 if (it!=argTable.end())
3098 {
3099 DString substArg = hash || inString ? it->second.raw : it->second.expanded;
3100 //printf("substArg='%s'\n",qPrint(substArg));
3101 // Stringified and pasted arguments are substituted without prescan.
3102 if (!hash && !inString)
3103 {
3104 expandArgument(yyscanner,substArg,level+1);
3105 }
3106 if (inString)
3107 {
3108 //printf("'%s'=stringize('%s')\n",qPrint(stringize(*subst)),subst->data());
3109
3110 // if the marker is inside a string (because a # was put
3111 // before the macro name) we must escape " and \ characters
3112 resExpr+=stringize(removeMarkers(substArg));
3113 }
3114 else
3115 {
3116 if (hash && substArg.empty())
3117 {
3118 resExpr+="@E"; // placemarker for an empty argument next to ##
3119 }
3120 resExpr+=substArg;
3121 }
3122 }
3123 }
3124 }
3125 else // no marker, just copy
3126 {
3127 if (!inString && d.at(k)=='\"')
3128 {
3129 inString=true; // entering a literal string
3130 }
3131 else if (k>2 && inString && d.at(k)=='\"' && (d.at(k-1)!='\\' || d.at(k-2)=='\\'))
3132 {
3133 inString=false; // leaving a literal string
3134 }
3135 resExpr+=d.at(k++);
3136 }
3137 }
3138 len=j-pos;
3139 result=resExpr;
3140 //printf("<replaceFunctionMacro(expr='%s',rest='%s',pos=%d,def='%s',result='%s') level=%zu return=true\n",qPrint(expr),rest ? qPrint(*rest) : 0,pos,qPrint(def->name),qPrint(result),preYYget_extra(yyscanner)->levelGuard.size());
3141 return true;
3142 }
3143 //printf("<replaceFunctionMacro(expr='%s',rest='%s',pos=%d,def='%s',result='%s') level=%zu return=false\n",qPrint(expr),rest ? qPrint(*rest) : 0,pos,qPrint(def->name),qPrint(result),preYYget_extra(yyscanner)->levelGuard.size());
3144 return false;
3145}
3146
3147
3148/*! returns the next identifier in string \a expr by starting at position \a p.
3149 * The position of the identifier is returned (or -1 if nothing is found)
3150 * and \a l is its length. Any quoted strings are skipping during the search.
3151 */
3152static int getNextId(const DString &expr,int p,int *l)
3153{
3154 int n;
3155 while (p<(int)expr.length())
3156 {
3157 char c=expr.at(p++);
3158 if (isdigit(c)) // skip number
3159 {
3160 while (p<(int)expr.length() && isId(expr.at(p))) p++;
3161 }
3162 else if (isalpha(c) || c=='_') // read id
3163 {
3164 n=p-1;
3165 while (p<(int)expr.length() && isId(expr.at(p))) p++;
3166 *l=p-n;
3167 return n;
3168 }
3169 else if (c=='"') // skip string
3170 {
3171 char ppc=0,pc=c;
3172 if (p<(int)expr.length()) c=expr.at(p);
3173 while (p<(int)expr.length() && (c!='"' || (pc=='\\' && ppc!='\\')))
3174 // continue as long as no " is found, but ignoring \", but not \\"
3175 {
3176 ppc=pc;
3177 pc=c;
3178 c=expr.at(p);
3179 p++;
3180 }
3181 if (p<(int)expr.length()) ++p; // skip closing quote
3182 }
3183 else if (c=='/') // skip C Comment
3184 {
3185 //printf("Found C comment at p=%d\n",p);
3186 char pc=c;
3187 if (p<(int)expr.length())
3188 {
3189 c=expr.at(p);
3190 if (c=='*') // Start of C comment
3191 {
3192 p++;
3193 while (p<(int)expr.length() && !(pc=='*' && c=='/'))
3194 {
3195 pc=c;
3196 c=expr.at(p++);
3197 }
3198 }
3199 }
3200 //printf("Found end of C comment at p=%d\n",p);
3201 }
3202 }
3203 return -1;
3204}
3205
3206#define MAX_EXPANSION_DEPTH 50
3207
3208static void addSeparatorsIfNeeded(yyscan_t yyscanner,const DString &expr,DString &resultExpr,DString &restExpr,int pos)
3209{
3210 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
3211 if (!state->nospaces)
3212 {
3213 // peek back in the stream, for a colon character
3214 char ccPrev = pos==0 || (int)expr.length()<pos ? state->prevChar : expr.at(pos-1);
3215 DString leftSpace = ccPrev!=':' && ccPrev!=' ' ? " " : "";
3216 int ccNext = 0;
3217 restExpr=restExpr.stripWhiteSpace();
3218 if (restExpr.empty()) // peek ahead in the stream for non-whitespace
3219 {
3220 uint32_t j=(uint32_t)resultExpr.length();
3221 while ((ccNext=getNextChar(yyscanner,resultExpr,nullptr,j))!=EOF && ccNext==' ') { }
3222 if (ccNext != EOF) unputChar(yyscanner,resultExpr,nullptr,j,(char)ccNext);
3223 }
3224 else // take first char from remainder
3225 {
3226 ccNext=restExpr.at(0);
3227 }
3228 // don't add whitespace before a colon
3229 DString rightSpace = ccNext!=':' && ccNext!=' ' ? " " : "";
3230 //printf("ccPrev='%c' ccNext='%c' p=%d expr=%zu restExpr='%s' left='%s' right='%s'\n",
3231 // ccPrev,ccNext,pos,expr.length(),qPrint(restExpr),qPrint(leftSpace),qPrint(rightSpace));
3232 resultExpr=leftSpace+resultExpr+rightSpace;
3233 }
3234}
3235
3236/*! performs recursive macro expansion on the string \a expr
3237 * starting at position \a pos.
3238 * May read additional characters from the input while re-scanning!
3239 */
3240static bool expandExpression(yyscan_t yyscanner,DString &expr,DString *rest,int pos,int level)
3241{
3242 struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
3243 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
3244 //printf(">expandExpression(expr='%s',rest='%s',pos=%d,level=%d)\n",qPrint(expr),rest ? qPrint(*rest) : "", pos, level);
3245 if (expr.empty())
3246 {
3247 //printf("<expandExpression: empty\n");
3248 return true;
3249 }
3250 if (state->expanded.find(expr.str())!=state->expanded.end() &&
3251 level>MAX_EXPANSION_DEPTH) // check for too deep recursive expansions
3252 {
3253 //printf("<expandExpression: already expanded expr='%s'\n",qPrint(expr));
3254 return false;
3255 }
3256 else
3257 {
3258 state->expanded.insert(expr.str());
3259 }
3260 DString macroName;
3261 DString expMacro;
3262 bool definedTest=false;
3263 int i=pos, l=0, p=0, len=0;
3264 int startPos = pos;
3265 int samePosCount=0;
3266 while ((p=getNextId(expr,i,&l))!=-1) // search for an macro name
3267 {
3268 bool replaced=false;
3269 DString resultExpr;
3270 macroName=expr.mid(p,l);
3271 //printf(" p=%d macroName=%s\n",p,qPrint(macroName));
3272 if (!(resultExpr = expandStandardMacro(yyscanner,macroName)).empty())
3273 {
3274 DString restExpr=expr.mid(p+8);
3275 expr=expr.left(p)+resultExpr+restExpr;
3276 }
3277 else if (p<2 || !(expr.at(p-2)=='@' && expr.at(p-1)=='-')) // no-rescan marker?
3278 {
3279 if (state->expandedDict.find(macroName.str())==state->expandedDict.end()) // expand macro
3280 {
3281 bool expanded=false;
3282 Define *def=isDefined(yyscanner,macroName);
3283 // In case EXPAND_ONLY_PREDEF is enabled prevent expansion unless the macro was explicitly
3284 // predefined
3285 if (yyextra->expandOnlyPredef && def && !def->isPredefined) def=nullptr;
3286 if (macroName=="defined")
3287 {
3288 //printf("found defined inside macro definition '%s'\n",qPrint(expr.mid(p)));
3289 definedTest=true;
3290 }
3291 else if (definedTest) // macro name was found after defined
3292 {
3293 if (def) expMacro = " 1 "; else expMacro = " 0 ";
3294 replaced=true;
3295 len=l;
3296 definedTest=false;
3297 }
3298 else if (def && def->nargs==-1) // simple macro
3299 {
3300 // substitute the definition of the macro
3301 expMacro=def->definition.stripWhiteSpace();
3302 //expMacro=def->definition.stripWhiteSpace();
3303 replaced=true;
3304 len=l;
3305 //printf("simple macro expansion='%s'->'%s'\n",qPrint(macroName),qPrint(expMacro));
3306 }
3307 else if (def && def->nargs>=0) // function macro
3308 {
3309 //printf(" >>>> call replaceFunctionMacro expr='%s'\n",qPrint(expr));
3310 replaced=replaceFunctionMacro(yyscanner,expr,rest,p+l,len,def,expMacro,level);
3311 //printf(" <<<< call replaceFunctionMacro: replaced=%d\n",replaced);
3312 len+=l;
3313 }
3314
3315 if (replaced) // expand the macro and rescan the expression
3316 {
3317 //printf(" replacing '%s'->'%s'\n",qPrint(expr.mid(p,len)),qPrint(expMacro));
3318 resultExpr=expMacro;
3319 DString restExpr=expr.mid(p+len);
3320 addSeparatorsIfNeeded(yyscanner,expr,resultExpr,restExpr,p);
3321 processConcatOperators(resultExpr);
3322 //printf(" macroName=%s restExpr='%s' def->nonRecursive=%d\n",qPrint(macroName),qPrint(restExpr),def ? def->nonRecursive : false);
3323 if (def && !def->nonRecursive)
3324 {
3325 state->expandedDict.emplace(toStdString(macroName),def);
3326 expanded = expandExpression(yyscanner,resultExpr,&restExpr,0,level+1);
3327 state->expandedDict.erase(toStdString(macroName));
3328 }
3329 else if (def && def->nonRecursive)
3330 {
3331 expanded = true;
3332 }
3333 if (expanded)
3334 {
3335 //printf("expanded '%s' + '%s' + '%s'\n",qPrint(expr.left(p)),qPrint(resultExpr),qPrint(restExpr));
3336 expr=expr.left(p)+resultExpr+restExpr;
3337 // The replacement has already been rescanned; continue with the remaining input.
3338 i=p+static_cast<int>(resultExpr.length());
3339 }
3340 else
3341 {
3342 //printf("not expanded '%s' + @- '%s'\n",qPrint(expr.left(p)),qPrint(expr.mid(p)));
3343 expr=expr.left(p)+"@-"+expr.mid(p);
3344 i=p+l+2;
3345 }
3346 }
3347 else // move to the next macro name
3348 {
3349 //printf(" moving to the next macro old i=%d new i=%d\n",i,p+l);
3350 i=p+l;
3351 }
3352 }
3353 else // move to the next macro name
3354 {
3355 const Define *def=state->expandedDict.find(macroName.str())->second;
3356 // A function-like macro without an opening parenthesis is not an invocation.
3357 if (def->nargs>=0 && !isFunctionMacroCall(yyscanner,expr,rest,p+l))
3358 {
3359 i=p+l;
3360 }
3361 else
3362 {
3363 expr=expr.left(p)+"@-"+expr.mid(p);
3364 i=p+l+2;
3365 }
3366 }
3367 // check for too many inplace expansions without making progress
3368 if (i==startPos)
3369 {
3370 samePosCount++;
3371 }
3372 else
3373 {
3374 startPos=i;
3375 samePosCount=0;
3376 }
3377 if (samePosCount>MAX_EXPANSION_DEPTH)
3378 {
3379 break;
3380 }
3381 }
3382 else // no re-scan marker found, skip the macro name
3383 {
3384 //printf("skipping marked macro\n");
3385 i=p+l;
3386 }
3387 }
3388 //printf("<expandExpression(expr='%s',rest='%s',pos=%d,level=%d)\n",qPrint(expr),rest ? qPrint(*rest) : "", pos,level);
3389 return true;
3390}
3391
3392/*! @brief Process string or character literal.
3393 *
3394 * \a inputStr should point to the start of a string or character literal.
3395 * the routine will return a pointer to just after the end of the literal
3396 * the character making up the literal will be added to \a result.
3397 */
3398static const char *processUntilMatchingTerminator(const char *inputStr,DString &result)
3399{
3400 if (inputStr==nullptr) return inputStr;
3401 char term = *inputStr; // capture start character of the literal
3402 if (term!='\'' && term!='"') return inputStr; // not a valid literal
3403 char c=term;
3404 // output start character
3405 result+=c;
3406 inputStr++;
3407 while ((c=*inputStr)) // while inside the literal
3408 {
3409 if (c==term) // found end marker of the literal
3410 {
3411 // output end character and stop
3412 result+=c;
3413 inputStr++;
3414 break;
3415 }
3416 else if (c=='\\') // escaped character, process next character
3417 // as well without checking for end marker.
3418 {
3419 result+=c;
3420 inputStr++;
3421 c=*inputStr;
3422 if (c==0) break; // unexpected end of string after escape character
3423 }
3424 result+=c;
3425 inputStr++;
3426 }
3427 return inputStr;
3428}
3429
3430/*! replaces all occurrences of @@@@ in \a s by @@
3431 * and replaces empty-argument markers with spaces.
3432 * All identifiers found are replaced by 0L
3433 */
3435{
3436 static const std::vector<std::string> signs = { "signed", "unsigned" };
3437 struct TypeInfo { std::string name; size_t size; };
3438 static const std::vector<TypeInfo> types = {
3439 { "short int", sizeof(short int) },
3440 { "long long int", sizeof(long long int) },
3441 { "long int", sizeof(long int) },
3442 { "long long", sizeof(long long) },
3443 { "long double", sizeof(long double) },
3444 { "int", sizeof(int) },
3445 { "short", sizeof(short) },
3446 { "bool", sizeof(bool) },
3447 { "long", sizeof(long) },
3448 { "char", sizeof(char) },
3449 { "float", sizeof(float) },
3450 { "double", sizeof(double) },
3451 };
3452
3453 // Check if string p starts with basic types ending with a ')', such as 'signed long)' or ' float )'
3454 // and return the pointer just past the ')' and the size of the type as a tuple.
3455 // If the pattern is not found the tuple (nullptr,0) is returned.
3456 auto process_cast_or_sizeof = [](const char *p) -> std::pair<const char *,size_t>
3457 {
3458 const char *q = p;
3459 while (*q==' ' || *q=='\t') q++;
3460 bool found=false;
3461 size_t size = sizeof(int); // '(signed)' or '(unsigned)' is an int type
3462 for (const auto &sgn : signs)
3463 {
3464 if (dstrncmp(q,sgn.c_str(),sgn.length())==0) { q+=sgn.length(); found=true; }
3465 }
3466 if (!found || *q==' ' || *q=='\t' || *q==')') // continue searching
3467 {
3468 while (*q==' ' || *q=='\t') q++;
3469 for (const auto &t : types)
3470 {
3471 if (dstrncmp(q,t.name.c_str(),t.name.length())==0)
3472 {
3473 q += t.name.length();
3474 size = t.size;
3475 break;
3476 }
3477 }
3478 while (*q==' ' || *q=='\t') q++;
3479 if (*q==')') return std::make_pair(++q,size);
3480 }
3481 return std::make_pair(nullptr,0);
3482 };
3483
3484 //printf("removeIdsAndMarkers(%s)\n",qPrint(s));
3485 if (s.empty()) return s;
3486 const char *p=s.data();
3487 bool inNum=false;
3488 DString result;
3489 if (p)
3490 {
3491 char c = 0;
3492 while ((c=*p))
3493 {
3494 if (c=='(') // potential cast, ignore it
3495 {
3496 const char *q = process_cast_or_sizeof(p+1).first;
3497 //printf("potential cast:\nin: %s\nout: %s\n",p,q);
3498 if (q)
3499 {
3500 p=q;
3501 continue;
3502 }
3503 }
3504 else if (c=='s' && literal_at(p,"sizeof")) // sizeof(...)
3505 {
3506 const char *q = p+6;
3507 while (*q==' ' || *q=='\t') q++;
3508 if (*q=='(')
3509 {
3510 auto r = process_cast_or_sizeof(q+1);
3511 //printf("sizeof:\nin: %s\nout: %zu%s\n--> sizeof=%zu\n",p,r.second,r.first,r.second);
3512 if (r.first)
3513 {
3514 result+=DString().setNum(r.second);
3515 p=r.first;
3516 continue;
3517 }
3518 }
3519 }
3520
3521 if (c=='@') // replace @@ with @ and remove @E
3522 {
3523 if (*(p+1)=='@')
3524 {
3525 result+=c;
3526 }
3527 else if (*(p+1)=='E')
3528 {
3529 result+=' ';
3530 }
3531 p+=2;
3532 }
3533 else if (isdigit(c)) // number
3534 {
3535 result+=c;
3536 p++;
3537 inNum=true;
3538 }
3539 else if (c=='\'') // quoted character
3540 {
3541 p = processUntilMatchingTerminator(p,result);
3542 }
3543 else if (c=='d' && !inNum) // identifier starting with a 'd'
3544 {
3545 if (literal_at(p,"defined ") || literal_at(p,"defined("))
3546 // defined keyword
3547 {
3548 p+=7; // skip defined
3549 }
3550 else
3551 {
3552 result+="0L";
3553 p++;
3554 while ((c=*p) && isId(c)) p++;
3555 }
3556 }
3557 else if ((isalpha(c) || c=='_') && !inNum) // replace identifier with 0L
3558 {
3559 result+="0L";
3560 p++;
3561 while ((c=*p) && isId(c)) p++;
3562 while ((c=*p) && isspace((uint8_t)c)) p++;
3563 if (*p=='(') // undefined function macro
3564 {
3565 p++;
3566 int count=1;
3567 while ((c=*p++))
3568 {
3569 if (c=='(') count++;
3570 else if (c==')')
3571 {
3572 count--;
3573 if (count==0) break;
3574 }
3575 else if (c=='/')
3576 {
3577 char pc=c;
3578 c=*++p;
3579 if (c=='*') // start of C comment
3580 {
3581 while (*p && !(pc=='*' && c=='/')) // search end of comment
3582 {
3583 pc=c;
3584 c=*++p;
3585 }
3586 p++;
3587 }
3588 }
3589 }
3590 }
3591 }
3592 else if (c=='/') // skip C comments
3593 {
3594 char pc=c;
3595 c=*++p;
3596 if (c=='*') // start of C comment
3597 {
3598 while (*p && !(pc=='*' && c=='/')) // search end of comment
3599 {
3600 pc=c;
3601 c=*++p;
3602 }
3603 p++;
3604 }
3605 else // oops, not comment but division
3606 {
3607 result+=pc;
3608 goto nextChar;
3609 }
3610 }
3611 else
3612 {
3613nextChar:
3614 result+=c;
3615 char lc=(char)tolower(c);
3616 if (!isId(lc) && lc!='.' /*&& lc!='-' && lc!='+'*/) inNum=false;
3617 p++;
3618 }
3619 }
3620 }
3621 //printf("removeIdsAndMarkers(%s)=%s\n",s,qPrint(result));
3622 return result;
3623}
3624
3625/*! Replaces escaped @ characters and removes internal expansion markers. */
3627{
3628 if (s.empty()) return s;
3629 const char *p=s.data();
3630 DString result;
3631 if (p)
3632 {
3633 char c = 0;
3634 while ((c=*p))
3635 {
3636 switch(c)
3637 {
3638 case '@': // replace @@ with @
3639 {
3640 if (*(p+1)=='@')
3641 {
3642 result+=c;
3643 }
3644 else if (*(p+1)=='E')
3645 {
3646 result+=' ';
3647 }
3648 p+=2;
3649 }
3650 break;
3651 case '/': // skip C comments
3652 {
3653 result+=c;
3654 char pc=c;
3655 c=*++p;
3656 if (c=='*') // start of C comment
3657 {
3658 while (*p && !(pc=='*' && c=='/')) // search end of comment
3659 {
3660 if (*p=='@' && *(p+1)=='@')
3661 {
3662 result+=c;
3663 p++;
3664 }
3665 else
3666 {
3667 result+=c;
3668 }
3669 pc=c;
3670 c=*++p;
3671 }
3672 if (*p)
3673 {
3674 result+=c;
3675 p++;
3676 }
3677 }
3678 }
3679 break;
3680 case '"': // skip string literals
3681 case '\'': // skip char literals
3682 p = processUntilMatchingTerminator(p,result);
3683 break;
3684 default:
3685 {
3686 result+=c;
3687 p++;
3688 }
3689 break;
3690 }
3691 }
3692 }
3693 //printf("RemoveMarkers(%s)=%s\n",s,qPrint(result));
3694 return result;
3695}
3696
3697/*! compute the value of the expression in string \a expr.
3698 * If needed the function may read additional characters from the input.
3699 */
3700
3701static bool computeExpression(yyscan_t yyscanner,const DString &expr)
3702{
3703 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
3704 DString e=expr;
3705 DString ee=expr;
3706 ee = removeMarkers(ee);
3707 state->expanded.clear();
3708 expandExpression(yyscanner,e,nullptr,0,0);
3709 //printf("after expansion '%s'\n",qPrint(e));
3710 e = removeIdsAndMarkers(e);
3711 if (e.empty()) return false;
3712 //printf("parsing '%s'\n",qPrint(e));
3713 return state->constExpParser.parse(state->fileName.data(),state->yyLineNr,e.str(),ee.str());
3714}
3715
3716/*! expands the macro definition in \a name
3717 * If needed the function may read additional characters from the input
3718 */
3719
3720static DString expandMacro(yyscan_t yyscanner,const DString &name)
3721{
3722 struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
3723 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
3724 state->prevChar = yyscanner->yytext_r > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ? *(yyscanner->yytext_r-1) : 0;
3725 DString n=name;
3726 state->expanded.clear();
3727 expandExpression(yyscanner,n,nullptr,0,0);
3728 n=removeMarkers(n);
3729 state->prevChar=0;
3730 //printf("expandMacro '%s'->'%s'\n",qPrint(name),qPrint(n));
3731 return n;
3732}
3733
3734static DString expandStandardMacro(yyscan_t yyscanner,const DString &name)
3735{
3736 struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
3737 DString resultExpr;
3738 if (name == "__LINE__")
3739 {
3740 return DString().setNum(yyextra->yyLineNr);
3741 }
3742 else if (name == "__FILE__")
3743 {
3744 resultExpr = "\"";
3745 resultExpr += yyextra->fileName;
3746 resultExpr += "\"";
3747 }
3748 else if (name == "__DATE__")
3749 {
3750 resultExpr = "\"";
3751 resultExpr += __DATE__;
3752 resultExpr += "\"";
3753 }
3754 else if (name == "__TIME__")
3755 {
3756 resultExpr = "\"";
3757 resultExpr += __TIME__;
3758 resultExpr += "\"";
3759 }
3760 return resultExpr;
3761}
3762
3763static void addDefine(yyscan_t yyscanner)
3764{
3765 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
3766 Define def;
3767 def.name = state->defName;
3768 def.definition = state->defText.stripWhiteSpace();
3769 def.nargs = state->defArgs;
3770 def.fileName = state->fileName;
3771 def.fileDef = state->yyFileDef;
3772 def.lineNr = state->yyLineNr-state->yyMLines;
3773 def.columnNr = state->yyColNr;
3774 def.varArgs = state->defVarArgs;
3775 //printf("newDefine: %s %s file: %s\n",qPrint(def.name),qPrint(def.definition),
3776 // def.fileDef ? qPrint(def.fileDef->name()) : qPrint(def.fileName));
3777 //printf("newDefine: '%s'->'%s'\n",qPrint(def.name),qPrint(def.definition));
3778 if (!def.name.empty() &&
3780 {
3781 def.isPredefined=true;
3782 def.expandAsDefined=true;
3783 }
3784 auto it = state->localDefines.find(def.name.str());
3785 if (it!=state->localDefines.end()) // redefine
3786 {
3787 state->localDefines.erase(it);
3788 }
3789 state->localDefines.emplace(def.name.str(),def);
3790}
3791
3792static void addMacroDefinition(yyscan_t yyscanner)
3793{
3794 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
3795 if (state->skip) return; // do not add this define as it is inside a
3796 // conditional section (cond command) that is disabled.
3797
3798 Define define;
3799 define.fileName = state->fileName;
3800 define.lineNr = state->yyLineNr - state->yyMLines;
3801 define.columnNr = state->yyColNr;
3802 define.name = state->defName;
3803 define.args = state->defArgsStr;
3804 define.fileDef = state->inputFileDef;
3805
3806 DString litText = state->defLitText;
3807 size_t l=litText.find('\n');
3808 if (l!=DString::npos && l>0 && litText.left(l).stripWhiteSpace()=="\\")
3809 {
3810 // strip first line if it only contains a slash
3811 litText = litText.mid(l+1);
3812 }
3813 else if (l!=DString::npos && l>0)
3814 {
3815 // align the items on the first line with the items on the second line
3816 size_t k=l+1;
3817 const char *p=litText.data()+k;
3818 char c = 0;
3819 while ((c=*p++) && (c==' ' || c=='\t')) k++;
3820 litText=litText.mid(l+1,k-l-1)+litText.stripWhiteSpace();
3821 }
3822 DString litTextStripped = state->defLitText.stripWhiteSpace();
3823 if (litTextStripped.contains('\n')>=1)
3824 {
3825 define.definition = litText;
3826 }
3827 else
3828 {
3829 define.definition = litTextStripped;
3830 }
3831 {
3832 state->macroDefinitions.push_back(define);
3833 }
3834}
3835
3836static inline void outputChar(yyscan_t yyscanner,char c)
3837{
3838 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
3839 if (state->includeStack.empty() || state->curlyCount>0) (*state->outputBuf)+=c;
3840}
3841
3842static inline void outputArray(yyscan_t yyscanner,const char *a,yy_size_t len)
3843{
3844 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
3845 if (state->includeStack.empty() || state->curlyCount>0) (*state->outputBuf)+=std::string_view(a,len);
3846}
3847
3848static inline void outputString(yyscan_t yyscanner,const DString &a)
3849{
3850 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
3851 if (state->includeStack.empty() || state->curlyCount>0) (*state->outputBuf)+=a.str();
3852}
3853
3854static inline void outputSpace(yyscan_t yyscanner,char c)
3855{
3856 if (c=='\t') outputChar(yyscanner,'\t');
3857 else outputChar(yyscanner,' ');
3858}
3859
3860static inline void outputSpaces(yyscan_t yyscanner,char *s)
3861{
3862 const char *p=s;
3863 char c = 0;
3864 while ((c=*p++))
3865 {
3866 if (c=='\t') outputChar(yyscanner,'\t');
3867 else outputChar(yyscanner,' ');
3868 }
3869}
3870
3871static inline void extraSpacing(yyscan_t yyscanner)
3872{
3873 struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
3874 if (!yyextra->defContinue) return;
3875 for (int i=0; i< (int)yyleng; i++)
3876 {
3877 if (yytext[i] == '\t')
3878 yyextra->defExtraSpacing+='\t';
3879 else
3880 yyextra->defExtraSpacing+=' ';
3881 }
3882}
3883
3884static void determineBlockName(yyscan_t yyscanner)
3885{
3886 struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
3887 yyextra->fenceSize=0;
3888 char c=0;
3889 if (yytext[1]=='f' && ((c=yytext[2])=='[' || c=='{' || c=='(' || c=='$'))
3890 {
3891 switch (c)
3892 {
3893 case '[': yyextra->blockName="]"; break;
3894 case '{': yyextra->blockName="}"; break;
3895 case '(': yyextra->blockName=")"; break;
3896 case '$': yyextra->blockName="$"; break;
3897 default: break;
3898 }
3899 yyextra->blockName=yyextra->blockName.stripWhiteSpace();
3900 }
3901 else
3902 {
3903 DString bn=DString(&yytext[1]).stripWhiteSpace();
3904 if (bn=="startuml")
3905 {
3906 yyextra->blockName="uml";
3907 }
3908 else
3909 {
3910 if (size_t i = bn.find('{'); // for \code{.c}
3911 i!=DString::npos) bn=bn.left(i).stripWhiteSpace();
3912 yyextra->blockName=bn;
3913 }
3914 }
3915}
3916
3917static void readIncludeFile(yyscan_t yyscanner,const DString &inc)
3918{
3919 AUTO_TRACE("inc={}",inc);
3920 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
3921 uint32_t i=0;
3922
3923 // find the start of the include file name
3924 while (i<inc.length() &&
3925 (inc.at(i)==' ' || inc.at(i)=='"' || inc.at(i)=='<')
3926 ) i++;
3927 uint32_t s=i;
3928
3929 // was it a local include?
3930 bool localInclude = s>0 && inc.at(s-1)=='"';
3931
3932 // find the end of the include file name
3933 while (i<inc.length() && inc.at(i)!='"' && inc.at(i)!='>') i++;
3934
3935 if (s<inc.length() && i>s) // valid include file name found
3936 {
3937 // extract include path+name
3938 DString incFileName=inc.mid(s,i-s).stripWhiteSpace();
3939 if (incFileName.endsWith(".exe") || incFileName.endsWith(".dll") || incFileName.endsWith(".tlb"))
3940 {
3941 // skip imported binary files (e.g. M$ type libraries)
3942 return;
3943 }
3944
3945 DString oldFileName = state->fileName;
3946 FileDef *oldFileDef = state->yyFileDef;
3947 int oldLineNr = state->yyLineNr;
3948 //printf("Searching for '%s'\n",qPrint(incFileName));
3949
3950 DString absIncFileName = determineAbsoluteIncludeName(state->fileName,incFileName);
3951
3952 // findFile will overwrite state->yyFileDef if found
3953 std::unique_ptr<FileState> fs;
3954 bool alreadyProcessed = false;
3955 //printf("calling findFile(%s)\n",qPrint(incFileName));
3956 fs=findFile(yyscanner,absIncFileName,localInclude,alreadyProcessed); // see if the absolute include file can be found
3957 if (fs)
3958 {
3959 {
3960 std::lock_guard<std::mutex> lock(g_globalDefineMutex);
3961 g_defineManager.addInclude(oldFileName.str(),absIncFileName.str());
3962 }
3963
3964 //printf("Found include file!\n");
3966 {
3967 for (i=0;i<state->includeStack.size();i++)
3968 {
3970 }
3971 Debug::print(Debug::Preprocessor,0,"#include {}: parsing...\n",incFileName);
3972 }
3973
3974 if (state->includeStack.empty() && oldFileDef)
3975 {
3976 PreIncludeInfo *ii = state->includeRelations.find(absIncFileName);
3977 if (ii==nullptr)
3978 {
3979 bool ambig = false;
3980 FileDef *incFd = Doxygen::inputNameLinkedMap->findFileDef(absIncFileName,ambig);
3981 state->includeRelations.add(
3982 absIncFileName,
3983 oldFileDef,
3984 ambig ? nullptr : incFd,
3985 incFileName,
3986 localInclude,
3987 state->isImported
3988 );
3989 }
3990 }
3991
3992 struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
3993 fs->bufState = YY_CURRENT_BUFFER;
3994 fs->lineNr = oldLineNr;
3995 fs->fileName = oldFileName;
3996 fs->curlyCount = state->curlyCount;
3997 //state->curlyCount = 0; // don't reset counter, see issue #10997
3998 fs->lexRulesPart = state->lexRulesPart;
3999 fs->levelGuard = state->levelGuard;
4000 while (!state->levelGuard.empty()) state->levelGuard.pop();
4001 state->lexRulesPart = false;
4002 // push the state on the stack
4003 FileState *fs_ptr = fs.get();
4004 state->includeStack.push_back(std::move(fs));
4005 // set the scanner to the include file
4006
4007 // Deal with file changes due to
4008 // #include's within { .. } blocks
4009 DString lineStr(state->fileName.length()+20, DString::ExplicitSize);
4010 lineStr.sprintf("# 1 \"%s\" 1\n",qPrint(state->fileName));
4011 outputString(yyscanner,lineStr);
4012
4013 AUTO_TRACE_ADD("Switching to include file {}",incFileName);
4014 state->expectGuard=true;
4015 state->inputBuf = &fs_ptr->fileBuf;
4016 state->inputBufPos=0;
4017 yy_switch_to_buffer(yy_create_buffer(0, YY_BUF_SIZE, yyscanner),yyscanner);
4018 }
4019 else
4020 {
4021 if (alreadyProcessed) // if this header was already process we can just copy the stored macros
4022 // in the local context
4023 {
4024 std::lock_guard<std::mutex> lock(g_globalDefineMutex);
4025 g_defineManager.addInclude(state->fileName.str(),absIncFileName.str());
4026 g_defineManager.retrieve(absIncFileName.str(),state->contextDefines);
4027 }
4028
4029 if (state->includeStack.empty() && oldFileDef)
4030 {
4031 PreIncludeInfo *ii = state->includeRelations.find(absIncFileName);
4032 if (ii==nullptr)
4033 {
4034 bool ambig = false;
4035 FileDef *incFd = Doxygen::inputNameLinkedMap->findFileDef(absIncFileName,ambig);
4036 ii = state->includeRelations.add(absIncFileName,
4037 oldFileDef,
4038 ambig ? nullptr : incFd,
4039 incFileName,
4040 localInclude,
4041 state->isImported
4042 );
4043 }
4044 }
4045
4047 {
4048 for (i=0;i<state->includeStack.size();i++)
4049 {
4051 }
4052 if (alreadyProcessed)
4053 {
4054 Debug::print(Debug::Preprocessor,0,"#include {}: already processed! skipping...\n",incFileName);
4055 }
4056 else
4057 {
4058 Debug::print(Debug::Preprocessor,0,"#include {}: not found! skipping...\n",incFileName);
4059 }
4060 //printf("error: include file %s not found\n",yytext);
4061 }
4062 if (localInclude && !state->includeStack.empty() && state->curlyCount>0 && !alreadyProcessed) // failed to find #include inside { ... }
4063 {
4064 warn(state->fileName,state->yyLineNr,"include file {} not found, perhaps you forgot to add its directory to INCLUDE_PATH?",incFileName);
4065 }
4066 }
4067 }
4068}
4069
4070/* ----------------------------------------------------------------- */
4071
4072static void startCondSection(yyscan_t yyscanner,const DString &sectId)
4073{
4074 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
4075 //printf("startCondSection: skip=%d stack=%d\n",state->skip,state->condStack.size());
4076 CondParser prs;
4077 bool expResult = prs.parse(state->fileName.data(),state->yyLineNr,sectId.data());
4078 state->condStack.emplace(std::make_unique<preYY_CondCtx>(state->fileName,state->yyLineNr,sectId,state->skip));
4079 if (!expResult)
4080 {
4081 state->skip=true;
4082 }
4083 //printf(" expResult=%d skip=%d\n",expResult,state->skip);
4084}
4085
4086static void endCondSection(yyscan_t yyscanner)
4087{
4088 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
4089 if (state->condGuardCount>0 && state->condGuardErrorLine==0)
4090 {
4091 state->condGuardErrorLine = state->yyLineNr;
4092 state->condGuardErrorFileName = state->fileName;
4093 state->condGuardErrorMessage = "more #if's than #endif's in \\cond..\\endcond section";
4094 }
4095 else if (state->condGuardCount<0 && state->condGuardErrorLine==0)
4096 {
4097 state->condGuardErrorLine = state->yyLineNr;
4098 state->condGuardErrorFileName = state->fileName;
4099 state->condGuardErrorMessage = "more #endif's than #if's in \\cond..\\endcond section";
4100 }
4101 else // balanced again -> no error
4102 {
4103 state->condGuardErrorLine = 0;
4104 }
4105 if (state->condStack.empty())
4106 {
4107 warn(state->fileName,state->yyLineNr,"the \\endcond does not have a corresponding \\cond in this file");
4108 state->skip=false;
4109 }
4110 else
4111 {
4112 const std::unique_ptr<preYY_CondCtx> &ctx = state->condStack.top();
4113 state->skip=ctx->skip;
4114 state->condStack.pop();
4115 }
4116 //printf("endCondSection: skip=%d stack=%d\n",state->skip,state->condStack.count());
4117}
4118
4119static void forceEndCondSection(yyscan_t yyscanner)
4120{
4121 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
4122 while (!state->condStack.empty())
4123 {
4124 state->condStack.pop();
4125 }
4126 state->skip=false;
4127}
4128
4129static DString escapeAt(const DString &text)
4130{
4131 DString result;
4132 if (!text.empty())
4133 {
4134 char c = 0;
4135 const char *p=text.data();
4136 while ((c=*p++))
4137 {
4138 if (c=='@') result+="@@"; else result+=c;
4139 }
4140 }
4141 return result;
4142}
4143
4144static char resolveTrigraph(char c)
4145{
4146 switch (c)
4147 {
4148 case '=': return '#';
4149 case '/': return '\\';
4150 case '\'': return '^';
4151 case '(': return '[';
4152 case ')': return ']';
4153 case '!': return '|';
4154 case '<': return '{';
4155 case '>': return '}';
4156 case '-': return '~';
4157 }
4158 return '?';
4159}
4160
4161/*@ ----------------------------------------------------------------------------
4162 */
4163
4164static int getNextChar(yyscan_t yyscanner,const DString &expr,DString *rest,uint32_t &pos)
4165{
4166 //printf("getNextChar(%s,%s,%d)\n",qPrint(expr),rest ? rest->data() : 0,pos);
4167 if (pos<expr.length())
4168 {
4169 //printf(" expr()='%c'\n",expr.at(pos));
4170 return expr.at(pos++);
4171 }
4172 else if (rest && !rest->empty())
4173 {
4174 int cc=rest->at(0);
4175 *rest=rest->right(rest->length()-1);
4176 //printf(" rest='%c'\n",cc);
4177 return cc;
4178 }
4179 else if (!preYYget_extra(yyscanner)->boundedExpansion)
4180 {
4181 int cc=yyinput(yyscanner);
4182 //printf(" yyinput()='%c' %d\n",cc,EOF);
4183 return cc;
4184 }
4185 return EOF;
4186}
4187
4188static int getCurrentChar(yyscan_t yyscanner,const DString &expr,DString *rest,uint32_t pos)
4189{
4190 //printf("getCurrentChar(%s,%s,%d)\n",qPrint(expr),rest ? rest->data() : 0,pos);
4191 if (pos<expr.length())
4192 {
4193 //printf("%c=expr()\n",expr.at(pos));
4194 return expr.at(pos);
4195 }
4196 else if (rest && !rest->empty())
4197 {
4198 int cc=rest->at(0);
4199 //printf("%c=rest\n",cc);
4200 return cc;
4201 }
4202 else if (!preYYget_extra(yyscanner)->boundedExpansion)
4203 {
4204 int cc=yyinput(yyscanner);
4205 returnCharToStream(yyscanner,(char)cc);
4206 //printf("%c=yyinput()\n",cc);
4207 return cc;
4208 }
4209 return EOF;
4210}
4211
4212static void unputChar(yyscan_t yyscanner,const DString &expr,DString *rest,uint32_t &pos,char c)
4213{
4214 //printf("unputChar(%s,%s,%d,%c)\n",qPrint(expr),rest ? rest->data() : 0,pos,c);
4215 if (pos<expr.length())
4216 {
4217 pos++;
4218 }
4219 else if (rest)
4220 {
4221 //printf(" prepending '%c' to rest!\n",c);
4222 char cs[2];cs[0]=c;cs[1]='\0';
4223 rest->prepend(cs);
4224 }
4225 else if (!preYYget_extra(yyscanner)->boundedExpansion)
4226 {
4227 //printf(" yyunput()='%c'\n",c);
4228 returnCharToStream(yyscanner,c);
4229 }
4230 //printf("result: unputChar(%s,%s,%d,%c)\n",qPrint(expr),rest ? rest->data() : 0,pos,c);
4231}
4232
4233/** Returns a reference to a Define object given its name or 0 if the Define does
4234 * not exist.
4235 */
4236static Define *isDefined(yyscan_t yyscanner,const DString &name)
4237{
4238 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
4239
4240 bool undef = false;
4241 auto findDefine = [&undef,&name](DefineMap &map)
4242 {
4243 Define *d=nullptr;
4244 auto it = map.find(name.str());
4245 if (it!=map.end())
4246 {
4247 d = &it->second;
4248 if (d->undef)
4249 {
4250 undef=true;
4251 d=nullptr;
4252 }
4253 }
4254 return d;
4255 };
4256
4257 Define *def = findDefine(state->localDefines);
4258 if (def==nullptr && !undef)
4259 {
4260 def = findDefine(state->contextDefines);
4261 }
4262 return def;
4263}
4264
4265static void initPredefined(yyscan_t yyscanner,const DString &fileName)
4266{
4267 YY_EXTRA_TYPE state = preYYget_extra(yyscanner);
4268
4269 // add predefined macros
4270 StringVector predefList = Config_getList(PREDEFINED);
4271 for (const auto &ds : predefList)
4272 {
4273 size_t i_equals=ds.find('=');
4274 size_t i_obrace=ds.find('(');
4275 size_t i_cbrace=ds.find(')');
4276 bool nonRecursive = i_equals!=std::string::npos && i_equals>0 && ds[i_equals-1]==':';
4277
4278 if ((i_obrace==0) || (i_equals==0) || (i_equals==1 && ds[i_equals-1]==':'))
4279 {
4280 continue; // no define name
4281 }
4282
4283 if (i_obrace<i_equals && i_cbrace<i_equals &&
4284 i_obrace!=std::string::npos && i_cbrace!=std::string::npos &&
4285 i_obrace<i_cbrace
4286 ) // predefined function macro definition
4287 {
4288 static const reg::Ex reId(R"(\a\w*)");
4289 std::map<std::string,int> argMap;
4290 std::string args = ds.substr(i_obrace+1,i_cbrace-i_obrace-1); // part between ( and )
4291 bool hasVarArgs = args.find("...")!=std::string::npos;
4292 //printf("predefined function macro '%s'\n",qPrint(ds));
4293 int count = 0;
4294 reg::Iterator arg_it(args,reId,0);
4295 reg::Iterator arg_end;
4296 // gather the formal arguments in a dictionary
4297 for (; arg_it!=arg_end; ++arg_it)
4298 {
4299 argMap.emplace(arg_it->str(),count++);
4300 }
4301 if (hasVarArgs) // add the variable argument if present
4302 {
4303 argMap.emplace("__VA_ARGS__",count++);
4304 }
4305
4306 // strip definition part
4307 std::string definition;
4308 std::string in=ds.substr(i_equals+1);
4309 reg::Iterator re_it(in,reId);
4310 reg::Iterator re_end;
4311 size_t i=0;
4312 // substitute all occurrences of formal arguments by their
4313 // corresponding markers
4314 for (; re_it!=re_end; ++re_it)
4315 {
4316 const auto &match = *re_it;
4317 size_t pi = match.position();
4318 size_t l = match.length();
4319 if (pi>i) definition+=in.substr(i,pi-i);
4320
4321 auto it = argMap.find(match.str());
4322 if (it!=argMap.end())
4323 {
4324 int argIndex = it->second;
4325 DString marker;
4326 marker.sprintf(" @%d ",argIndex);
4327 definition+=marker.str();
4328 }
4329 else
4330 {
4331 definition+=match.str();
4332 }
4333 i=pi+l;
4334 }
4335 definition+=in.substr(i);
4336
4337 // add define definition to the dictionary of defines for this file
4338 std::string dname = ds.substr(0,i_obrace);
4339 if (!dname.empty())
4340 {
4341 Define def;
4342 def.name = dname;
4343 def.definition = definition;
4344 def.nargs = count;
4345 def.isPredefined = true;
4346 def.nonRecursive = nonRecursive;
4347 def.fileDef = state->yyFileDef;
4348 def.fileName = fileName;
4349 def.varArgs = hasVarArgs;
4350 state->contextDefines.emplace(def.name.str(),def);
4351
4352 //printf("#define '%s' '%s' #nargs=%d hasVarArgs=%d\n",
4353 // qPrint(def.name),qPrint(def.definition),def.nargs,def.varArgs);
4354 }
4355 }
4356 else if (!ds.empty()) // predefined non-function macro definition
4357 {
4358 //printf("predefined normal macro '%s'\n",qPrint(ds));
4359 Define def;
4360 if (i_equals==std::string::npos) // simple define without argument
4361 {
4362 def.name = ds;
4363 def.definition = "1"; // substitute occurrences by 1 (true)
4364 }
4365 else // simple define with argument
4366 {
4367 int ine=static_cast<int>(i_equals) - (nonRecursive ? 1 : 0);
4368 def.name = ds.substr(0,ine);
4369 def.definition = ds.substr(i_equals+1);
4370 }
4371 if (!def.name.empty())
4372 {
4373 def.nargs = -1;
4374 def.isPredefined = true;
4375 def.nonRecursive = nonRecursive;
4376 def.fileDef = state->yyFileDef;
4377 def.fileName = fileName;
4378 state->contextDefines.emplace(def.name.str(),def);
4379 }
4380 }
4381 }
4382}
4383
4384///////////////////////////////////////////////////////////////////////////////////////////////
4385
4391
4393{
4394 YY_EXTRA_TYPE state = preYYget_extra(p->yyscanner);
4395 FileInfo fi(dir.str());
4396 if (fi.isDir()) state->pathList.push_back(fi.absFilePath());
4397}
4398
4400{
4401 preYYlex_init_extra(&p->state,&p->yyscanner);
4402 addSearchDir(".");
4403}
4404
4406{
4407 preYYlex_destroy(p->yyscanner);
4408}
4409
4410void Preprocessor::processFile(const DString &fileName,const std::string &input,std::string &output)
4411{
4412 AUTO_TRACE("fileName={}",fileName);
4413 yyscan_t yyscanner = p->yyscanner;
4414 YY_EXTRA_TYPE state = preYYget_extra(p->yyscanner);
4415 struct yyguts_t *yyg = (struct yyguts_t*)p->yyscanner;
4416
4417#ifdef FLEX_DEBUG
4418 preYYset_debug(Debug::isFlagSet(Debug::Lex_pre)?1:0,yyscanner);
4419#endif
4420
4421 DebugLex debugLex(Debug::Lex_pre, __FILE__, qPrint(fileName));
4422 //printf("##########################\n%s\n####################\n",
4423 // qPrint(input));
4424
4425 state->macroExpansion = Config_getBool(MACRO_EXPANSION);
4426 state->expandOnlyPredef = Config_getBool(EXPAND_ONLY_PREDEF);
4427 state->skip=false;
4428 state->curlyCount=0;
4429 state->lexRulesPart=false;
4430 state->nospaces=false;
4431 state->inputBuf=&input;
4432 state->inputBufPos=0;
4433 state->outputBuf=&output;
4434 state->includeStack.clear();
4435 state->expandedDict.clear();
4436 state->contextDefines.clear();
4437 state->pragmaSet.clear();
4438 state->condGuardCount=0;
4439 state->condGuardErrorLine=0;
4440 while (!state->levelGuard.empty()) state->levelGuard.pop();
4441 while (!state->condStack.empty()) state->condStack.pop();
4442
4443 setFileName(yyscanner,fileName);
4444
4445 state->inputFileDef = state->yyFileDef;
4446 //yyextra->defineManager.startContext(state->fileName);
4447
4448 initPredefined(yyscanner,fileName);
4449
4450 state->yyLineNr = 1;
4451 state->yyColNr = 1;
4452 state->ifcount = 0;
4453
4454 BEGIN( Start );
4455
4456 state->expectGuard = EntryType::guessSection(fileName).isHeader();
4457 state->guardName.clear();
4458 state->lastGuardName.clear();
4459 state->guardExpr.clear();
4460
4461 preYYlex(yyscanner);
4462
4463 while (!state->condStack.empty())
4464 {
4465 const std::unique_ptr<preYY_CondCtx> &ctx = state->condStack.top();
4466 DString sectionInfo = " ";
4467 if (ctx->sectionId!=" ") sectionInfo.sprintf(" with label '%s' ",qPrint(ctx->sectionId.stripWhiteSpace()));
4468 warn(ctx->fileName,ctx->lineNr,"Conditional section{}does not have "
4469 "a corresponding \\endcond command within this file.",sectionInfo);
4470 state->condStack.pop();
4471 }
4472 // make sure we don't extend a \cond with missing \endcond over multiple files (see bug 624829)
4473 forceEndCondSection(yyscanner);
4474
4475 if (!state->levelGuard.empty())
4476 {
4477 if (yyextra->condGuardErrorLine!=0)
4478 {
4479 warn(yyextra->condGuardErrorFileName,yyextra->condGuardErrorLine,"{}",yyextra->condGuardErrorMessage);
4480 }
4481 else
4482 {
4483 warn(state->fileName,state->yyLineNr,"More #if's than #endif's found (might be in an included file).");
4484 }
4485 }
4486
4488 {
4489 std::lock_guard<std::mutex> lock(g_debugMutex);
4490 Debug::print(Debug::Preprocessor,0,"Preprocessor output of {} (size: {} bytes):\n",fileName,output.size());
4491 std::string contents;
4493 {
4494 contents=output;
4495 }
4496 else // need to add line numbers
4497 {
4498 int line=1;
4499 bool startOfLine = true;
4500 size_t content_size = output.size() +
4501 output.size()*6/40; // assuming 40 chars per line on average
4502 // and 6 chars extra for the line number
4503 contents.reserve(content_size);
4504 size_t pos=0;
4505 while (pos<output.size())
4506 {
4507 if (startOfLine)
4508 {
4509 char lineNrStr[15];
4510 snprintf(lineNrStr,15,"%05d ",line++);
4511 contents+=lineNrStr;
4512 }
4513 contents += output[pos];
4514 startOfLine = output[pos]=='\n';
4515 pos++;
4516 }
4517 }
4518 char end[2]={0,0};
4519 if (!contents.empty() && contents[contents.length()-1]!='\n')
4520 {
4521 end[0]='\n';
4522 }
4523 Debug::print(Debug::Preprocessor,0,"---------\n{}{}---------\n",contents,end);
4524 if (yyextra->contextDefines.size()>0)
4525 {
4526 Debug::print(Debug::Preprocessor,0,"Macros accessible in this file ({}):\n", fileName);
4527 Debug::print(Debug::Preprocessor,0,"---------\n");
4528 for (auto &kv : yyextra->contextDefines)
4529 {
4530 Debug::print(Debug::Preprocessor,0,"{} ",kv.second.name);
4531 }
4532 for (auto &kv : yyextra->localDefines)
4533 {
4534 Debug::print(Debug::Preprocessor,0,"{} ",kv.second.name);
4535 }
4536 Debug::print(Debug::Preprocessor,0,"\n---------\n");
4537 }
4538 else
4539 {
4540 Debug::print(Debug::Preprocessor,0,"No macros accessible in this file ({}).\n", fileName);
4541 }
4542 }
4543
4544 {
4545 std::lock_guard<std::mutex> lock(g_updateGlobals);
4546 for (const auto &inc : state->includeRelations)
4547 {
4548 auto toKind = [](bool local,bool imported) -> IncludeKind
4549 {
4550 if (local)
4551 {
4552 if (imported)
4553 {
4555 }
4557 }
4558 else if (imported)
4559 {
4561 }
4563 };
4564 if (inc->fromFileDef)
4565 {
4566 inc->fromFileDef->addIncludeDependency(inc->toFileDef,inc->includeName,toKind(inc->local,inc->imported));
4567 }
4568 if (inc->toFileDef && inc->fromFileDef)
4569 {
4570 inc->toFileDef->addIncludedByDependency(inc->fromFileDef,inc->fromFileDef->docName(),toKind(inc->local,inc->imported));
4571 }
4572 }
4573 // add the macro definition for this file to the global map
4574 Doxygen::macroDefinitions.emplace(state->fileName.str(),std::move(state->macroDefinitions));
4575 }
4576
4577 //yyextra->defineManager.endContext();
4578}
4579
4580#include "pre.l.h"
Copyright (C) 1997-2026 by Dimitri van Heesch.
Definition condparser.h:29
bool parse(const DString &fileName, int lineNr, const DString &expr)
parses and evaluates the given expression.
void clear()
Definition dstring.h:214
DString mid(size_t index, size_t len=npos) const
Definition dstring.h:318
DString substr(size_t pos=0, size_t count=npos) const
Returns a substring of length count starting at pos.
Definition dstring.h:223
char & at(size_t i)
Returns a reference to the character at index i.
Definition dstring.h:686
DString right(size_t len) const
Definition dstring.h:311
size_t size() const
Returns the length of the string, not counting the 0-terminator.
Definition dstring.h:154
DString & prepend(const char *s)
Definition dstring.h:515
size_t find(char c, size_t pos=0) const
Definition dstring.h:239
DString & sprintf(const char *format,...)
Definition dstring.cpp:34
const char * data() const
Returns a pointer to the contents of the string in the form of a 0-terminated C string.
Definition dstring.h:157
bool endsWith(const char *s) const
Definition dstring.h:617
@ NoLineNo
Definition debug.h:43
@ Lex_pre
Definition debug.h:66
bool varArgs
Definition define.h:42
FileDef * fileDef
Definition define.h:37
DString args
Definition define.h:36
static StringUnorderedSet expandAsDefinedSet
Definition doxygen.h:112
static FileNameLinkedMap * inputNameLinkedMap
Definition doxygen.h:97
static DefinesPerFileList macroDefinitions
Definition doxygen.h:128
static FileNameLinkedMap * includeNameLinkedMap
Definition doxygen.h:94
Wrapper class for the Entry type.
Definition types.h:860
static EntryType guessSection(const DString &name)
Definition types.cpp:22
virtual DString absFilePath() const =0
Minimal replacement for QFileInfo.
Definition fileinfo.h:26
bool exists() const
Definition fileinfo.cpp:35
bool match(const PatternList &patList, bool caseSenseNames, PatternElem *elem=nullptr, PatternGet getter=[](const std::string &s){ return s;}) const
Match the file name against a list of patterns.
Definition fileinfo.h:60
bool isDir() const
Definition fileinfo.cpp:75
bool isFile() const
Definition fileinfo.cpp:68
std::string dirPath(bool absPath=true) const
Definition fileinfo.cpp:142
std::string absFilePath() const
Definition fileinfo.cpp:106
FileDef * findFileDef(const DString &n, bool &ambig) const
Returns the file definition in fnMap that matches the file name n.
Definition filename.cpp:38
~Preprocessor()
Definition pre.l:4405
void processFile(const DString &fileName, const std::string &input, std::string &output)
Definition pre.l:4410
Preprocessor()
Definition pre.l:4399
void addSearchDir(const DString &dir)
Definition pre.l:4392
std::unique_ptr< Private > p
Definition pre.h:37
Class representing a regular expression.
Definition regex.h:39
Class to iterate through matches.
Definition regex.h:245
std::string str() const
Return a string representing the matching part.
Definition regex.h:172
#define YY_BUF_SIZE
Definition commentcnv.l:19
#define Config_getList(name)
Definition config.h:38
DirIterator end(const DirIterator &) noexcept
Definition dir.cpp:180
#define AUTO_TRACE_ADD(...)
Definition docnode.cpp:54
#define AUTO_TRACE(...)
Definition docnode.cpp:53
bool isId(char c)
Returns true if c is a valid character for an identifier.
Definition dstring.h:895
int dstrncmp(const char *str1, const char *str2, size_t len)
Definition dstring.h:56
IncludeKind
Definition filedef.h:44
@ IncludeLocal
Definition filedef.h:47
@ ImportSystemObjC
Definition filedef.h:48
@ ImportLocalObjC
Definition filedef.h:49
@ IncludeSystem
Definition filedef.h:46
bool recognizeFixedForm(const DString &contents, FortranFormat format)
FortranFormat convertFileNameFortranParserCode(const DString &fn)
#define term(fmt,...)
Definition message.h:137
bool isAbsolutePath(const DString &fileName)
Definition portable.cpp:513
Definition message.h:146
Definition dstring.h:913
static void addSeparatorsIfNeeded(yyscan_t yyscanner, const DString &expr, DString &resultExpr, DString &restExpr, int pos)
Definition pre.l:3208
static std::unique_ptr< FileState > checkAndOpenFile(yyscan_t yyscanner, const DString &fileName, bool &alreadyProcessed)
Definition pre.l:2357
static std::unique_ptr< FileState > findFile(yyscan_t yyscanner, const DString &fileName, bool localInclude, bool &alreadyProcessed)
Definition pre.l:2414
#define MAX_EXPANSION_DEPTH
Definition pre.l:3206
static DString stringize(const DString &s)
Definition pre.l:2549
static void processConcatOperators(DString &expr)
Definition pre.l:2627
static void skipCommentMacroName(yyscan_t yyscanner, const DString &expr, DString *rest, int &cc, uint32_t &j, int &len)
Definition pre.l:2754
static int getNextId(const DString &expr, int p, int *l)
Definition pre.l:3152
static void unputChar(yyscan_t yyscanner, const DString &expr, DString *rest, uint32_t &pos, char c)
Definition pre.l:4212
static void expandArgument(yyscan_t yyscanner, DString &arg, int level)
Definition pre.l:2539
static bool isFunctionMacroCall(yyscan_t yyscanner, const DString &expr, DString *rest, int pos)
Definition pre.l:2785
static void returnCharToStream(yyscan_t yyscanner, char c)
Definition pre.l:2713
static int getCurrentChar(yyscan_t yyscanner, const DString &expr, DString *rest, uint32_t pos)
Definition pre.l:4188
static const char * processUntilMatchingTerminator(const char *inputStr, DString &result)
Process string or character literal.
Definition pre.l:3398
static void forceEndCondSection(yyscan_t yyscanner)
Definition pre.l:4119
static DString expandVAOpt(const DString &vaStr, bool hasOptionalArgs)
Definition pre.l:2816
static void addTillEndOfComment(yyscan_t yyscanner, const DString &expr, DString *rest, uint32_t &pos, char term, DString &arg)
Definition pre.l:2738
static bool replaceFunctionMacro(yyscan_t yyscanner, const DString &expr, DString *rest, int pos, int &len, const Define *def, DString &result, int level)
Definition pre.l:2868
static DString removeMarkers(const DString &s)
Definition pre.l:3626
static void addTillEndOfString(yyscan_t yyscanner, const DString &expr, DString *rest, uint32_t &pos, char term, DString &arg)
Definition pre.l:2719
static int getNextChar(yyscan_t yyscanner, const DString &expr, DString *rest, uint32_t &pos)
Definition pre.l:4164
static void initPredefined(yyscan_t yyscanner, const DString &fileName)
Definition pre.l:4265
static DString removeIdsAndMarkers(const DString &s)
Definition pre.l:3434
static bool expandExpression(yyscan_t yyscanner, DString &expr, DString *rest, int pos, int level)
Definition pre.l:3240
void addTerminalCharIfMissing(std::string &s, char c)
Definition stringutil.h:87
bool literal_at(const char *data, const char(&str)[N])
returns true iff data points to a substring that matches string literal str
Definition stringutil.h:101
preYY_state state
Definition pre.l:4389
yyscan_t yyscanner
Definition pre.l:4388
FortranFormat
Definition types.h:614
bool readInputFile(const DString &fileName, std::string &contents, const ReadInputFileOptions &options)
read a file name fileName and optionally filter and transcode it
Definition util.cpp:4506
bool useCaseSenseNames()
Returns true if the names of the symbols can be case sensitive.
Definition util.cpp:2811
DString determineAbsoluteIncludeName(const DString &curFile, const DString &incFileName)
Definition util.cpp:3061