Skip to content

Commit

Permalink
Enable -Wconversion (facebook#39291)
Browse files Browse the repository at this point in the history
Summary:
Pull Request resolved: facebook#39291

X-link: facebook/yoga#1359

This enables clang warnings around potentially unsafe conversions, such as those with mismatched signedness, or ones which may lead to truncation.

This should catch issues in local development which create errors for MSVC (e.g. Dash), who's default `/W3` includes warnings akin to `-Wshorten-64-to-32`.

This full set of warnings here is a tad spammy, but probably more useful than not.

Changelog: [Internal]

Reviewed By: yungsters

Differential Revision: D48954777

fbshipit-source-id: 1ccc07b99d09d1c2d428158149698ffd04025605
  • Loading branch information
NickGerleman authored and facebook-github-bot committed Sep 6, 2023
1 parent 850349b commit 9411e59
Show file tree
Hide file tree
Showing 13 changed files with 124 additions and 103 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@ namespace {
const int HAS_NEW_LAYOUT = 16;

union YGNodeContext {
uintptr_t edgesSet = 0;
int32_t edgesSet = 0;
void* asVoidPtr;
};

class YGNodeEdges {
uintptr_t edges_;
int32_t edges_;

public:
enum Edge {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ static int YGJNILogFunc(
va_list argsCopy;
va_copy(argsCopy, args);
int result = vsnprintf(nullptr, 0, format, argsCopy);
std::vector<char> buffer(1 + result);
std::vector<char> buffer(1 + static_cast<size_t>(result));
vsnprintf(buffer.data(), buffer.size(), format, args);

auto jloggerPtr =
Expand Down Expand Up @@ -236,7 +236,9 @@ static void jni_YGNodeInsertChildJNI(
jlong childPointer,
jint index) {
YGNodeInsertChild(
_jlong2YGNodeRef(nativePointer), _jlong2YGNodeRef(childPointer), index);
_jlong2YGNodeRef(nativePointer),
_jlong2YGNodeRef(childPointer),
static_cast<uint32_t>(index));
}

static void jni_YGNodeSwapChildJNI(
Expand All @@ -246,7 +248,9 @@ static void jni_YGNodeSwapChildJNI(
jlong childPointer,
jint index) {
YGNodeSwapChild(
_jlong2YGNodeRef(nativePointer), _jlong2YGNodeRef(childPointer), index);
_jlong2YGNodeRef(nativePointer),
_jlong2YGNodeRef(childPointer),
static_cast<uint32_t>(index));
}

static void jni_YGNodeSetIsReferenceBaselineJNI(
Expand Down Expand Up @@ -307,13 +311,13 @@ static void YGTransferLayoutOutputsRecursive(
const int arrSize = 6 + (marginFieldSet ? 4 : 0) + (paddingFieldSet ? 4 : 0) +
(borderFieldSet ? 4 : 0);
float arr[18];
arr[LAYOUT_EDGE_SET_FLAG_INDEX] = fieldFlags;
arr[LAYOUT_EDGE_SET_FLAG_INDEX] = static_cast<float>(fieldFlags);
arr[LAYOUT_WIDTH_INDEX] = YGNodeLayoutGetWidth(root);
arr[LAYOUT_HEIGHT_INDEX] = YGNodeLayoutGetHeight(root);
arr[LAYOUT_LEFT_INDEX] = YGNodeLayoutGetLeft(root);
arr[LAYOUT_TOP_INDEX] = YGNodeLayoutGetTop(root);
arr[LAYOUT_DIRECTION_INDEX] =
static_cast<jint>(YGNodeLayoutGetDirection(root));
static_cast<float>(YGNodeLayoutGetDirection(root));
if (marginFieldSet) {
arr[LAYOUT_MARGIN_START_INDEX] = YGNodeLayoutGetMargin(root, YGEdgeLeft);
arr[LAYOUT_MARGIN_START_INDEX + 1] = YGNodeLayoutGetMargin(root, YGEdgeTop);
Expand Down Expand Up @@ -670,9 +674,10 @@ static YGSize YGJNIMeasureFunc(
sizeof(measureResult) == 8,
"Expected measureResult to be 8 bytes, or two 32 bit ints");

int32_t wBits = 0xFFFFFFFF & (measureResult >> 32);
int32_t hBits = 0xFFFFFFFF & measureResult;
uint32_t wBits = 0xFFFFFFFF & (measureResult >> 32);
uint32_t hBits = 0xFFFFFFFF & measureResult;

// TODO: this is unsafe under strict aliasing and should use bit_cast
const float* measuredWidth = reinterpret_cast<float*>(&wBits);
const float* measuredHeight = reinterpret_cast<float*>(&hBits);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
#include "jni.h"

class PtrJNodeMapVanilla {
std::map<YGNodeConstRef, size_t> ptrsToIdxs_{};
std::map<YGNodeConstRef, jsize> ptrsToIdxs_{};
jobjectArray javaNodes_{};

public:
Expand All @@ -25,13 +25,13 @@ class PtrJNodeMapVanilla {
using namespace facebook::yoga::vanillajni;

JNIEnv* env = getCurrentEnv();
size_t nativePointersSize = env->GetArrayLength(javaNativePointers);
std::vector<jlong> nativePointers(nativePointersSize);
jsize nativePointersSize = env->GetArrayLength(javaNativePointers);
std::vector<jlong> nativePointers(static_cast<size_t>(nativePointersSize));
env->GetLongArrayRegion(
javaNativePointers, 0, nativePointersSize, nativePointers.data());

for (size_t i = 0; i < nativePointersSize; ++i) {
ptrsToIdxs_[(YGNodeConstRef) nativePointers[i]] = i;
for (jsize i = 0; i < nativePointersSize; ++i) {
ptrsToIdxs_[(YGNodeConstRef) nativePointers[static_cast<size_t>(i)]] = i;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ void registerNatives(

assertNoPendingJniExceptionIf(env, !clazz);

auto result = env->RegisterNatives(clazz, methods, numMethods);
auto result =
env->RegisterNatives(clazz, methods, static_cast<int32_t>(numMethods));

assertNoPendingJniExceptionIf(env, result != JNI_OK);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ add_compile_options(
-Wall
-Wextra
-Werror
-Wconversion
# Disable RTTI
$<$<COMPILE_LANGUAGE:CXX>:-fno-rtti>
# Use -O2 (prioritize speed)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -823,8 +823,8 @@ static void zeroOutLayoutRecursively(
yoga::Node* const node,
void* layoutContext) {
node->getLayout() = {};
node->setLayoutDimension(0, 0);
node->setLayoutDimension(0, 1);
node->setLayoutDimension(0, YGDimensionWidth);
node->setLayoutDimension(0, YGDimensionHeight);
node->setHasNewLayout(true);

node->iterChildrenAfterCloningIfNeeded(
Expand Down Expand Up @@ -1488,19 +1488,19 @@ static void YGJustifyMainAxis(
betweenMainDim +=
yoga::maxOrDefined(
collectedFlexItemsValues.remainingFreeSpace, 0) /
(collectedFlexItemsValues.itemsOnLine - 1);
static_cast<float>(collectedFlexItemsValues.itemsOnLine - 1);
}
break;
case YGJustifySpaceEvenly:
// Space is distributed evenly across all elements
leadingMainDim = collectedFlexItemsValues.remainingFreeSpace /
(collectedFlexItemsValues.itemsOnLine + 1);
static_cast<float>(collectedFlexItemsValues.itemsOnLine + 1);
betweenMainDim += leadingMainDim;
break;
case YGJustifySpaceAround:
// Space on the edges is half of the space between elements
leadingMainDim = 0.5f * collectedFlexItemsValues.remainingFreeSpace /
collectedFlexItemsValues.itemsOnLine;
static_cast<float>(collectedFlexItemsValues.itemsOnLine);
betweenMainDim += leadingMainDim * 2;
break;
case YGJustifyFlexStart:
Expand Down Expand Up @@ -1550,7 +1550,7 @@ static void YGJustifyMainAxis(
if (child->marginLeadingValue(mainAxis).unit == YGUnitAuto) {
collectedFlexItemsValues.mainDim +=
collectedFlexItemsValues.remainingFreeSpace /
numberOfAutoMarginsOnCurrentLine;
static_cast<float>(numberOfAutoMarginsOnCurrentLine);
}

if (performLayout) {
Expand All @@ -1563,7 +1563,7 @@ static void YGJustifyMainAxis(
if (child->marginTrailingValue(mainAxis).unit == YGUnitAuto) {
collectedFlexItemsValues.mainDim +=
collectedFlexItemsValues.remainingFreeSpace /
numberOfAutoMarginsOnCurrentLine;
static_cast<float>(numberOfAutoMarginsOnCurrentLine);
}
bool canSkipFlex =
!performLayout && measureModeCrossDim == YGMeasureModeExactly;
Expand Down Expand Up @@ -1890,7 +1890,7 @@ static void calculateLayoutImpl(
if (childCount > 1) {
totalMainDim +=
node->getGapForAxis(mainAxis, availableInnerCrossDim).unwrap() *
(childCount - 1);
static_cast<float>(childCount - 1);
}

const bool mainAxisOverflows =
Expand Down Expand Up @@ -2261,22 +2261,26 @@ static void calculateLayoutImpl(
break;
case YGAlignStretch:
if (availableInnerCrossDim > totalLineCrossDim) {
crossDimLead = remainingAlignContentDim / lineCount;
crossDimLead =
remainingAlignContentDim / static_cast<float>(lineCount);
}
break;
case YGAlignSpaceAround:
if (availableInnerCrossDim > totalLineCrossDim) {
currentLead += remainingAlignContentDim / (2 * lineCount);
currentLead +=
remainingAlignContentDim / (2 * static_cast<float>(lineCount));
if (lineCount > 1) {
crossDimLead = remainingAlignContentDim / lineCount;
crossDimLead =
remainingAlignContentDim / static_cast<float>(lineCount);
}
} else {
currentLead += remainingAlignContentDim / 2;
}
break;
case YGAlignSpaceBetween:
if (availableInnerCrossDim > totalLineCrossDim && lineCount > 1) {
crossDimLead = remainingAlignContentDim / (lineCount - 1);
crossDimLead =
remainingAlignContentDim / static_cast<float>(lineCount - 1);
}
break;
case YGAlignAuto:
Expand Down Expand Up @@ -2843,11 +2847,11 @@ bool calculateLayoutInternal(
layout->lastOwnerDirection = ownerDirection;

if (cachedResults == nullptr) {
if (layout->nextCachedMeasurementsIndex + 1 >
(uint32_t) layoutMarkerData.maxMeasureCache) {
layoutMarkerData.maxMeasureCache =
layout->nextCachedMeasurementsIndex + 1;
}

layoutMarkerData.maxMeasureCache = std::max(
layoutMarkerData.maxMeasureCache,
layout->nextCachedMeasurementsIndex + 1u);

if (layout->nextCachedMeasurementsIndex ==
LayoutResults::MaxCachedMeasurements) {
if (gPrintChanges) {
Expand Down
27 changes: 10 additions & 17 deletions packages/react-native/ReactCommon/yoga/yoga/bits/NumericBitfield.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@

namespace facebook::yoga::details {

constexpr size_t log2ceilFn(size_t n) {
constexpr uint8_t log2ceilFn(uint8_t n) {
return n < 1 ? 0 : (1 + log2ceilFn(n / 2));
}

constexpr int mask(size_t bitWidth, size_t index) {
return ((1 << bitWidth) - 1) << index;
constexpr uint32_t mask(uint8_t bitWidth, uint8_t index) {
return ((1u << bitWidth) - 1u) << index;
}

} // namespace facebook::yoga::details
Expand All @@ -29,38 +29,31 @@ namespace facebook::yoga {

// The number of bits necessary to represent enums defined with YG_ENUM_SEQ_DECL
template <typename Enum>
constexpr size_t minimumBitCount() {
constexpr uint8_t minimumBitCount() {
static_assert(
enums::count<Enum>() > 0, "Enums must have at least one entries");
return details::log2ceilFn(enums::count<Enum>() - 1);
}

template <typename Enum>
constexpr Enum getEnumData(int flags, size_t index) {
constexpr Enum getEnumData(uint32_t flags, uint8_t index) {
return static_cast<Enum>(
(flags & details::mask(minimumBitCount<Enum>(), index)) >> index);
}

template <typename Enum>
void setEnumData(uint32_t& flags, size_t index, int newValue) {
flags = (flags & ~details::mask(minimumBitCount<Enum>(), index)) |
((newValue << index) & (details::mask(minimumBitCount<Enum>(), index)));
}

template <typename Enum>
void setEnumData(uint8_t& flags, size_t index, int newValue) {
void setEnumData(uint32_t& flags, uint8_t index, uint32_t newValue) {
flags =
(flags &
~static_cast<uint8_t>(details::mask(minimumBitCount<Enum>(), index))) |
((newValue << index) &
(static_cast<uint8_t>(details::mask(minimumBitCount<Enum>(), index))));
~static_cast<uint32_t>(details::mask(minimumBitCount<Enum>(), index))) |
((newValue << index) & (details::mask(minimumBitCount<Enum>(), index)));
}

constexpr bool getBooleanData(int flags, size_t index) {
constexpr bool getBooleanData(uint32_t flags, uint8_t index) {
return (flags >> index) & 1;
}

inline void setBooleanData(uint8_t& flags, size_t index, bool value) {
inline void setBooleanData(uint32_t& flags, uint8_t index, bool value) {
if (value) {
flags |= 1 << index;
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ static void appendFormattedString(std::string& str, const char* fmt, ...) {
va_start(args, fmt);
va_list argsCopy;
va_copy(argsCopy, args);
std::vector<char> buf(1 + vsnprintf(NULL, 0, fmt, args));
std::vector<char> buf(1 + static_cast<size_t>(vsnprintf(NULL, 0, fmt, args)));
va_end(args);
vsnprintf(buf.data(), buf.size(), fmt, argsCopy);
va_end(argsCopy);
Expand Down Expand Up @@ -96,7 +96,7 @@ static void appendEdges(
} else {
for (int edge = YGEdgeLeft; edge != YGEdgeAll; ++edge) {
std::string str = key + "-" + YGEdgeToString(static_cast<YGEdge>(edge));
appendNumberIfNotZero(base, str, edges[edge]);
appendNumberIfNotZero(base, str, edges[static_cast<size_t>(edge)]);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/react-native/ReactCommon/yoga/yoga/event/event.h
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ enum struct LayoutPassReason : int {
struct LayoutData {
int layouts;
int measures;
int maxMeasureCache;
uint32_t maxMeasureCache;
int cachedLayouts;
int cachedMeasures;
int measureCallbacks;
Expand Down
23 changes: 13 additions & 10 deletions packages/react-native/ReactCommon/yoga/yoga/node/LayoutResults.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@

namespace facebook::yoga {

#pragma pack(push)
#pragma pack(1)
struct LayoutResultFlags {
uint32_t direction : 2;
bool hadOverflow : 1;
};
#pragma pack(pop)

struct LayoutResults {
// This value was chosen based on empirical data:
// 98% of analyzed layouts require less than 8 entries.
Expand All @@ -27,10 +35,7 @@ struct LayoutResults {
std::array<float, 4> padding = {};

private:
static constexpr size_t directionOffset = 0;
static constexpr size_t hadOverflowOffset =
directionOffset + minimumBitCount<YGDirection>();
uint8_t flags = 0;
LayoutResultFlags flags_{};

public:
uint32_t computedFlexBasisGeneration = 0;
Expand All @@ -48,17 +53,15 @@ struct LayoutResults {
CachedMeasurement cachedLayout{};

YGDirection direction() const {
return getEnumData<YGDirection>(flags, directionOffset);
return static_cast<YGDirection>(flags_.direction);
}

void setDirection(YGDirection direction) {
setEnumData<YGDirection>(flags, directionOffset, direction);
flags_.direction = static_cast<uint32_t>(direction) & 0x03;
}

bool hadOverflow() const { return getBooleanData(flags, hadOverflowOffset); }
void setHadOverflow(bool hadOverflow) {
setBooleanData(flags, hadOverflowOffset, hadOverflow);
}
bool hadOverflow() const { return flags_.hadOverflow; }
void setHadOverflow(bool hadOverflow) { flags_.hadOverflow = hadOverflow; }

bool operator==(LayoutResults layout) const;
bool operator!=(LayoutResults layout) const { return !(*this == layout); }
Expand Down
Loading

0 comments on commit 9411e59

Please sign in to comment.