Doxygen
Loading...
Searching...
No Matches
linkifytext.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 header
17#include "linkifytext.h"
18
19#include <algorithm>
20#include <string>
21
22// other includes
23#include "classdef.h"
24#include "conceptdef.h"
25#include "filedef.h"
26#include "memberdef.h"
27#include "regex.h"
28#include "symbolresolver.h"
29#include "trace.h"
30#include "util.h"
31
32// Returns the name of the template parameter declared by \a a, or an empty string if it cannot be determined.
33static std::string templateParameterName(const Argument &a,SrcLangExt lang)
34{
35 bool fromType = a.name.empty(); // type parameters like "typename T" have their name in the type
36 std::string_view s = fromType ? a.type.view() : a.name.view();
37 auto isSpaceOrDot = [](char c) { return c==' ' || c=='\t' || c=='\n' || c=='.'; };
38 while (!s.empty() && isSpaceOrDot(s.back())) s.remove_suffix(1); // also strips parameter pack ellipsis
39 size_t end = s.length();
40 size_t start = end;
41 while (start>0 && isId(s[start-1])) start--;
42 if (start==end) return std::string();
43 if (fromType)
44 {
45 std::string_view prefix = s.substr(0,start);
46 while (!prefix.empty() && isSpaceOrDot(prefix.back())) prefix.remove_suffix(1);
47 auto endsWithKeyword = [&prefix](std::string_view kw)
48 {
49 return prefix.length()>=kw.length() &&
50 prefix.substr(prefix.length()-kw.length())==kw &&
51 (prefix.length()==kw.length() || !isId(prefix[prefix.length()-kw.length()-1]));
52 };
53 bool hasKeyword = endsWithKeyword("class") || endsWithKeyword("typename") || endsWithKeyword("struct") || endsWithKeyword("record");
54 // in C# and Java the type parameter is just an identifier
55 if (!hasKeyword && !(prefix.empty() && lang!=SrcLangExt::Cpp)) return std::string();
56 }
57 return std::string(s.substr(start));
58}
59
60static void addTemplateParameterNames(const ArgumentList &al,SrcLangExt lang,std::vector<std::string> &names)
61{
62 for (const Argument &a : al)
63 {
64 std::string name = templateParameterName(a,lang);
65 if (!name.empty()) names.push_back(std::move(name));
66 }
67}
68
69// Collects the names of the template parameters that are in effect for the
70// definitions in \a options. These names hide any symbol with the same name.
71static std::vector<std::string> getTemplateParameterNames(const LinkifyTextOptions &options)
72{
73 std::vector<std::string> names;
74 for (const ArgumentList *al : options.templateArgumentLists())
75 {
76 if (al) addTemplateParameterNames(*al,options.scope() ? options.scope()->getLanguage() : SrcLangExt::Cpp,names);
77 }
78 auto addScopes = [&names](const Definition *d)
79 {
80 for (; d; d=d->getOuterScope())
81 {
82 SrcLangExt lang = d->getLanguage();
83 if (d->definitionType()==Definition::TypeClass)
84 {
85 const ClassDef *cd = toClassDef(d);
86 if (cd->templateMaster()==nullptr) // template instances have their arguments substituted
87 {
89 }
90 }
91 else if (d->definitionType()==Definition::TypeMember)
92 {
93 const MemberDef *md = toMemberDef(d);
96 {
97 addTemplateParameterNames(al,lang,names);
98 }
99 }
100 else if (d->definitionType()==Definition::TypeConcept)
101 {
102 addTemplateParameterNames(toConceptDef(d)->getTemplateParameterList(),lang,names);
103 }
104 else
105 {
106 break;
107 }
108 }
109 };
110 addScopes(options.self());
111 if (options.scope()!=options.self()) addScopes(options.scope());
112 return names;
113}
114
115void linkifyText(const TextGeneratorIntf &out, const DString &text,
116 const LinkifyTextOptions &options)
117{
118 const Definition *scope = options.scope();
119 const FileDef *fileScope = options.fileScope();
120 const Definition *self = options.self();
121 AUTO_TRACE("scope={} fileScope={} text={} autoBreak={} external={} keepSpaces={} indentLevel={}",
122 scope?scope->name():"",fileScope?fileScope->name():"",
123 text,options.autoBreak(),options.external(),options.keepSpaces(),options.indentLevel());
124 if (text.empty()) return;
125
126 //printf("linkify='%s'\n",qPrint(text));
127 std::string_view txtStr=text.view();
128 size_t strLen = txtStr.length();
129 if (strLen==0) return;
130
131 static const reg::Ex regExp(R"((::)?\a[\w~!\\.:$"]*)");
132 reg::Iterator it(txtStr,regExp);
134
135 //printf("linkifyText scope=%s fileScope=%s strtxt=%s strlen=%zu external=%d\n",
136 // scope ? qPrint(scope->name()):"<none>",
137 // fileScope ? qPrint(fileScope->name()) : "<none>",
138 // qPrint(txtStr),strLen,options.external());
139 const std::vector<std::string> templateNames = getTemplateParameterNames(options);
140 size_t index=0;
141 size_t skipIndex=0;
142 size_t floatingIndex=0;
143 for (; it!=end ; ++it) // for each word from the text string
144 {
145 const auto &match = *it;
146 size_t newIndex = match.position();
147 size_t matchLen = match.length();
148 floatingIndex+=newIndex-skipIndex+matchLen;
149 if (newIndex>0 && txtStr.at(newIndex-1)=='0') // ignore hex numbers (match x00 in 0x00)
150 {
151 std::string_view part = txtStr.substr(skipIndex,newIndex+matchLen-skipIndex);
152 out.writeString(part,options.keepSpaces());
153 skipIndex=index=newIndex+matchLen;
154 continue;
155 }
156
157 // add non-word part to the result
158 bool insideString=false;
159 for (size_t i=index;i<newIndex;i++)
160 {
161 if (txtStr.at(i)=='"') insideString=!insideString;
162 if (txtStr.at(i)=='\\') i++; // skip next character it is escaped
163 }
164
165 //printf("floatingIndex=%d strlen=%d autoBreak=%d\n",floatingIndex,strLen,options.autoBreak());
166 if (strLen>options.breakThreshold()+5 && floatingIndex>options.breakThreshold() &&
167 options.autoBreak()) // try to insert a split point
168 {
169 std::string_view splitText = txtStr.substr(skipIndex,newIndex-skipIndex);
170 size_t splitLength = splitText.length();
171 size_t offset=1;
172 size_t i = splitText.find(',');
173 if (i==std::string::npos) { i=splitText.find('<'); if (i!=std::string::npos) offset=0; }
174 if (i==std::string::npos) { i=splitText.find("||"); if (i!=std::string::npos) offset=2; }
175 if (i==std::string::npos) { i=splitText.find("&&"); if (i!=std::string::npos) offset=2; }
176 if (i==std::string::npos) { i=splitText.find(">>"); if (i!=std::string::npos) offset=2; }
177 if (i==std::string::npos) i=splitText.find('>');
178 if (i==std::string::npos) i=splitText.find(' ');
179 //printf("splitText=[%s] len=%d i=%d offset=%d\n",qPrint(splitText),splitLength,i,offset);
180 if (i!=std::string::npos) // add a link-break at i in case of Html output
181 {
182 std::string_view part1 = splitText.substr(0,i+offset);
183 out.writeString(part1,options.keepSpaces());
184 out.writeBreak(options.indentLevel()==0 ? 0 : options.indentLevel()+1);
185 std::string_view part2 = splitText.substr(i+offset);
186 out.writeString(part2,options.keepSpaces());
187 floatingIndex=splitLength-i-offset+matchLen;
188 }
189 else
190 {
191 out.writeString(splitText,options.keepSpaces());
192 }
193 }
194 else
195 {
196 //ol.docify(txtStr.mid(skipIndex,newIndex-skipIndex));
197 std::string_view part = txtStr.substr(skipIndex,newIndex-skipIndex);
198 out.writeString(part,options.keepSpaces());
199 }
200 // get word from string
201 std::string_view word=txtStr.substr(newIndex,matchLen);
202 DString matchWord = substitute(substitute(word,"\\","::"),".","::");
203 bool found=false;
204 // check for argument name
205 if (options.argumentList())
206 {
207 for (auto it1 = options.argumentList()->begin(); it1!=options.argumentList()->end(); ++it1)
208 {
209 if (it1->name == matchWord)
210 {
211 out.writeString(matchWord.data(),options.keepSpaces());
212 found = true;
213 break;
214 }
215 }
216 }
217 // check for template parameter name
218 if (!found && !templateNames.empty())
219 {
220 std::string_view plainWord = word;
221 while (!plainWord.empty() && plainWord.back()=='.') plainWord.remove_suffix(1); // parameter pack
222 if (std::find(templateNames.begin(),templateNames.end(),plainWord)!=templateNames.end())
223 {
224 out.writeString(word,options.keepSpaces());
225 found = true;
226 }
227 }
228 //printf("linkifyText word=%s matchWord=%s scope=%s\n",
229 // qPrint(word),qPrint(matchWord),scope ? qPrint(scope->name()) : "<none>");
230 if (!insideString && !found)
231 {
232 const ClassDef *cd=nullptr;
233 const ConceptDef *cnd=nullptr;
234 const Definition *d=nullptr;
235 //printf("** Match word '%s'\n",qPrint(matchWord));
236
237 SymbolResolver resolver(fileScope);
238 cd=resolver.resolveClass(scope,matchWord);
239 const MemberDef *typeDef = resolver.getTypedef();
240 if (typeDef) // First look at typedef then class, see bug 584184.
241 {
242 if (options.external() ? typeDef->isLinkable() : typeDef->isLinkableInProject())
243 {
244 if (typeDef->getOuterScope()!=self)
245 {
246 //printf("Found typedef %s word='%s'\n",qPrint(typeDef->name()),qPrint(word));
247 out.writeLink(typeDef->getReference(),
248 typeDef->getOutputFileBase(),
249 typeDef->anchor(),
250 word);
251 found=true;
252 }
253 }
254 }
255 auto writeCompoundName = [&](const auto *cd_) {
256 if (options.external() ? cd_->isLinkable() : cd_->isLinkableInProject())
257 {
258 if (self==nullptr || cd_->qualifiedName()!=self->qualifiedName())
259 {
260 //printf("Found compound %s word='%s'\n",qPrint(cd->name()),qPrint(word));
261 out.writeLink(cd_->getReference(),cd_->getOutputFileBase(),cd_->anchor(),word);
262 found=true;
263 }
264 }
265 };
266
267 if (found)
268 {
269 //printf(" -> skip\n");
270 }
271 else if ((cd=getClass(matchWord)))
272 {
273 writeCompoundName(cd);
274 }
275 else if ((cd=getClass(matchWord+"-p"))) // search for Obj-C protocols as well
276 {
277 writeCompoundName(cd);
278 }
279 else if ((cnd=getConcept(matchWord))) // search for concepts
280 {
281 writeCompoundName(cnd);
282 }
283 else if ((d=resolver.resolveSymbol(scope,matchWord)))
284 {
285 writeCompoundName(d);
286 }
287 else
288 {
289 //printf(" -> nothing\n");
290 }
291
292 size_t m = matchWord.rfind("::");
293 DString scopeName;
294 if (scope &&
297 )
298 )
299 {
300 scopeName=scope->name();
301 }
302 else if (m!=DString::npos)
303 {
304 scopeName = matchWord.left(m);
305 matchWord = matchWord.mid(m+2);
306 }
307
308 //printf("ScopeName=%s\n",qPrint(scopeName));
309 //if (!found) printf("Trying to link '%s' in '%s'\n",qPrint(word),qPrint(scopeName));
310 if (!found)
311 {
312 GetDefInput input(scopeName,matchWord,DString());
313 GetDefResult result = getDefs(input);
314 if (result.found && result.md &&
315 (options.external() ? result.md->isLinkable() : result.md->isLinkableInProject())
316 )
317 {
318 //printf("Found ref scope=%s\n",d ? qPrint(d->name()) : "<global>");
319 //ol.writeObjectLink(d->getReference(),d->getOutputFileBase(),
320 // md->anchor(),word);
321 if (result.md!=self && (self==nullptr || result.md->name()!=self->name()))
322 // name check is needed for overloaded members, where getDefs just returns one
323 {
324 /* in case of Fortran scope and the variable is a non Fortran variable: don't link,
325 * see also getLink in fortrancode.l
326 */
327 if (!(scope &&
328 (scope->getLanguage() == SrcLangExt::Fortran) &&
329 result.md->isVariable() &&
330 (result.md->getLanguage() != SrcLangExt::Fortran)
331 )
332 )
333 {
334 //printf("found symbol %s word='%s'\n",qPrint(result.md->name()),qPrint(word));
335 out.writeLink(result.md->getReference(),result.md->getOutputFileBase(),
336 result.md->anchor(),word);
337 found=true;
338 }
339 }
340 }
341 }
342 }
343
344 if (!found) // add word to the result
345 {
346 out.writeString(word,options.keepSpaces());
347 }
348 // set next start point in the string
349 //printf("index=%d/%d\n",index,txtStr.length());
350 skipIndex=index=newIndex+matchLen;
351 }
352 // add last part of the string to the result.
353 std::string_view lastPart = txtStr.substr(skipIndex);
354 out.writeString(lastPart,options.keepSpaces());
355}
constexpr auto prefix
Definition anchor.cpp:47
This class contains the information about the argument of a function or template.
Definition arguments.h:27
DString name
Definition arguments.h:45
DString type
Definition arguments.h:43
This class represents an function or template argument list.
Definition arguments.h:66
iterator end()
Definition arguments.h:95
iterator begin()
Definition arguments.h:94
A abstract class representing of a compound symbol.
Definition classdef.h:100
virtual const ArgumentList & templateArguments() const =0
Returns the template arguments of this class.
virtual const ClassDef * templateMaster() const =0
Returns the template master of which this class is an instance.
A String class for use with Doxygen wrapping std::string and adding some additional functionality off...
Definition dstring.h:84
size_t rfind(char c, size_t pos=npos) const
Definition dstring.h:244
DString mid(size_t index, size_t len=npos) const
Definition dstring.h:318
bool empty() const
Returns true iff the string is empty (std::string compatible alias for isEmpty()).
Definition dstring.h:148
std::string_view view() const
Definition dstring.h:162
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
DString left(size_t len) const
Definition dstring.h:306
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
The common base class of all entity definitions found in the sources.
Definition definition.h:77
virtual SrcLangExt getLanguage() const =0
Returns the programming language this definition was written in.
virtual bool isLinkable() const =0
virtual DefType definitionType() const =0
virtual const DString & name() const =0
virtual bool isLinkableInProject() const =0
virtual DString qualifiedName() const =0
virtual DString anchor() const =0
virtual DString getReference() const =0
virtual Definition * getOuterScope() const =0
virtual DString getOutputFileBase() const =0
A model of a file symbol.
Definition filedef.h:97
A model of a class/file/namespace member symbol.
Definition memberdef.h:45
virtual const ArgumentList & templateArguments() const =0
virtual const ArgumentLists & definitionTemplateParameterLists() const =0
virtual bool isVariable() const =0
const ClassDef * resolveClass(const Definition *scope, const DString &name, bool maybeUnlinkable=false, bool mayBeHidden=false)
Find the class definition matching name within the scope set.
const Definition * resolveSymbol(const Definition *scope, const DString &name, const DString &args=DString(), bool checkCV=false, bool insideCode=false, bool onlyLinkable=false)
Find the symbool definition matching name within the scope set.
const MemberDef * getTypedef() const
In case a call to resolveClass() resolves to a type member (e.g. an enum) this method will return it.
Abstract interface for a hyperlinked text fragment.
Definition linkifytext.h:31
virtual void writeString(std::string_view, bool) const =0
virtual void writeBreak(int indent) const =0
virtual void writeLink(const DString &extRef, const DString &file, const DString &anchor, std::string_view text) const =0
ClassDef * getClass(const DString &n)
ClassDef * toClassDef(Definition *d)
Class representing a regular expression.
Definition regex.h:39
Class to iterate through matches.
Definition regex.h:245
ConceptDef * getConcept(const DString &n)
ConceptDef * toConceptDef(Definition *d)
DirIterator end(const DirIterator &) noexcept
Definition dir.cpp:180
#define AUTO_TRACE(...)
Definition docnode.cpp:53
DString substitute(const DString &s, const DString &src, const DString &dst)
substitute all occurrences of src in s by dst
Definition dstring.cpp:485
bool isId(char c)
Returns true if c is a valid character for an identifier.
Definition dstring.h:895
static void addTemplateParameterNames(const ArgumentList &al, SrcLangExt lang, std::vector< std::string > &names)
static std::string templateParameterName(const Argument &a, SrcLangExt lang)
void linkifyText(const TextGeneratorIntf &out, const DString &text, const LinkifyTextOptions &options)
static std::vector< std::string > getTemplateParameterNames(const LinkifyTextOptions &options)
MemberDef * toMemberDef(Definition *d)
const MemberDef * md
Definition util.h:113
bool found
Definition util.h:112
int indentLevel() const
Definition linkifytext.h:56
bool external() const
Definition linkifytext.h:54
const ArgumentList * argumentList() const
Definition linkifytext.h:51
const Definition * scope() const
Definition linkifytext.h:48
const Definition * self() const
Definition linkifytext.h:50
size_t breakThreshold() const
Definition linkifytext.h:57
bool keepSpaces() const
Definition linkifytext.h:55
const FileDef * fileScope() const
Definition linkifytext.h:49
const std::vector< const ArgumentList * > & templateArgumentLists() const
Definition linkifytext.h:52
bool autoBreak() const
Definition linkifytext.h:53
SrcLangExt
Definition types.h:207
GetDefResult getDefs(const GetDefInput &input)
Definition util.cpp:1926
A bunch of utility functions.