Doxygen XLinks
by
V: 2511R0
Website: doxygen
Loading...
Searching...
No Matches
sourcereplacer.cpp
1//==================================================================================================
2// This implementation-file is part of DoxygenXLinks - A doxygen post-processor that allows to
3// define smarter <b>Doxygen</b>-links.
4//
5// \emoji :copyright: 2025-2026 A-Worx GmbH, Germany.
6// Published under \ref mainpage_license "Boost Software License".
7//==================================================================================================
8#include "jobs.hpp"
9#include "dxl.hpp"
10#include "xlink.hpp"
11#include "dxlapp.hpp"
12#include "ALib.ALox.H"
13#include "ALib.App.H" // TODO(251204 09:14): we need this only for the definition of LOX_LOX.
14 // How can we avoid to include the whole app?
15
16#include <iostream>
17#include <fstream>
18
19using namespace alib;
20using namespace std;
21
22namespace dxl {
23
25 Lox_SetDomain("DXL/SREPL/JOB", Scope::Method )
26 Lox_Info( "Reading source file {!Q} of size {}", srcFileNode.Name(),
28 dxl.Stats.ReplSourceFileSize.fetch_add(int(srcFileNode->Size()));
29
30 Path path;
31 {ALIB_LOCK_SHARED_WITH(dxl.GetSourceTreeLock())
32 srcFileNode.AssembleRealPath(path, lang::Inclusion::Include);
33 }
34
35 // read exclamations applicable to this file once
37 dxl.Exclamations.Get(srcFileNode.Name(), exclamations);
38
40
41 Lox_Info("Reading source file: {}", path )
42 MappedFile& sourceFile= poolWorker->InputFile;
43 std::errc errc= sourceFile.Open(path.Terminate(), srcFileNode->Size(), false);
44 if(errc != std::errc()) {
45 app.cErr->Add(app.cli.ExitCodeDecls.Find(ExitCodes::CantOpenReplSrcFile).Mapped()->FormatString(),
46 path);
47 app.machine.SetExitCode(ExitCodes::CantOpenReplSrcFile);
48 return true;
49 }
50 MappedFile::Data<char> mfc= sourceFile.GetData<char>();
51
52 // output buffer (fileSize * 3). And: we add some padding bytes, to be able to test
53 // backward contents without checking actual write-size.
54 AString& writeBuffer= poolWorker->WriteBuffer;
55 writeBuffer.EnsureRemainingCapacity(integer(srcFileNode->Size() * 3));
56 constexpr integer writeBufferPadSize= 20;
57 writeBuffer._(Fill(0, writeBufferPadSize));
58 char* writeBufferStart= writeBuffer.VBuffer();
59 char* wb = writeBufferStart + writeBufferPadSize;
60
61 // if the application has an exit code, we stop right now
62 // todo: this periodical check makes sense but was never tested, yet.
63 // it has to go into the loop below and also to other jobs
64 if ( app.machine.GetExitCode().Integral() )
65 return true;
66
67 // we want maximum speed and even spare the fast log calls in the loop.
68 Verbosity verbosity;
69 Lox_GetVerbosity(verbosity)
70
71 //------------------------------------------- main loop ------------------------------------------
72 bool fileChanged = false;
73 int lineNo = 1;
74 String512 linkString;
75 integer lineStartRemaining = mfc.Remaining();
76 while (!mfc.IsEOF()) {
77 char c= mfc.Next<NC>();
78 if (c == '\n') { *wb++= '\n'; lineNo++; lineStartRemaining= mfc.Remaining(); continue; }
79 if (c != '#' ) { *wb++= c; continue; }
80
81 if (mfc.Remaining()<3) {
82 *wb++= c;
83 while (mfc.Remaining()){
84 c= mfc.Next<NC>();
85 if ( c == '\n')
86 ++lineNo;
87 *wb++= c;
88 }
89 break;
90 }
91
92 //---- 2nd character ----
93 c= mfc.Next<NC>();
94
95 // if double hash is given, skip it.
96 // Note: This is mainly needed for the documentation of this tool ;-)
97 if (c == '#' ) { *wb++= '#'; *wb++= '#'; continue;}
98
99 // not '"' ?
100 if ( c != '\"' ) {
101 *wb++= '#';
102 *wb++= c;
103 if ( c == '\n')
104 ++lineNo;
105 continue;
106 }
107
108 //---- 3rd character: not an allowed link start? ----
109 c= mfc.Next<NC>();
110 if ( !isalpha(c) && String(".%^_<").IndexOf(c) < 0 ) {
111 *wb++= '#';
112 *wb++= '\"';
113 *wb++= c;
114 if ( c == '\n')
115 ++lineNo;
116 continue;
117 }
118
119 int colNo= int(lineStartRemaining - mfc.Remaining() - 2);
120
121 // search for exclamations
122 { auto exclIt= exclamations.begin();
123 for (; exclIt!=exclamations.end(); ++exclIt )
124 if ( (*exclIt)->Matches(lineNo, colNo ) )
125 break;
126 if (exclIt != exclamations.end()) {
127 *wb++= '#';
128 *wb++= '\"';
129 *wb++= c;
130 continue;
131 } }
132
133 // This seems to be an XLink!
134 bool suppressedAnchor;
135 linkString.Reset(c); {
136 bool foundEnd= false;
137 while (mfc.Remaining()) {
138 c= mfc.Next<NC>();
139 if ( c == '\\') { linkString._<NC>(c); linkString._<NC>(mfc.Next()); continue; }
140 if ( c == '\"') { foundEnd= true; break;}
141 if ( c == '\n') { lineNo++; break; }
142 linkString._<NC>(c);
143 if (linkString.Length() == 511 ) {
144 Lox_Warning( "Found unterminated XLink pattern {!Q} in HTML file {}:{}:{}",
145 linkString, path, lineNo, colNo )
146 break;
147 } }
148
149 suppressedAnchor= linkString.CharAtStart() == '%';
150
151 // end not found?
152 if (!foundEnd) {
153 *wb++= '#';
154 *wb++= '\"';
155 for ( auto lsC : linkString )
156 *wb++= lsC;
157 *wb++= '\n';
158 Lox_Warning( "Found unterminated XLink pattern {!Q} in replacement source file {}:{}:{}",
159 linkString, path, lineNo -1, colNo )
160 continue;
161 }
162
163 if (suppressedAnchor)
164 linkString[0]= ' ';
165 linkString.Trim();
166 }
167
168 if (verbosity >= Verbosity::Info)
169 Lox_Info( "Found XLink pattern {!Q} in replacement source file {}:{}:{}",
170 linkString, path, lineNo, colNo )
171
172 XLink* xLink= dxl.GetXLink(linkString, FTFile());
173 // attach this source file to the XLink and vice versa
174 {ALIB_LOCK_WITH(xLink->Lock)
175 xLink->SourceLocations.push_back({srcFileNode, lineNo, colNo}); }
176 { ALIB_LOCK_WITH(dxl.GetSourceTreeLock())
177 if (!srcFileNode.HasCustomData())
178 srcFileNode.AttachCustomData<XLinkList>(dxl.GetSourceTree().GetAllocator());
179 srcFileNode.GetCustomData<XLinkList>().emplace_back( xLink, lineNo, colNo );
180 }
181
182 // re-activate AString
183 ALIB_ASSERT_ERROR(wb - writeBufferStart < writeBuffer.Capacity(), "DXL/SREPL/JOB",
184 "Write buffer overflow detected" )
185 writeBuffer.SetLength(wb - writeBufferStart);
186
187 // not resolved?
188 if ( !xLink->IsResolved() ) {
189 // paste the original XLink to the output
190 writeBuffer._<NC>( "#")._<NC>( "\"");
191 if ( suppressedAnchor )
192 writeBuffer._<NC>( "%");
193 writeBuffer._<NC>(linkString)._<NC>( "\"");
194 } else {
195 fileChanged= true;
196 auto& node = xLink->Result().Node;
197
198 // write replacement
199 String256 entityPath;
201 ALIB_LOCK_SHARED_WITH(node.Index().SLock)
202 ( node.IsA(Target::EnumElement) ? node.Parent() : node ).Path(entityPath);
203 if( node.IsA(Target::Function))
204 entityPath.ShortenTo(entityPath.IndexOfOrLength('('));
205 } else
206 entityPath= node.Name();
207
208 ConvertHTMLEntitiesToAscii(entityPath);
209 writeBuffer._<NC>( "\\ref " )
210 ._<NC>(entityPath)
211 ._<NC>(" \"")
212 ._<NC>(xLink->Display)
213 ._<NC>('"');
214 }
215 wb= writeBuffer.VBuffer() + writeBuffer.Length();
216
217 } // the read-loop
218
219 // add stats
220 dxl.Stats.ReplSourceFileLines.fetch_add(lineNo);
221
222 //------------------------------------------- write file -----------------------------------------
223 if ( fileChanged && !app.dryrun) {
224 Lox_Verbose("Writing replacement source file: {}", path )
225
226 Path tempPath;
227 tempPath << path << ".tmp";
228 ofstream outFile(tempPath.Terminate());
229 if ( !outFile.is_open() ) {
230 app.cErr->Add( app.cli.ExitCodeDecls.Find(ExitCodes::CantWriteReplSrcFile).Mapped()->FormatString(),
231 tempPath);
232 return true;
233 }
234 ALIB_ASSERT_ERROR(wb - writeBufferStart < writeBuffer.Capacity(), "DXL/SREPL/JOB",
235 "Write buffer overflow detected" )
236 outFile.write(writeBuffer.Buffer() + writeBufferPadSize, wb - writeBufferStart - writeBufferPadSize);
237 outFile.close();
238
239 if ( outFile.fail() ) {
240 app.cErr->Add( app.cli.ExitCodeDecls.Find(ExitCodes::CantWriteReplSrcFile).Mapped()->FormatString(),
241 tempPath);
242 return true;
243 }
244
245 sourceFile.Close();
246 std::error_code ec;
247 std::filesystem::rename(tempPath.Terminate(), path.Terminate(), ec);
248 if ( ec.value() != 0 ) {
249 app.cErr->Add( app.cli.ExitCodeDecls.Find(ExitCodes::CantWriteReplSrcFile).Mapped()->FormatString(),
250 path, ec.message());
251 return true;
252 } }
253 return true;
254}
255} //namespace [dxl]
#define ALIB_LOCK_SHARED_WITH(lock)
#define ALIB_ASSERT_ERROR(cond, domain,...)
#define ALIB_LOCK_WITH(lock)
#define Lox_Info(...)
#define Lox_SetDomain(...)
#define Lox_GetVerbosity(result,...)
#define Lox_Verbose(...)
#define Lox_Warning(...)
constexpr const TChar * Terminate() const
TAString & ShortenTo(integer newLength)
TAString & Trim(const TCString< TChar > &trimChars=CStringConstantsTraits< TChar >::DefaultWhitespaces())
constexpr integer Length() const
TChar CharAtStart() const
integer IndexOfOrLength(TChar needle) const
integer Remaining() const noexcept
bool IsEOF() const noexcept
void Close() noexcept
std::errc Open(const CPathString &path, std::size_t knownSize=(std::numeric_limits< std::size_t >::max)(), bool disableMMap=false, bool willNeed=true)
Data< T > GetData() const noexcept
class DXLApp
Definition dxlapp.hpp:37
@ Function
Denotes a namespace- or member-function.
Definition target.hpp:47
@ File
Denotes a source file.
Definition target.hpp:31
@ EnumElement
Denotes an enumeration element.
Definition target.hpp:49
@ Macro
Denotes a preprocessor definition.
Definition target.hpp:44
@ Dir
Denotes a source folder.
Definition target.hpp:30
@ DocAnchor
Denotes a preprocessor definition.
Definition target.hpp:34
TApp & Get()
lox::Verbosity Verbosity
strings::TFill< character > Fill
lang::integer integer
strings::TString< character > String
system::Path Path
system::MappedFile MappedFile
filetree::FTFile FTFile
LocalString< 256 > String256
strings::TAString< character, lang::HeapAllocator > AString
std::vector< T, StdMA< T > > StdVectorMA
LocalString< 512 > String512
todox
Definition doxyfile.cpp:20
alib::StdVectorMA< ResolvedLocation > XLinkList
Definition xlink.hpp:41
void ConvertHTMLEntitiesToAscii(alib::AString &buffer)
Definition dxl.cpp:103
@ CantOpenReplSrcFile
A replacement source file was not found or could not be accessed.
Definition dxl.hpp:101
@ CantWriteReplSrcFile
A replacement source file was not found or could not be accessed.
Definition dxl.hpp:102
DXLPoolWorker * poolWorker
The pool worker that executes this job.
Node Node
The cursor pointing to the result.
Definition index.hpp:387
alib::filetree::FTFile srcFileNode
The source-file to load and search for DoxygenXLinks links.
Definition jobs.hpp:110