From b877c81c3221ca930a0b1359d9a90bee405882d2 Mon Sep 17 00:00:00 2001 From: Sylvie <35663410+Rangi42@users.noreply.github.com> Date: Mon, 9 Dec 2024 21:56:54 -0500 Subject: [PATCH] Use C++-style casts (#1576) --- CMakeLists.txt | 2 +- Makefile | 2 +- include/asm/fstack.hpp | 4 +-- include/asm/symbol.hpp | 4 +-- include/either.hpp | 4 +-- include/gfx/rgba.hpp | 2 +- include/itertools.hpp | 4 +-- src/asm/charmap.cpp | 12 +++---- src/asm/fixpoint.cpp | 2 +- src/asm/format.cpp | 9 +++--- src/asm/fstack.cpp | 10 +++--- src/asm/lexer.cpp | 25 ++++++++------- src/asm/macro.cpp | 4 +-- src/asm/main.cpp | 2 +- src/asm/output.cpp | 26 +++++++-------- src/asm/parser.y | 8 ++--- src/asm/rpn.cpp | 68 +++++++++++++++++++++------------------- src/asm/section.cpp | 26 +++++++-------- src/asm/symbol.cpp | 8 ++--- src/fix/main.cpp | 47 +++++++++++++++++---------- src/gfx/process.cpp | 4 +-- src/gfx/reverse.cpp | 2 +- src/link/assign.cpp | 6 ++-- src/link/main.cpp | 16 +++++----- src/link/object.cpp | 10 +++--- src/link/output.cpp | 2 +- src/link/patch.cpp | 18 +++++------ src/link/script.y | 8 ++--- src/link/sdas_obj.cpp | 19 ++++++----- src/opmath.cpp | 8 ++--- src/util.cpp | 2 +- test/gfx/randtilegen.cpp | 2 +- test/gfx/rgbgfx_test.cpp | 4 +-- 33 files changed, 197 insertions(+), 173 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 345e0bd0..98bd79c7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -61,7 +61,7 @@ else() if(MORE_WARNINGS) add_compile_options(-Werror -Wextra -Walloc-zero -Wcast-align -Wcast-qual -Wduplicated-branches -Wduplicated-cond - -Wfloat-equal -Wlogical-op -Wnull-dereference -Wshift-overflow=2 + -Wfloat-equal -Wlogical-op -Wnull-dereference -Wold-style-cast -Wshift-overflow=2 -Wstringop-overflow=4 -Wundef -Wuninitialized -Wunused -Wshadow # TODO: -Wshadow=compatible-local? -Wformat=2 -Wformat-overflow=2 -Wformat-truncation=1 diff --git a/Makefile b/Makefile index 1046d6c5..18e288c0 100644 --- a/Makefile +++ b/Makefile @@ -201,7 +201,7 @@ checkdiff: develop: $Q${MAKE} WARNFLAGS="${WARNFLAGS} -Werror -Wextra \ -Walloc-zero -Wcast-align -Wcast-qual -Wduplicated-branches -Wduplicated-cond \ - -Wfloat-equal -Wlogical-op -Wnull-dereference -Wshift-overflow=2 \ + -Wfloat-equal -Wlogical-op -Wnull-dereference -Wold-style-cast -Wshift-overflow=2 \ -Wstringop-overflow=4 -Wundef -Wuninitialized -Wunused -Wshadow \ -Wformat=2 -Wformat-overflow=2 -Wformat-truncation=1 \ -Wno-format-nonliteral -Wno-strict-overflow -Wno-unused-but-set-variable \ diff --git a/include/asm/fstack.hpp b/include/asm/fstack.hpp index 433652e3..9889d7bc 100644 --- a/include/asm/fstack.hpp +++ b/include/asm/fstack.hpp @@ -30,8 +30,8 @@ struct FileStackNode { // Meaningless at the root level, but gets written to the object file anyway, so init it uint32_t lineNo = 0; - // Set only if referenced: ID within the object file, -1 if not output yet - uint32_t ID = -1; + // Set only if referenced: ID within the object file, `UINT32_MAX` if not output yet + uint32_t ID = UINT32_MAX; // REPT iteration counts since last named node, in reverse depth order std::vector &iters() { return data.get>(); } diff --git a/include/asm/symbol.hpp b/include/asm/symbol.hpp index 4e53c2e2..9aec7195 100644 --- a/include/asm/symbol.hpp +++ b/include/asm/symbol.hpp @@ -45,7 +45,7 @@ struct Symbol { > data; - uint32_t ID; // ID of the symbol in the object file (-1 if none) + uint32_t ID; // ID of the symbol in the object file (`UINT32_MAX` if none) uint32_t defIndex; // Ordering of the symbol in the state file bool isDefined() const { return type != SYM_REF; } @@ -55,7 +55,7 @@ struct Symbol { bool isConstant() const { if (type == SYM_LABEL) { Section const *sect = getSection(); - return sect && sect->org != (uint32_t)-1; + return sect && sect->org != UINT32_MAX; } return type == SYM_EQU || type == SYM_VAR; } diff --git a/include/either.hpp b/include/either.hpp index 47adbbda..54eae2c8 100644 --- a/include/either.hpp +++ b/include/either.hpp @@ -43,11 +43,11 @@ private: // Generic field accessors; for internal use only. template auto &field() { - return pick((T *)nullptr); + return pick(static_cast(nullptr)); } template auto const &field() const { - return pick((T *)nullptr); + return pick(static_cast(nullptr)); } public: diff --git a/include/gfx/rgba.hpp b/include/gfx/rgba.hpp index 04b17e54..9e2dcc5c 100644 --- a/include/gfx/rgba.hpp +++ b/include/gfx/rgba.hpp @@ -28,7 +28,7 @@ struct Rgba { _5to8(cgbColor), _5to8(cgbColor >> 5), _5to8(cgbColor >> 10), - (uint8_t)(cgbColor & 0x8000 ? 0x00 : 0xFF), + static_cast(cgbColor & 0x8000 ? 0x00 : 0xFF), }; } diff --git a/include/itertools.hpp b/include/itertools.hpp index 9fd5f106..09e2cba6 100644 --- a/include/itertools.hpp +++ b/include/itertools.hpp @@ -18,7 +18,7 @@ class EnumSeq { explicit Iterator(T value) : _value(value) {} Iterator &operator++() { - _value = (T)(_value + 1); + _value = static_cast(_value + 1); return *this; } @@ -29,7 +29,7 @@ class EnumSeq { }; public: - explicit EnumSeq(T stop) : _start((T)0), _stop(stop) {} + explicit EnumSeq(T stop) : _start(static_cast(0)), _stop(stop) {} explicit EnumSeq(T start, T stop) : _start(start), _stop(stop) {} Iterator begin() { return Iterator(_start); } diff --git a/src/asm/charmap.cpp b/src/asm/charmap.cpp index 81ce492c..1aa1beb9 100644 --- a/src/asm/charmap.cpp +++ b/src/asm/charmap.cpp @@ -53,7 +53,7 @@ bool charmap_ForEach( mappings[nodeIdx] = mapping; for (unsigned c = 0; c < 256; c++) { if (size_t nextIdx = node.next[c]; nextIdx) - prefixes.push({nextIdx, mapping + (char)c}); + prefixes.push({nextIdx, mapping + static_cast(c)}); } } mapFunc(charmap.name); @@ -64,7 +64,7 @@ bool charmap_ForEach( } void charmap_New(std::string const &name, std::string const *baseName) { - size_t baseIdx = (size_t)-1; + size_t baseIdx = SIZE_MAX; if (baseName != nullptr) { if (auto search = charmapMap.find(*baseName); search == charmapMap.end()) @@ -82,7 +82,7 @@ void charmap_New(std::string const &name, std::string const *baseName) { charmapMap[name] = charmapList.size(); Charmap &charmap = charmapList.emplace_back(); - if (baseIdx != (size_t)-1) + if (baseIdx != SIZE_MAX) charmap.nodes = charmapList[baseIdx].nodes; // Copies `charmapList[baseIdx].nodes` else charmap.nodes.emplace_back(); // Zero-init the root node @@ -129,7 +129,7 @@ void charmap_Add(std::string const &mapping, std::vector &&value) { size_t nodeIdx = 0; for (char c : mapping) { - size_t &nextIdxRef = charmap.nodes[nodeIdx].next[(uint8_t)c]; + size_t &nextIdxRef = charmap.nodes[nodeIdx].next[static_cast(c)]; size_t nextIdx = nextIdxRef; if (!nextIdx) { @@ -157,7 +157,7 @@ bool charmap_HasChar(std::string const &input) { size_t nodeIdx = 0; for (char c : input) { - nodeIdx = charmap.nodes[nodeIdx].next[(uint8_t)c]; + nodeIdx = charmap.nodes[nodeIdx].next[static_cast(c)]; if (!nodeIdx) return false; @@ -184,7 +184,7 @@ size_t charmap_ConvertNext(std::string_view &input, std::vector *output size_t inputIdx = 0; for (size_t nodeIdx = 0; inputIdx < input.length();) { - nodeIdx = charmap.nodes[nodeIdx].next[(uint8_t)input[inputIdx]]; + nodeIdx = charmap.nodes[nodeIdx].next[static_cast(input[inputIdx])]; if (!nodeIdx) break; diff --git a/src/asm/fixpoint.cpp b/src/asm/fixpoint.cpp index ec0a7223..04b35cab 100644 --- a/src/asm/fixpoint.cpp +++ b/src/asm/fixpoint.cpp @@ -29,7 +29,7 @@ static int32_t double2fix(double d, int32_t q) { return 0; if (isinf(d)) return d < 0 ? INT32_MIN : INT32_MAX; - return (int32_t)round(d * pow(2.0, q)); + return static_cast(round(d * pow(2.0, q))); } static double turn2rad(double t) { diff --git a/src/asm/format.cpp b/src/asm/format.cpp index 4e12c4f8..41457b59 100644 --- a/src/asm/format.cpp +++ b/src/asm/format.cpp @@ -250,15 +250,16 @@ void FormatSpec::appendNumber(std::string &str, uint32_t value) const { } double fval = fabs(value / pow(2.0, usePrec)); - if (useExact) - snprintf(valueBuf, sizeof(valueBuf), "%.*fq%zu", (int)useFracWidth, fval, usePrec); + if (int fracWidthArg = static_cast(useFracWidth); useExact) + snprintf(valueBuf, sizeof(valueBuf), "%.*fq%zu", fracWidthArg, fval, usePrec); else - snprintf(valueBuf, sizeof(valueBuf), "%.*f", (int)useFracWidth, fval); + snprintf(valueBuf, sizeof(valueBuf), "%.*f", fracWidthArg, fval); } else if (useType == 'd') { // Decimal numbers may be formatted with a '-' sign by `snprintf`, so `abs` prevents that, // with a special case for `INT32_MIN` since `labs(INT32_MIN)` is UB. The sign will be // printed later from `signChar`. - uint32_t uval = value != (uint32_t)INT32_MIN ? labs((int32_t)value) : value; + uint32_t uval = + value != static_cast(INT32_MIN) ? labs(static_cast(value)) : value; snprintf(valueBuf, sizeof(valueBuf), "%" PRIu32, uval); } else { char const *spec = useType == 'u' ? "%" PRIu32 diff --git a/src/asm/fstack.cpp b/src/asm/fstack.cpp index 551d2534..b33646ea 100644 --- a/src/asm/fstack.cpp +++ b/src/asm/fstack.cpp @@ -170,8 +170,10 @@ bool yywrap() { // If this is a FOR, update the symbol value if (context.isForLoop && fileInfoIters.front() <= context.nbReptIters) { // Avoid arithmetic overflow runtime error - uint32_t forValue = (uint32_t)context.forValue + (uint32_t)context.forStep; - context.forValue = forValue <= INT32_MAX ? forValue : -(int32_t)~forValue - 1; + uint32_t forValue = + static_cast(context.forValue) + static_cast(context.forStep); + context.forValue = + forValue <= INT32_MAX ? forValue : -static_cast(~forValue) - 1; Symbol *sym = sym_AddVar(context.forName, context.forValue); // This error message will refer to the current iteration @@ -347,9 +349,9 @@ void fstk_RunFor( uint32_t count = 0; if (step > 0 && start < stop) - count = ((int64_t)stop - start - 1) / step + 1; + count = (static_cast(stop) - start - 1) / step + 1; else if (step < 0 && stop < start) - count = ((int64_t)start - stop - 1) / -(int64_t)step + 1; + count = (static_cast(start) - stop - 1) / -static_cast(step) + 1; else if (step == 0) error("FOR cannot have a step value of 0\n"); diff --git a/src/asm/lexer.cpp b/src/asm/lexer.cpp index 161b4b6a..5290eaa3 100644 --- a/src/asm/lexer.cpp +++ b/src/asm/lexer.cpp @@ -86,7 +86,7 @@ static char *mapFile(int fd, std::string const &path, size_t size) { printf("mmap(%s, MAP_PRIVATE) failed, retrying with MAP_SHARED\n", path.c_str()); mappingAddr = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0); } - return mappingAddr != MAP_FAILED ? (char *)mappingAddr : nullptr; + return mappingAddr != MAP_FAILED ? static_cast(mappingAddr) : nullptr; } struct FileUnmapDeleter { @@ -102,7 +102,7 @@ struct FileUnmapDeleter { using namespace std::literals; // Bison 3.6 changed token "types" to "kinds"; cast to int for simple compatibility -#define T_(name) (int)yy::parser::token::name +#define T_(name) static_cast(yy::parser::token::name) struct Token { int type; @@ -424,7 +424,7 @@ bool LexerState::setFileAsNextState(std::string const &filePath, bool updateStat bool isMmapped = false; - if (size_t size = (size_t)statBuf.st_size; statBuf.st_size > 0) { + if (size_t size = static_cast(statBuf.st_size); statBuf.st_size > 0) { // Try using `mmap` for better performance if (char *mappingAddr = mapFile(fd, path, size); mappingAddr != nullptr) { close(fd); @@ -543,7 +543,7 @@ size_t BufferedContent::readMore(size_t startIndex, size_t nbChars) { size += nbReadChars; // `nbReadChars` cannot be negative, so it's fine to cast to `size_t` - return (size_t)nbReadChars; + return static_cast(nbReadChars); } void lexer_SetMode(LexerMode mode) { @@ -709,20 +709,20 @@ int LexerState::peekChar() { // This is `.peekCharAhead()` modified for zero lookahead distance for (Expansion &exp : expansions) { if (exp.offset < exp.size()) - return (uint8_t)(*exp.contents)[exp.offset]; + return static_cast((*exp.contents)[exp.offset]); } if (content.holds()) { auto &view = content.get(); if (view.offset < view.span.size) - return (uint8_t)view.span.ptr[view.offset]; + return static_cast(view.span.ptr[view.offset]); } else { auto &cbuf = content.get(); if (cbuf.size == 0) cbuf.refill(); assume(cbuf.offset < LEXER_BUF_SIZE); if (cbuf.size > 0) - return (uint8_t)cbuf.buf[cbuf.offset]; + return static_cast(cbuf.buf[cbuf.offset]); } // If there aren't enough chars, give up @@ -738,21 +738,21 @@ int LexerState::peekCharAhead() { // and `.peekCharAhead()` will continue with its parent assume(exp.offset <= exp.size()); if (exp.offset + distance < exp.size()) - return (uint8_t)(*exp.contents)[exp.offset + distance]; + return static_cast((*exp.contents)[exp.offset + distance]); distance -= exp.size() - exp.offset; } if (content.holds()) { auto &view = content.get(); if (view.offset + distance < view.span.size) - return (uint8_t)view.span.ptr[view.offset + distance]; + return static_cast(view.span.ptr[view.offset + distance]); } else { auto &cbuf = content.get(); assume(distance < LEXER_BUF_SIZE); if (cbuf.size <= distance) cbuf.refill(); if (cbuf.size > distance) - return (uint8_t)cbuf.buf[(cbuf.offset + distance) % LEXER_BUF_SIZE]; + return static_cast(cbuf.buf[(cbuf.offset + distance) % LEXER_BUF_SIZE]); } // If there aren't enough chars, give up @@ -1032,11 +1032,12 @@ static uint32_t readFractionalPart(uint32_t integer) { precision = fixPrecision; } - if (integer >= ((uint64_t)1 << (32 - precision))) + if (integer >= (1ULL << (32 - precision))) warning(WARNING_LARGE_CONSTANT, "Magnitude of fixed-point constant is too large\n"); // Cast to unsigned avoids undefined overflow behavior - uint32_t fractional = (uint32_t)round((double)value / divisor * pow(2.0, precision)); + uint32_t fractional = + static_cast(round(static_cast(value) / divisor * pow(2.0, precision))); return (integer << precision) | fractional; } diff --git a/src/asm/macro.cpp b/src/asm/macro.cpp index f04ec203..4a6d9006 100644 --- a/src/asm/macro.cpp +++ b/src/asm/macro.cpp @@ -55,10 +55,10 @@ void MacroArgs::appendArg(std::shared_ptr arg) { void MacroArgs::shiftArgs(int32_t count) { if (size_t nbArgs = args.size(); - count > 0 && ((uint32_t)count > nbArgs || shift > nbArgs - count)) { + count > 0 && (static_cast(count) > nbArgs || shift > nbArgs - count)) { warning(WARNING_MACRO_SHIFT, "Cannot shift macro arguments past their end\n"); shift = nbArgs; - } else if (count < 0 && shift < (uint32_t)-count) { + } else if (count < 0 && shift < static_cast(-count)) { warning(WARNING_MACRO_SHIFT, "Cannot shift macro arguments past their beginning\n"); shift = 0; } else { diff --git a/src/asm/main.cpp b/src/asm/main.cpp index d12cc47c..6b7cf2f6 100644 --- a/src/asm/main.cpp +++ b/src/asm/main.cpp @@ -112,7 +112,7 @@ int main(int argc, char *argv[]) { // Support SOURCE_DATE_EPOCH for reproducible builds // https://reproducible-builds.org/docs/source-date-epoch/ if (char const *sourceDateEpoch = getenv("SOURCE_DATE_EPOCH"); sourceDateEpoch) - now = (time_t)strtoul(sourceDateEpoch, nullptr, 0); + now = static_cast(strtoul(sourceDateEpoch, nullptr, 0)); Defer closeDependFile{[&] { if (dependFile) diff --git a/src/asm/output.cpp b/src/asm/output.cpp index c9873175..01b17a3a 100644 --- a/src/asm/output.cpp +++ b/src/asm/output.cpp @@ -40,10 +40,10 @@ static std::deque> fileStackNodes; static void putLong(uint32_t n, FILE *file) { uint8_t bytes[] = { - (uint8_t)n, - (uint8_t)(n >> 8), - (uint8_t)(n >> 16), - (uint8_t)(n >> 24), + static_cast(n), + static_cast(n >> 8), + static_cast(n >> 16), + static_cast(n >> 24), }; fwrite(bytes, 1, sizeof(bytes), file); } @@ -55,25 +55,25 @@ static void putString(std::string const &s, FILE *file) { void out_RegisterNode(std::shared_ptr node) { // If node is not already registered, register it (and parents), and give it a unique ID - for (; node && node->ID == (uint32_t)-1; node = node->parent) { + for (; node && node->ID == UINT32_MAX; node = node->parent) { node->ID = fileStackNodes.size(); fileStackNodes.push_front(node); } } -// Return a section's ID, or -1 if the section is not in the list +// Return a section's ID, or UINT32_MAX if the section is not in the list static uint32_t getSectIDIfAny(Section *sect) { if (!sect) - return (uint32_t)-1; + return UINT32_MAX; if (auto search = sectionMap.find(sect->name); search != sectionMap.end()) - return (uint32_t)(sectionMap.size() - search->second - 1); + return static_cast(sectionMap.size() - search->second - 1); fatalerror("Unknown section '%s'\n", sect->name.c_str()); } static void writePatch(Patch const &patch, FILE *file) { - assume(patch.src->ID != (uint32_t)-1); + assume(patch.src->ID != UINT32_MAX); putLong(patch.src->ID, file); putLong(patch.lineNo, file); @@ -86,7 +86,7 @@ static void writePatch(Patch const &patch, FILE *file) { } static void writeSection(Section const §, FILE *file) { - assume(sect.src->ID != (uint32_t)-1); + assume(sect.src->ID != UINT32_MAX); putString(sect.name, file); @@ -119,7 +119,7 @@ static void writeSymbol(Symbol const &sym, FILE *file) { if (!sym.isDefined()) { putc(SYMTYPE_IMPORT, file); } else { - assume(sym.src->ID != (uint32_t)-1); + assume(sym.src->ID != UINT32_MAX); putc(sym.isExported ? SYMTYPE_EXPORT : SYMTYPE_LOCAL, file); putLong(sym.src->ID, file); @@ -131,7 +131,7 @@ static void writeSymbol(Symbol const &sym, FILE *file) { static void registerUnregisteredSymbol(Symbol &sym) { // Check for `sym.src`, to skip any built-in symbol from rgbasm - if (sym.src && sym.ID == (uint32_t)-1 && !sym_IsPC(&sym)) { + if (sym.src && sym.ID == UINT32_MAX && !sym_IsPC(&sym)) { sym.ID = objectSymbols.size(); // Set the symbol's ID within the object file objectSymbols.push_back(&sym); out_RegisterNode(sym.src); @@ -288,7 +288,7 @@ static void writeAssert(Assertion &assert, FILE *file) { } static void writeFileStackNode(FileStackNode const &node, FILE *file) { - putLong(node.parent ? node.parent->ID : (uint32_t)-1, file); + putLong(node.parent ? node.parent->ID : UINT32_MAX, file); putLong(node.lineNo, file); putc(node.type, file); if (node.type != NODE_REPT) { diff --git a/src/asm/parser.y b/src/asm/parser.y index f4aae733..820ddf49 100644 --- a/src/asm/parser.y +++ b/src/asm/parser.y @@ -707,7 +707,7 @@ align_spec: } else if ($3 <= -(1 << $1) || $3 >= 1 << $1) { ::error( "The absolute alignment offset (%" PRIu32 ") must be less than alignment size (%d)\n", - (uint32_t)($3 < 0 ? -$3 : $3), + static_cast($3 < 0 ? -$3 : $3), 1 << $1 ); $$.alignment = $$.alignOfs = 0; @@ -1636,7 +1636,7 @@ strfmt_va_args: %empty {} | strfmt_va_args COMMA const_no_str { $$ = std::move($1); - $$.args.push_back((uint32_t)$3); + $$.args.push_back(static_cast($3)); } | strfmt_va_args COMMA string { $$ = std::move($1); @@ -2456,7 +2456,7 @@ static uint32_t strToNum(std::vector const &s) { if (length == 1) { // The string is a single character with a single value, // which can be used directly as a number. - return (uint32_t)s[0]; + return static_cast(s[0]); } warning(WARNING_OBSOLETE, "Treating multi-unit strings as numbers is deprecated\n"); @@ -2601,7 +2601,7 @@ static uint32_t adjustNegativePos(int32_t pos, size_t len, char const *functionN warning(WARNING_BUILTIN_ARG, "%s: Position starts at 1\n", functionName); pos = 1; } - return (uint32_t)pos; + return static_cast(pos); } static std::string strrpl(std::string_view str, std::string const &old, std::string const &rep) { diff --git a/src/asm/rpn.cpp b/src/asm/rpn.cpp index 827769a7..126c0248 100644 --- a/src/asm/rpn.cpp +++ b/src/asm/rpn.cpp @@ -48,7 +48,7 @@ int32_t Expression::getConstVal() const { Symbol const *Expression::symbolOf() const { if (!isSymbol) return nullptr; - return sym_FindScopedSymbol((char const *)&rpn[1]); + return sym_FindScopedSymbol(reinterpret_cast(&rpn[1])); } bool Expression::isDiffConstant(Symbol const *sym) const { @@ -65,7 +65,7 @@ bool Expression::isDiffConstant(Symbol const *sym) const { void Expression::makeNumber(uint32_t value) { clear(); - data = (int32_t)value; + data = static_cast(value); } void Expression::makeSymbol(std::string const &symName) { @@ -89,7 +89,7 @@ void Expression::makeSymbol(std::string const &symName) { *ptr++ = RPN_SYM; memcpy(ptr, sym->name.c_str(), nameLen); } else { - data = (int32_t)sym_GetConstantValue(symName); + data = static_cast(sym_GetConstantValue(symName)); } } @@ -100,12 +100,12 @@ void Expression::makeBankSymbol(std::string const &symName) { if (!currentSection) { error("PC has no bank outside of a section\n"); data = 1; - } else if (currentSection->bank == (uint32_t)-1) { + } else if (currentSection->bank == UINT32_MAX) { data = "Current section's bank is not known"; *reserveSpace(1) = RPN_BANK_SELF; } else { - data = (int32_t)currentSection->bank; + data = static_cast(currentSection->bank); } return; } else if (sym && !sym->isLabel()) { @@ -115,9 +115,9 @@ void Expression::makeBankSymbol(std::string const &symName) { sym = sym_Ref(symName); assume(sym); // If the symbol didn't exist, it should have been created - if (sym->getSection() && sym->getSection()->bank != (uint32_t)-1) { + if (sym->getSection() && sym->getSection()->bank != UINT32_MAX) { // Symbol's section is known and bank is fixed - data = (int32_t)sym->getSection()->bank; + data = static_cast(sym->getSection()->bank); } else { data = sym_IsPurgedScoped(symName) ? "\""s + symName + "\"'s bank is not known; it was purged" @@ -135,8 +135,8 @@ void Expression::makeBankSymbol(std::string const &symName) { void Expression::makeBankSection(std::string const §Name) { clear(); - if (Section *sect = sect_FindSectionByName(sectName); sect && sect->bank != (uint32_t)-1) { - data = (int32_t)sect->bank; + if (Section *sect = sect_FindSectionByName(sectName); sect && sect->bank != UINT32_MAX) { + data = static_cast(sect->bank); } else { data = "Section \""s + sectName + "\"'s bank is not known"; @@ -151,7 +151,7 @@ void Expression::makeBankSection(std::string const §Name) { void Expression::makeSizeOfSection(std::string const §Name) { clear(); if (Section *sect = sect_FindSectionByName(sectName); sect && sect->isSizeKnown()) { - data = (int32_t)sect->size; + data = static_cast(sect->size); } else { data = "Section \""s + sectName + "\"'s size is not known"; @@ -165,8 +165,8 @@ void Expression::makeSizeOfSection(std::string const §Name) { void Expression::makeStartOfSection(std::string const §Name) { clear(); - if (Section *sect = sect_FindSectionByName(sectName); sect && sect->org != (uint32_t)-1) { - data = (int32_t)sect->org; + if (Section *sect = sect_FindSectionByName(sectName); sect && sect->org != UINT32_MAX) { + data = static_cast(sect->org); } else { data = "Section \""s + sectName + "\"'s start is not known"; @@ -216,9 +216,9 @@ static bool tryConstLogNot(Expression const &expr) { Section const § = *sym->getSection(); int32_t unknownBits = (1 << 16) - (1 << sect.align); - // `sym->getValue()` attempts to add the section's address, but that's "-1" + // `sym->getValue()` attempts to add the section's address, but that's `UINT32_MAX` // because the section is floating (otherwise we wouldn't be here) - assume(sect.org == (uint32_t)-1); + assume(sect.org == UINT32_MAX); int32_t symbolOfs = sym->getValue() + 1; int32_t knownBits = (symbolOfs + sect.alignOfs) & ~unknownBits; @@ -243,9 +243,9 @@ static int32_t tryConstLow(Expression const &expr) { if (sect.align < 8) return -1; - // `sym->getValue()` attempts to add the section's address, but that's "-1" + // `sym->getValue()` attempts to add the section's address, but that's `UINT32_MAX` // because the section is floating (otherwise we wouldn't be here) - assume(sect.org == (uint32_t)-1); + assume(sect.org == UINT32_MAX); int32_t symbolOfs = sym->getValue() + 1; return (symbolOfs + sect.alignOfs) & 0xFF; @@ -284,9 +284,9 @@ static int32_t tryConstMask(Expression const &lhs, Expression const &rhs) { if (int32_t unknownBits = (1 << 16) - (1 << sect.align); (unknownBits & mask) != 0) return -1; - // `sym.getValue()` attempts to add the section's address, but that's "-1" + // `sym.getValue()` attempts to add the section's address, but that's `UINT32_MAX` // because the section is floating (otherwise we wouldn't be here) - assume(sect.org == (uint32_t)-1); + assume(sect.org == UINT32_MAX); int32_t symbolOfs = sym.getValue() + 1; return (symbolOfs + sect.alignOfs) & mask; @@ -298,10 +298,11 @@ void Expression::makeUnaryOp(RPNCommand op, Expression &&src) { if (src.isKnown()) { // If the expressions is known, just compute the value int32_t val = src.value(); + uint32_t uval = static_cast(val); switch (op) { case RPN_NEG: - data = (int32_t) - (uint32_t)val; + data = static_cast(-uval); break; case RPN_NOT: data = ~val; @@ -310,16 +311,16 @@ void Expression::makeUnaryOp(RPNCommand op, Expression &&src) { data = !val; break; case RPN_HIGH: - data = (int32_t)((uint32_t)val >> 8 & 0xFF); + data = static_cast(uval >> 8 & 0xFF); break; case RPN_LOW: data = val & 0xFF; break; case RPN_BITWIDTH: - data = val != 0 ? 32 - clz((uint32_t)val) : 0; + data = val != 0 ? 32 - clz(uval) : 0; break; case RPN_TZCOUNT: - data = val != 0 ? ctz((uint32_t)val) : 32; + data = val != 0 ? ctz(uval) : 32; break; case RPN_LOGOR: @@ -374,6 +375,7 @@ void Expression::makeBinaryOp(RPNCommand op, Expression &&src1, Expression const if (src1.isKnown() && src2.isKnown()) { // If both expressions are known, just compute the value int32_t lval = src1.value(), rval = src2.value(); + uint32_t ulval = static_cast(lval), urval = static_cast(rval); switch (op) { case RPN_LOGOR: @@ -401,10 +403,10 @@ void Expression::makeBinaryOp(RPNCommand op, Expression &&src1, Expression const data = lval != rval; break; case RPN_ADD: - data = (int32_t)((uint32_t)lval + (uint32_t)rval); + data = static_cast(ulval + urval); break; case RPN_SUB: - data = (int32_t)((uint32_t)lval - (uint32_t)rval); + data = static_cast(ulval - urval); break; case RPN_XOR: data = lval ^ rval; @@ -452,7 +454,7 @@ void Expression::makeBinaryOp(RPNCommand op, Expression &&src1, Expression const data = op_shift_right_unsigned(lval, rval); break; case RPN_MUL: - data = (int32_t)((uint32_t)lval * (uint32_t)rval); + data = static_cast(ulval * urval); break; case RPN_DIV: if (rval == 0) @@ -522,10 +524,10 @@ void Expression::makeBinaryOp(RPNCommand op, Expression &&src1, Expression const uint32_t lval = src1.value(); uint8_t bytes[] = { RPN_CONST, - (uint8_t)lval, - (uint8_t)(lval >> 8), - (uint8_t)(lval >> 16), - (uint8_t)(lval >> 24), + static_cast(lval), + static_cast(lval >> 8), + static_cast(lval >> 16), + static_cast(lval >> 24), }; rpn.clear(); rpnPatchSize = 0; @@ -546,10 +548,10 @@ void Expression::makeBinaryOp(RPNCommand op, Expression &&src1, Expression const uint32_t rval = src2.value(); uint8_t bytes[] = { RPN_CONST, - (uint8_t)rval, - (uint8_t)(rval >> 8), - (uint8_t)(rval >> 16), - (uint8_t)(rval >> 24), + static_cast(rval), + static_cast(rval >> 8), + static_cast(rval >> 16), + static_cast(rval >> 24), }; uint8_t *ptr = reserveSpace(sizeof(bytes) + 1, sizeof(bytes) + 1); memcpy(ptr, bytes, sizeof(bytes)); diff --git a/src/asm/section.cpp b/src/asm/section.cpp index 94c3746a..25553888 100644 --- a/src/asm/section.cpp +++ b/src/asm/section.cpp @@ -109,9 +109,9 @@ static unsigned int mergeSectUnion( if (sect_HasData(type)) sectError("Cannot declare ROM sections as UNION\n"); - if (org != (uint32_t)-1) { + if (org != UINT32_MAX) { // If both are fixed, they must be the same - if (sect.org != (uint32_t)-1 && sect.org != org) + if (sect.org != UINT32_MAX && sect.org != org) sectError( "Section already declared as fixed at different address $%04" PRIx32 "\n", sect.org ); @@ -127,7 +127,7 @@ static unsigned int mergeSectUnion( } else if (alignment != 0) { // Make sure any fixed address given is compatible - if (sect.org != (uint32_t)-1) { + if (sect.org != UINT32_MAX) { if ((sect.org - alignOffset) & mask(alignment)) sectError( "Section already declared as fixed at incompatible address $%04" PRIx32 "\n", @@ -159,11 +159,11 @@ static unsigned int // Fragments only need "compatible" constraints, and they end up with the strictest // combination of both. // The merging is however performed at the *end* of the original section! - if (org != (uint32_t)-1) { + if (org != UINT32_MAX) { uint16_t curOrg = org - sect.size; // If both are fixed, they must be the same - if (sect.org != (uint32_t)-1 && sect.org != curOrg) + if (sect.org != UINT32_MAX && sect.org != curOrg) sectError( "Section already declared as fixed at incompatible address $%04" PRIx32 "\n", sect.org @@ -185,7 +185,7 @@ static unsigned int curOfs += 1U << alignment; // Make sure any fixed address given is compatible - if (sect.org != (uint32_t)-1) { + if (sect.org != UINT32_MAX) { if ((sect.org - curOfs) & mask(alignment)) sectError( "Section already declared as fixed at incompatible address $%04" PRIx32 "\n", @@ -238,10 +238,10 @@ static void mergeSections( // Common checks // If the section's bank is unspecified, override it - if (sect.bank == (uint32_t)-1) + if (sect.bank == UINT32_MAX) sect.bank = bank; // If both specify a bank, it must be the same one - else if (bank != (uint32_t)-1 && sect.bank != bank) + else if (bank != UINT32_MAX && sect.bank != bank) sectError("Section already declared with different bank %" PRIu32 "\n", sect.bank); break; @@ -312,7 +312,7 @@ static Section *getSection( // First, validate parameters, and normalize them if applicable - if (bank != (uint32_t)-1) { + if (bank != UINT32_MAX) { if (type != SECTTYPE_ROMX && type != SECTTYPE_VRAM && type != SECTTYPE_SRAM && type != SECTTYPE_WRAMX) error("BANK only allowed for ROMX, WRAMX, SRAM, or VRAM sections\n"); @@ -338,7 +338,7 @@ static Section *getSection( alignOffset = 0; } - if (org != (uint32_t)-1) { + if (org != UINT32_MAX) { if (org < sectionTypeInfo[type].startAddr || org > endaddr(type)) error( "Section \"%s\"'s fixed address $%04" PRIx32 " is outside of range [$%04" PRIx16 @@ -358,7 +358,7 @@ static Section *getSection( // It doesn't make sense to have both alignment and org set uint32_t mask = mask(alignment); - if (org != (uint32_t)-1) { + if (org != UINT32_MAX) { if ((org - alignOffset) & mask) error("Section \"%s\"'s fixed address doesn't match its alignment\n", name.c_str()); alignment = 0; // Ignore it if it's satisfied @@ -518,7 +518,7 @@ uint32_t sect_GetAlignBytes(uint8_t alignment, uint16_t offset) { if (!sect) return 0; - bool isFixed = sect->org != (uint32_t)-1; + bool isFixed = sect->org != UINT32_MAX; // If the section is not aligned, no bytes are needed // (fixed sections count as being maximally aligned for this purpose) @@ -539,7 +539,7 @@ void sect_AlignPC(uint8_t alignment, uint16_t offset) { Section *sect = sect_GetSymbolSection(); uint32_t alignSize = 1 << alignment; // Size of an aligned "block" - if (sect->org != (uint32_t)-1) { + if (sect->org != UINT32_MAX) { if ((sect->org + curOffset - offset) % alignSize) error( "Section's fixed address fails required alignment (PC = $%04" PRIx32 ")\n", diff --git a/src/asm/symbol.cpp b/src/asm/symbol.cpp index 9b946f9c..fa829268 100644 --- a/src/asm/symbol.cpp +++ b/src/asm/symbol.cpp @@ -123,7 +123,7 @@ static void updateSymbolFilename(Symbol &sym) { sym.fileLine = sym.src ? lexer_GetLineNo() : 0; // If the old node was registered, ensure the new one is too - if (oldSrc && oldSrc->ID != (uint32_t)-1) + if (oldSrc && oldSrc->ID != UINT32_MAX) out_RegisterNode(sym.src); } @@ -258,7 +258,7 @@ void sym_Purge(std::string const &symName) { error("'%s' not defined\n", symName.c_str()); } else if (sym->isBuiltin) { error("Built-in symbol '%s' cannot be purged\n", symName.c_str()); - } else if (sym->ID != (uint32_t)-1) { + } else if (sym->ID != UINT32_MAX) { error("Symbol \"%s\" is referenced and thus cannot be purged\n", symName.c_str()); } else { if (sym->isExported) @@ -460,7 +460,7 @@ static Symbol *addLabel(std::string const &symName) { } // If the symbol already exists as a ref, just "take over" it sym->type = SYM_LABEL; - sym->data = (int32_t)sect_GetSymbolOffset(); + sym->data = static_cast(sect_GetSymbolOffset()); // Don't export anonymous labels if (exportAll && !symName.starts_with('!')) sym->isExported = true; @@ -627,7 +627,7 @@ void sym_Init(time_t now) { sym_AddEqu("__RGBDS_RC__"s, PACKAGE_VERSION_RC)->isBuiltin = true; #endif - if (now == (time_t)-1) { + if (now == static_cast(-1)) { warn("Failed to determine current time"); // Fall back by pretending we are at the Epoch now = 0; diff --git a/src/fix/main.cpp b/src/fix/main.cpp index 46b9c28c..ce9a1d8d 100644 --- a/src/fix/main.cpp +++ b/src/fix/main.cpp @@ -227,7 +227,7 @@ static MbcType parseMBC(char const *name) { return MBC_BAD; if (mbc > 0xFF) return MBC_BAD_RANGE; - return (MbcType)mbc; + return static_cast(mbc); } else { // Begin by reading the MBC type: @@ -568,7 +568,7 @@ static MbcType parseMBC(char const *name) { if (*ptr) return MBC_BAD; - return (MbcType)mbc; + return static_cast(mbc); } } @@ -882,9 +882,9 @@ static void processFile(int input, int output, char const *name, off_t fileSize) report( "FATAL: \"%s\" too short, expected at least %jd ($%jx) bytes, got only %jd\n", name, - (intmax_t)headerSize, - (intmax_t)headerSize, - (intmax_t)rom0Len + static_cast(headerSize), + static_cast(headerSize), + static_cast(rom0Len) ); return; } @@ -894,17 +894,27 @@ static void processFile(int input, int output, char const *name, off_t fileSize) overwriteBytes(rom0, 0x0104, logo, sizeof(logo), logoFilename ? "logo" : "Nintendo logo"); if (title) - overwriteBytes(rom0, 0x134, (uint8_t const *)title, titleLen, "title"); + overwriteBytes(rom0, 0x134, reinterpret_cast(title), titleLen, "title"); if (gameID) - overwriteBytes(rom0, 0x13F, (uint8_t const *)gameID, gameIDLen, "manufacturer code"); + overwriteBytes( + rom0, + 0x13F, + reinterpret_cast(gameID), + gameIDLen, + "manufacturer code" + ); if (model != DMG) overwriteByte(rom0, 0x143, model == BOTH ? 0x80 : 0xC0, "CGB flag"); if (newLicensee) overwriteBytes( - rom0, 0x144, (uint8_t const *)newLicensee, newLicenseeLen, "new licensee code" + rom0, + 0x144, + reinterpret_cast(newLicensee), + newLicenseeLen, + "new licensee code" ); if (sgb) @@ -1076,7 +1086,10 @@ static void processFile(int input, int output, char const *name, off_t fileSize) if (fixSpec & TRASH_GLOBAL_SUM) globalSum = ~globalSum; - uint8_t bytes[2] = {(uint8_t)(globalSum >> 8), (uint8_t)(globalSum & 0xFF)}; + uint8_t bytes[2] = { + static_cast(globalSum >> 8), + static_cast(globalSum & 0xFF) + }; overwriteBytes(rom0, 0x14E, bytes, sizeof(bytes), "global checksum"); } @@ -1086,7 +1099,7 @@ static void processFile(int input, int output, char const *name, off_t fileSize) // In case the output depends on the input, reset to the beginning of the file, and only // write the header if (input == output) { - if (lseek(output, 0, SEEK_SET) == (off_t)-1) { + if (lseek(output, 0, SEEK_SET) == static_cast(-1)) { report("FATAL: Failed to rewind \"%s\": %s\n", name, strerror(errno)); return; } @@ -1103,9 +1116,9 @@ static void processFile(int input, int output, char const *name, off_t fileSize) } else if (writeLen < rom0Len) { report( "FATAL: Could only write %jd of \"%s\"'s %jd ROM0 bytes\n", - (intmax_t)writeLen, + static_cast(writeLen), name, - (intmax_t)rom0Len + static_cast(rom0Len) ); return; } @@ -1118,10 +1131,10 @@ static void processFile(int input, int output, char const *name, off_t fileSize) if (writeLen == -1) { report("FATAL: Failed to write \"%s\"'s ROMX: %s\n", name, strerror(errno)); return; - } else if ((size_t)writeLen < totalRomxLen) { + } else if (static_cast(writeLen) < totalRomxLen) { report( "FATAL: Could only write %jd of \"%s\"'s %zu ROMX bytes\n", - (intmax_t)writeLen, + static_cast(writeLen), name, totalRomxLen ); @@ -1132,7 +1145,7 @@ static void processFile(int input, int output, char const *name, off_t fileSize) // Output padding if (padValue != UNSPECIFIED) { if (input == output) { - if (lseek(output, 0, SEEK_END) == (off_t)-1) { + if (lseek(output, 0, SEEK_END) == static_cast(-1)) { report("FATAL: Failed to seek to end of \"%s\": %s\n", name, strerror(errno)); return; } @@ -1147,7 +1160,7 @@ static void processFile(int input, int output, char const *name, off_t fileSize) // The return value is either -1, or at most `thisLen`, // so it's fine to cast to `size_t` - if ((size_t)ret != thisLen) { + if (static_cast(ret) != thisLen) { report("FATAL: Failed to write \"%s\"'s padding: %s\n", name, strerror(errno)); break; } @@ -1188,7 +1201,7 @@ static bool processFilename(char const *name) { report( "FATAL: \"%s\" too short, expected at least 336 ($150) bytes, got only %jd\n", name, - (intmax_t)stat.st_size + static_cast(stat.st_size) ); } else { processFile(input, input, name, stat.st_size); diff --git a/src/gfx/process.cpp b/src/gfx/process.cpp index 9bcb64e5..94a567fa 100644 --- a/src/gfx/process.cpp +++ b/src/gfx/process.cpp @@ -104,7 +104,7 @@ class Png { "bytes after reading %zu)", self->c_str(), length - nbBytesRead, - (size_t)self->file->pubseekoff(0, std::ios_base::cur) + static_cast(self->file->pubseekoff(0, std::ios_base::cur)) ); } } @@ -193,7 +193,7 @@ public: options.verbosePrint(Options::VERB_INTERM, "PNG header signature is OK\n"); png = png_create_read_struct( - PNG_LIBPNG_VER_STRING, (png_voidp)this, handleError, handleWarning + PNG_LIBPNG_VER_STRING, static_cast(this), handleError, handleWarning ); if (!png) { fatal("Failed to allocate PNG structure: %s", strerror(errno)); diff --git a/src/gfx/reverse.cpp b/src/gfx/reverse.cpp index 57b16379..82904156 100644 --- a/src/gfx/reverse.cpp +++ b/src/gfx/reverse.cpp @@ -164,7 +164,7 @@ void reverse() { // Pick the smallest width that will result in a landscape-aspect rectangular image. // Thus a prime number of tiles will result in a horizontal row. // This avoids redundancy with `-r 1` which results in a vertical column. - width = (size_t)ceil(sqrt(mapSize)); + width = static_cast(ceil(sqrt(mapSize))); for (; width < mapSize; ++width) { if (mapSize % width == 0) break; diff --git a/src/link/assign.cpp b/src/link/assign.cpp index 9a2e4edc..0cfc5a8d 100644 --- a/src/link/assign.cpp +++ b/src/link/assign.cpp @@ -248,7 +248,7 @@ static void placeSection(Section §ion) { bankMem.insert( bankMem.begin() + spaceIdx + 1, {.address = sectionEnd, - .size = (uint16_t)(freeSpace.address + freeSpace.size - sectionEnd)} + .size = static_cast(freeSpace.address + freeSpace.size - sectionEnd)} ); // **`freeSpace` cannot be reused from this point on, because `bankMem.insert` // invalidates all references to itself!** @@ -279,7 +279,7 @@ static void placeSection(Section §ion) { sizeof(where), "in bank $%02" PRIx32 " with align mask $%" PRIx16, section.bank, - (uint16_t)~section.alignMask + static_cast(~section.alignMask) ); else snprintf(where, sizeof(where), "in bank $%02" PRIx32, section.bank); @@ -291,7 +291,7 @@ static void placeSection(Section §ion) { where, sizeof(where), "with align mask $%" PRIx16 " and offset $%" PRIx16, - (uint16_t)~section.alignMask, + static_cast(~section.alignMask), section.alignOfs ); else diff --git a/src/link/main.cpp b/src/link/main.cpp index 2f542a70..8e0069a6 100644 --- a/src/link/main.cpp +++ b/src/link/main.cpp @@ -209,8 +209,8 @@ static void parseScrambleSpec(char const *spec) { // Remember where the region's name begins and ends char const *regionName = spec; size_t regionNameLen = strcspn(spec, "=, \t"); - // Length of region name string slice for printing, truncated if too long - int regionNamePrintLen = regionNameLen > INT_MAX ? INT_MAX : (int)regionNameLen; + // Length of region name string slice for print formatting, truncated if too long + int regionNameFmtLen = regionNameLen > INT_MAX ? INT_MAX : static_cast(regionNameLen); ScrambledRegion region = SCRAMBLE_UNK; // If this trips, `spec` must be pointing at a ',' or '=' (or NUL) due to the assumption @@ -228,7 +228,7 @@ static void parseScrambleSpec(char const *spec) { spec += regionNameLen + strspn(&spec[regionNameLen], " \t"); if (*spec != '\0' && *spec != ',' && *spec != '=') { argErr( - 'S', "Unexpected '%c' after region name \"%.*s\"", regionNamePrintLen, regionName + 'S', "Unexpected '%c' after region name \"%.*s\"", regionNameFmtLen, regionName ); // Skip to next ',' or '=' (or NUL) and keep parsing spec += 1 + strcspn(&spec[1], ",="); @@ -246,7 +246,7 @@ static void parseScrambleSpec(char const *spec) { } if (region == SCRAMBLE_UNK) - argErr('S', "Unknown region \"%.*s\"", regionNamePrintLen, regionName); + argErr('S', "Unknown region \"%.*s\"", regionNameFmtLen, regionName); if (*spec == '=') { spec++; // `strtoul` will skip the whitespace on its own @@ -254,7 +254,7 @@ static void parseScrambleSpec(char const *spec) { char *endptr; if (*spec == '\0' || *spec == ',') { - argErr('S', "Empty limit for region \"%.*s\"", regionNamePrintLen, regionName); + argErr('S', "Empty limit for region \"%.*s\"", regionNameFmtLen, regionName); goto next; } limit = strtoul(spec, &endptr, 10); @@ -263,7 +263,7 @@ static void parseScrambleSpec(char const *spec) { argErr( 'S', "Invalid non-numeric limit for region \"%.*s\"", - regionNamePrintLen, + regionNameFmtLen, regionName ); endptr = strchr(endptr, ','); @@ -274,7 +274,7 @@ static void parseScrambleSpec(char const *spec) { argErr( 'S', "Limit for region \"%.*s\" may not exceed %" PRIu16, - regionNamePrintLen, + regionNameFmtLen, regionName, scrambleSpecs[region].max ); @@ -298,7 +298,7 @@ static void parseScrambleSpec(char const *spec) { // Only WRAMX can be implied, since ROMX and SRAM size may vary scrambleWRAMX = 7; } else { - argErr('S', "Cannot imply limit for region \"%.*s\"", regionNamePrintLen, regionName); + argErr('S', "Cannot imply limit for region \"%.*s\"", regionNameFmtLen, regionName); } next: // Can't `continue` a `for` loop with this nontrivial iteration logic diff --git a/src/link/object.cpp b/src/link/object.cpp index fd17d85b..971a8b10 100644 --- a/src/link/object.cpp +++ b/src/link/object.cpp @@ -40,13 +40,13 @@ static std::vector> nodes; if (tmpVal == (errval)) { \ errx(__VA_ARGS__, feof(tmpFile) ? "Unexpected end of file" : strerror(errno)); \ } \ - var = (vartype)tmpVal; \ + var = static_cast(tmpVal); \ } while (0) /* * Reads an unsigned long (32-bit) value from a file. * @param file The file to read from. This will read 4 bytes from the file. - * @return The value read, cast to a int64_t, or -1 on failure. + * @return The value read, cast to a int64_t, or `INT64_MAX` on failure. */ static int64_t readLong(FILE *file) { uint32_t value = 0; @@ -63,7 +63,7 @@ static int64_t readLong(FILE *file) { // `uint8_t`, because int is large enough to hold a byte. This // however causes values larger than 127 to be too large when // shifted, potentially triggering undefined behavior. - value |= (unsigned int)byte << shift; + value |= static_cast(byte) << shift; } return value; } @@ -128,7 +128,7 @@ static void readFileStackNode( uint32_t parentID; tryReadLong(parentID, file, "%s: Cannot read node #%" PRIu32 "'s parent ID: %s", fileName, i); - node.parent = parentID != (uint32_t)-1 ? &fileNodes[parentID] : nullptr; + node.parent = parentID != UINT32_MAX ? &fileNodes[parentID] : nullptr; tryReadLong( node.lineNo, file, "%s: Cannot read node #%" PRIu32 "'s line number: %s", fileName, i ); @@ -329,7 +329,7 @@ static void readPatch( static void linkPatchToPCSect(Patch &patch, std::vector> const &fileSections) { patch.pcSection = - patch.pcSectionID != (uint32_t)-1 ? fileSections[patch.pcSectionID].get() : nullptr; + patch.pcSectionID != UINT32_MAX ? fileSections[patch.pcSectionID].get() : nullptr; } /* diff --git a/src/link/output.cpp b/src/link/output.cpp index f7760ce7..f1bfe94e 100644 --- a/src/link/output.cpp +++ b/src/link/output.cpp @@ -363,7 +363,7 @@ static void writeSymBank(SortedSections const &bankSections, SectionType type, u if (!sym->name.empty() && canStartSymName(sym->name[0])) symList.push_back({ .sym = sym, - .addr = (uint16_t)(sym->label().offset + sect->org), + .addr = static_cast(sym->label().offset + sect->org), }); } }); diff --git a/src/link/patch.cpp b/src/link/patch.cpp index 1d7d2764..a64f1df1 100644 --- a/src/link/patch.cpp +++ b/src/link/patch.cpp @@ -53,7 +53,7 @@ static uint32_t getRPNByte(uint8_t const *&expression, int32_t &size, Patch cons } static Symbol const *getSymbol(std::vector const &symbolList, uint32_t index) { - assume(index != (uint32_t)-1); // PC needs to be handled specially, not here + assume(index != UINT32_MAX); // PC needs to be handled specially, not here Symbol const &symbol = symbolList[index]; // If the symbol is defined elsewhere... @@ -73,12 +73,12 @@ static Symbol const *getSymbol(std::vector const &symbolList, uint32_t i */ static int32_t computeRPNExpr(Patch const &patch, std::vector const &fileSymbols) { uint8_t const *expression = patch.rpnExpression.data(); - int32_t size = (int32_t)patch.rpnExpression.size(); + int32_t size = static_cast(patch.rpnExpression.size()); rpnStack.clear(); while (size > 0) { - RPNCommand command = (RPNCommand)getRPNByte(expression, size, patch); + RPNCommand command = static_cast(getRPNByte(expression, size, patch)); int32_t value; isError = false; @@ -150,11 +150,11 @@ static int32_t computeRPNExpr(Patch const &patch, std::vector const &fil case RPN_BITWIDTH: value = popRPN(patch); - value = value != 0 ? 32 - clz((uint32_t)value) : 0; + value = value != 0 ? 32 - clz(static_cast(value)) : 0; break; case RPN_TZCOUNT: value = popRPN(patch); - value = value != 0 ? ctz((uint32_t)value) : 32; + value = value != 0 ? ctz(static_cast(value)) : 32; break; case RPN_OR: @@ -249,7 +249,7 @@ static int32_t computeRPNExpr(Patch const &patch, std::vector const &fil case RPN_BANK_SECT: { // `expression` is not guaranteed to be '\0'-terminated. If it is not, // `getRPNByte` will have a fatal internal error. - char const *name = (char const *)expression; + char const *name = reinterpret_cast(expression); while (getRPNByte(expression, size, patch)) ; @@ -280,7 +280,7 @@ static int32_t computeRPNExpr(Patch const &patch, std::vector const &fil case RPN_SIZEOF_SECT: { // This has assumptions commented in the `RPN_BANK_SECT` case above. - char const *name = (char const *)expression; + char const *name = reinterpret_cast(expression); while (getRPNByte(expression, size, patch)) ; @@ -301,7 +301,7 @@ static int32_t computeRPNExpr(Patch const &patch, std::vector const &fil case RPN_STARTOF_SECT: { // This has assumptions commented in the `RPN_BANK_SECT` case above. - char const *name = (char const *)expression; + char const *name = reinterpret_cast(expression); while (getRPNByte(expression, size, patch)) ; @@ -428,7 +428,7 @@ void patch_CheckAssertions() { for (Assertion &assert : assertions) { int32_t value = computeRPNExpr(assert.patch, *assert.fileSymbols); - AssertionType type = (AssertionType)assert.patch.type; + AssertionType type = static_cast(assert.patch.type); if (!isError && !value) { switch (type) { diff --git a/src/link/script.y b/src/link/script.y index 09b52e74..a534877f 100644 --- a/src/link/script.y +++ b/src/link/script.y @@ -557,8 +557,8 @@ static void alignTo(uint32_t alignment, uint32_t alignOfs) { "Cannot align: the next suitable address after $%04" PRIx16 " is $%04" PRIx16 ", past $%04" PRIx16, pc, - (uint16_t)(pc + length), - (uint16_t)(endaddr(activeType) + 1) + static_cast(pc + length), + static_cast(endaddr(activeType) + 1) ); return; } @@ -588,7 +588,7 @@ static void pad(uint32_t length) { "Cannot increase the current address by %u bytes: only %u bytes to $%04" PRIx16, length, typeInfo.size - offset, - (uint16_t)(endaddr(activeType) + 1) + static_cast(endaddr(activeType) + 1) ); } else { pc += length; @@ -689,7 +689,7 @@ static void placeSection(std::string const &name, bool isOptional) { name.c_str(), org, alignment, - (uint16_t)(org & section->alignMask), + static_cast(org & section->alignMask), alignment, section->alignOfs ); diff --git a/src/link/sdas_obj.cpp b/src/link/sdas_obj.cpp index 0697f965..5a03ff96 100644 --- a/src/link/sdas_obj.cpp +++ b/src/link/sdas_obj.cpp @@ -468,7 +468,7 @@ void sdobj_ReadFile(FileStackNode const &where, FILE *file, std::vector getToken(nullptr, "'R' line is too short"); areaIdx = parseByte(where, lineNo, token, numberType); getToken(nullptr, "'R' line is too short"); - areaIdx |= (uint16_t)parseByte(where, lineNo, token, numberType) << 8; + areaIdx |= static_cast(parseByte(where, lineNo, token, numberType)) << 8; if (areaIdx >= fileSections.size()) fatal( &where, @@ -532,8 +532,9 @@ void sdobj_ReadFile(FileStackNode const &where, FILE *file, std::vector if ((flags & 0xF0) == 0xF0) { getToken(nullptr, "Incomplete relocation"); - flags = - (flags & 0x0F) | (uint16_t)parseByte(where, lineNo, token, numberType) << 4; + flags = (flags & 0x0F) + | static_cast(parseByte(where, lineNo, token, numberType)) + << 4; } getToken(nullptr, "Incomplete relocation"); @@ -560,7 +561,7 @@ void sdobj_ReadFile(FileStackNode const &where, FILE *file, std::vector uint16_t idx = parseByte(where, lineNo, token, numberType); getToken(nullptr, "Incomplete relocation"); - idx |= (uint16_t)parseByte(where, lineNo, token, numberType); + idx |= static_cast(parseByte(where, lineNo, token, numberType)); // Loudly fail on unknown flags if (flags & (1 << RELOC_ZPAGE | 1 << RELOC_NPAGE)) @@ -646,7 +647,7 @@ void sdobj_ReadFile(FileStackNode const &where, FILE *file, std::vector patch.rpnExpression.resize(1 + sym.name.length() - 2 + 1); patch.rpnExpression[0] = RPN_SIZEOF_SECT; memcpy( - (char *)&patch.rpnExpression[1], + reinterpret_cast(&patch.rpnExpression[1]), &sym.name.c_str()[2], sym.name.length() - 2 + 1 ); @@ -654,7 +655,7 @@ void sdobj_ReadFile(FileStackNode const &where, FILE *file, std::vector patch.rpnExpression.resize(1 + sym.name.length() - 2 + 1); patch.rpnExpression[0] = RPN_STARTOF_SECT; memcpy( - (char *)&patch.rpnExpression[1], + reinterpret_cast(&patch.rpnExpression[1]), &sym.name.c_str()[2], sym.name.length() - 2 + 1 ); @@ -700,7 +701,11 @@ void sdobj_ReadFile(FileStackNode const &where, FILE *file, std::vector patch.rpnExpression.resize(1 + name.length() + 1); patch.rpnExpression[0] = RPN_STARTOF_SECT; // The cast is fine, it's just different signedness - memcpy((char *)&patch.rpnExpression[1], name.c_str(), name.length() + 1); + memcpy( + reinterpret_cast(&patch.rpnExpression[1]), + name.c_str(), + name.length() + 1 + ); } patch.rpnExpression.push_back(RPN_CONST); diff --git a/src/opmath.cpp b/src/opmath.cpp index e653e24f..619b3536 100644 --- a/src/opmath.cpp +++ b/src/opmath.cpp @@ -48,7 +48,7 @@ int32_t op_shift_left(int32_t value, int32_t amount) { // Use unsigned to force a bitwise shift // Casting back is OK because the types implement two's complement behavior - return (uint32_t)value << amount; + return static_cast(value) << amount; } int32_t op_shift_right(int32_t value, int32_t amount) { @@ -63,7 +63,7 @@ int32_t op_shift_right(int32_t value, int32_t amount) { return op_shift_left(value, -amount); if (value > 0) - return (uint32_t)value >> amount; + return static_cast(value) >> amount; // Calculate an OR mask for sign extension // 1->0x80000000, 2->0xC0000000, ..., 31->0xFFFFFFFE @@ -71,7 +71,7 @@ int32_t op_shift_right(int32_t value, int32_t amount) { // The C++ standard leaves shifting right negative values // undefined, so use a left shift manually sign-extended - return ((uint32_t)value >> amount) | amount_high_bits; + return (static_cast(value) >> amount) | amount_high_bits; } int32_t op_shift_right_unsigned(int32_t value, int32_t amount) { @@ -83,5 +83,5 @@ int32_t op_shift_right_unsigned(int32_t value, int32_t amount) { if (amount < 0) return op_shift_left(value, -amount); - return (uint32_t)value >> amount; + return static_cast(value) >> amount; } diff --git a/src/util.cpp b/src/util.cpp index 29bca3c3..60db9a38 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -43,7 +43,7 @@ char const *printChar(int c) { default: // Print as hex buf[0] = '0'; buf[1] = 'x'; - snprintf(&buf[2], 3, "%02hhX", (uint8_t)c); // includes the '\0' + snprintf(&buf[2], 3, "%02hhX", static_cast(c)); // includes the '\0' return buf; } buf[0] = '\''; diff --git a/test/gfx/randtilegen.cpp b/test/gfx/randtilegen.cpp index 154d227f..e4e06a0f 100644 --- a/test/gfx/randtilegen.cpp +++ b/test/gfx/randtilegen.cpp @@ -37,7 +37,7 @@ static unsigned long long getRandomBits(unsigned count) { if (data == EOF) { exit(0); } - randbits |= (unsigned long long)data << randcount; + randbits |= static_cast(data) << randcount; randcount += 8; } unsigned long long result = randbits & ((1ULL << count) - 1); diff --git a/test/gfx/rgbgfx_test.cpp b/test/gfx/rgbgfx_test.cpp index 16e30e25..e2bcd7a1 100644 --- a/test/gfx/rgbgfx_test.cpp +++ b/test/gfx/rgbgfx_test.cpp @@ -115,7 +115,7 @@ class Png { "bytes after reading %zu)", self->path.c_str(), length - nbBytesRead, - (size_t)self->file.pubseekoff(0, std::ios_base::cur) + static_cast(self->file.pubseekoff(0, std::ios_base::cur)) ); } } @@ -152,7 +152,7 @@ public: } png = png_create_read_struct( - PNG_LIBPNG_VER_STRING, (png_voidp)this, handleError, handleWarning + PNG_LIBPNG_VER_STRING, static_cast(this), handleError, handleWarning ); if (!png) { fatal("Failed to allocate PNG structure: %s", strerror(errno));