Doxygen
Loading...
Searching...
No Matches
clangparser.cpp
Go to the documentation of this file.
1/******************************************************************************
2 *
3 * Copyright (C) 1997-2026 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
16// own include
17#include "clangparser.h"
18
19// standard includes
20#include <cstdio>
21#include <cstdint>
22#include <cstdlib>
23#include <string>
24#include <vector>
25#include <mutex>
26
27// other includes
28#include "settings.h"
29
30#if USE_LIBCLANG
31// clang includes
32#include "clang/Tooling/CompilationDatabase.h"
33#include "clang/Tooling/Tooling.h"
34#include "clang-c/Index.h"
35
36// other includes
37#include "classdef.h"
38#include "config.h"
39#include "doxygen.h"
40#include "filedef.h"
41#include "filename.h"
42#include "memberdef.h"
43#include "membername.h"
44#include "message.h"
45#include "outputgen.h"
46#include "outputlist.h"
47#include "searchindex.h"
48#include "tooltip.h"
49#include "trace.h"
50#include "utf8.h"
51#include "util.h"
52#endif
53
54//--------------------------------------------------------------------------
55
56static std::mutex g_clangMutex;
57
59{
60 std::lock_guard<std::mutex> lock(g_clangMutex);
61 if (s_instance==nullptr) s_instance = new ClangParser;
62 return s_instance;
63}
64
66
67//--------------------------------------------------------------------------
68#if USE_LIBCLANG
69
70static std::mutex g_docCrossReferenceMutex;
71
72enum class DetectedLang { Cpp, ObjC, ObjCpp };
73
74static const char * keywordToType(const char *keyword)
75{
76 static const StringUnorderedSet flowKeywords({
77 "break", "case", "catch", "continue", "default", "do",
78 "else", "finally", "for", "foreach", "for each", "goto",
79 "if", "return", "switch", "throw", "throws", "try",
80 "while", "@try", "@catch", "@finally" });
81 static const StringUnorderedSet typeKeywords({
82 "bool", "char", "double", "float", "int", "long", "object",
83 "short", "signed", "unsigned", "void", "wchar_t", "size_t",
84 "boolean", "id", "SEL", "string", "nullptr" });
85 if (flowKeywords.find(keyword)!=flowKeywords.end()) return "keywordflow";
86 if (typeKeywords.find(keyword)!=typeKeywords.end()) return "keywordtype";
87 return "keyword";
88}
89
90static std::string getQualifiedCursorName(CXCursor cursor)
91{
92 std::vector<std::string> names;
93 while (!clang_Cursor_isNull(cursor) &&
94 clang_getCursorKind(cursor)!=CXCursor_TranslationUnit)
95 {
96 CXString spelling = clang_getCursorSpelling(cursor);
97 const char *name = clang_getCString(spelling);
98 if (name && *name) names.emplace_back(name);
99 clang_disposeString(spelling);
100 cursor = clang_getCursorSemanticParent(cursor);
101 }
102 std::string result;
103 for (auto it=names.rbegin();it!=names.rend();++it)
104 {
105 if (!result.empty()) result+="::";
106 result+=*it;
107 }
108 return result;
109}
110
111
112//--------------------------------------------------------------------------
113
115{
116 public:
117 Private(const ClangParser &p,const FileDef *fd)
118 : parser(p), fileDef(fd) {}
119 const ClangParser &parser;
120 const FileDef *fileDef;
121 CXIndex index = nullptr;
122 uint32_t curToken = 0;
123 DetectedLang detectedLang = DetectedLang::Cpp;
124 size_t numFiles = 0;
125 std::vector<DString> sources;
126 std::vector<CXUnsavedFile> ufs;
127 std::vector<CXCursor> cursors;
128 std::unordered_map<std::string,uint32_t> fileMapping;
129 CXTranslationUnit tu = nullptr;
130 CXToken *tokens = nullptr;
131 uint32_t numTokens = 0;
133 TooltipManager tooltipManager;
134 std::vector<const Definition *> foldStack;
135
136 // state while parsing sources
137 const MemberDef *currentMemberDef=nullptr;
138 uint32_t currentLine=0;
139 bool searchForBody=false;
140 bool insideBody=false;
141 uint32_t bracketCount=0;
142};
143
144ClangTUParser::ClangTUParser(const ClangParser &parser,const FileDef *fd)
145 : p(std::make_unique<Private>(parser,fd))
146{
147 //printf("ClangTUParser::ClangTUParser() this=%p\n",this);
148}
149
151{
152 return p->filesInSameTU;
153}
154
156{
157 //printf("ClangTUParser::parse() this=%p\n",this);
158 DString fileName = p->fileDef->absFilePath();
159 p->fileDef->getAllIncludeFilesRecursively(p->filesInSameTU);
160 //printf("ClangTUParser::ClangTUParser(fileName=%s,#filesInSameTU=%d)\n",
161 // qPrint(fileName),(int)p->filesInSameTU.size());
162 bool clangAssistedParsing = Config_getBool(CLANG_ASSISTED_PARSING);
163 bool clangIncludeInputPaths = Config_getBool(CLANG_ADD_INC_PATHS);
164 bool filterSourceFiles = Config_getBool(FILTER_SOURCE_FILES);
165 StringVector includePath = Config_getList(INCLUDE_PATH);
166 StringVector clangOptions = Config_getList(CLANG_OPTIONS);
167 if (!clangAssistedParsing) return;
168 //printf("ClangParser::start(%s)\n",fileName);
169 ASSERT(p->index==nullptr);
170 ASSERT(p->tokens==nullptr);
171 ASSERT(p->numTokens==0);
172 p->index = clang_createIndex(0, 0);
173 p->curToken = 0;
174 p->cursors.clear();
175 std::vector<clang::tooling::CompileCommand> command;
176 if (p->parser.database()!=nullptr)
177 {
178 // check if the file we are parsing is in the DB
179 command = p->parser.database()->getCompileCommands(fileName.data());
180 }
181 std::vector<char *> argv;
182 if (!command.empty() )
183 {
184 std::vector<std::string> options = command[command.size()-1].CommandLine;
185 // copy each compiler option used from the database. Skip the first which is compiler exe.
186 for (auto option = options.begin()+1; option != options.end(); option++)
187 {
188 argv.push_back(dstrdup(option->c_str()));
189 }
190 // The last compile command (last entry of argv) should be the filename of the source
191 // file to parse. It does not matter to clang_parseTranslationUnit below if we pass the file name
192 // separately in its second argument or if we just pass it a nullptr as the second
193 // argument and pass the file name with the other compile commands.
194 // However, in some cases (e.g., starting from Clang 14, if we are parsing a header file, see
195 // https://github.com/doxygen/doxygen/issues/10733), the compile commands returned by
196 // getCompileCommands include a "--" as second to last argument (which is supposed to make it
197 // easier to parse the argument list). If we pass this "--" to clang_parseTranslationUnit below,
198 // it returns an error. To avoid this, we remove the file name argument (and the "--" if present)
199 // from argv and pass the file name separately.
200 dstrfree(argv.back());
201 argv.pop_back(); // remove file name
202 if (argv.size()>0 && dstrcmp(argv[argv.size() - 1],"--")==0) {
203 // remove '--' from argv
204 dstrfree(argv.back());
205 argv.pop_back();
206 }
207
208 // user specified options
209 for (size_t i=0;i<clangOptions.size();i++)
210 {
211 argv.push_back(dstrdup(clangOptions[i].c_str()));
212 }
213 // this extra addition to argv is accounted for as we are skipping the first entry in
214 argv.push_back(dstrdup("-w")); // finally, turn off warnings.
215 }
216 else
217 {
218 // add include paths for input files
219 if (clangIncludeInputPaths)
220 {
221 for (const std::string &path : Doxygen::inputPaths)
222 {
223 DString inc = DString("-I")+path.data();
224 argv.push_back(dstrdup(inc.data()));
225 //printf("argv[%d]=%s\n",argc,argv[argc]);
226 }
227 }
228 // add external include paths
229 for (size_t i=0;i<includePath.size();i++)
230 {
231 DString inc = "-I"+includePath[i];
232 argv.push_back(dstrdup(inc.data()));
233 }
234 // user specified options
235 for (size_t i=0;i<clangOptions.size();i++)
236 {
237 argv.push_back(dstrdup(clangOptions[i].c_str()));
238 }
239 // extra options
240 argv.push_back(dstrdup("-ferror-limit=0"));
241 argv.push_back(dstrdup("-x"));
242
243 // Since we can be presented with a .h file that can contain C/C++ or
244 // Objective C code and we need to configure the parser before knowing this,
245 // we use the source file to detected the language. Detection will fail if you
246 // pass a bunch of .h files containing ObjC code, and no sources :-(
247 SrcLangExt lang = getLanguageFromFileName(fileName);
248 DString fn = fileName.lower();
249 if (lang==SrcLangExt::ObjC || p->detectedLang!=DetectedLang::Cpp)
250 {
251 if (p->detectedLang!=DetectedLang::Cpp &&
252 (fn.endsWith(".cpp") || fn.endsWith(".cxx") ||
253 fn.endsWith(".cc") || fn.endsWith(".c")))
254 { // fall back to C/C++ once we see an extension that indicates this
255 p->detectedLang = DetectedLang::Cpp;
256 }
257 else if (fn.endsWith(".mm")) // switch to Objective C++
258 {
259 p->detectedLang = DetectedLang::ObjCpp;
260 }
261 else if (fn.endsWith(".m")) // switch to Objective C
262 {
263 p->detectedLang = DetectedLang::ObjC;
264 }
265 }
266 switch (p->detectedLang)
267 {
268 case DetectedLang::Cpp:
269 if (fn.endsWith(".hpp") || fn.endsWith(".hxx") ||
270 fn.endsWith(".hh") || fn.endsWith(".h"))
271 argv.push_back(dstrdup("c++-header"));
272 else
273 argv.push_back(dstrdup("c++"));
274 break;
275 case DetectedLang::ObjC: argv.push_back(dstrdup("objective-c")); break;
276 case DetectedLang::ObjCpp: argv.push_back(dstrdup("objective-c++")); break;
277 }
278 }
279 //printf("source %s ----------\n%s\n-------------\n\n",
280 // fileName,p->source.data());
281 size_t numUnsavedFiles = p->filesInSameTU.size()+1;
282 p->numFiles = numUnsavedFiles;
283 p->sources.resize(numUnsavedFiles);
284 p->ufs.resize(numUnsavedFiles);
285 size_t refIndent = 0;
286 p->sources[0] = detab(fileToString(fileName,filterSourceFiles,true),refIndent);
287 p->ufs[0].Filename = dstrdup(fileName.data());
288 p->ufs[0].Contents = p->sources[0].data();
289 p->ufs[0].Length = p->sources[0].length();
290 p->fileMapping.emplace(fileName.data(),0);
291 size_t i=1;
292 for (auto it = p->filesInSameTU.begin();
293 it != p->filesInSameTU.end() && i<numUnsavedFiles;
294 ++it, i++)
295 {
296 p->fileMapping.emplace(std::make_pair(*it,static_cast<uint32_t>(i)));
297 p->sources[i] = detab(fileToString(DString(*it),filterSourceFiles,true),refIndent);
298 p->ufs[i].Filename = dstrdup(it->c_str());
299 p->ufs[i].Contents = p->sources[i].data();
300 p->ufs[i].Length = p->sources[i].length();
301 }
302
303 // let libclang do the actual parsing
304 //for (i=0;i<argv.size();i++) printf("Argument %d: %s\n",i,argv[i]);
305 p->tu = clang_parseTranslationUnit(p->index, fileName.data(),
306 argv.data(), static_cast<int>(argv.size()), p->ufs.data(), numUnsavedFiles,
307 CXTranslationUnit_DetailedPreprocessingRecord);
308 //printf(" tu=%p\n",p->tu);
309 // free arguments
310 for (i=0;i<argv.size();++i)
311 {
312 dstrfree(argv[i]);
313 }
314
315 if (p->tu)
316 {
317 // show any warnings that the compiler produced
318 size_t n=clang_getNumDiagnostics(p->tu);
319 for (i=0; i!=n; ++i)
320 {
321 CXDiagnostic diag = clang_getDiagnostic(p->tu, static_cast<unsigned>(i));
322 CXString string = clang_formatDiagnostic(diag,
323 clang_defaultDiagnosticDisplayOptions());
324 std::string context;
325 {
326 CXFile diagFile;
327 clang_getExpansionLocation(clang_getDiagnosticLocation(diag),&diagFile,nullptr,nullptr,nullptr);
328 if (diagFile)
329 {
330 struct IncData { CXFile file; std::string text; } data { diagFile, "" };
331 clang_getInclusions(p->tu,
332 [](CXFile includedFile,CXSourceLocation *stack,unsigned len,CXClientData cd)
333 {
334 auto *d = static_cast<IncData*>(cd);
335 if (len>0 && clang_File_isEqual(includedFile,d->file) && d->text.empty())
336 {
337 // stack[0] is the direct includer, stack[len-1] the main file
338 for (unsigned k=0;k<len;k++)
339 {
340 CXFile f; unsigned line;
341 clang_getSpellingLocation(stack[k],&f,&line,nullptr,nullptr);
342 CXString fn = clang_getFileName(f);
343 d->text += std::string(k==0 ? "In file included from " : " from ")
344 + clang_getCString(fn) + ":" + std::to_string(line)
345 + (k+1==len ? ":\n" : ",\n");
346 clang_disposeString(fn);
347 }
348 if (len>0) d->text += " ";
349 }
350 },&data);
351 context = data.text;
352 }
353 }
354 err("{}{} [clang]\n",context,clang_getCString(string));
355 clang_disposeString(string);
356 clang_disposeDiagnostic(diag);
357 }
358 }
359 else
360 {
361 err("clang: Failed to parse translation unit {}\n",fileName);
362 }
363}
364
366{
367 //printf("ClangTUParser::~ClangTUParser() this=%p\n",this);
368 bool clangAssistedParsing = Config_getBool(CLANG_ASSISTED_PARSING);
369 if (!clangAssistedParsing) return;
370 if (p->tu)
371 {
372 p->cursors.clear();
373 clang_disposeTokens(p->tu,p->tokens,p->numTokens);
374 clang_disposeTranslationUnit(p->tu);
375 clang_disposeIndex(p->index);
376 p->fileMapping.clear();
377 p->tokens = nullptr;
378 p->numTokens = 0;
379 }
380 for (size_t i=0;i<p->numFiles;i++)
381 {
382 dstrfree(p->ufs[i].Filename);
383 }
384 p->ufs.clear();
385 p->sources.clear();
386 p->numFiles = 0;
387 p->tu = nullptr;
388}
389
391{
392 //printf("ClangTUParser::switchToFile(%s) this=%p\n",qPrint(fd->absFilePath()),this);
393 if (p->tu)
394 {
395 p->cursors.clear();
396 clang_disposeTokens(p->tu,p->tokens,p->numTokens);
397 p->tokens = nullptr;
398 p->numTokens = 0;
399
400 CXFile f = clang_getFile(p->tu, fd->absFilePath().data());
401 auto it = p->fileMapping.find(fd->absFilePath().data());
402 if (it!=p->fileMapping.end() && it->second < p->numFiles)
403 {
404 uint32_t i = it->second;
405 //printf("switchToFile %s: len=%ld\n",fileName,p->ufs[i].Length);
406 CXSourceLocation fileBegin = clang_getLocationForOffset(p->tu, f, 0);
407 CXSourceLocation fileEnd = clang_getLocationForOffset(p->tu, f, p->ufs[i].Length);
408 CXSourceRange fileRange = clang_getRange(fileBegin, fileEnd);
409
410 clang_tokenize(p->tu,fileRange,&p->tokens,&p->numTokens);
411 p->cursors.resize(p->numTokens);
412 clang_annotateTokens(p->tu,p->tokens,p->numTokens,p->cursors.data());
413 p->curToken = 0;
414 }
415 else
416 {
417 err("clang: Failed to find input file {} in mapping\n",fd->absFilePath());
418 }
419 }
420}
421
422std::string ClangTUParser::lookup(uint32_t line,const char *symbol)
423{
424 AUTO_TRACE("line={},symbol={}",line,symbol);
425 std::string result;
426 if (symbol==nullptr) return result;
427 bool clangAssistedParsing = Config_getBool(CLANG_ASSISTED_PARSING);
428 if (!clangAssistedParsing) return result;
429
430 auto getCurrentTokenLine = [this]() -> uint32_t
431 {
432 uint32_t l=0, c=0;
433 if (p->numTokens==0) return 1;
434 // guard against filters that reduce the number of lines
435 if (p->curToken>=p->numTokens) p->curToken=p->numTokens-1;
436 CXSourceLocation start = clang_getTokenLocation(p->tu,p->tokens[p->curToken]);
437 clang_getSpellingLocation(start, nullptr, &l, &c, nullptr);
438 return l;
439 };
440
441 int sl = strlen(symbol);
442 uint32_t l = getCurrentTokenLine();
443 while (l>=line && p->curToken>0)
444 {
445 if (l==line) // already at the right line
446 {
447 p->curToken--; // linear search to start of the line
448 l = getCurrentTokenLine();
449 }
450 else
451 {
452 p->curToken/=2; // binary search backward
453 l = getCurrentTokenLine();
454 }
455 }
456 bool found=false;
457 while (l<=line && p->curToken<p->numTokens && !found)
458 {
459 CXString tokenString = clang_getTokenSpelling(p->tu, p->tokens[p->curToken]);
460 if (l==line)
461 {
462 AUTO_TRACE_ADD("try to match symbol {} with token {}",symbol,clang_getCString(tokenString));
463 }
464 const char *ts = clang_getCString(tokenString);
465 int tl = strlen(ts);
466 int startIndex = p->curToken;
467 if (l==line && strncmp(ts,symbol,tl)==0) // found partial match at the correct line
468 {
469 int offset = tl;
470 while (offset<sl) // symbol spans multiple tokens
471 {
472 //printf("found partial match\n");
473 p->curToken++;
474 if (p->curToken>=p->numTokens)
475 {
476 break; // end of token stream
477 }
478 l = getCurrentTokenLine();
479 clang_disposeString(tokenString);
480 tokenString = clang_getTokenSpelling(p->tu, p->tokens[p->curToken]);
481 ts = clang_getCString(tokenString);
482 tl = ts ? strlen(ts) : 0;
483 // skip over any spaces in the symbol
484 char c = 0;
485 while (offset<sl && ((c=symbol[offset])==' ' || c=='\t' || c=='\r' || c=='\n'))
486 {
487 offset++;
488 }
489 if (strncmp(ts,symbol+offset,tl)!=0) // next token matches?
490 {
491 //printf("no match '%s'<->'%s'\n",ts,symbol+offset);
492 break; // no match
493 }
494 AUTO_TRACE_ADD("partial match '{}'<->'{}'",ts,symbol+offset);
495 offset+=tl;
496 }
497 if (offset==sl) // symbol matches the token(s)
498 {
499 CXCursor c = p->cursors[p->curToken];
500 CXString usr = clang_getCursorUSR(c);
501 AUTO_TRACE_ADD("found full match {} usr='{}'",symbol,clang_getCString(usr));
502 result = clang_getCString(usr);
503 clang_disposeString(usr);
504 found=true;
505 }
506 else // reset token cursor to start of the search
507 {
508 p->curToken = startIndex;
509 }
510 }
511 clang_disposeString(tokenString);
512 p->curToken++;
513 if (p->curToken<p->numTokens)
514 {
515 l = getCurrentTokenLine();
516 }
517 }
518 if (!found)
519 {
520 AUTO_TRACE_EXIT("Did not find symbol {} at line {} :-(",symbol,line);
521 }
522 else
523 {
524 AUTO_TRACE_EXIT("Found symbol {} usr={}",symbol,result);
525 }
526 return result;
527}
528
529void ClangTUParser::codeFolding(OutputCodeList &ol,const Definition *d,uint32_t line)
530{
531 if (Config_getBool(HTML_CODE_FOLDING))
532 {
533 endCodeFold(ol,line);
534 if (d)
535 {
536 int startLine = d->getStartDefLine();
537 int endLine = d->getEndBodyLine();
538 if (endLine!=-1 && startLine!=endLine &&
539 // since the end of a section is closed after the last line, we need to avoid starting a
540 // new section if the previous section ends at the same line, i.e. something like
541 // struct X {
542 // ...
543 // }; struct S { <- start of S and end of X at the same line
544 // ...
545 // };
546 (p->foldStack.empty() || p->foldStack.back()->getEndBodyLine()!=startLine))
547 {
549 {
550 const MemberDef *md = toMemberDef(d);
551 if (md && md->isDefine())
552 {
553 ol.startFold(line,"",""); // #define X ...
554 }
555 else if (md && md->isCallable())
556 {
557 ol.startFold(line,"{","}"); // func() { ... }
558 }
559 else
560 {
561 ol.startFold(line,"{","};"); // enum X { ... }
562 }
563 }
565 {
566 ol.startFold(line,"{","};"); // class X { ... };
567 }
568 else
569 {
570 ol.startFold(line,"{","}"); // namespace X {...}
571 }
572 p->foldStack.push_back(d);
573 }
574 }
575 }
576}
577
578void ClangTUParser::endCodeFold(OutputCodeList &ol,uint32_t line)
579{
580 while (!p->foldStack.empty())
581 {
582 const Definition *dd = p->foldStack.back();
583 if (dd->getEndBodyLine()+1==static_cast<int>(line))
584 {
585 ol.endFold();
586 p->foldStack.pop_back();
587 }
588 else
589 {
590 break;
591 }
592 }
593}
594
595void ClangTUParser::writeLineNumber(OutputCodeList &ol,const FileDef *fd,uint32_t line,bool writeLineAnchor)
596{
597 const Definition *d = fd ? fd->getSourceDefinition(line) : nullptr;
598 if (d)
599 {
600 p->currentLine=line;
601 const MemberDef *md = fd->getSourceMember(line);
602 //printf("writeLineNumber(%p,line=%d)\n",(void*)md,line);
603 if (md && md->isLinkable()) // link to member
604 {
605 if (p->currentMemberDef!=md) // new member, start search for body
606 {
607 p->searchForBody=true;
608 p->insideBody=false;
609 p->bracketCount=0;
610 }
611 p->currentMemberDef=md;
612 codeFolding(ol,md,line);
614 md->getOutputFileBase(),
615 md->anchor(),
616 line,writeLineAnchor);
617 }
618 else if (d->isLinkable()) // link to compound
619 {
620 p->currentMemberDef=nullptr;
621 codeFolding(ol,d,line);
624 d->anchor(),
625 line,writeLineAnchor);
626 }
627 else // no link
628 {
629 codeFolding(ol,nullptr,line);
630 ol.writeLineNumber(DString(),DString(),DString(),line,writeLineAnchor);
631 }
632 }
633 else // no link
634 {
635 codeFolding(ol,nullptr,line);
636 ol.writeLineNumber(DString(),DString(),DString(),line,writeLineAnchor);
637 }
638
639 // set search page target
640 if (Doxygen::searchIndex.enabled())
641 {
642 DString lineAnchor;
643 lineAnchor.sprintf("l%05d",line);
644 Doxygen::searchIndex.setCurrentDoc(fd,lineAnchor,true);
645 }
646
647 //printf("writeLineNumber(%d) g_searchForBody=%d\n",line,g_searchForBody);
648}
649
650void ClangTUParser::codifyLines(OutputCodeList &ol,const FileDef *fd,const char *text,
651 uint32_t &line,uint32_t &column,const char *fontClass)
652{
653 if (fontClass) ol.startFontClass(fontClass);
654 const char *p=text,*sp=p;
655 char c = 0;
656 bool inlineCodeFragment = false;
657 bool done=false;
658 while (!done)
659 {
660 sp=p;
661 while ((c=*p++) && c!='\n') { column++; }
662 if (c=='\n')
663 {
664 line++;
665 size_t l = static_cast<size_t>(p-sp-1);
666 column=l+1;
667 ol.codify(DString(sp,l));
668 if (fontClass) ol.endFontClass();
669 ol.endCodeLine();
670 writeLineNumber(ol,fd,line,inlineCodeFragment);
671 ol.startCodeLine(line);
672 if (fontClass) ol.startFontClass(fontClass);
673 }
674 else
675 {
676 ol.codify(sp);
677 done=true;
678 }
679 }
680 if (fontClass) ol.endFontClass();
681}
682
684 const FileDef *fd,uint32_t &line,uint32_t &column,
685 const Definition *d,
686 const char *text)
687{
688 bool sourceTooltips = Config_getBool(SOURCE_TOOLTIPS);
689 p->tooltipManager.addTooltip(d);
690 DString ref = d->getReference();
691 DString file = d->getOutputFileBase();
692 DString anchor = d->anchor();
693 DString tooltip;
694 if (!sourceTooltips) // fall back to simple "title" tooltips
695 {
696 tooltip = d->briefDescriptionAsTooltip();
697 }
698 bool inlineCodeFragment = false;
699 bool done=false;
700 const char *p=text;
701 while (!done)
702 {
703 const char *sp=p;
704 char c = 0;
705 while ((c=*p++) && c!='\n') { column++; }
706 if (c=='\n')
707 {
708 line++;
709 //printf("writeCodeLink(%s,%s,%s,%s)\n",ref,file,anchor,sp);
710 ol.writeCodeLink(d->codeSymbolType(),ref,file,anchor,DString(sp,p-sp-1),tooltip);
711 ol.endCodeLine();
712 writeLineNumber(ol,fd,line,inlineCodeFragment);
713 ol.startCodeLine(line);
714 }
715 else
716 {
717 //printf("writeCodeLink(%s,%s,%s,%s)\n",ref,file,anchor,sp);
718 ol.writeCodeLink(d->codeSymbolType(),ref,file,anchor,sp,tooltip);
719 done=true;
720 }
721 }
722}
723
725 uint32_t &line,uint32_t &column,const char *text,bool inPreprocessor)
726{
727 DString incName = text;
728 incName = incName.mid(1,incName.length()-2); // strip ".." or <..>
729 FileDef *ifd=nullptr;
730 if (!incName.empty())
731 {
732 FileName *fn = Doxygen::inputNameLinkedMap->find(incName);
733 if (fn)
734 {
735 // see if this source file actually includes the file
736 auto it = std::find_if(fn->begin(),
737 fn->end(),
738 [&fd](const auto &ifd)
739 { return fd->isIncluded(ifd->absFilePath()); });
740 bool found = it!=fn->end();
741 if (found)
742 {
743 //printf(" include file %s found=%d\n",(*it)->absFilePath().data(),found);
744 ifd = it->get();
745 }
746 }
747 }
748 if (ifd)
749 {
751 ifd->getReference(),
752 ifd->getOutputFileBase(),
753 DString(),
754 text,
756 column+=static_cast<uint32_t>(strlen(text));
757 }
758 else
759 {
760 codifyLines(ol,fd,text,line,column,inPreprocessor ? nullptr : "preprocessor");
761 }
762}
763
765 uint32_t &line,uint32_t &column,const char *text)
766{
767 MemberName *mn=Doxygen::functionNameLinkedMap->find(text);
768 if (mn)
769 {
770 for (const auto &md : *mn)
771 {
772 if (md->isDefine())
773 {
774 writeMultiLineCodeLink(ol,fd,line,column,md.get(),text);
775 return;
776 }
777 }
778 }
779 codifyLines(ol,fd,text,line,column);
780}
781
782
784 uint32_t &line,uint32_t &column,const char *text,int tokenIndex)
785{
786 AUTO_TRACE("line={} column={} text={}",line,column,text);
787 CXCursor c = p->cursors[tokenIndex];
788 CXCursorKind cKind = clang_getCursorKind(c);
789 AUTO_TRACE_ADD("cursor kind={}",(int)cKind);
790 CXCursor r = clang_getCursorReferenced(c);
791 AUTO_TRACE_ADD("cursor reference kind={}",(int)clang_getCursorKind(r));
792 if (!clang_equalCursors(r, c))
793 {
794 AUTO_TRACE_ADD("link to referenced location");
795 c=r; // link to referenced location
796 }
797 if (!clang_isDeclaration(cKind))
798 {
799 CXCursor t = clang_getSpecializedCursorTemplate(c);
800 AUTO_TRACE_ADD("cursor template kind={}",(int)clang_getCursorKind(t));
801 if (!clang_Cursor_isNull(t) && !clang_equalCursors(t,c))
802 {
803 c=t; // link to template
804 }
805 }
806 CXString usr = clang_getCursorUSR(c);
807 const char *usrStr = clang_getCString(usr);
808 AUTO_TRACE_ADD("usr={}",usrStr);
809
810 const Definition *d = nullptr;
811 auto kv = Doxygen::clangUsrMap->find(usrStr);
812 if (kv!=Doxygen::clangUsrMap->end())
813 {
814 d = kv->second;
815 }
816 if (!d)
817 {
818 DString qualifiedName = getQualifiedCursorName(c);
819 d = getClass(qualifiedName);
820 }
821 if (d==0)
822 {
823 AUTO_TRACE_ADD("didn't find definition for '{}' usr='{}' kind={}",
824 text,usrStr,(int)clang_getCursorKind(c));
825 }
826 else
827 {
828 AUTO_TRACE_ADD("found definition for '{}' usr='{}' name='{}'",
829 text,usrStr,d->name().data());
830 }
831
832 if (d && d->isLinkable())
833 {
834 //printf("linkIdentifier(%s) p->insideBody=%d p->currentMemberDef=%p\n",text,p->insideBody,(void*)p->currentMemberDef);
835 if (p->insideBody &&
836 p->currentMemberDef && d->definitionType()==Definition::TypeMember &&
837 (p->currentMemberDef!=d || p->currentLine<line)) // avoid self-reference
838 {
839 std::lock_guard<std::mutex> lock(g_docCrossReferenceMutex);
840 addDocCrossReference(p->currentMemberDef,toMemberDef(d));
841 }
842 writeMultiLineCodeLink(ol,fd,line,column,d,text);
843 }
844 else
845 {
846 codifyLines(ol,fd,text,line,column);
847 }
848 clang_disposeString(usr);
849}
850
851void ClangTUParser::detectFunctionBody(const char *s)
852{
853 //printf("punct=%s g_searchForBody=%d g_insideBody=%d g_bracketCount=%d\n",
854 // s,g_searchForBody,g_insideBody,g_bracketCount);
855
856 if (p->searchForBody && (dstrcmp(s,":")==0 || dstrcmp(s,"{")==0)) // start of 'body' (: is for constructor)
857 {
858 p->searchForBody=false;
859 p->insideBody=true;
860 }
861 else if (p->searchForBody && dstrcmp(s,";")==0) // declaration only
862 {
863 p->searchForBody=false;
864 p->insideBody=false;
865 }
866 if (p->insideBody && dstrcmp(s,"{")==0) // increase scoping level
867 {
868 p->bracketCount++;
869 }
870 if (p->insideBody && dstrcmp(s,"}")==0) // decrease scoping level
871 {
872 p->bracketCount--;
873 if (p->bracketCount<=0) // got outside of function body
874 {
875 p->insideBody=false;
876 p->bracketCount=0;
877 }
878 }
879}
880
882{
883 AUTO_TRACE("file={}",fd->name());
884 // (re)set global parser state
885 p->currentMemberDef=nullptr;
886 p->currentLine=0;
887 p->searchForBody=false;
888 p->insideBody=false;
889 p->bracketCount=0;
890 p->foldStack.clear();
891
892 unsigned int line=1,column=1;
893 DString lineNumber,lineAnchor;
894 bool inlineCodeFragment = false;
895 auto getIncludeText = [this](unsigned int start,unsigned int &end)
896 {
897 std::string includeName;
898 end=start;
899 if (start>=p->numTokens ||
900 clang_getCursorKind(p->cursors[start])!=CXCursor_InclusionDirective)
901 {
902 return includeName;
903 }
904 CXTokenKind firstKind=clang_getTokenKind(p->tokens[start]);
905 if (firstKind==CXToken_Literal)
906 {
907 CXString tokenString=clang_getTokenSpelling(p->tu,p->tokens[start]);
908 includeName=clang_getCString(tokenString);
909 clang_disposeString(tokenString);
910 return includeName;
911 }
912 CXString firstTokenString=clang_getTokenSpelling(p->tu,p->tokens[start]);
913 const char *firstToken=clang_getCString(firstTokenString);
914 if (firstKind!=CXToken_Punctuation || strcmp(firstToken,"<")!=0)
915 {
916 clang_disposeString(firstTokenString);
917 return includeName;
918 }
919 includeName=firstToken;
920 clang_disposeString(firstTokenString);
921 unsigned int previousLine=0,previousColumn=0;
922 CXSourceLocation firstStart=clang_getTokenLocation(p->tu,p->tokens[start]);
923 clang_getSpellingLocation(firstStart,nullptr,&previousLine,&previousColumn,nullptr);
924 size_t previousTokenLength=1;
925 for (unsigned int j=start+1;j<p->numTokens;j++)
926 {
927 if (clang_getCursorKind(p->cursors[j])!=CXCursor_InclusionDirective) break;
928 CXString nextTokenString=clang_getTokenSpelling(p->tu,p->tokens[j]);
929 const char *nextToken=clang_getCString(nextTokenString);
930 unsigned int nextLine=0,nextColumn=0;
931 CXSourceLocation nextStart=clang_getTokenLocation(p->tu,p->tokens[j]);
932 clang_getSpellingLocation(nextStart,nullptr,&nextLine,&nextColumn,nullptr);
933 if (nextLine==previousLine &&
934 nextColumn>previousColumn+previousTokenLength)
935 {
936 includeName.append(nextColumn-previousColumn-previousTokenLength,' ');
937 }
938 includeName+=nextToken;
939 previousLine=nextLine;
940 previousColumn=nextColumn;
941 previousTokenLength=strlen(nextToken);
942 end=j;
943 bool closed=clang_getTokenKind(p->tokens[j])==CXToken_Punctuation &&
944 strcmp(nextToken,">")==0;
945 clang_disposeString(nextTokenString);
946 if (closed) return includeName;
947 }
948 return std::string();
949 };
950 writeLineNumber(ol,fd,line,!inlineCodeFragment);
951 ol.startCodeLine(line);
952 for (unsigned int i=0;i<p->numTokens;i++)
953 {
954 CXSourceLocation start = clang_getTokenLocation(p->tu, p->tokens[i]);
955 unsigned int l=0, c=0;
956 clang_getSpellingLocation(start, nullptr, &l, &c, nullptr);
957 if (l > line) column = 1;
958 while (line<l)
959 {
960 line++;
961 ol.endCodeLine();
962 writeLineNumber(ol,fd,line,!inlineCodeFragment);
963 ol.startCodeLine(line);
964 }
965 while (column<c) { ol.codify(" "); column++; }
966 CXString tokenString = clang_getTokenSpelling(p->tu, p->tokens[i]);
967 char const *s = clang_getCString(tokenString);
968 CXCursorKind cursorKind = clang_getCursorKind(p->cursors[i]);
969 CXTokenKind tokenKind = clang_getTokenKind(p->tokens[i]);
970 //printf("%d:%d %s cursorKind=%d tokenKind=%d\n",line,column,s,cursorKind,tokenKind);
971 if (tokenKind==CXToken_Punctuation &&
972 strcmp(s,"#")==0 && i+1<p->numTokens)
973 {
974 CXString nextTokenString = clang_getTokenSpelling(p->tu,p->tokens[i+1]);
975 const char *nextToken = clang_getCString(nextTokenString);
976 unsigned int nextLine=0,nextColumn=0;
977 CXSourceLocation nextStart = clang_getTokenLocation(p->tu,p->tokens[i+1]);
978 clang_getSpellingLocation(nextStart,nullptr,&nextLine,&nextColumn,nullptr);
979 if (nextLine==line &&
980 strcmp(nextToken,"include")==0)
981 {
982 std::string directive="#";
983 if (nextColumn>column+1) directive.append(nextColumn-column-1,' ');
984 directive+=nextToken;
985 unsigned int includeEnd=i+1;
986 std::string includeName=getIncludeText(i+2,includeEnd);
987 if (!includeName.empty())
988 {
989 ol.startFontClass("preprocessor");
990 ol.codify(directive.c_str());
991 column+=static_cast<uint32_t>(directive.length());
992 unsigned int includeLine=0,includeColumn=0;
993 CXSourceLocation includeStart=clang_getTokenLocation(p->tu,p->tokens[i+2]);
994 clang_getSpellingLocation(includeStart,nullptr,&includeLine,&includeColumn,nullptr);
995 while (line<includeLine)
996 {
997 line++;
998 ol.endCodeLine();
999 writeLineNumber(ol,fd,line,!inlineCodeFragment);
1000 ol.startCodeLine(line);
1001 column=1;
1002 }
1003 while (column<includeColumn) { ol.codify(" "); column++; }
1004 linkInclude(ol,fd,line,column,includeName.c_str(),true);
1005 ol.endFontClass();
1006 clang_disposeString(nextTokenString);
1007 clang_disposeString(tokenString);
1008 i=includeEnd;
1009 continue;
1010 }
1011 codifyLines(ol,fd,directive.c_str(),line,column,"preprocessor");
1012 clang_disposeString(nextTokenString);
1013 clang_disposeString(tokenString);
1014 ++i;
1015 continue;
1016 }
1017 clang_disposeString(nextTokenString);
1018 }
1019 switch (tokenKind)
1020 {
1021 case CXToken_Keyword:
1022 if (strcmp(s,"operator")==0)
1023 {
1024 linkIdentifier(ol,fd,line,column,s,i);
1025 }
1026 else
1027 {
1028 codifyLines(ol,fd,s,line,column,
1029 cursorKind==CXCursor_PreprocessingDirective ? "preprocessor" :
1030 keywordToType(s));
1031 }
1032 break;
1033 case CXToken_Literal:
1034 if (cursorKind==CXCursor_InclusionDirective)
1035 {
1036 linkInclude(ol,fd,line,column,s);
1037 }
1038 else if (s[0]=='"' || s[0]=='\'')
1039 {
1040 codifyLines(ol,fd,s,line,column,"stringliteral");
1041 }
1042 else
1043 {
1044 codifyLines(ol,fd,s,line,column);
1045 }
1046 break;
1047 case CXToken_Comment:
1048 codifyLines(ol,fd,s,line,column,"comment");
1049 break;
1050 default: // CXToken_Punctuation or CXToken_Identifier
1051 if (tokenKind==CXToken_Punctuation)
1052 {
1054 //printf("punct %s: %d\n",s,cursorKind);
1055 }
1056 switch (cursorKind)
1057 {
1058 case CXCursor_PreprocessingDirective:
1059 codifyLines(ol,fd,s,line,column,"preprocessor");
1060 break;
1061 case CXCursor_MacroDefinition:
1062 codifyLines(ol,fd,s,line,column,"preprocessor");
1063 break;
1064 case CXCursor_InclusionDirective:
1065 if (tokenKind==CXToken_Punctuation && strcmp(s,"<")==0)
1066 {
1067 unsigned int end=i;
1068 std::string includeName=getIncludeText(i,end);
1069 if (!includeName.empty())
1070 {
1071 linkInclude(ol,fd,line,column,includeName.c_str());
1072 i=end;
1073 }
1074 else
1075 {
1076 codifyLines(ol,fd,s,line,column,"preprocessor");
1077 }
1078 }
1079 else
1080 {
1081 linkInclude(ol,fd,line,column,s);
1082 }
1083 break;
1084 case CXCursor_MacroExpansion:
1085 linkMacro(ol,fd,line,column,s);
1086 break;
1087 default:
1088 if (tokenKind==CXToken_Identifier ||
1089 (tokenKind==CXToken_Punctuation && // for operators
1090 (cursorKind==CXCursor_DeclRefExpr ||
1091 cursorKind==CXCursor_MemberRefExpr ||
1092 cursorKind==CXCursor_CallExpr ||
1093 cursorKind==CXCursor_ObjCMessageExpr)
1094 )
1095 )
1096 {
1097 linkIdentifier(ol,fd,line,column,s,i);
1098 if (Doxygen::searchIndex.enabled())
1099 {
1101 }
1102 }
1103 else
1104 {
1105 codifyLines(ol,fd,s,line,column);
1106 }
1107 break;
1108 }
1109 }
1110 clang_disposeString(tokenString);
1111 }
1112 ol.endCodeLine();
1113 if (Config_getBool(HTML_CODE_FOLDING))
1114 {
1115 while (!p->foldStack.empty())
1116 {
1117 ol.endFold();
1118 p->foldStack.pop_back();
1119 }
1120 }
1121 p->tooltipManager.writeTooltips(ol);
1122}
1123
1124//--------------------------------------------------------------------------
1125
1127{
1128 public:
1129 Private()
1130 {
1131 std::string error;
1132 DString clangCompileDatabase = Config_getString(CLANG_DATABASE_PATH);
1133 // load a clang compilation database (https://clang.llvm.org/docs/JSONCompilationDatabase.html)
1134 db = clang::tooling::CompilationDatabase::loadFromDirectory(clangCompileDatabase.data(), error);
1135 if (!clangCompileDatabase.empty() && clangCompileDatabase!="0" && db==nullptr)
1136 {
1137 // user specified a path, but DB file was not found
1138 err("{} using clang compilation database path of: \"{}\"\n", error, clangCompileDatabase);
1139 }
1140 }
1141
1142 std::unique_ptr<clang::tooling::CompilationDatabase> db;
1143};
1144
1145const clang::tooling::CompilationDatabase *ClangParser::database() const
1146{
1147 return p->db.get();
1148}
1149
1150ClangParser::ClangParser() : p(std::make_unique<Private>())
1151{
1152}
1153
1155{
1156}
1157
1158std::unique_ptr<ClangTUParser> ClangParser::createTUParser(const FileDef *fd) const
1159{
1160 //printf("ClangParser::createTUParser()\n");
1161 return std::make_unique<ClangTUParser>(*this,fd);
1162}
1163
1164
1165//--------------------------------------------------------------------------
1166#else // use stubbed functionality in case libclang support is disabled.
1167
1169{
1170};
1171
1173{
1174}
1175
1177{
1178}
1179
1181{
1182}
1183
1187
1188std::string ClangTUParser::lookup(uint32_t,const char *)
1189{
1190 return std::string();
1191}
1192
1194{
1195};
1196
1198{
1199}
1200
1204
1205std::unique_ptr<ClangTUParser> ClangParser::createTUParser(const FileDef *) const
1206{
1207 return nullptr;
1208}
1209
1210#endif
1211//--------------------------------------------------------------------------
1212
static std::mutex g_clangMutex
Wrapper for to let libclang assisted parsing.
Definition clangparser.h:80
static ClangParser * s_instance
Definition clangparser.h:94
std::unique_ptr< ClangTUParser > createTUParser(const FileDef *fd) const
virtual ~ClangParser()
const clang::tooling::CompilationDatabase * database() const
static ClangParser * instance()
Returns the one and only instance of the class.
std::unique_ptr< Private > p
Definition clangparser.h:90
StringVector filesInSameTU() const
Returns the list of files for this translation unit.
ClangTUParser(const ClangParser &parser, const FileDef *fd)
void linkIdentifier(OutputCodeList &ol, const FileDef *fd, uint32_t &line, uint32_t &column, const char *text, int tokenIndex)
void endCodeFold(OutputCodeList &ol, uint32_t line)
void writeLineNumber(OutputCodeList &ol, const FileDef *fd, uint32_t line, bool writeLineAnchor)
void codeFolding(OutputCodeList &ol, const Definition *d, uint32_t line)
void switchToFile(const FileDef *fd)
Switches to another file within the translation unit started with start().
void parse()
Parse the file given at construction time as a translation unit This file should already be preproces...
virtual ~ClangTUParser()
void codifyLines(OutputCodeList &ol, const FileDef *fd, const char *text, uint32_t &line, uint32_t &column, const char *fontClass=nullptr)
void linkMacro(OutputCodeList &ol, const FileDef *fd, uint32_t &line, uint32_t &column, const char *text)
std::string lookup(uint32_t line, const char *symbol)
Looks for symbol which should be found at line.
std::unique_ptr< Private > p
Definition clangparser.h:75
void linkInclude(OutputCodeList &ol, const FileDef *fd, uint32_t &line, uint32_t &column, const char *text, bool inPreprocessor=false)
void writeMultiLineCodeLink(OutputCodeList &ol, const FileDef *fd, uint32_t &line, uint32_t &column, const Definition *d, const char *text)
void detectFunctionBody(const char *s)
void writeSources(OutputCodeList &ol, const FileDef *fd)
writes the syntax highlighted source code for a file
DString mid(size_t index, size_t len=npos) const
Definition dstring.h:318
DString lower() const
Definition dstring.h:326
bool empty() const
Returns true iff the string is empty (std::string compatible alias for isEmpty()).
Definition dstring.h:148
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
size_t length() const
Returns the length of the string, not counting the 0-terminator.
Definition dstring.h:151
The common base class of all entity definitions found in the sources.
Definition definition.h:77
virtual int getEndBodyLine() const =0
virtual bool isLinkable() const =0
virtual DefType definitionType() const =0
virtual const DString & name() const =0
virtual DString briefDescriptionAsTooltip() const =0
virtual DString anchor() const =0
virtual int getStartDefLine() const =0
virtual DString getReference() const =0
virtual CodeSymbolType codeSymbolType() const =0
virtual DString getOutputFileBase() const =0
static StringUnorderedSet inputPaths
Definition doxygen.h:96
static FileNameLinkedMap * inputNameLinkedMap
Definition doxygen.h:97
static MemberNameLinkedMap * functionNameLinkedMap
Definition doxygen.h:105
static SearchIndexIntf searchIndex
Definition doxygen.h:117
static ClangUsrMap * clangUsrMap
Definition doxygen.h:119
A model of a file symbol.
Definition filedef.h:97
virtual const Definition * getSourceDefinition(int lineNr) const =0
virtual const MemberDef * getSourceMember(int lineNr) const =0
virtual DString absFilePath() const =0
const T * find(const std::string &key) const
Definition linkedmap.h:47
virtual bool isDefine() const =0
virtual bool isCallable() const =0
Class representing a list of different code generators.
Definition outputlist.h:162
void writeLineNumber(const DString &ref, const DString &file, const DString &anchor, int lineNumber, bool writeLineAnchor)
Definition outputlist.h:253
void endCodeLine()
Definition outputlist.h:264
void startFold(int lineNr, const DString &startMarker, const DString &endMarker)
Definition outputlist.h:282
void writeCodeLink(CodeSymbolType type, const DString &ref, const DString &file, const DString &anchor, const DString &name, const DString &tooltip)
Definition outputlist.h:247
void endFontClass()
Definition outputlist.h:270
void startFontClass(const DString &c)
Definition outputlist.h:267
void startCodeLine(int lineNr)
Definition outputlist.h:261
void codify(const DString &s)
Definition outputlist.h:232
void addWord(const DString &word, bool hiPriority)
void setCurrentDoc(const Definition *ctx, const DString &anchor, bool isSourceFile)
ClassDef * getClass(const DString &n)
#define Config_getList(name)
Definition config.h:38
#define Config_getBool(name)
Definition config.h:33
#define Config_getString(name)
Definition config.h:32
std::unordered_set< std::string > StringUnorderedSet
Definition containers.h:29
std::vector< std::string > StringVector
Definition containers.h:33
DirIterator end(const DirIterator &) noexcept
Definition dir.cpp:180
#define AUTO_TRACE_ADD(...)
Definition docnode.cpp:54
#define AUTO_TRACE(...)
Definition docnode.cpp:53
#define AUTO_TRACE_EXIT(...)
Definition docnode.cpp:55
void dstrfree(const char *str)
Frees the memory allocated using dstrdup().
Definition dstring.cpp:431
char * dstrdup(const char *str)
Definition dstring.cpp:424
int dstrcmp(const char *str1, const char *str2)
Definition dstring.h:50
void addDocCrossReference(const MemberDef *s, const MemberDef *d)
MemberDef * toMemberDef(Definition *d)
#define err(fmt,...)
Definition message.h:127
#define ASSERT(x)
Definition message.h:142
const char * name(int level)
Definition latexgen.h:368
Definition dstring.h:913
Web server based search engine.
SrcLangExt
Definition types.h:207
Various UTF8 related helper functions.
DString detab(const DString &s, size_t &refIndent)
Definition util.cpp:5330
SrcLangExt getLanguageFromFileName(const DString &fileName, SrcLangExt defLang)
Definition util.cpp:4300
DString fileToString(const DString &name, bool filter, bool isSourceCode)
Definition util.cpp:1058
A bunch of utility functions.