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 "dxlapp.hpp"
11#include "ALib.ALox.H"
12#include "ALib.App.H" // TODO(251204 09:14): we need this only for the definition of LOX_LOX.
13 // How can we avoid to include the whole app?
14
15#include <iostream>
16#include <fstream>
17
18using namespace alib;
19using namespace std;
20
21namespace dxl {
22
24 Lox_SetDomain("DXL/SREPL/JOB", Scope::Method )
25 Lox_Info( "Reading source file {!Q} of size {}", srcFileNode.Name(),
27 dxl.Stats.ReplSourceFileSize.fetch_add(int(srcFileNode->Size()));
28
29 Path path;
30 {ALIB_LOCK_SHARED_WITH(dxl.GetSourceTreeLock())
31 srcFileNode.AssembleRealPath(path, lang::Inclusion::Include);
32 }
33
34 // read exclamations applicable to this file once
36 dxl.Exclamations.Get(srcFileNode.Name(), exclamations);
37
39
40 Lox_Info("Reading source file: {}", path )
41 MappedFile& sourceFile= poolWorker->InputFile;
43 try {
44 mfc= sourceFile.Open(path.Terminate(), srcFileNode->Size(), false);
45 } catch (std::exception&) {
46 app.cErr->Add(app.cli.ExitCodeDecls.Find(ExitCodes::CantOpenReplSrcFile).Mapped()->FormatString(),
47 path);
48 app.machine.SetExitCode(ExitCodes::CantOpenReplSrcFile);
49 return true;
50 }
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 size_t lineStartRemaining = mfc.Remaining();
76 while (!mfc.IsEOF()) {
77 char c= char( 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= char(mfc.Next<NC>());
85 if ( c == '\n')
86 ++lineNo;
87 *wb++= c;
88 }
89 break;
90 }
91
92 //---- 2nd character ----
93 c= char(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= char(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= char(mfc.Next<NC>());
139 if ( c == '\\') { linkString._<NC>(c); linkString._<NC>(char(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
150 suppressedAnchor= linkString.CharAtStart() == '%';
151
152 // end not found?
153 if (!foundEnd) {
154 *wb++= '#';
155 *wb++= '\"';
156 for ( auto lsC : linkString )
157 *wb++= lsC;
158 *wb++= '\n';
159 Lox_Warning( "Found unterminated XLink pattern {!Q} in replacement source file {}:{}:{}",
160 linkString, path, lineNo -1, colNo )
161 continue;
162 }
163
164 if (suppressedAnchor)
165 linkString[0]= ' ';
166 linkString.Trim();
167 }
168
169 if (verbosity >= Verbosity::Info)
170 Lox_Info( "Found XLink pattern {!Q} in replacement source file {}:{}:{}",
171 linkString, path, lineNo, colNo )
172
173 XLink* xLink= dxl.GetXLink(linkString, File());
174 // attach this source file to the XLink and vice versa
175 {ALIB_LOCK_WITH(xLink->Lock)
176 xLink->SourceLocations.push_back({srcFileNode, lineNo, colNo}); }
177 { ALIB_LOCK_WITH(dxl.GetSourceTreeLock())
178 if (!srcFileNode.HasCustomData())
179 srcFileNode.AttachCustomData<XLinkList>(dxl.GetSourceTree().GetAllocator());
180 srcFileNode.GetCustomData<XLinkList>().emplace_back( xLink, lineNo, colNo );
181 }
182
183 // re-activate AString
184 ALIB_ASSERT_ERROR(wb - writeBufferStart < writeBuffer.Capacity(), "DXL/SREPL/JOB",
185 "Write buffer overflow detected" )
186 writeBuffer.SetLength(wb - writeBufferStart);
187
188 // not resolved?
189 if ( !xLink->IsResolved() ) {
190 // paste the original XLink to the output
191 writeBuffer._<NC>( "#")._<NC>( "\"");
192 if ( suppressedAnchor )
193 writeBuffer._<NC>( "%");
194 writeBuffer._<NC>(linkString)._<NC>( "\"");
195 } else {
196 fileChanged= true;
197 auto& node = xLink->Result().Node;
198
199 // write replacement
200 String256 entityPath;
202 ALIB_LOCK_SHARED_WITH(node.Index().SLock)
203 ( node.IsA(Target::EnumElement) ? node.Parent() : node ).Path(entityPath);
204 if( node.IsA(Target::Function))
205 entityPath.ShortenTo(entityPath.IndexOfOrLength('('));
206 } else
207 entityPath= node.Name();
208
209 ConvertHTMLEntitiesToAscii(entityPath);
210 String256 entityDisplay(xLink->Display);
211 ConvertHTMLEntitiesToAscii(entityDisplay);
212 writeBuffer._<NC>( "\\ref " )
213 ._<NC>(entityPath)
214 ._<NC>(" \"")
215 ._<NC>(entityDisplay)
216 ._<NC>('"');
217 }
218 wb= writeBuffer.VBuffer() + writeBuffer.Length();
219
220 } // the read-loop
221
222 // add stats
223 dxl.Stats.ReplSourceFileLines.fetch_add(lineNo);
224
225 //-------------------------- write file ---------------------------------
226 if ( fileChanged && app.cli.DryRun != cli::DryRunModes::Application) {
227 Lox_Verbose("Writing replacement source file: {}", path )
228
229 Path tempPath;
230 tempPath << path << ".tmp";
231 ofstream outFile(tempPath.Terminate());
232 if ( !outFile.is_open() ) {
233 app.cErr->Add( app.cli.ExitCodeDecls.Find(ExitCodes::CantWriteReplSrcFile).Mapped()->FormatString(),
234 tempPath);
235 return true;
236 }
237 ALIB_ASSERT_ERROR(wb - writeBufferStart < writeBuffer.Capacity(), "DXL/SREPL/JOB",
238 "Write buffer overflow detected" )
239 outFile.write(writeBuffer.Buffer() + writeBufferPadSize, wb - writeBufferStart - writeBufferPadSize);
240 outFile.close();
241
242 if ( outFile.fail() ) {
243 app.cErr->Add( app.cli.ExitCodeDecls.Find(ExitCodes::CantWriteReplSrcFile).Mapped()->FormatString(),
244 tempPath);
245 return true;
246 }
247
248 sourceFile.Close();
249 std::error_code ec;
250 std::filesystem::rename(tempPath.Terminate(), path.Terminate(), ec);
251 if ( ec.value() != 0 ) {
252 app.cErr->Add( app.cli.ExitCodeDecls.Find(ExitCodes::CantWriteReplSrcFile).Mapped()->FormatString(),
253 path, ec.message());
254 return true;
255 }
256 }
257 return true;
258}
259} //namespace [dxl]
260
#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(...)
bool IsEOF() const noexcept
std::size_t Remaining() const noexcept
void Close() noexcept
Data Open(const char *path, std::size_t knownSize=std::numeric_limits< std::size_t >::max(), bool disableMMap=false)
constexpr const TChar * Terminate() const
integer Capacity() const
TAString & ShortenTo(integer newLength)
TChar * VBuffer() const
TAString & Trim(const TCString< TChar > &trimChars=CStringConstantsTraits< TChar >::DefaultWhitespaces())
void EnsureRemainingCapacity(integer spaceNeeded)
void SetLength(integer newLength)
constexpr integer Length() const
TChar CharAtStart() const
constexpr const TChar * Buffer() const
integer IndexOfOrLength(TChar needle) const
class DXLApp
Definition dxlapp.hpp:37
@ Function
Denotes a namespace- or member-function.
Definition target.hpp:46
@ File
Denotes a source file.
Definition target.hpp:31
@ EnumElement
Denotes an enumeration element.
Definition target.hpp:48
@ Macro
Denotes a preprocessor definition.
Definition target.hpp:43
@ 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
files::File File
lang::integer integer
strings::TString< character > String
system::Path Path
files::MappedFile MappedFile
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:40
void ConvertHTMLEntitiesToAscii(alib::AString &buffer)
Definition dxl.cpp:104
@ 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:386
alib::files::File srcFileNode
The source-file to load and search for DoxygenXLinks links.
Definition jobs.hpp:110