Doxygen
Loading...
Searching...
No Matches
codefragment.cpp
Go to the documentation of this file.
1/******************************************************************************
2 *
3 * Copyright (C) 1997-2023 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#include <mutex>
17#include <unordered_map>
18#include <map>
19
20#include "codefragment.h"
21#include "util.h"
22#include "doxygen.h"
23#include "parserintf.h"
24#include "outputlist.h"
25#include "clangparser.h"
26#include "trace.h"
27#include "fileinfo.h"
28#include "filedef.h"
29#include "portable.h"
30#include "message.h"
31#include "filename.h"
32
34{
36 {
37 size_t indent=0;
38 std::string key;
39 std::vector<int> lines;
40 };
41
43 {
47 void findBlockMarkers();
49 std::map<int,BlockMarker> blocks;
50 std::map<std::string,const BlockMarker*> blocksById;
51 std::mutex mutex;
52 };
53
54 std::unordered_map<std::string,std::unique_ptr<FragmentInfo> > fragments;
55 std::mutex mutex;
56};
57
59{
60 AUTO_TRACE("findBlockMarkers() size={}",fileContents.size());
61 // give fileContents and a list of candidate [XYZ] labels with/without trim left flag (from commentscan?)
62 if (fileContents.empty()) return;
63
64 // find the potential snippet blocks (can also be other array like stuff in the file)
65 const char *s=fileContents.data();
66 int lineNr=1;
67 char c=0;
68 const char *foundOpen=nullptr;
69 std::unordered_map<std::string,BlockMarker> candidates;
70 while ((c=*s))
71 {
72 if (c=='[')
73 {
74 foundOpen=s;
75 }
76 else if (foundOpen && c==']' && foundOpen+1<s) // non-empty [...] section
77 {
78 std::string key(foundOpen+1,s-foundOpen-1);
79 candidates[key].lines.push_back(lineNr);
80 }
81 else if (c=='\n')
82 {
83 foundOpen=nullptr;
84 lineNr++;
85 }
86 s++;
87 }
88
89 // Sort the valid snippet blocks by line number, Look for blocks that appears twice,
90 // where candidate has block id as key and the start and end line as value.
91 // Store the key in marker.key
92 for (auto &kv : candidates)
93 {
94 auto &marker = kv.second;
95 if (marker.lines.size()==2 && marker.lines[0]+1<=marker.lines[1]-1)
96 {
97 marker.key = kv.first;
98 int startLine = marker.lines[0];
99 blocks[startLine] = marker;
100 blocksById["["+kv.first+"]"] = &blocks[startLine];
101 }
102 }
103
104 // determine the shared indentation for each line in each block, and store it in marker.indent
105 s=fileContents.data();
106 static auto gotoLine = [](const char *startBuf, const char *startPos, int startLine, int targetLine) -> const char *
107 {
108 char cc=0;
109 if (targetLine<startLine)
110 {
111 //printf("gotoLine(pos=%p,start=%d,target=%d) backward\n",(void*)startPos,startLine,targetLine);
112 while (startLine>=targetLine && startPos>=startBuf && (cc=*startPos--)) { if (cc=='\n') startLine--; }
113 if (startPos>startBuf)
114 {
115 // given fragment:
116 // line1\n
117 // line2\n
118 // line3
119 // and targetLine==2 then startPos ends at character '1' of line 1 before we detect that startLine<targetLine,
120 // so we need to advance startPos with 2 to be at the start of line2, unless we are already at the first line.
121 startPos+=2;
122 }
123 //printf("result=[%s]\n",qPrint(DString(startPos).left(20)));
124 }
125 else
126 {
127 //printf("gotoLine(pos=%p,start=%d,target=%d) forward\n",(void*)startPos,startLine,targetLine);
128 while (startLine<targetLine && (cc=*startPos++)) { if (cc=='\n') startLine++; }
129 //printf("result=[%s]\n",qPrint(DString(startPos).left(20)));
130 }
131 return startPos;
132 };
133 static auto lineIndent = [](const char *&ss, size_t orgCol) -> size_t
134 {
135 int tabSize=Config_getInt(TAB_SIZE);
136 int col = 0;
137 char cc = 0;
138 while ((cc=*ss++))
139 {
140 if (cc==' ') col++;
141 else if (cc=='\t') col+=tabSize-(col%tabSize);
142 else if (cc=='\n') return orgCol;
143 else
144 {
145 // goto end of the line
146 while ((cc=*ss++) && cc!='\n');
147 return col;
148 }
149 }
150 return orgCol;
151 };
152 lineNr=1;
153 const char *startBuf = s;
154 for (auto &kv : blocks)
155 {
156 auto &marker = kv.second;
157 s = gotoLine(startBuf,s,lineNr,marker.lines[0]+1);
158 lineNr=marker.lines[1];
159 const char *e = gotoLine(startBuf,s,marker.lines[0]+1,lineNr);
160
161 const char *ss = s;
162 size_t minIndent=100000;
163 size_t indent = minIndent;
164 while (ss<e)
165 {
166 indent = lineIndent(ss, indent);
167 if (indent<minIndent)
168 {
169 minIndent=indent;
170 if (minIndent==0) break;
171 }
172 }
173 marker.indent = minIndent;
174
175 AUTO_TRACE_ADD("found snippet key='{}' range=[{}..{}] indent={}",
176 marker.key,
177 marker.lines[0]+1,
178 marker.lines[1]-1,
179 marker.indent);
180 s=e;
181 }
182}
183
187
189
195
197{
198 AUTO_TRACE("file={}",file);
199 if (Portable::isAbsolutePath(file))
200 {
201 FileInfo fi(file.str());
202 if (fi.exists())
203 {
204 size_t indent=0;
205 return detab(fileToString(file,Config_getBool(FILTER_SOURCE_FILES)),indent);
206 }
207 }
208 StringVector examplePathList = Config_getList(EXAMPLE_PATH);
209 for (const auto &s : examplePathList)
210 {
211 std::string absFileName = s+(Portable::pathSeparator()+file).str();
212 FileInfo fi(absFileName);
213 if (fi.exists())
214 {
215 size_t indent=0;
216 return detab(fileToString(absFileName,Config_getBool(FILTER_SOURCE_FILES)),indent);
217 }
218 }
219
220 // as a fallback we also look in the exampleNameDict
221 bool ambig=false;
223 if (fd)
224 {
225 if (ambig)
226 {
227 err("included file name '{}' is ambiguous.\nPossible candidates:\n{}\n",file,
228 Doxygen::exampleNameLinkedMap->showFileDefMatches(file)
229 );
230 }
231 size_t indent = 0;
232 return detab(fileToString(fd->absFilePath(),Config_getBool(FILTER_SOURCE_FILES)),indent);
233 }
234 else
235 {
236 err("included file {} is not found. Check your EXAMPLE_PATH\n",file);
237 }
238 return DString();
239}
240
241
243 const DString & fileName,
244 const DString & blockId,
245 const DString & scopeName,
246 bool showLineNumbers,
247 bool trimLeft,
248 bool stripCodeComments
249 )
250{
251 AUTO_TRACE("CodeFragmentManager::parseCodeFragment({},blockId={},scopeName={},showLineNumber={},trimLeft={},stripCodeComments={}",
252 fileName, blockId, scopeName, showLineNumbers, trimLeft, stripCodeComments);
253 std::string fragmentKey=fileName.str()+":"+scopeName.str();
254 std::unordered_map< std::string,std::unique_ptr<Private::FragmentInfo> >::iterator it;
255 bool inserted = false;
256 {
257 // create new entry if it is not yet in the map
258 std::lock_guard lock(p->mutex);
259 it = p->fragments.find(fragmentKey);
260 if (it == p->fragments.end())
261 {
262 it = p->fragments.emplace(fragmentKey, std::make_unique<Private::FragmentInfo>()).first;
263 inserted = true;
264 AUTO_TRACE_ADD("new fragment");
265 }
266 }
267 // only lock the one item we are working with
268 auto &codeFragment = it->second;
269 std::lock_guard lock(codeFragment->mutex);
270 if (inserted) // new entry, need to parse the file and record the output and cache it
271 {
272 SrcLangExt langExt = getLanguageFromFileName(fileName);
273 FileInfo cfi( fileName.str() );
274 auto fd = createFileDef( cfi.dirPath(), cfi.fileName() );
276 intf->resetCodeParserState();
277 bool filterSourceFiles = Config_getBool(FILTER_SOURCE_FILES);
278 bool needs2PassParsing =
279 Doxygen::parseSourcesNeeded && // we need to parse (filtered) sources for cross-references
280 !filterSourceFiles && // but user wants to show sources as-is
281 !getFileFilter(fileName,true).empty(); // and there is a filter used while parsing
282 codeFragment->fileContents = readTextFileByName(fileName);
283 //printf("fileContents=[%s]\n",qPrint(codeFragment->fileContents));
284 if (needs2PassParsing)
285 {
286 OutputCodeList devNullList;
287 devNullList.add<DevNullCodeGenerator>();
288 intf->parseCode(devNullList,
289 scopeName,
290 codeFragment->fileContents,
291 langExt,
292 stripCodeComments, // actually not important here
294 );
295 }
296 codeFragment->findBlockMarkers();
297 if (!codeFragment->fileContents.empty()) // parse the normal version
298 {
299 intf->parseCode(codeFragment->recorderCodeList,
300 scopeName,
301 codeFragment->fileContents,
302 langExt, // lang
303 false, // strip code comments (overruled before replaying)
305 .setFileDef(fd.get())
306 .setInlineFragment(true)
307 .setCollectXRefs(false)
308 );
309 }
310 }
311 // use the recorded OutputCodeList from the cache to output a pre-recorded fragment
312 auto blockKv = codeFragment->blocksById.find(blockId.str());
313 if (blockKv != codeFragment->blocksById.end())
314 {
315 const auto &marker = blockKv->second;
316 int startLine = marker->lines[0];
317 int endLine = marker->lines[1];
318 size_t indent = marker->indent;
319 AUTO_TRACE_ADD("replay(start={},end={},indent={}) fileContentsTrimLeft.empty()={}",
320 startLine,endLine,indent,codeFragment->fileContentsTrimLeft.empty());
321 auto recorder = codeFragment->recorderCodeList.get<OutputCodeRecorder>(OutputType::Recorder);
322 recorder->replay(codeOutList,
323 startLine+1,
324 endLine,
325 showLineNumbers,
326 stripCodeComments,
327 trimLeft ? indent : 0
328 );
329 }
330 else
331 {
332 AUTO_TRACE_ADD("block not found!");
333 }
334}
335
static CodeFragmentManager & instance()
std::unique_ptr< Private > p
void parseCodeFragment(OutputCodeList &codeOutList, const DString &fileName, const DString &blockId, const DString &scopeName, bool showLineNumbers, bool trimLeft, bool stripCodeComments)
A String class for use with Doxygen wrapping std::string and adding some additional functionality off...
Definition dstring.h:89
DString()=default
bool empty() const
Returns true iff the string is empty (std::string compatible alias for isEmpty()).
Definition dstring.h:153
size_t size() const
Returns the length of the string, not counting the 0-terminator.
Definition dstring.h:159
const std::string & str() const
Definition dstring.h:650
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:162
Class implementing OutputCodeIntf by throwing away everything.
Definition devnullgen.h:21
static bool parseSourcesNeeded
Definition doxygen.h:123
static ParserManager * parserManager
Definition doxygen.h:129
static FileNameLinkedMap * exampleNameLinkedMap
Definition doxygen.h:102
A model of a file symbol.
Definition filedef.h:99
virtual DString absFilePath() const =0
Minimal replacement for QFileInfo.
Definition fileinfo.h:26
bool exists() const
Definition fileinfo.cpp:30
std::string fileName() const
Definition fileinfo.cpp:118
std::string dirPath(bool absPath=true) const
Definition fileinfo.cpp:137
FileDef * findFileDef(const DString &n, bool &ambig) const
Returns the file definition in fnMap that matches the file name n.
Definition filename.cpp:36
Class representing a list of different code generators.
Definition outputlist.h:166
void add(OutputCodeIntfPtr &&p)
Definition outputlist.h:196
Implementation that allows capturing calls made to the code interface to later invoke them on a Outpu...
Definition outputlist.h:114
void replay(OutputCodeList &ol, int startLine, int endLine, bool showLineNumbers, bool stripComment, size_t stripIndentAmount)
std::unique_ptr< CodeParserInterface > getCodeParser(const DString &extension)
Gets the interface to the parser associated with a given extension.
Definition parserintf.h:254
static DString readTextFileByName(const DString &file)
#define Config_getInt(name)
Definition config.h:34
#define Config_getList(name)
Definition config.h:38
#define Config_getBool(name)
Definition config.h:33
std::vector< std::string > StringVector
Definition containers.h:33
#define AUTO_TRACE_ADD(...)
Definition docnode.cpp:51
#define AUTO_TRACE(...)
Definition docnode.cpp:50
std::unique_ptr< FileDef > createFileDef(const DString &p, const DString &n, const DString &ref, const DString &dn)
Definition filedef.cpp:270
#define err(fmt,...)
Definition message.h:127
DString pathSeparator()
Definition portable.cpp:374
bool isAbsolutePath(const DString &fileName)
Definition portable.cpp:497
Definition dstring.h:918
Portable versions of functions that are platform dependent.
std::map< std::string, const BlockMarker * > blocksById
std::map< int, BlockMarker > blocks
std::unordered_map< std::string, std::unique_ptr< FragmentInfo > > fragments
Options to configure the code parser.
Definition parserintf.h:78
CodeParserOptions & setInlineFragment(bool enable)
Definition parserintf.h:107
CodeParserOptions & setCollectXRefs(bool enable)
Definition parserintf.h:119
SrcLangExt
Definition types.h:207
DString detab(const DString &s, size_t &refIndent)
Definition util.cpp:5378
DString getFileNameExtension(const DString &fn)
Definition util.cpp:4277
SrcLangExt getLanguageFromFileName(const DString &fileName, SrcLangExt defLang)
Definition util.cpp:4235
DString getFileFilter(const DString &name, bool isSourceCode)
Definition util.cpp:1052
DString fileToString(const DString &name, bool filter, bool isSourceCode)
Definition util.cpp:1120
A bunch of utility functions.