From 47d602cf884b14e4c529286238e2085fe97338d7 Mon Sep 17 00:00:00 2001 From: Mubashshir Date: Sat, 16 Nov 2024 00:32:45 +0600 Subject: Add util string formatter Signed-off-by: Mubashshir --- src/system.yy | 6 ++++-- src/util.h | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 src/util.h diff --git a/src/system.yy b/src/system.yy index cd6ddc9..0727213 100644 --- a/src/system.yy +++ b/src/system.yy @@ -27,6 +27,7 @@ bool legacy = true; #include #include "lexer.h" #include "location.h" +#include "util.h" } //%locations @@ -69,7 +70,8 @@ block_end: ofstream f(p, ios_base::out | ios_base::binary); msg.SerializeToOstream(&f); f.close(); - } + } else + throw syntax_error(string_format("Block EPOCH mismatch: begin:%llu, end:%llu", msg.epoch(), $ULONG)); msg.Clear(); } @@ -275,7 +277,7 @@ namespace yy // Report an error to the user. auto parser::error (const std::string& msg) -> void { - std::cerr << msg << " on line " << lexer.lineno() << '\n'; + std::cerr << "\nERROR: " << msg << " on line " << lexer.lineno() - 1<< '\n'; } } diff --git a/src/util.h b/src/util.h new file mode 100644 index 0000000..a54d3eb --- /dev/null +++ b/src/util.h @@ -0,0 +1,19 @@ +#ifndef __UTIL_H__ +#define __UTIL_H__ + +#include +#include +#include + +template +std::string string_format( const std::string& format, Args ... args ) +{ + int size_s = std::snprintf( nullptr, 0, format.c_str(), args ... ) + 1; // Extra space for '\0' + if( size_s <= 0 ){ throw std::runtime_error( "Error during formatting." ); } + auto size = static_cast( size_s ); + std::unique_ptr buf( new char[ size ] ); + std::snprintf( buf.get(), size, format.c_str(), args ... ); + return std::string( buf.get(), buf.get() + size - 1 ); // We don't want the '\0' inside +} + +#endif /* __UTIL_H__ */ -- cgit v1.2.3