Use C++-style casts (#1576)

This commit is contained in:
Sylvie
2024-12-09 21:56:54 -05:00
committed by GitHub
parent e66da4c8c7
commit b877c81c32
33 changed files with 197 additions and 173 deletions

View File

@@ -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

View File

@@ -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 \

View File

@@ -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<uint32_t> &iters() { return data.get<std::vector<uint32_t>>(); }

View File

@@ -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;
}

View File

@@ -43,11 +43,11 @@ private:
// Generic field accessors; for internal use only.
template<typename T>
auto &field() {
return pick((T *)nullptr);
return pick(static_cast<T *>(nullptr));
}
template<typename T>
auto const &field() const {
return pick((T *)nullptr);
return pick(static_cast<T *>(nullptr));
}
public:

View File

@@ -28,7 +28,7 @@ struct Rgba {
_5to8(cgbColor),
_5to8(cgbColor >> 5),
_5to8(cgbColor >> 10),
(uint8_t)(cgbColor & 0x8000 ? 0x00 : 0xFF),
static_cast<uint8_t>(cgbColor & 0x8000 ? 0x00 : 0xFF),
};
}

View File

@@ -18,7 +18,7 @@ class EnumSeq {
explicit Iterator(T value) : _value(value) {}
Iterator &operator++() {
_value = (T)(_value + 1);
_value = static_cast<T>(_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<T>(0)), _stop(stop) {}
explicit EnumSeq(T start, T stop) : _start(start), _stop(stop) {}
Iterator begin() { return Iterator(_start); }

View File

@@ -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<char>(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<int32_t> &&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<uint8_t>(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<uint8_t>(c)];
if (!nodeIdx)
return false;
@@ -184,7 +184,7 @@ size_t charmap_ConvertNext(std::string_view &input, std::vector<int32_t> *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<uint8_t>(input[inputIdx])];
if (!nodeIdx)
break;

View File

@@ -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<int32_t>(round(d * pow(2.0, q)));
}
static double turn2rad(double t) {

View File

@@ -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<int>(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<uint32_t>(INT32_MIN) ? labs(static_cast<int32_t>(value)) : value;
snprintf(valueBuf, sizeof(valueBuf), "%" PRIu32, uval);
} else {
char const *spec = useType == 'u' ? "%" PRIu32

View File

@@ -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<uint32_t>(context.forValue) + static_cast<uint32_t>(context.forStep);
context.forValue =
forValue <= INT32_MAX ? forValue : -static_cast<int32_t>(~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<int64_t>(stop) - start - 1) / step + 1;
else if (step < 0 && stop < start)
count = ((int64_t)start - stop - 1) / -(int64_t)step + 1;
count = (static_cast<int64_t>(start) - stop - 1) / -static_cast<int64_t>(step) + 1;
else if (step == 0)
error("FOR cannot have a step value of 0\n");

View File

@@ -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<char *>(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<int>(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<size_t>(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<size_t>(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<uint8_t>((*exp.contents)[exp.offset]);
}
if (content.holds<ViewedContent>()) {
auto &view = content.get<ViewedContent>();
if (view.offset < view.span.size)
return (uint8_t)view.span.ptr[view.offset];
return static_cast<uint8_t>(view.span.ptr[view.offset]);
} else {
auto &cbuf = content.get<BufferedContent>();
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<uint8_t>(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<uint8_t>((*exp.contents)[exp.offset + distance]);
distance -= exp.size() - exp.offset;
}
if (content.holds<ViewedContent>()) {
auto &view = content.get<ViewedContent>();
if (view.offset + distance < view.span.size)
return (uint8_t)view.span.ptr[view.offset + distance];
return static_cast<uint8_t>(view.span.ptr[view.offset + distance]);
} else {
auto &cbuf = content.get<BufferedContent>();
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<uint8_t>(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<uint32_t>(round(static_cast<double>(value) / divisor * pow(2.0, precision)));
return (integer << precision) | fractional;
}

View File

@@ -55,10 +55,10 @@ void MacroArgs::appendArg(std::shared_ptr<std::string> 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<uint32_t>(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<uint32_t>(-count)) {
warning(WARNING_MACRO_SHIFT, "Cannot shift macro arguments past their beginning\n");
shift = 0;
} else {

View File

@@ -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<time_t>(strtoul(sourceDateEpoch, nullptr, 0));
Defer closeDependFile{[&] {
if (dependFile)

View File

@@ -40,10 +40,10 @@ static std::deque<std::shared_ptr<FileStackNode>> 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<uint8_t>(n),
static_cast<uint8_t>(n >> 8),
static_cast<uint8_t>(n >> 16),
static_cast<uint8_t>(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<FileStackNode> 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<uint32_t>(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 &sect, 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) {

View File

@@ -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<uint32_t>($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<uint32_t>($3));
}
| strfmt_va_args COMMA string {
$$ = std::move($1);
@@ -2456,7 +2456,7 @@ static uint32_t strToNum(std::vector<int32_t> 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<uint32_t>(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<uint32_t>(pos);
}
static std::string strrpl(std::string_view str, std::string const &old, std::string const &rep) {

View File

@@ -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<char const *>(&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<int32_t>(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<int32_t>(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<int32_t>(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<int32_t>(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 &sectName) {
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<int32_t>(sect->bank);
} else {
data = "Section \""s + sectName + "\"'s bank is not known";
@@ -151,7 +151,7 @@ void Expression::makeBankSection(std::string const &sectName) {
void Expression::makeSizeOfSection(std::string const &sectName) {
clear();
if (Section *sect = sect_FindSectionByName(sectName); sect && sect->isSizeKnown()) {
data = (int32_t)sect->size;
data = static_cast<int32_t>(sect->size);
} else {
data = "Section \""s + sectName + "\"'s size is not known";
@@ -165,8 +165,8 @@ void Expression::makeSizeOfSection(std::string const &sectName) {
void Expression::makeStartOfSection(std::string const &sectName) {
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<int32_t>(sect->org);
} else {
data = "Section \""s + sectName + "\"'s start is not known";
@@ -216,9 +216,9 @@ static bool tryConstLogNot(Expression const &expr) {
Section const &sect = *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<uint32_t>(val);
switch (op) {
case RPN_NEG:
data = (int32_t) - (uint32_t)val;
data = static_cast<int32_t>(-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<int32_t>(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<uint32_t>(lval), urval = static_cast<uint32_t>(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<int32_t>(ulval + urval);
break;
case RPN_SUB:
data = (int32_t)((uint32_t)lval - (uint32_t)rval);
data = static_cast<int32_t>(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<int32_t>(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<uint8_t>(lval),
static_cast<uint8_t>(lval >> 8),
static_cast<uint8_t>(lval >> 16),
static_cast<uint8_t>(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<uint8_t>(rval),
static_cast<uint8_t>(rval >> 8),
static_cast<uint8_t>(rval >> 16),
static_cast<uint8_t>(rval >> 24),
};
uint8_t *ptr = reserveSpace(sizeof(bytes) + 1, sizeof(bytes) + 1);
memcpy(ptr, bytes, sizeof(bytes));

View File

@@ -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",

View File

@@ -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<int32_t>(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<time_t>(-1)) {
warn("Failed to determine current time");
// Fall back by pretending we are at the Epoch
now = 0;

View File

@@ -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<MbcType>(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<MbcType>(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<intmax_t>(headerSize),
static_cast<intmax_t>(headerSize),
static_cast<intmax_t>(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<uint8_t const *>(title), titleLen, "title");
if (gameID)
overwriteBytes(rom0, 0x13F, (uint8_t const *)gameID, gameIDLen, "manufacturer code");
overwriteBytes(
rom0,
0x13F,
reinterpret_cast<uint8_t const *>(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<uint8_t const *>(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<uint8_t>(globalSum >> 8),
static_cast<uint8_t>(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<off_t>(-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<intmax_t>(writeLen),
name,
(intmax_t)rom0Len
static_cast<intmax_t>(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<size_t>(writeLen) < totalRomxLen) {
report(
"FATAL: Could only write %jd of \"%s\"'s %zu ROMX bytes\n",
(intmax_t)writeLen,
static_cast<intmax_t>(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<off_t>(-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<size_t>(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<intmax_t>(stat.st_size)
);
} else {
processFile(input, input, name, stat.st_size);

View File

@@ -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<size_t>(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<png_voidp>(this), handleError, handleWarning
);
if (!png) {
fatal("Failed to allocate PNG structure: %s", strerror(errno));

View File

@@ -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<size_t>(ceil(sqrt(mapSize)));
for (; width < mapSize; ++width) {
if (mapSize % width == 0)
break;

View File

@@ -248,7 +248,7 @@ static void placeSection(Section &section) {
bankMem.insert(
bankMem.begin() + spaceIdx + 1,
{.address = sectionEnd,
.size = (uint16_t)(freeSpace.address + freeSpace.size - sectionEnd)}
.size = static_cast<uint16_t>(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 &section) {
sizeof(where),
"in bank $%02" PRIx32 " with align mask $%" PRIx16,
section.bank,
(uint16_t)~section.alignMask
static_cast<uint16_t>(~section.alignMask)
);
else
snprintf(where, sizeof(where), "in bank $%02" PRIx32, section.bank);
@@ -291,7 +291,7 @@ static void placeSection(Section &section) {
where,
sizeof(where),
"with align mask $%" PRIx16 " and offset $%" PRIx16,
(uint16_t)~section.alignMask,
static_cast<uint16_t>(~section.alignMask),
section.alignOfs
);
else

View File

@@ -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<int>(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

View File

@@ -40,13 +40,13 @@ static std::vector<std::vector<FileStackNode>> nodes;
if (tmpVal == (errval)) { \
errx(__VA_ARGS__, feof(tmpFile) ? "Unexpected end of file" : strerror(errno)); \
} \
var = (vartype)tmpVal; \
var = static_cast<vartype>(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<unsigned int>(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<std::unique_ptr<Section>> const &fileSections) {
patch.pcSection =
patch.pcSectionID != (uint32_t)-1 ? fileSections[patch.pcSectionID].get() : nullptr;
patch.pcSectionID != UINT32_MAX ? fileSections[patch.pcSectionID].get() : nullptr;
}
/*

View File

@@ -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<uint16_t>(sym->label().offset + sect->org),
});
}
});

View File

@@ -53,7 +53,7 @@ static uint32_t getRPNByte(uint8_t const *&expression, int32_t &size, Patch cons
}
static Symbol const *getSymbol(std::vector<Symbol> 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<Symbol> const &symbolList, uint32_t i
*/
static int32_t computeRPNExpr(Patch const &patch, std::vector<Symbol> const &fileSymbols) {
uint8_t const *expression = patch.rpnExpression.data();
int32_t size = (int32_t)patch.rpnExpression.size();
int32_t size = static_cast<int32_t>(patch.rpnExpression.size());
rpnStack.clear();
while (size > 0) {
RPNCommand command = (RPNCommand)getRPNByte(expression, size, patch);
RPNCommand command = static_cast<RPNCommand>(getRPNByte(expression, size, patch));
int32_t value;
isError = false;
@@ -150,11 +150,11 @@ static int32_t computeRPNExpr(Patch const &patch, std::vector<Symbol> const &fil
case RPN_BITWIDTH:
value = popRPN(patch);
value = value != 0 ? 32 - clz((uint32_t)value) : 0;
value = value != 0 ? 32 - clz(static_cast<uint32_t>(value)) : 0;
break;
case RPN_TZCOUNT:
value = popRPN(patch);
value = value != 0 ? ctz((uint32_t)value) : 32;
value = value != 0 ? ctz(static_cast<uint32_t>(value)) : 32;
break;
case RPN_OR:
@@ -249,7 +249,7 @@ static int32_t computeRPNExpr(Patch const &patch, std::vector<Symbol> 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<char const *>(expression);
while (getRPNByte(expression, size, patch))
;
@@ -280,7 +280,7 @@ static int32_t computeRPNExpr(Patch const &patch, std::vector<Symbol> 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<char const *>(expression);
while (getRPNByte(expression, size, patch))
;
@@ -301,7 +301,7 @@ static int32_t computeRPNExpr(Patch const &patch, std::vector<Symbol> 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<char const *>(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<AssertionType>(assert.patch.type);
if (!isError && !value) {
switch (type) {

View File

@@ -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<uint16_t>(pc + length),
static_cast<uint16_t>(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<uint16_t>(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<uint16_t>(org & section->alignMask),
alignment,
section->alignOfs
);

View File

@@ -468,7 +468,7 @@ void sdobj_ReadFile(FileStackNode const &where, FILE *file, std::vector<Symbol>
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<uint16_t>(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<Symbol>
if ((flags & 0xF0) == 0xF0) {
getToken(nullptr, "Incomplete relocation");
flags =
(flags & 0x0F) | (uint16_t)parseByte(where, lineNo, token, numberType) << 4;
flags = (flags & 0x0F)
| static_cast<uint16_t>(parseByte(where, lineNo, token, numberType))
<< 4;
}
getToken(nullptr, "Incomplete relocation");
@@ -560,7 +561,7 @@ void sdobj_ReadFile(FileStackNode const &where, FILE *file, std::vector<Symbol>
uint16_t idx = parseByte(where, lineNo, token, numberType);
getToken(nullptr, "Incomplete relocation");
idx |= (uint16_t)parseByte(where, lineNo, token, numberType);
idx |= static_cast<uint16_t>(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<Symbol>
patch.rpnExpression.resize(1 + sym.name.length() - 2 + 1);
patch.rpnExpression[0] = RPN_SIZEOF_SECT;
memcpy(
(char *)&patch.rpnExpression[1],
reinterpret_cast<char *>(&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<Symbol>
patch.rpnExpression.resize(1 + sym.name.length() - 2 + 1);
patch.rpnExpression[0] = RPN_STARTOF_SECT;
memcpy(
(char *)&patch.rpnExpression[1],
reinterpret_cast<char *>(&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<Symbol>
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<char *>(&patch.rpnExpression[1]),
name.c_str(),
name.length() + 1
);
}
patch.rpnExpression.push_back(RPN_CONST);

View File

@@ -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<uint32_t>(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<uint32_t>(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<uint32_t>(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<uint32_t>(value) >> amount;
}

View File

@@ -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<uint8_t>(c)); // includes the '\0'
return buf;
}
buf[0] = '\'';

View File

@@ -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<unsigned long long>(data) << randcount;
randcount += 8;
}
unsigned long long result = randbits & ((1ULL << count) - 1);

View File

@@ -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<size_t>(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<png_voidp>(this), handleError, handleWarning
);
if (!png) {
fatal("Failed to allocate PNG structure: %s", strerror(errno));