ALib C++ Library
Library Version: 2510 R0
Documentation generated by doxygen
Loading...
Searching...
No Matches
scopeinfo.inl
Go to the documentation of this file.
1//==================================================================================================
2/// \file
3/// This header-file is part of module \alib_alox of the \aliblong.
4///
5/// \emoji :copyright: 2013-2025 A-Worx GmbH, Germany.
6/// Published under \ref mainpage_license "Boost Software License".
7//==================================================================================================
8ALIB_EXPORT namespace alib { namespace lox { namespace detail {
9
10//==================================================================================================
11/// Encapsulates information of the caller that can be collected. This is platform-specific, in
12/// this case, C++. What we receive from the C++ preprocessor is the source file name
13/// of the calling code, the line number within the source file name and the name of the method
14/// the call is placed in.
15/// Furthermore, we collect the <c>std::type_info*</c> in case the call was not placed in a
16/// static or namespace function.
17///
18/// The method has a list of interface functions that gets such source information and some derived
19/// variants of it. In addition, thread and timer information is stored and managed.
20///
21/// As far as possible, 'lazy' techniques come to practice with this class. This means, only
22/// the things that are queried in-between to invocations of method #Set are calculated.
23///
24/// ## Friends ##
25/// class \alib{lox;Lox}
26//==================================================================================================
28{
29public:
30#if !ALIB_SINGLE_THREADED
31 /// A map we use to translate thread IDs to thread names
33#endif
34
35 // ###############################################################################################
36 // Protected fields
37 // ###############################################################################################
38 protected:
39 #if !DOXYGEN
40 friend struct LoxImpl;
41 friend void LI::MapThreadName(LoxImpl*, const String&, threads::ThreadID);
42 friend void LI::GetState( LoxImpl*, NAString&, StateInfo);
43 #endif
44
45 /// Defines how source paths names are to be trimmed. \alox allows a set of global rules and
46 /// a set that is 'local', hence specific to a \b Lox.
48 {
49 NAString Path; ///< The path string
50 NAString TrimReplacement; ///< Optional replacement string for trimmed paths.
51 int TrimOffset; ///< Additional offset of the trim position
52 lang::Inclusion IncludeString; ///< Denotes if #Path itself should be included when trimmed
53 lang::Case Sensitivity; ///< The sensitivity of the comparison when trimming
54 variables::Priority Priority; ///< The priority of the rule. Depends on origin: source code, config...)
55 bool IsPrefix; ///< \c true if path was not starting with <c>'*'</c>, when provided.
56 };
57
58 /// List of trim definitions for portions of source paths to be ignored.
60 static std::vector<SourcePathTrimRule> GlobalSPTRs;
61
62 /// List of trim definitions for portions of source paths to be ignored.
63 std::vector<SourcePathTrimRule> LocalSPTRs;
64
65 /// Flag to determine if global rules have been read from config already.
68
69 /// If true, next time a source path cannot be trimmed successfully with custom
70 /// trim information provided with
71 /// \ref alib::lox::Lox::SetSourcePathTrimRule "Lox::SetSourcePathTrimRule"
72 /// some trim information is automatically created by comparing such source file's path
73 /// with the path of the executable of the current process.
75
76 #if !ALIB_SINGLE_THREADED
77 /// The C++ native ID.
78 std::thread::id threadNativeIDx;
79
80 /// The thread passed with #Set.
81 Thread* thread = nullptr;
82
83 /// The name of the thread that executed the log.
85
86 /// Dictionary to translate thread IDs into something maybe nicer/shorter.
87 /// The dictionary may be filled by the user of the library using \alox{Lox.MapThreadName}.
89 #endif
90
91 /// Information of a single source file. Stored in field #parsedFileNameCache.
93 {
94 /// Path and name of source file (given by the C++ preprocessor).
96
97 /// Full path of source file (evaluated).
98 NString fullPath = nullptr;
99
100 /// Trimmed path of source file (evaluated).
102
103 /// Prefix for the trimmed path taken from trim rule. Has to be added on writing
104 /// the trimmed path *
106
107 /// File name (evaluated).
108 NString name = nullptr;
109
110 /// File name without extension (evaluated).
112
113 /// Index of last path separator in #origFile.
115
116 /// Constructor.
117 /// @param filename Stored in #origFile.
118 ParsedFileName( const NCString filename) : origFile(filename) {}
119 };
120
121 /// Serves as template parameter \p{TValueDescriptor} of field #parsedFileNameCache.
122 struct ValueDescriptorPFN : containers::TSubsetKeyDescriptor<ParsedFileName, NCString>
123 {
124 /// Provides access to the key-portion of the cached set.
125 /// @param src The cached element.
126 /// @return The key portion of the element.
127 NCString Key (ParsedFileName& src) const { return src.origFile; }
128 };
129
130 /// Least recently used cache of parsed file name.
132
133 /// Holds values for the current scope. Because recursive logging might occur (e.g., when
134 /// parameters rely on method invocations which incorporate log statements), objects of this
135 /// class are stored in stack #callStack.
137 {
138 /// Time of the call that created this record.
140
141 /// The entry from the #parsedFileNameCache
143
144 /// Line number within the source file (given by the C++ preprocessor)
146
147 /// Function/method name (given by the C++ preprocessor)
149
150 /// Type information. Nullptr if call from static or global function.
151 const std::type_info* typeInfo;
152 };
153
154 /// A stack of scopes (allows recursive calls/nested logging).
156
157 /// The current depth of recursive invocations.
159
160 // #############################################################################################
161 // Types exposed
162 // #############################################################################################
163 public:
164 /// The name of the Lox we are attached to.
166
167
168 // #############################################################################################
169 // Constructor
170 // #############################################################################################
171 public:
172 /// Constructs a scope info.
173 /// @param name The name of the Lox that this object belongs to.
174 /// Will be converted to upper case.
175 /// @param allocator The monotonic allocator of "our" \b %Lox, used for long-term allocations
177 ScopeInfo( const NString& name, MonoAllocator& allocator);
178
179 // #############################################################################################
180 // public interface
181 // #############################################################################################
182public:
183 /// Changes the capacity of the \b %LRUCacheTable for parsed file names by calling
184 /// \alib{containers;LRUCacheTable::Reserve}.
185 /// @param numberOfLists The number of LRU-lists to use.
186 /// @param entriesPerList The maximum length of each cache list.
187 void SetFileNameCacheCapacity( integer numberOfLists, integer entriesPerList )
188 { parsedFileNameCache.Reserve( numberOfLists, entriesPerList ); }
189
190 /// Stores C++ specific caller parameters and some other values like the time stamp.
191 /// Also, flags thread information as not received, yet.
192 /// Counts the recursion counter up.
193 /// @param ci The caller information.
195 void Set( const lang::CallerInfo& ci );
196
197 /// Releases latest scope information.
199 {
201 ALIB_ASSERT( callStackSize >= -1 , "ALOX")
202 }
203
204
205 /// Does the job for
206 /// \ref alib::lox::Lox::SetSourcePathTrimRule "Lox::SetSourcePathTrimRule" and
207 /// \ref alib::lox::Lox::ClearSourcePathTrimRules "Lox::ClearSourcePathTrimRules".
208 ///
209 /// @param path The path to search for. If not starting with <c> '*'</c>,
210 /// a prefix is searched.
211 /// @param includeString Determines if \p{path} should be included in the trimmed path or not.
212 /// @param trimOffset Adjusts the portion of \p{path} that is trimmed. 999999 to clear!
213 /// @param sensitivity Determines if the comparison of \p{path} with a source file's path
214 /// is performed case-sensitive or not.
215 /// @param trimReplacement Replacement string for trimmed portion of the path.
216 /// @param reach Denotes whether the rule is applied locally (to this \b %Lox only)
217 /// or applies to all instances of class \b %Lox.
218 /// Defaults to \b %Reach::Global.
219 /// @param priority The priority of the setting.
221 void SetSourcePathTrimRule( const NCString& path,
222 lang::Inclusion includeString,
223 int trimOffset,
224 lang::Case sensitivity,
225 const NString& trimReplacement,
226 lang::Reach reach,
227 Priority priority );
228
229 /// Receives the name of the \b Lox we are belonging to (this is a 1:1 relationship).
230 /// @return The name of the \b Lox.
232 {
233 return loxName;
234 }
235
236 /// Receives the original filename and path of the source file
237 /// (usually provided by the preprocessor).
238 /// @return The full path and filename of the source file.
240 {
241 return callStack[size_t(callStackSize)].Parsed->origFile;
242 }
243
244 /// Receives the path of the source file (not trimmed, see #GetTrimmedPath).
245 /// @return The path of the source file.
247 {
248 auto& srcFile= *callStack[size_t(callStackSize)].Parsed;
249 if( srcFile.fullPath.IsNull() )
250 {
251 integer idx= getPathLength();
252 if( idx >= 0 )
253 srcFile.fullPath= NString( srcFile.origFile.Buffer(), idx );
254 else
255 srcFile.fullPath= "";
256 }
257
258 return srcFile.fullPath;
259 }
260
261 /// Writes the path of the source file, trimmed according to trim-information provided
262 /// with #SetSourcePathTrimRule or detected according to #AutoDetectTrimableSourcePath.
263 /// @param target The target string to append the trimmed path to.
264 void GetTrimmedPath( AString& target )
265 {
266 auto& srcFile= *callStack[size_t(callStackSize)].Parsed;
267 if( srcFile.trimmedPath.IsNull() )
268 trimPath();
269
270 target._( srcFile.trimmedPathPrefix )
271 ._( srcFile.trimmedPath );
272 }
273
274 /// Receives the source file name excluding the path (usually provided by the preprocessor).
275 /// @return The source file name excluding the path
277 {
278 auto& srcFile= *callStack[size_t(callStackSize)].Parsed;
279 if( srcFile.name.IsNull() )
280 {
281 integer idx= getPathLength();
282 if( idx >= 0 )
283 srcFile.name= NString( srcFile.origFile.Buffer() + idx + 1,
284 srcFile.origFile.Length() - idx - 1 );
285 else
286 srcFile.name= "";
287 }
288 return srcFile.name;
289 }
290
291 /// Receives the source file name excluding the path and without an extension
292 /// (usually provided by the preprocessor).
293 /// @return The source file name excluding the path and extension.
295 {
296 auto& srcFile= *callStack[size_t(callStackSize)].Parsed;
297 if( srcFile.nameWOExt.IsNull() )
298 {
299 srcFile.nameWOExt= GetFileName();
300 integer lastDot= srcFile.nameWOExt.LastIndexOf( '.' );
301 if ( lastDot > 0 )
302 srcFile.nameWOExt= NString( srcFile.nameWOExt.Buffer(), lastDot );
303 }
304 return srcFile.nameWOExt;
305 }
306
307
308 /// Receives the method name (usually provided by the preprocessor).
309 /// @return The method name.
311 {
312 return callStack[size_t(callStackSize)].origMethod;
313 }
314
315 /// Receives the source file line number (usually provided by the preprocessor).
316 /// @return The source file line number.
318 {
319 return callStack[size_t(callStackSize)].origLine;
320 }
321
322 /// The timestamp of the last invocation of #Set.
323 /// @return The latest timestamp.
325 {
326 return callStack[size_t(callStackSize)].timeStamp;
327 }
328
329 /// Receives the type information of the caller.
330 /// If called from global function or static method, this will be \c nullptr.
331 /// @returns The type information, if available.
332 const std::type_info* GetTypeInfo()
333 {
334 return callStack[size_t(callStackSize)].typeInfo;
335 }
336
337#if !ALIB_SINGLE_THREADED
338 /// Receives the thread ID of the caller.
339 /// @returns The thread ID.
341 {
342 if( thread == nullptr )
344 return thread->GetID();
345 }
346
347 /// Receives the thread ID of the caller.
348 /// @returns The thread ID.
349 std::thread::id GetThreadNativeID() { return threadNativeIDx; }
350
351 /// Receives information about the thread that the current call was invoked with.
352 /// @param id Output parameter receiving the \alib thread ID. If nullptr, it will be
353 /// ignored.
354 /// @returns The name of the current thread. The id is stored within the provided
355 /// pointer.
357 {
358 if ( threadName.IsNull() )
359 {
360 // get current thread, if not passed with set()
361 if( thread == nullptr )
363
364 if (id != nullptr)
365 *id= thread->GetID();
366
367 // do we have a dictionary entry?
368 auto it= threadDictionary.Find( thread->GetID() );
369 if (it != threadDictionary.end() )
370 threadName= it->second;
371 else
372 threadName= thread->GetName();
373 }
374
375 return threadName;
376 }
377#endif
378
379 // #############################################################################################
380 // Internals
381 // #############################################################################################
382 protected:
383
384 /// Tries to trim the source file's path. Sets variable SourceFile::trimmedPath to either
385 /// the successfully trimmed path or to the non-trimmed one. This way, it is executed
386 /// only once, at it is 'lazily' invoked by #GetTrimmedPath()
388 void trimPath();
389
390 /// Gets position of path/filename separator. This is evaluated only once after an
391 /// invocation of #Set.
392 /// @return The index of the path separator in SourceFile::origFile.
394 {
395 auto& srcFile= *callStack[size_t(callStackSize)].Parsed;
396 if( srcFile.origFilePathLength == -2 )
397 srcFile.origFilePathLength= srcFile.origFile.LastIndexOf( system::DIRECTORY_SEPARATOR );
398 return srcFile.origFilePathLength;
399 }
400}; // class ScopeInfo
401
402}}} // namespace [alib::lox::detail]
403
static ALIB_DLL std::vector< SourcePathTrimRule > GlobalSPTRs
List of trim definitions for portions of source paths to be ignored.
Definition scopeinfo.inl:60
const NString GetFileNameWithoutExtension()
const NCString & GetOrigFile()
const alib::String & GetThreadNameAndID(threads::ThreadID *id)
std::thread::id GetThreadNativeID()
void GetTrimmedPath(AString &target)
threads::ThreadID GetThreadID()
static ALIB_DLL bool GlobalSPTRsReadFromConfig
Flag to determine if global rules have been read from config already.
Definition scopeinfo.inl:67
ALIB_DLL ScopeInfo(const NString &name, MonoAllocator &allocator)
Definition scopeinfo.cpp:63
HashMap< MonoAllocator, threads::ThreadID, String32 > ThreadDictionary
A map we use to translate thread IDs to thread names.
Definition scopeinfo.inl:32
ALIB_DLL void SetSourcePathTrimRule(const NCString &path, lang::Inclusion includeString, int trimOffset, lang::Case sensitivity, const NString &trimReplacement, lang::Reach reach, Priority priority)
NString loxName
The name of the Lox we are attached to.
void SetFileNameCacheCapacity(integer numberOfLists, integer entriesPerList)
StdVectorMono< FrameRecord > callStack
A stack of scopes (allows recursive calls/nested logging).
ThreadDictionary threadDictionary
Definition scopeinfo.inl:88
void PopNestedScope()
Releases latest scope information.
String threadName
The name of the thread that executed the log.
Definition scopeinfo.inl:84
LRUCacheTable< MonoAllocator, ValueDescriptorPFN, std::hash< NString > > parsedFileNameCache
Least recently used cache of parsed file name.
Thread * thread
The thread passed with Set.
Definition scopeinfo.inl:81
int callStackSize
The current depth of recursive invocations.
ALIB_DLL void Set(const lang::CallerInfo &ci)
std::vector< SourcePathTrimRule > LocalSPTRs
List of trim definitions for portions of source paths to be ignored.
Definition scopeinfo.inl:63
std::thread::id threadNativeIDx
The C++ native ID.
Definition scopeinfo.inl:78
const std::type_info * GetTypeInfo()
TAString & _(const TAppendable &src)
static ALIB_DLL Thread * Get(std::thread::id nativeID)
Definition thread.cpp:329
#define ALIB_DLL
Definition alib.inl:496
#define ALIB_ASSERT(cond, domain)
Definition alib.inl:1048
#define ALIB_EXPORT
Definition alib.inl:488
Reach
Denotes the reach of something.
Case
Denotes upper and lower case character treatment.
Inclusion
Denotes how members of a set something should be taken into account.
constexpr PathCharType DIRECTORY_SEPARATOR
The standard path separator character. Defaults to '\' on Windows OS, '/' else.
Definition path.inl:63
integer ThreadID
The ALib thread identifier type.
Definition thread.inl:23
containers::LRUCacheTable< TAllocator, TValueDescriptor, THash, TEqual > LRUCacheTable
Type alias in namespace alib.
strings::TAString< character, lang::HeapAllocator > AString
Type alias in namespace alib.
std::vector< T, SCAMono< T > > StdVectorMono
Type alias in namespace alib.
lang::integer integer
Type alias in namespace alib.
Definition integers.inl:149
strings::TString< nchar > NString
Type alias in namespace alib.
Definition string.inl:2390
strings::TAString< nchar, lang::HeapAllocator > NAString
Type alias in namespace alib.
containers::HashMap< TAllocator, TKey, TMapped, THash, TEqual, THashCaching, TRecycling > HashMap
Type alias in namespace alib.
monomem::TMonoAllocator< lang::HeapAllocator > MonoAllocator
threads::Thread Thread
Type alias in namespace alib.
Definition thread.inl:389
strings::TCString< nchar > NCString
Type alias in namespace alib.
Definition cstring.inl:512
alib::variables::Priority Priority
Type alias in namespace alib.
strings::TString< character > String
Type alias in namespace alib.
Definition string.inl:2381
time::Ticks Ticks
Type alias in namespace alib.
Definition ticks.inl:109
static ALIB_DLL void MapThreadName(LoxImpl *impl, const String &threadName, threads::ThreadID id)
static ALIB_DLL void GetState(LoxImpl *impl, NAString &buf, StateInfo flags)
Ticks timeStamp
Time of the call that created this record.
const std::type_info * typeInfo
Type information. Nullptr if call from static or global function.
NCString origMethod
Function/method name (given by the C++ preprocessor)
ParsedFileName * Parsed
The entry from the parsedFileNameCache.
int origLine
Line number within the source file (given by the C++ preprocessor)
Information of a single source file. Stored in field parsedFileNameCache.
Definition scopeinfo.inl:93
NCString origFile
Path and name of source file (given by the C++ preprocessor).
Definition scopeinfo.inl:95
NString name
File name (evaluated).
NString nameWOExt
File name without extension (evaluated).
integer origFilePathLength
Index of last path separator in origFile.
NString fullPath
Full path of source file (evaluated).
Definition scopeinfo.inl:98
NString trimmedPath
Trimmed path of source file (evaluated).
int TrimOffset
Additional offset of the trim position.
Definition scopeinfo.inl:51
lang::Inclusion IncludeString
Denotes if Path itself should be included when trimmed.
Definition scopeinfo.inl:52
variables::Priority Priority
The priority of the rule. Depends on origin: source code, config...)
Definition scopeinfo.inl:54
bool IsPrefix
true if path was not starting with '*', when provided.
Definition scopeinfo.inl:55
lang::Case Sensitivity
The sensitivity of the comparison when trimming.
Definition scopeinfo.inl:53
NAString TrimReplacement
Optional replacement string for trimmed paths.
Definition scopeinfo.inl:50
Serves as template parameter TValueDescriptor of field parsedFileNameCache.
NCString Key(ParsedFileName &src) const