From feb5f5e8192047137d07c0a2611f3dffecb0335f Mon Sep 17 00:00:00 2001 From: Nick Gerleman Date: Sat, 2 Mar 2024 23:11:50 -0800 Subject: [PATCH] Enable Clang Tidy Summary: X-link: https://github.com/facebook/react-native/pull/43299 Add the React Clang Tidy config to Yoga, run the auto fixes (with some mechanical manual tweaks). Notably, the automatic changes to the infra for generating a Yoga tree from JSON capture make it 70% faster. Before: {F1463947076} After: {F1463946802} This also cleans up all the no-op shallow const parameters in headers. {F1463943386} Not all checks are available in all environments, but that is okay, as Clang Tidy will gracefully skip them. Changelog: [Internal] Differential Revision: D54461054 --- .clang-tidy | 217 ++++++++++++++++++++++++++++ benchmark/Benchmark.cpp | 10 +- benchmark/Benchmark.h | 5 +- benchmark/TreeDeserialization.cpp | 32 ++--- benchmark/TreeDeserialization.h | 28 ++-- capture/CaptureTree.h | 2 +- capture/NodeToString.h | 2 +- java/jni/ScopedGlobalRef.h | 6 +- java/jni/ScopedLocalRef.h | 5 +- java/jni/YGJNI.h | 2 +- java/jni/YGJNIVanilla.cpp | 28 ++-- java/jni/YogaJniException.cpp | 2 +- java/jni/YogaJniException.h | 4 +- java/jni/common.cpp | 16 +-- java/jni/corefunctions.cpp | 10 +- java/jni/yogajni.cpp | 4 +- tests/EventsTest.cpp | 7 +- tests/SmallValueBufferTest.cpp | 2 +- tests/YGBaselineFuncTest.cpp | 2 +- tests/YGConfigTest.cpp | 16 ++- tests/YGDefaultValuesTest.cpp | 2 +- tests/YGHadOverflowTest.cpp | 5 +- tests/YGMeasureCacheTest.cpp | 2 +- tests/YGMeasureModeTest.cpp | 23 ++- tests/YGMeasureTest.cpp | 2 +- tests/util/TestUtil.h | 2 +- yoga/YGNode.cpp | 4 +- yoga/algorithm/AbsoluteLayout.h | 18 +-- yoga/algorithm/CalculateLayout.cpp | 219 ++++++++++++++--------------- yoga/algorithm/CalculateLayout.h | 32 ++--- yoga/algorithm/FlexLine.cpp | 2 +- yoga/algorithm/FlexLine.h | 2 +- yoga/algorithm/PixelGrid.h | 14 +- yoga/config/Config.cpp | 2 +- yoga/config/Config.h | 6 +- yoga/debug/Log.h | 2 +- yoga/event/event.cpp | 4 +- yoga/event/event.h | 11 +- yoga/node/Node.cpp | 47 +++---- yoga/node/Node.h | 30 ++-- yoga/style/SmallValueBuffer.h | 6 +- yoga/style/StyleValuePool.h | 4 +- 42 files changed, 537 insertions(+), 302 deletions(-) create mode 100644 .clang-tidy diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 00000000..291ed4ec --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,217 @@ +--- +InheritParentConfig: true +Checks: '> +bugprone-argument-comment, +bugprone-assert-side-effect, +bugprone-bool-pointer-implicit-conversion, +bugprone-copy-constructor-init, +bugprone-dangling-handle, +bugprone-exception-escape, +bugprone-fold-init-type, +bugprone-forward-declaration-namespace, +bugprone-forwarding-reference-overload, +bugprone-incorrect-enable-if, +bugprone-inaccurate-erase, +bugprone-incorrect-roundings, +bugprone-infinite-loop, +bugprone-integer-division, +bugprone-macro-parentheses, +bugprone-macro-repeated-side-effects, +bugprone-misplaced-operator-in-strlen-in-alloc, +bugprone-misplaced-widening-cast, +bugprone-move-forwarding-reference, +bugprone-multiple-statement-macro, +bugprone-optional-value-conversion, +bugprone-parent-virtual-call, +bugprone-redundant-branch-condition, +bugprone-shared-ptr-array-mismatch, +bugprone-signed-char-misuse, +bugprone-sizeof-container, +bugprone-sizeof-expression, +bugprone-string-constructor, +bugprone-string-integer-assignment, +bugprone-string-literal-with-embedded-nul, +bugprone-suspicious-enum-usage, +bugprone-suspicious-memset-usage, +bugprone-suspicious-missing-comma, +bugprone-suspicious-semicolon, +bugprone-suspicious-string-compare, +bugprone-swapped-arguments, +bugprone-terminating-continue, +bugprone-throw-keyword-missing, +bugprone-too-small-loop-variable, +bugprone-undefined-memory-manipulation, +bugprone-undelegated-constructor, +bugprone-unique-ptr-array-mismatch, +bugprone-unsafe-functions, +bugprone-unused-raii, +bugprone-unused-return-value, +bugprone-use-after-move, +bugprone-virtual-near-miss, +clang-analyzer-apiModeling.google.GTest, +clang-analyzer-apiModeling.StdCLibraryFunctions, +clang-analyzer-apiModeling.TrustNonnull, +clang-analyzer-core.builtin.BuiltinFunctions, +clang-analyzer-core.builtin.NoReturnFunctions, +clang-analyzer-core.CallAndMessage, +clang-analyzer-core.DivideZero, +clang-analyzer-core.DynamicTypePropagation, +clang-analyzer-core.NonnilStringConstants, +clang-analyzer-core.NonNullParamChecker, +clang-analyzer-core.NullDereference, +clang-analyzer-core.StackAddressEscape, +clang-analyzer-core.UndefinedBinaryOperatorResult, +clang-analyzer-core.uninitialized.ArraySubscript, +clang-analyzer-core.uninitialized.Assign, +clang-analyzer-core.uninitialized.Branch, +clang-analyzer-core.uninitialized.CapturedBlockVariable, +clang-analyzer-core.uninitialized.UndefReturn, +clang-analyzer-core.VLASize, +clang-analyzer-cplusplus.InnerPointer, +clang-analyzer-cplusplus.Move, +clang-analyzer-cplusplus.NewDelete, +clang-analyzer-cplusplus.NewDeleteLeaks, +clang-analyzer-cplusplus.SelfAssignment, +clang-analyzer-deadcode.DeadStores, +clang-analyzer-nullability.NullableDereferenced, +clang-analyzer-nullability.NullablePassedToNonnull, +clang-analyzer-nullability.NullableReturnedFromNonnull, +clang-analyzer-nullability.NullPassedToNonnull, +clang-analyzer-nullability.NullReturnedFromNonnull, +clang-analyzer-optin.cplusplus.VirtualCall, +clang-analyzer-optin.mpi.MPI-Checker, +clang-analyzer-optin.performance.GCDAntipattern, +clang-analyzer-optin.performance.Padding, +clang-analyzer-optin.portability.UnixAPI, +clang-analyzer-security.FloatLoopCounter, +clang-analyzer-security.insecureAPI.bcmp, +clang-analyzer-security.insecureAPI.bcopy, +clang-analyzer-security.insecureAPI.bzero, +clang-analyzer-security.insecureAPI.getpw, +clang-analyzer-security.insecureAPI.gets, +clang-analyzer-security.insecureAPI.mkstemp, +clang-analyzer-security.insecureAPI.mktemp, +clang-analyzer-security.insecureAPI.rand, +clang-analyzer-security.insecureAPI.strcpy, +clang-analyzer-security.insecureAPI.UncheckedReturn, +clang-analyzer-security.insecureAPI.vfork, +clang-analyzer-unix.API, +clang-analyzer-unix.cstring.BadSizeArg, +clang-analyzer-unix.cstring.NullArg, +clang-analyzer-unix.Malloc, +clang-analyzer-unix.MallocSizeof, +clang-analyzer-unix.MismatchedDeallocator, +clang-analyzer-unix.Vfork, +clang-analyzer-valist.CopyToSelf, +clang-analyzer-valist.Uninitialized, +clang-analyzer-valist.Unterminated, +clang-diagnostic-*, +cppcoreguidelines-avoid-const-or-ref-data-members, +cppcoreguidelines-avoid-non-const-global-variables, +cppcoreguidelines-init-variables, +cppcoreguidelines-interfaces-global-init, +cppcoreguidelines-macro-usage, +cppcoreguidelines-missing-std-forward, +cppcoreguidelines-narrowing-conversions, +cppcoreguidelines-no-malloc, +cppcoreguidelines-prefer-member-initializer, +cppcoreguidelines-pro-bounds-pointer-arithmetic, +cppcoreguidelines-pro-type-const-cast, +cppcoreguidelines-pro-type-cstyle-cast, +cppcoreguidelines-pro-type-member-init, +cppcoreguidelines-pro-type-reinterpret-cast, +cppcoreguidelines-pro-type-union-access, +cppcoreguidelines-pro-type-vararg, +cppcoreguidelines-slicing, +cppcoreguidelines-special-member-functions, +facebook-hte-BadEnum, +facebook-hte-MissingStatic, +google-build-using-namespace, +misc-definitions-in-headers, +misc-header-include-cycle, +misc-misplaced-const, +misc-new-delete-overloads, +misc-non-copyable-objects, +misc-static-assert, +misc-throw-by-value-catch-by-reference, +misc-unconventional-assign-operator, +misc-uniqueptr-reset-release, +misc-unused-alias-decls, +misc-unused-parameters, +misc-unused-using-decls, +modernize-avoid-bind, +modernize-avoid-c-arrays, +modernize-concat-nested-namespaces, +modernize-deprecated-headers, +modernize-deprecated-ios-base-aliases, +modernize-loop-convert, +modernize-make-shared, +modernize-make-unique, +modernize-pass-by-value, +modernize-raw-string-literal, +modernize-redundant-void-arg, +modernize-replace-auto-ptr, +modernize-replace-random-shuffle, +modernize-return-braced-init-list, +modernize-shrink-to-fit, +modernize-unary-static-assert, +modernize-use-auto, +modernize-use-bool-literals, +modernize-use-constraints, +modernize-use-default-member-init, +modernize-use-designated-initializers, +modernize-use-emplace, +modernize-use-equals-default, +modernize-use-equals-delete, +modernize-use-noexcept, +modernize-use-nullptr, +modernize-use-override, +modernize-use-starts-ends-with, +modernize-use-transparent-functors, +modernize-use-using, +performance-faster-string-find, +performance-for-range-copy, +performance-implicit-conversion-in-loop, +performance-inefficient-algorithm, +performance-inefficient-string-concatenation, +performance-inefficient-vector-operation, +performance-move-const-arg, +performance-move-constructor-init, +performance-noexcept-move-constructor, +performance-type-promotion-in-math-fn, +performance-unnecessary-copy-initialization, +performance-unnecessary-value-param, +readability-avoid-const-params-in-decls, +readability-braces-around-statements, +readability-const-return-type, +readability-container-size-empty, +readability-delete-null-pointer, +readability-deleted-default, +readability-implicit-bool-conversion, +readability-inconsistent-declaration-parameter-name, +readability-isolate-declaration, +readability-misplaced-array-index, +readability-named-parameter, +readability-non-const-parameter, +readability-redundant-control-flow, +readability-redundant-declaration, +readability-redundant-function-ptr-dereference, +readability-redundant-preprocessor, +readability-redundant-smartptr-get, +readability-redundant-string-cstr, +readability-redundant-string-init, +readability-simplify-boolean-expr, +readability-simplify-subscript-expr, +readability-static-accessed-through-instance, +readability-static-definition-in-anonymous-namespace, +readability-string-compare, +readability-uniqueptr-delete-release, +' + +CheckOptions: +- key: performance-unnecessary-value-param.AllowedTypes + value: '[Pp]ointer$;[Pp]tr$;[Rr]ef(erence)?$;' +- key: performance-unnecessary-copy-initialization.AllowedTypes + value: '[Pp]ointer$;[Pp]tr$;[Rr]ef(erence)?$' + +... diff --git a/benchmark/Benchmark.cpp b/benchmark/Benchmark.cpp index 04fb5fcb..0bd4c45d 100644 --- a/benchmark/Benchmark.cpp +++ b/benchmark/Benchmark.cpp @@ -113,8 +113,8 @@ std::shared_ptr buildConfigFromJson(const json& j) { } std::string edgeStringFromPropertyName( - std::string key, - std::string propertyName) { + const std::string& key, + const std::string& propertyName) { return key.substr(propertyName.length() + 1); } @@ -299,7 +299,7 @@ std::shared_ptr buildTreeFromJson( if (j.contains("children")) { json children = j["children"]; size_t childIndex = 0; - for (json child : children) { + for (const json& child : children) { buildTreeFromJson(child, fns, wrapper, childIndex); childIndex++; } @@ -331,9 +331,9 @@ BenchmarkResult generateBenchmark(json& capture) { } static void printBenchmarkResult( - std::string name, + const std::string& name, SteadyClockDurations& durations) { - std::array timesInMs; + std::array timesInMs{}; double mean = 0; for (uint32_t i = 0; i < kNumRepititions; i++) { auto ms = duration(durations[i]).count(); diff --git a/benchmark/Benchmark.h b/benchmark/Benchmark.h index 941d5acd..85e202db 100644 --- a/benchmark/Benchmark.h +++ b/benchmark/Benchmark.h @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -21,7 +22,9 @@ struct YogaNodeAndConfig { std::shared_ptr node, std::shared_ptr config, std::vector> children) - : node_(node), config_(config), children_(children) {} + : node_(std::move(node)), + config_(std::move(config)), + children_(std::move(children)) {} std::shared_ptr node_; std::shared_ptr config_; diff --git a/benchmark/TreeDeserialization.cpp b/benchmark/TreeDeserialization.cpp index 38dc1daf..a699b97d 100644 --- a/benchmark/TreeDeserialization.cpp +++ b/benchmark/TreeDeserialization.cpp @@ -22,8 +22,8 @@ static inline bool isAuto(json& j) { } static inline std::string invalidArgumentMessage( - std::string arg, - std::string enumName) { + const std::string& arg, + const std::string& enumName) { return arg + " does not represent any " + enumName + " values"; } @@ -36,7 +36,7 @@ static inline float floatFromJson(json& j) { return result; } -YGFlexDirection flexDirectionFromString(std::string str) { +YGFlexDirection flexDirectionFromString(const std::string& str) { if (str == "row") { return YGFlexDirectionRow; } else if (str == "row-reverse") { @@ -50,7 +50,7 @@ YGFlexDirection flexDirectionFromString(std::string str) { } } -YGJustify justifyContentFromString(std::string str) { +YGJustify justifyContentFromString(const std::string& str) { if (str == "flex-start") { return YGJustifyFlexStart; } else if (str == "center") { @@ -68,7 +68,7 @@ YGJustify justifyContentFromString(std::string str) { } } -YGAlign alignFromString(std::string str) { +YGAlign alignFromString(const std::string& str) { if (str == "auto") { return YGAlignAuto; } else if (str == "flex-start") { @@ -92,7 +92,7 @@ YGAlign alignFromString(std::string str) { } } -YGWrap wrapFromString(std::string str) { +YGWrap wrapFromString(const std::string& str) { if (str == "no-wrap") { return YGWrapNoWrap; } else if (str == "wrap") { @@ -104,7 +104,7 @@ YGWrap wrapFromString(std::string str) { } } -YGOverflow overflowFromString(std::string str) { +YGOverflow overflowFromString(const std::string& str) { if (str == "visible") { return YGOverflowVisible; } else if (str == "hidden") { @@ -116,7 +116,7 @@ YGOverflow overflowFromString(std::string str) { } } -YGDisplay displayFromString(std::string str) { +YGDisplay displayFromString(const std::string& str) { if (str == "flex") { return YGDisplayFlex; } else if (str == "none") { @@ -126,7 +126,7 @@ YGDisplay displayFromString(std::string str) { } } -YGPositionType positionTypeFromString(std::string str) { +YGPositionType positionTypeFromString(const std::string& str) { if (str == "static") { return YGPositionTypeStatic; } else if (str == "relative") { @@ -153,7 +153,7 @@ YGUnit unitFromJson(json& j) { } } -YGEdge edgeFromString(std::string str) { +YGEdge edgeFromString(const std::string& str) { if (str == "left") { return YGEdgeLeft; } else if (str == "top") { @@ -177,7 +177,7 @@ YGEdge edgeFromString(std::string str) { } } -YGErrata errataFromString(std::string str) { +YGErrata errataFromString(const std::string& str) { if (str == "none") { return YGErrataNone; } else if (str == "all") { @@ -189,7 +189,7 @@ YGErrata errataFromString(std::string str) { } } -YGExperimentalFeature experimentalFeatureFromString(std::string str) { +YGExperimentalFeature experimentalFeatureFromString(const std::string& str) { if (str == "web-flex-basis") { return YGExperimentalFeatureWebFlexBasis; } else { @@ -199,12 +199,12 @@ YGExperimentalFeature experimentalFeatureFromString(std::string str) { } std::string edgeStringFromPropertyName( - json::iterator it, - std::string propertyName) { + const json::iterator& it, + const std::string& propertyName) { return it.key().substr(propertyName.length() + 1); } -YGDirection directionFromString(std::string str) { +YGDirection directionFromString(const std::string& str) { if (str == "ltr") { return YGDirectionLTR; } else if (str == "rtl") { @@ -216,7 +216,7 @@ YGDirection directionFromString(std::string str) { } } -YGMeasureMode measureModeFromString(std::string str) { +YGMeasureMode measureModeFromString(const std::string& str) { if (str == "at-most") { return YGMeasureModeAtMost; } else if (str == "exactly") { diff --git a/benchmark/TreeDeserialization.h b/benchmark/TreeDeserialization.h index 91f346ac..84fb7f51 100644 --- a/benchmark/TreeDeserialization.h +++ b/benchmark/TreeDeserialization.h @@ -18,35 +18,35 @@ namespace facebook::yoga { using namespace nlohmann; -YGFlexDirection flexDirectionFromString(std::string str); +YGFlexDirection flexDirectionFromString(const std::string& str); -YGJustify justifyContentFromString(std::string str); +YGJustify justifyContentFromString(const std::string& str); -YGAlign alignFromString(std::string str); +YGAlign alignFromString(const std::string& str); -YGWrap wrapFromString(std::string str); +YGWrap wrapFromString(const std::string& str); -YGOverflow overflowFromString(std::string str); +YGOverflow overflowFromString(const std::string& str); -YGDisplay displayFromString(std::string str); +YGDisplay displayFromString(const std::string& str); -YGPositionType positionTypeFromString(std::string str); +YGPositionType positionTypeFromString(const std::string& str); YGUnit unitFromJson(json& j); -YGEdge edgeFromString(std::string str); +YGEdge edgeFromString(const std::string& str); -YGErrata errataFromString(std::string str); +YGErrata errataFromString(const std::string& str); -YGExperimentalFeature experimentalFeatureFromString(std::string str); +YGExperimentalFeature experimentalFeatureFromString(const std::string& str); std::string edgeStringFromPropertyName( - json::iterator it, - std::string propertyName); + const json::iterator& it, + const std::string& propertyName); -YGDirection directionFromString(std::string str); +YGDirection directionFromString(const std::string& str); -YGMeasureMode measureModeFromString(std::string str); +YGMeasureMode measureModeFromString(const std::string& str); SerializedMeasureFunc serializedMeasureFuncFromJson(json& j); } // namespace facebook::yoga diff --git a/capture/CaptureTree.h b/capture/CaptureTree.h index 7d3be10a..7302f6c0 100644 --- a/capture/CaptureTree.h +++ b/capture/CaptureTree.h @@ -22,7 +22,7 @@ struct SerializedMeasureFunc { YGMeasureMode heightMode{YGMeasureModeUndefined}; float outputWidth{0.0f}; float outputHeight{0.0f}; - std::chrono::steady_clock::duration::rep durationNs; + std::chrono::steady_clock::duration::rep durationNs{}; }; using SerializedMeasureFuncMap = diff --git a/capture/NodeToString.h b/capture/NodeToString.h index 20714faf..9fadaa64 100644 --- a/capture/NodeToString.h +++ b/capture/NodeToString.h @@ -28,7 +28,7 @@ YG_DEFINE_ENUM_FLAG_OPERATORS(PrintOptions); void serializeTree( nlohmann::json& j, SerializedMeasureFuncMap& nodesToMeasureFuncs, - YGNodeRef root, + YGNodeRef node, PrintOptions options); void serializeLayoutInputs( diff --git a/java/jni/ScopedGlobalRef.h b/java/jni/ScopedGlobalRef.h index b563d052..c0ca023e 100644 --- a/java/jni/ScopedGlobalRef.h +++ b/java/jni/ScopedGlobalRef.h @@ -62,7 +62,7 @@ class ScopedGlobalRef { * * @param globalRef the global reference to wrap. Can be NULL. */ - ScopedGlobalRef(T globalRef) : mGlobalRef(globalRef) {} + explicit ScopedGlobalRef(T globalRef) : mGlobalRef(globalRef) {} /** * Equivalent to ScopedGlobalRef(NULL) @@ -72,12 +72,12 @@ class ScopedGlobalRef { /** * Move construction is allowed. */ - ScopedGlobalRef(ScopedGlobalRef&& s) : mGlobalRef(s.release()) {} + ScopedGlobalRef(ScopedGlobalRef&& s) noexcept : mGlobalRef(s.release()) {} /** * Move assignment is allowed. */ - ScopedGlobalRef& operator=(ScopedGlobalRef&& s) { + ScopedGlobalRef& operator=(ScopedGlobalRef&& s) noexcept { reset(s.release()); return *this; } diff --git a/java/jni/ScopedLocalRef.h b/java/jni/ScopedLocalRef.h index 6765078b..fd49e832 100644 --- a/java/jni/ScopedLocalRef.h +++ b/java/jni/ScopedLocalRef.h @@ -70,12 +70,13 @@ class ScopedLocalRef { /** * Move construction is allowed. */ - ScopedLocalRef(ScopedLocalRef&& s) : mEnv(s.mEnv), mLocalRef(s.release()) {} + ScopedLocalRef(ScopedLocalRef&& s) noexcept + : mEnv(s.mEnv), mLocalRef(s.release()) {} /** * Move assignment is allowed. */ - ScopedLocalRef& operator=(ScopedLocalRef&& s) { + ScopedLocalRef& operator=(ScopedLocalRef&& s) noexcept { reset(s.release()); mEnv = s.mEnv; return *this; diff --git a/java/jni/YGJNI.h b/java/jni/YGJNI.h index 489df201..9b260977 100644 --- a/java/jni/YGJNI.h +++ b/java/jni/YGJNI.h @@ -36,7 +36,7 @@ class YGNodeEdges { BORDER = 4, }; - YGNodeEdges(YGNodeRef node) { + explicit YGNodeEdges(YGNodeRef node) { auto context = YGNodeContext{}; context.asVoidPtr = YGNodeGetContext(node); edges_ = context.edgesSet; diff --git a/java/jni/YGJNIVanilla.cpp b/java/jni/YGJNIVanilla.cpp index 97fb1789..82e0dc17 100644 --- a/java/jni/YGJNIVanilla.cpp +++ b/java/jni/YGJNIVanilla.cpp @@ -54,7 +54,9 @@ static void jni_YGConfigSetExperimentalFeatureEnabledJNI( jboolean enabled) { const YGConfigRef config = _jlong2YGConfigRef(nativePointer); YGConfigSetExperimentalFeatureEnabled( - config, static_cast(feature), enabled); + config, + static_cast(feature), + static_cast(enabled)); } static void jni_YGConfigSetUseWebDefaultsJNI( @@ -63,7 +65,7 @@ static void jni_YGConfigSetUseWebDefaultsJNI( jlong nativePointer, jboolean useWebDefaults) { const YGConfigRef config = _jlong2YGConfigRef(nativePointer); - YGConfigSetUseWebDefaults(config, useWebDefaults); + YGConfigSetUseWebDefaults(config, static_cast(useWebDefaults)); } static void jni_YGConfigSetPointScaleFactorJNI( @@ -161,7 +163,7 @@ static void jni_YGConfigSetLoggerJNI( auto context = reinterpret_cast*>(YGConfigGetContext(config)); - if (logger) { + if (logger != nullptr) { if (context == nullptr) { context = new ScopedGlobalRef(); YGConfigSetContext(config, context); @@ -225,14 +227,15 @@ static void jni_YGNodeSetIsReferenceBaselineJNI( jlong nativePointer, jboolean isReferenceBaseline) { YGNodeSetIsReferenceBaseline( - _jlong2YGNodeRef(nativePointer), isReferenceBaseline); + _jlong2YGNodeRef(nativePointer), static_cast(isReferenceBaseline)); } static jboolean jni_YGNodeIsReferenceBaselineJNI( JNIEnv* /*env*/, jobject /*obj*/, jlong nativePointer) { - return YGNodeIsReferenceBaseline(_jlong2YGNodeRef(nativePointer)); + return static_cast( + YGNodeIsReferenceBaseline(_jlong2YGNodeRef(nativePointer))); } static void jni_YGNodeRemoveAllChildrenJNI( @@ -340,7 +343,7 @@ static void jni_YGNodeCalculateLayoutJNI( try { PtrJNodeMapVanilla* layoutContext = nullptr; auto map = PtrJNodeMapVanilla{}; - if (nativePointers) { + if (nativePointers != nullptr) { map = PtrJNodeMapVanilla{nativePointers, javaNodes}; layoutContext = ↦ } @@ -356,7 +359,7 @@ static void jni_YGNodeCalculateLayoutJNI( YGTransferLayoutOutputsRecursive(env, obj, root); } catch (const YogaJniException& jniException) { ScopedLocalRef throwable = jniException.getThrowable(); - if (throwable.get()) { + if (throwable.get() != nullptr) { env->Throw(throwable.get()); } } catch (const std::logic_error& ex) { @@ -626,8 +629,8 @@ static YGSize YGJNIMeasureFunc( uint32_t wBits = 0xFFFFFFFF & (measureResult >> 32); uint32_t hBits = 0xFFFFFFFF & measureResult; - float measuredWidth = std::bit_cast(wBits); - float measuredHeight = std::bit_cast(hBits); + auto measuredWidth = std::bit_cast(wBits); + auto measuredHeight = std::bit_cast(hBits); return YGSize{measuredWidth, measuredHeight}; } else { @@ -645,7 +648,7 @@ static void jni_YGNodeSetHasMeasureFuncJNI( jboolean hasMeasureFunc) { YGNodeSetMeasureFunc( _jlong2YGNodeRef(nativePointer), - hasMeasureFunc ? YGJNIMeasureFunc : nullptr); + static_cast(hasMeasureFunc) ? YGJNIMeasureFunc : nullptr); } static float YGJNIBaselineFunc(YGNodeConstRef node, float width, float height) { @@ -669,7 +672,7 @@ static void jni_YGNodeSetHasBaselineFuncJNI( jboolean hasBaselineFunc) { YGNodeSetBaselineFunc( _jlong2YGNodeRef(nativePointer), - hasBaselineFunc ? YGJNIBaselineFunc : nullptr); + static_cast(hasBaselineFunc) ? YGJNIBaselineFunc : nullptr); } static void jni_YGNodeSetAlwaysFormsContainingBlockJNI( @@ -678,7 +681,8 @@ static void jni_YGNodeSetAlwaysFormsContainingBlockJNI( jlong nativePointer, jboolean alwaysFormsContainingBlock) { YGNodeSetAlwaysFormsContainingBlock( - _jlong2YGNodeRef(nativePointer), alwaysFormsContainingBlock); + _jlong2YGNodeRef(nativePointer), + static_cast(alwaysFormsContainingBlock)); } static jlong diff --git a/java/jni/YogaJniException.cpp b/java/jni/YogaJniException.cpp index a30b8a6a..e8c6ca92 100644 --- a/java/jni/YogaJniException.cpp +++ b/java/jni/YogaJniException.cpp @@ -25,7 +25,7 @@ YogaJniException::YogaJniException(jthrowable throwable) { throwable_ = newGlobalRef(getCurrentEnv(), throwable); } -YogaJniException::YogaJniException(YogaJniException&& rhs) +YogaJniException::YogaJniException(YogaJniException&& rhs) noexcept : throwable_(std::move(rhs.throwable_)) {} YogaJniException::YogaJniException(const YogaJniException& rhs) { diff --git a/java/jni/YogaJniException.h b/java/jni/YogaJniException.h index 1d2cc956..8c53d412 100644 --- a/java/jni/YogaJniException.h +++ b/java/jni/YogaJniException.h @@ -22,9 +22,9 @@ class YogaJniException : public std::exception { explicit YogaJniException(jthrowable throwable); - YogaJniException(YogaJniException&& rhs); + YogaJniException(YogaJniException&& rhs) noexcept; - YogaJniException(const YogaJniException& other); + YogaJniException(const YogaJniException& rhs); ScopedLocalRef getThrowable() const noexcept; diff --git a/java/jni/common.cpp b/java/jni/common.cpp index e2dc0df2..d634b0af 100644 --- a/java/jni/common.cpp +++ b/java/jni/common.cpp @@ -16,7 +16,7 @@ void registerNatives( size_t numMethods) { jclass clazz = env->FindClass(className); - assertNoPendingJniExceptionIf(env, !clazz); + assertNoPendingJniExceptionIf(env, clazz == nullptr); auto result = env->RegisterNatives(clazz, methods, static_cast(numMethods)); @@ -31,7 +31,7 @@ jmethodID getStaticMethodId( const char* methodDescriptor) { jmethodID methodId = env->GetStaticMethodID(clazz, methodName, methodDescriptor); - assertNoPendingJniExceptionIf(env, !methodId); + assertNoPendingJniExceptionIf(env, methodId == nullptr); return methodId; } @@ -41,7 +41,7 @@ jmethodID getMethodId( const char* methodName, const char* methodDescriptor) { jmethodID methodId = env->GetMethodID(clazz, methodName, methodDescriptor); - assertNoPendingJniExceptionIf(env, !methodId); + assertNoPendingJniExceptionIf(env, methodId == nullptr); return methodId; } @@ -51,7 +51,7 @@ jfieldID getFieldId( const char* fieldName, const char* fieldSignature) { jfieldID fieldId = env->GetFieldID(clazz, fieldName, fieldSignature); - assertNoPendingJniExceptionIf(env, !fieldId); + assertNoPendingJniExceptionIf(env, fieldId == nullptr); return fieldId; } @@ -82,14 +82,14 @@ callStaticObjectMethod(JNIEnv* env, jclass clazz, jmethodID methodId, ...) { va_start(args, methodId); jobject result = env->CallStaticObjectMethodV(clazz, methodId, args); va_end(args); - assertNoPendingJniExceptionIf(env, !result); + assertNoPendingJniExceptionIf(env, result == nullptr); return make_local_ref(env, result); } ScopedGlobalRef newGlobalRef(JNIEnv* env, jobject obj) { jobject result = env->NewGlobalRef(obj); - if (!result) { + if (result == nullptr) { logErrorMessageAndDie("Could not obtain global reference from object"); } @@ -97,9 +97,9 @@ ScopedGlobalRef newGlobalRef(JNIEnv* env, jobject obj) { } ScopedGlobalRef newGlobalRef(JNIEnv* env, jthrowable obj) { - jthrowable result = static_cast(env->NewGlobalRef(obj)); + auto result = static_cast(env->NewGlobalRef(obj)); - if (!result) { + if (result == nullptr) { logErrorMessageAndDie("Could not obtain global reference from object"); } diff --git a/java/jni/corefunctions.cpp b/java/jni/corefunctions.cpp index f094357c..6fcbf780 100644 --- a/java/jni/corefunctions.cpp +++ b/java/jni/corefunctions.cpp @@ -12,9 +12,9 @@ namespace facebook::yoga::vanillajni { namespace { -JavaVM* globalVm = NULL; +JavaVM* globalVm = nullptr; struct JavaVMInitializer { - JavaVMInitializer(JavaVM* vm) { + explicit JavaVMInitializer(JavaVM* vm) { if (!vm) { logErrorMessageAndDie( "You cannot pass a NULL JavaVM to ensureInitialized"); @@ -27,7 +27,7 @@ struct JavaVMInitializer { jint ensureInitialized(JNIEnv** env, JavaVM* vm) { static JavaVMInitializer init(vm); - if (!env) { + if (env == nullptr) { logErrorMessageAndDie( "Need to pass a valid JNIEnv pointer to vanillajni initialization " "routine"); @@ -43,7 +43,7 @@ jint ensureInitialized(JNIEnv** env, JavaVM* vm) { // TODO why we need JNIEXPORT for getCurrentEnv ? JNIEXPORT JNIEnv* getCurrentEnv() { - JNIEnv* env; + JNIEnv* env = nullptr; jint ret = globalVm->GetEnv((void**)&env, JNI_VERSION_1_6); if (ret != JNI_OK) { logErrorMessageAndDie( @@ -68,7 +68,7 @@ void assertNoPendingJniException(JNIEnv* env) { } auto throwable = env->ExceptionOccurred(); - if (!throwable) { + if (throwable == nullptr) { logErrorMessageAndDie("Unable to get pending JNI exception."); } env->ExceptionClear(); diff --git a/java/jni/yogajni.cpp b/java/jni/yogajni.cpp index cab45a13..5bc99431 100644 --- a/java/jni/yogajni.cpp +++ b/java/jni/yogajni.cpp @@ -10,8 +10,8 @@ using namespace facebook::yoga; -jint JNI_OnLoad(JavaVM* vm, void*) { - JNIEnv* env; +jint JNI_OnLoad(JavaVM* vm, void* /*unused*/) { + JNIEnv* env = nullptr; jint ret = vanillajni::ensureInitialized(&env, vm); YGJNIVanilla::registerNatives(env); return ret; diff --git a/tests/EventsTest.cpp b/tests/EventsTest.cpp index 0612f8f8..f911b4b2 100644 --- a/tests/EventsTest.cpp +++ b/tests/EventsTest.cpp @@ -45,8 +45,11 @@ struct EventArgs { }; class EventTest : public ::testing::Test { - ScopedEventSubscription subscription = {&EventTest::listen}; - static void listen(YGNodeConstRef, Event::Type, Event::Data); + ScopedEventSubscription subscription{&EventTest::listen}; + static void listen( + YGNodeConstRef /*node*/, + Event::Type /*type*/, + Event::Data /*data*/); public: static std::vector events; diff --git a/tests/SmallValueBufferTest.cpp b/tests/SmallValueBufferTest.cpp index 0ed9d94b..21f897e3 100644 --- a/tests/SmallValueBufferTest.cpp +++ b/tests/SmallValueBufferTest.cpp @@ -13,7 +13,7 @@ namespace facebook::yoga { constexpr size_t kBufferSize = 4; TEST(SmallValueBuffer, copy_assignment_with_overflow) { - std::array handles; + std::array handles{}; SmallValueBuffer buffer1; for (size_t i = 0; i < kBufferSize + 1; ++i) { diff --git a/tests/YGBaselineFuncTest.cpp b/tests/YGBaselineFuncTest.cpp index a2ea2415..5c937225 100644 --- a/tests/YGBaselineFuncTest.cpp +++ b/tests/YGBaselineFuncTest.cpp @@ -10,7 +10,7 @@ static float _baseline(YGNodeConstRef node, const float /*width*/, const float /*height*/) { - float* baseline = (float*)YGNodeGetContext(node); + auto* baseline = (float*)YGNodeGetContext(node); return *baseline; } diff --git a/tests/YGConfigTest.cpp b/tests/YGConfigTest.cpp index ced84a70..d19457bf 100644 --- a/tests/YGConfigTest.cpp +++ b/tests/YGConfigTest.cpp @@ -21,10 +21,16 @@ struct ConfigCloningTest : public ::testing::Test { void TearDown() override; static yoga::Node clonedNode; - static YGNodeRef cloneNode(YGNodeConstRef, YGNodeConstRef, size_t) { + static YGNodeRef cloneNode( + YGNodeConstRef /*unused*/, + YGNodeConstRef /*unused*/, + size_t /*unused*/) { return &clonedNode; } - static YGNodeRef doNotClone(YGNodeConstRef, YGNodeConstRef, size_t) { + static YGNodeRef doNotClone( + YGNodeConstRef /*unused*/, + YGNodeConstRef /*unused*/, + size_t /*unused*/) { return nullptr; } }; @@ -32,7 +38,8 @@ struct ConfigCloningTest : public ::testing::Test { TEST_F(ConfigCloningTest, uses_values_provided_by_cloning_callback) { config->setCloneNodeCallback(cloneNode); - yoga::Node node{}, owner{}; + yoga::Node node{}; + yoga::Node owner{}; auto clone = config->cloneNode(&node, &owner, 0); ASSERT_EQ(clone, &clonedNode); @@ -43,7 +50,8 @@ TEST_F( falls_back_to_regular_cloning_if_callback_returns_null) { config->setCloneNodeCallback(doNotClone); - yoga::Node node{}, owner{}; + yoga::Node node{}; + yoga::Node owner{}; auto clone = config->cloneNode(&node, &owner, 0); ASSERT_NE(clone, nullptr); diff --git a/tests/YGDefaultValuesTest.cpp b/tests/YGDefaultValuesTest.cpp index 2c72021e..2558d404 100644 --- a/tests/YGDefaultValuesTest.cpp +++ b/tests/YGDefaultValuesTest.cpp @@ -12,7 +12,7 @@ TEST(YogaTest, assert_default_values) { const YGNodeRef root = YGNodeNew(); ASSERT_EQ(0u, YGNodeGetChildCount(root)); - ASSERT_EQ(NULL, YGNodeGetChild(root, 1)); + ASSERT_EQ(nullptr, YGNodeGetChild(root, 1)); ASSERT_EQ(YGDirectionInherit, YGNodeStyleGetDirection(root)); ASSERT_EQ(YGFlexDirectionColumn, YGNodeStyleGetFlexDirection(root)); diff --git a/tests/YGHadOverflowTest.cpp b/tests/YGHadOverflowTest.cpp index 5537a4b8..a21bb990 100644 --- a/tests/YGHadOverflowTest.cpp +++ b/tests/YGHadOverflowTest.cpp @@ -12,8 +12,7 @@ using namespace ::testing; class YogaTest_HadOverflowTests : public Test { protected: - YogaTest_HadOverflowTests() { - config = YGConfigNew(); + YogaTest_HadOverflowTests() : config(YGConfigNew()) { root = YGNodeNewWithConfig(config); YGNodeStyleSetWidth(root, 200); YGNodeStyleSetHeight(root, 100); @@ -21,7 +20,7 @@ class YogaTest_HadOverflowTests : public Test { YGNodeStyleSetFlexWrap(root, YGWrapNoWrap); } - ~YogaTest_HadOverflowTests() { + ~YogaTest_HadOverflowTests() override { YGNodeFreeRecursive(root); YGConfigFree(config); } diff --git a/tests/YGMeasureCacheTest.cpp b/tests/YGMeasureCacheTest.cpp index 98a0f568..71183c72 100644 --- a/tests/YGMeasureCacheTest.cpp +++ b/tests/YGMeasureCacheTest.cpp @@ -50,7 +50,7 @@ static YGSize _measure_84_49( float /*height*/, YGMeasureMode /*heightMode*/) { int* measureCount = (int*)YGNodeGetContext(node); - if (measureCount) { + if (measureCount != nullptr) { (*measureCount)++; } diff --git a/tests/YGMeasureModeTest.cpp b/tests/YGMeasureModeTest.cpp index b4d7f4fb..97c916c2 100644 --- a/tests/YGMeasureModeTest.cpp +++ b/tests/YGMeasureModeTest.cpp @@ -26,8 +26,7 @@ static YGSize _measure( YGMeasureMode widthMode, float height, YGMeasureMode heightMode) { - struct _MeasureConstraintList* constraintList = - (struct _MeasureConstraintList*)YGNodeGetContext(node); + auto* constraintList = (struct _MeasureConstraintList*)YGNodeGetContext(node); struct _MeasureConstraint* constraints = constraintList->constraints; uint32_t currentIndex = constraintList->length; (&constraints[currentIndex])->width = width; @@ -43,7 +42,7 @@ static YGSize _measure( } TEST(YogaTest, exactly_measure_stretched_child_column) { - struct _MeasureConstraintList constraintList = _MeasureConstraintList{ + auto constraintList = _MeasureConstraintList{ 0, (struct _MeasureConstraint*)malloc( 10 * sizeof(struct _MeasureConstraint)), @@ -70,7 +69,7 @@ TEST(YogaTest, exactly_measure_stretched_child_column) { } TEST(YogaTest, exactly_measure_stretched_child_row) { - struct _MeasureConstraintList constraintList = _MeasureConstraintList{ + auto constraintList = _MeasureConstraintList{ 0, (struct _MeasureConstraint*)malloc( 10 * sizeof(struct _MeasureConstraint)), @@ -98,7 +97,7 @@ TEST(YogaTest, exactly_measure_stretched_child_row) { } TEST(YogaTest, at_most_main_axis_column) { - struct _MeasureConstraintList constraintList = _MeasureConstraintList{ + auto constraintList = _MeasureConstraintList{ 0, (struct _MeasureConstraint*)malloc( 10 * sizeof(struct _MeasureConstraint)), @@ -125,7 +124,7 @@ TEST(YogaTest, at_most_main_axis_column) { } TEST(YogaTest, at_most_cross_axis_column) { - struct _MeasureConstraintList constraintList = _MeasureConstraintList{ + auto constraintList = _MeasureConstraintList{ 0, (struct _MeasureConstraint*)malloc( 10 * sizeof(struct _MeasureConstraint)), @@ -153,7 +152,7 @@ TEST(YogaTest, at_most_cross_axis_column) { } TEST(YogaTest, at_most_main_axis_row) { - struct _MeasureConstraintList constraintList = _MeasureConstraintList{ + auto constraintList = _MeasureConstraintList{ 0, (struct _MeasureConstraint*)malloc( 10 * sizeof(struct _MeasureConstraint)), @@ -181,7 +180,7 @@ TEST(YogaTest, at_most_main_axis_row) { } TEST(YogaTest, at_most_cross_axis_row) { - struct _MeasureConstraintList constraintList = _MeasureConstraintList{ + auto constraintList = _MeasureConstraintList{ 0, (struct _MeasureConstraint*)malloc( 10 * sizeof(struct _MeasureConstraint)), @@ -210,7 +209,7 @@ TEST(YogaTest, at_most_cross_axis_row) { } TEST(YogaTest, flex_child) { - struct _MeasureConstraintList constraintList = _MeasureConstraintList{ + auto constraintList = _MeasureConstraintList{ 0, (struct _MeasureConstraint*)malloc( 10 * sizeof(struct _MeasureConstraint)), @@ -240,7 +239,7 @@ TEST(YogaTest, flex_child) { } TEST(YogaTest, flex_child_with_flex_basis) { - struct _MeasureConstraintList constraintList = _MeasureConstraintList{ + auto constraintList = _MeasureConstraintList{ 0, (struct _MeasureConstraint*)malloc( 10 * sizeof(struct _MeasureConstraint)), @@ -268,7 +267,7 @@ TEST(YogaTest, flex_child_with_flex_basis) { } TEST(YogaTest, overflow_scroll_column) { - struct _MeasureConstraintList constraintList = _MeasureConstraintList{ + auto constraintList = _MeasureConstraintList{ 0, (struct _MeasureConstraint*)malloc( 10 * sizeof(struct _MeasureConstraint)), @@ -300,7 +299,7 @@ TEST(YogaTest, overflow_scroll_column) { } TEST(YogaTest, overflow_scroll_row) { - struct _MeasureConstraintList constraintList = _MeasureConstraintList{ + auto constraintList = _MeasureConstraintList{ 0, (struct _MeasureConstraint*)malloc( 10 * sizeof(struct _MeasureConstraint)), diff --git a/tests/YGMeasureTest.cpp b/tests/YGMeasureTest.cpp index de9e757d..7fc0c4ef 100644 --- a/tests/YGMeasureTest.cpp +++ b/tests/YGMeasureTest.cpp @@ -15,7 +15,7 @@ static YGSize _measure( float /*height*/, YGMeasureMode /*heightMode*/) { int* measureCount = (int*)YGNodeGetContext(node); - if (measureCount) { + if (measureCount != nullptr) { (*measureCount)++; } diff --git a/tests/util/TestUtil.h b/tests/util/TestUtil.h index 1f5bf743..3a448fd5 100644 --- a/tests/util/TestUtil.h +++ b/tests/util/TestUtil.h @@ -20,7 +20,7 @@ struct TestUtil { }; struct ScopedEventSubscription { - ScopedEventSubscription(std::function&&); + explicit ScopedEventSubscription(std::function&&); ~ScopedEventSubscription(); }; diff --git a/yoga/YGNode.cpp b/yoga/YGNode.cpp index 57f0473b..a34685ee 100644 --- a/yoga/YGNode.cpp +++ b/yoga/YGNode.cpp @@ -216,12 +216,12 @@ void YGNodeSetChildren( auto owner = resolveRef(ownerRef); auto children = reinterpret_cast(childrenRefs); - if (!owner) { + if (owner == nullptr) { return; } const std::vector childrenVector = {children, children + count}; - if (childrenVector.size() == 0) { + if (childrenVector.empty()) { if (owner->getChildCount() > 0) { for (auto* child : owner->getChildren()) { child->setLayout({}); diff --git a/yoga/algorithm/AbsoluteLayout.h b/yoga/algorithm/AbsoluteLayout.h index 3beabf9a..ae84e6da 100644 --- a/yoga/algorithm/AbsoluteLayout.h +++ b/yoga/algorithm/AbsoluteLayout.h @@ -13,16 +13,16 @@ namespace facebook::yoga { void layoutAbsoluteChild( - const yoga::Node* const containingNode, - const yoga::Node* const node, - yoga::Node* const child, - const float containingBlockWidth, - const float containingBlockHeight, - const SizingMode widthMode, - const Direction direction, + const yoga::Node* containingNode, + const yoga::Node* node, + yoga::Node* child, + float containingBlockWidth, + float containingBlockHeight, + SizingMode widthMode, + Direction direction, LayoutData& layoutMarkerData, - const uint32_t depth, - const uint32_t generationCount); + uint32_t depth, + uint32_t generationCount); void layoutAbsoluteDescendants( yoga::Node* containingNode, diff --git a/yoga/algorithm/CalculateLayout.cpp b/yoga/algorithm/CalculateLayout.cpp index 9b214cf5..c6fb81e7 100644 --- a/yoga/algorithm/CalculateLayout.cpp +++ b/yoga/algorithm/CalculateLayout.cpp @@ -80,8 +80,8 @@ static void computeFlexBasisForChild( const float mainAxisSize = isMainAxisRow ? width : height; const float mainAxisownerSize = isMainAxisRow ? ownerWidth : ownerHeight; - float childWidth; - float childHeight; + float childWidth = YGUndefined; + float childHeight = YGUndefined; SizingMode childWidthSizingMode; SizingMode childHeightSizingMode; @@ -120,8 +120,6 @@ static void computeFlexBasisForChild( } else { // Compute the flex basis and hypothetical main size (i.e. the clamped flex // basis). - childWidth = YGUndefined; - childHeight = YGUndefined; childWidthSizingMode = SizingMode::MaxContent; childHeightSizingMode = SizingMode::MaxContent; @@ -606,7 +604,7 @@ static float distributeFreeSpaceSecondPass( -currentLineChild->resolveFlexShrink() * childFlexBasis; // Is this child able to shrink? if (flexShrinkScaledFactor != 0) { - float childSize; + float childSize = YGUndefined; if (yoga::isDefined(flexLine.layout.totalFlexShrinkScaledFactors) && flexLine.layout.totalFlexShrinkScaledFactors == 0) { @@ -650,7 +648,7 @@ static float distributeFreeSpaceSecondPass( const float marginCross = currentLineChild->style().computeMarginForAxis( crossAxis, availableInnerWidth); - float childCrossSize; + float childCrossSize = YGUndefined; float childMainSize = updatedMainSize + marginMain; SizingMode childCrossSizingMode; SizingMode childMainSizingMode = SizingMode::StretchFit; @@ -1794,13 +1792,13 @@ static void calculateLayoutImpl( size_t endIndex = 0; for (size_t i = 0; i < lineCount; i++) { const size_t startIndex = endIndex; - size_t ii; + size_t ii = startIndex; // compute the line's height and find the endIndex float lineHeight = 0; float maxAscentForCurrentLine = 0; float maxDescentForCurrentLine = 0; - for (ii = startIndex; ii < childCount; ii++) { + for (; ii < childCount; ii++) { const auto child = node->getChild(ii); if (child->style().display() == Display::None) { continue; @@ -1837,113 +1835,110 @@ static void calculateLayoutImpl( endIndex = ii; currentLead += i != 0 ? crossAxisGap : 0; - if (performLayout) { - for (ii = startIndex; ii < endIndex; ii++) { - const auto child = node->getChild(ii); - if (child->style().display() == Display::None) { - continue; - } - if (child->style().positionType() != PositionType::Absolute) { - switch (resolveChildAlignment(node, child)) { - case Align::FlexStart: { - child->setLayoutPosition( - currentLead + - child->style().computeFlexStartPosition( - crossAxis, direction, availableInnerWidth), - flexStartEdge(crossAxis)); - break; - } - case Align::FlexEnd: { - child->setLayoutPosition( - currentLead + lineHeight - - child->style().computeFlexEndMargin( - crossAxis, direction, availableInnerWidth) - - child->getLayout().measuredDimension( - dimension(crossAxis)), - flexStartEdge(crossAxis)); - break; - } - case Align::Center: { - float childHeight = - child->getLayout().measuredDimension(dimension(crossAxis)); - - child->setLayoutPosition( - currentLead + (lineHeight - childHeight) / 2, - flexStartEdge(crossAxis)); - break; - } - case Align::Stretch: { - child->setLayoutPosition( - currentLead + - child->style().computeFlexStartMargin( - crossAxis, direction, availableInnerWidth), - flexStartEdge(crossAxis)); - - // Remeasure child with the line height as it as been only - // measured with the owners height yet. - if (!child->hasDefiniteLength( - dimension(crossAxis), availableInnerCrossDim)) { - const float childWidth = isMainAxisRow - ? (child->getLayout().measuredDimension( - Dimension::Width) + - child->style().computeMarginForAxis( - mainAxis, availableInnerWidth)) - : leadPerLine + lineHeight; - - const float childHeight = !isMainAxisRow - ? (child->getLayout().measuredDimension( - Dimension::Height) + - child->style().computeMarginForAxis( - crossAxis, availableInnerWidth)) - : leadPerLine + lineHeight; - - if (!(yoga::inexactEquals( - childWidth, - child->getLayout().measuredDimension( - Dimension::Width)) && - yoga::inexactEquals( - childHeight, - child->getLayout().measuredDimension( - Dimension::Height)))) { - calculateLayoutInternal( - child, - childWidth, - childHeight, - direction, - SizingMode::StretchFit, - SizingMode::StretchFit, - availableInnerWidth, - availableInnerHeight, - true, - LayoutPassReason::kMultilineStretch, - layoutMarkerData, - depth, - generationCount); - } - } - break; - } - case Align::Baseline: { - child->setLayoutPosition( - currentLead + maxAscentForCurrentLine - - calculateBaseline(child) + - child->style().computeFlexStartPosition( - FlexDirection::Column, - direction, - availableInnerCrossDim), - PhysicalEdge::Top); - - break; - } - case Align::Auto: - case Align::SpaceBetween: - case Align::SpaceAround: - case Align::SpaceEvenly: - break; + for (ii = startIndex; ii < endIndex; ii++) { + const auto child = node->getChild(ii); + if (child->style().display() == Display::None) { + continue; + } + if (child->style().positionType() != PositionType::Absolute) { + switch (resolveChildAlignment(node, child)) { + case Align::FlexStart: { + child->setLayoutPosition( + currentLead + + child->style().computeFlexStartPosition( + crossAxis, direction, availableInnerWidth), + flexStartEdge(crossAxis)); + break; } + case Align::FlexEnd: { + child->setLayoutPosition( + currentLead + lineHeight - + child->style().computeFlexEndMargin( + crossAxis, direction, availableInnerWidth) - + child->getLayout().measuredDimension( + dimension(crossAxis)), + flexStartEdge(crossAxis)); + break; + } + case Align::Center: { + float childHeight = + child->getLayout().measuredDimension(dimension(crossAxis)); + + child->setLayoutPosition( + currentLead + (lineHeight - childHeight) / 2, + flexStartEdge(crossAxis)); + break; + } + case Align::Stretch: { + child->setLayoutPosition( + currentLead + + child->style().computeFlexStartMargin( + crossAxis, direction, availableInnerWidth), + flexStartEdge(crossAxis)); + + // Remeasure child with the line height as it as been only + // measured with the owners height yet. + if (!child->hasDefiniteLength( + dimension(crossAxis), availableInnerCrossDim)) { + const float childWidth = isMainAxisRow + ? (child->getLayout().measuredDimension(Dimension::Width) + + child->style().computeMarginForAxis( + mainAxis, availableInnerWidth)) + : leadPerLine + lineHeight; + + const float childHeight = !isMainAxisRow + ? (child->getLayout().measuredDimension(Dimension::Height) + + child->style().computeMarginForAxis( + crossAxis, availableInnerWidth)) + : leadPerLine + lineHeight; + + if (!(yoga::inexactEquals( + childWidth, + child->getLayout().measuredDimension( + Dimension::Width)) && + yoga::inexactEquals( + childHeight, + child->getLayout().measuredDimension( + Dimension::Height)))) { + calculateLayoutInternal( + child, + childWidth, + childHeight, + direction, + SizingMode::StretchFit, + SizingMode::StretchFit, + availableInnerWidth, + availableInnerHeight, + true, + LayoutPassReason::kMultilineStretch, + layoutMarkerData, + depth, + generationCount); + } + } + break; + } + case Align::Baseline: { + child->setLayoutPosition( + currentLead + maxAscentForCurrentLine - + calculateBaseline(child) + + child->style().computeFlexStartPosition( + FlexDirection::Column, + direction, + availableInnerCrossDim), + PhysicalEdge::Top); + + break; + } + case Align::Auto: + case Align::SpaceBetween: + case Align::SpaceAround: + case Align::SpaceEvenly: + break; } } } + currentLead = currentLead + leadPerLine + lineHeight; } } @@ -2244,7 +2239,7 @@ bool calculateLayoutInternal( layout->nextCachedMeasurementsIndex = 0; } - CachedMeasurement* newCacheEntry; + CachedMeasurement* newCacheEntry = nullptr; if (performLayout) { // Use the single layout cache entry. newCacheEntry = &layout->cachedLayout; diff --git a/yoga/algorithm/CalculateLayout.h b/yoga/algorithm/CalculateLayout.h index 1d5a3fd7..5e6884ec 100644 --- a/yoga/algorithm/CalculateLayout.h +++ b/yoga/algorithm/CalculateLayout.h @@ -15,24 +15,24 @@ namespace facebook::yoga { void calculateLayout( - yoga::Node* const node, - const float ownerWidth, - const float ownerHeight, - const Direction ownerDirection); + yoga::Node* node, + float ownerWidth, + float ownerHeight, + Direction ownerDirection); bool calculateLayoutInternal( - yoga::Node* const node, - const float availableWidth, - const float availableHeight, - const Direction ownerDirection, - const SizingMode widthSizingMode, - const SizingMode heightSizingMode, - const float ownerWidth, - const float ownerHeight, - const bool performLayout, - const LayoutPassReason reason, + yoga::Node* node, + float availableWidth, + float availableHeight, + Direction ownerDirection, + SizingMode widthSizingMode, + SizingMode heightSizingMode, + float ownerWidth, + float ownerHeight, + bool performLayout, + LayoutPassReason reason, LayoutData& layoutMarkerData, - const uint32_t depth, - const uint32_t generationCount); + uint32_t depth, + uint32_t generationCount); } // namespace facebook::yoga diff --git a/yoga/algorithm/FlexLine.cpp b/yoga/algorithm/FlexLine.cpp index 69ae351e..1fe3e486 100644 --- a/yoga/algorithm/FlexLine.cpp +++ b/yoga/algorithm/FlexLine.cpp @@ -69,7 +69,7 @@ FlexLine calculateFlexLine( if (sizeConsumedIncludingMinConstraint + flexBasisWithMinAndMaxConstraints + childMarginMainAxis + childLeadingGapMainAxis > availableInnerMainDim && - isNodeFlexWrap && itemsInFlow.size() > 0) { + isNodeFlexWrap && !itemsInFlow.empty()) { break; } diff --git a/yoga/algorithm/FlexLine.h b/yoga/algorithm/FlexLine.h index 161a1031..0f888be5 100644 --- a/yoga/algorithm/FlexLine.h +++ b/yoga/algorithm/FlexLine.h @@ -63,7 +63,7 @@ struct FlexLine { // computedFlexBasis properly computed(To do this use // computeFlexBasisForChildren function). FlexLine calculateFlexLine( - yoga::Node* const node, + yoga::Node* node, Direction ownerDirection, float mainAxisownerSize, float availableInnerWidth, diff --git a/yoga/algorithm/PixelGrid.h b/yoga/algorithm/PixelGrid.h index 6bedd3ac..f3bf79f9 100644 --- a/yoga/algorithm/PixelGrid.h +++ b/yoga/algorithm/PixelGrid.h @@ -15,15 +15,15 @@ namespace facebook::yoga { // Round a point value to the nearest physical pixel based on DPI // (pointScaleFactor) float roundValueToPixelGrid( - const double value, - const double pointScaleFactor, - const bool forceCeil, - const bool forceFloor); + double value, + double pointScaleFactor, + bool forceCeil, + bool forceFloor); // Round the layout results of a node and its subtree to the pixel grid. void roundLayoutResultsToPixelGrid( - yoga::Node* const node, - const double absoluteLeft, - const double absoluteTop); + yoga::Node* node, + double absoluteLeft, + double absoluteTop); } // namespace facebook::yoga diff --git a/yoga/config/Config.cpp b/yoga/config/Config.cpp index 607e5774..c2a55f40 100644 --- a/yoga/config/Config.cpp +++ b/yoga/config/Config.cpp @@ -20,7 +20,7 @@ bool configUpdateInvalidatesLayout( oldConfig.useWebDefaults() != newConfig.useWebDefaults(); } -Config::Config(YGLogger logger) : cloneNodeCallback_{nullptr} { +Config::Config(YGLogger logger) { setLogger(logger); } diff --git a/yoga/config/Config.h b/yoga/config/Config.h index e902bd0d..cddfef6d 100644 --- a/yoga/config/Config.h +++ b/yoga/config/Config.h @@ -32,7 +32,7 @@ bool configUpdateInvalidatesLayout( class YG_EXPORT Config : public ::YGConfig { public: - Config(YGLogger logger); + explicit Config(YGLogger logger); void setUseWebDefaults(bool useWebDefaults); bool useWebDefaults() const; @@ -67,8 +67,8 @@ class YG_EXPORT Config : public ::YGConfig { static const Config& getDefault(); private: - YGCloneNodeFunc cloneNodeCallback_; - YGLogger logger_; + YGCloneNodeFunc cloneNodeCallback_{nullptr}; + YGLogger logger_{}; bool useWebDefaults_ : 1 = false; diff --git a/yoga/debug/Log.h b/yoga/debug/Log.h index 94dc0e0c..0a932d80 100644 --- a/yoga/debug/Log.h +++ b/yoga/debug/Log.h @@ -20,7 +20,7 @@ void log(LogLevel level, const char* format, ...) noexcept; void log( const yoga::Node* node, LogLevel level, - const char* message, + const char* format, ...) noexcept; void log( diff --git a/yoga/event/event.cpp b/yoga/event/event.cpp index b47e1fab..e286ded0 100644 --- a/yoga/event/event.cpp +++ b/yoga/event/event.cpp @@ -40,14 +40,14 @@ struct Node { std::function subscriber = nullptr; Node* next = nullptr; - Node(std::function&& subscriber) + explicit Node(std::function&& subscriber) : subscriber{std::move(subscriber)} {} }; std::atomic subscribers{nullptr}; Node* push(Node* newHead) { - Node* oldHead; + Node* oldHead = nullptr; do { oldHead = subscribers.load(std::memory_order_relaxed); if (newHead != nullptr) { diff --git a/yoga/event/event.h b/yoga/event/event.h index 4e96e049..b4be8ab2 100644 --- a/yoga/event/event.h +++ b/yoga/event/event.h @@ -9,8 +9,8 @@ #include -#include #include +#include #include #include @@ -46,7 +46,7 @@ struct LayoutData { measureCallbackReasonsCount; }; -const char* LayoutPassReasonToString(const LayoutPassReason value); +const char* LayoutPassReasonToString(LayoutPassReason value); struct YG_EXPORT Event { enum Type { @@ -72,7 +72,7 @@ struct YG_EXPORT Event { public: template - Data(const TypedData& data) : data_{&data} {} + explicit Data(const TypedData& data) : data_{&data} {} template const TypedData& get() const { @@ -90,7 +90,10 @@ struct YG_EXPORT Event { } private: - static void publish(YGNodeConstRef, Type, const Data&); + static void publish( + YGNodeConstRef /*node*/, + Type /*eventType*/, + const Data& /*eventData*/); }; template <> diff --git a/yoga/node/Node.cpp b/yoga/node/Node.cpp index c431940e..adb63663 100644 --- a/yoga/node/Node.cpp +++ b/yoga/node/Node.cpp @@ -26,23 +26,23 @@ Node::Node(const yoga::Config* config) : config_{config} { } } -Node::Node(Node&& node) { - hasNewLayout_ = node.hasNewLayout_; - isReferenceBaseline_ = node.isReferenceBaseline_; - isDirty_ = node.isDirty_; - alwaysFormsContainingBlock_ = node.alwaysFormsContainingBlock_; - nodeType_ = node.nodeType_; - context_ = node.context_; - measureFunc_ = node.measureFunc_; - baselineFunc_ = node.baselineFunc_; - dirtiedFunc_ = node.dirtiedFunc_; - style_ = node.style_; - layout_ = node.layout_; - lineIndex_ = node.lineIndex_; - owner_ = node.owner_; - children_ = std::move(node.children_); - config_ = node.config_; - resolvedDimensions_ = node.resolvedDimensions_; +Node::Node(Node&& node) noexcept + : hasNewLayout_(node.hasNewLayout_), + isReferenceBaseline_(node.isReferenceBaseline_), + isDirty_(node.isDirty_), + alwaysFormsContainingBlock_(node.alwaysFormsContainingBlock_), + nodeType_(node.nodeType_), + context_(node.context_), + measureFunc_(node.measureFunc_), + baselineFunc_(node.baselineFunc_), + dirtiedFunc_(node.dirtiedFunc_), + style_(std::move(node.style_)), + layout_(node.layout_), + lineIndex_(node.lineIndex_), + owner_(node.owner_), + children_(std::move(node.children_)), + config_(node.config_), + resolvedDimensions_(node.resolvedDimensions_) { for (auto c : children_) { c->setOwner(this); } @@ -83,7 +83,7 @@ void Node::setMeasureFunc(YGMeasureFunc measureFunc) { } else { yoga::assertFatalWithNode( this, - children_.size() == 0, + children_.empty(), "Cannot set measure function: Nodes with measure functions cannot have " "children."); // TODO: t18095186 Move nodeType to opt-in function and mark appropriate @@ -122,18 +122,17 @@ void Node::setConfig(yoga::Config* config) { } void Node::setDirty(bool isDirty) { - if (isDirty == isDirty_) { + if (static_cast(isDirty) == isDirty_) { return; } isDirty_ = isDirty; - if (isDirty && dirtiedFunc_) { + if (isDirty && (dirtiedFunc_ != nullptr)) { dirtiedFunc_(this); } } bool Node::removeChild(Node* child) { - std::vector::iterator p = - std::find(children_.begin(), children_.end(), child); + auto p = std::find(children_.begin(), children_.end(), child); if (p != children_.end()) { children_.erase(p); return true; @@ -307,7 +306,7 @@ void Node::markDirtyAndPropagate() { if (!isDirty_) { setDirty(true); setLayoutComputedFlexBasis(FloatOptional()); - if (owner_) { + if (owner_ != nullptr) { owner_->markDirtyAndPropagate(); } } @@ -351,7 +350,7 @@ bool Node::isNodeFlexible() { void Node::reset() { yoga::assertFatalWithNode( this, - children_.size() == 0, + children_.empty(), "Cannot reset a node which still has children attached"); yoga::assertFatalWithNode( this, owner_ == nullptr, "Cannot reset a node still attached to a owner"); diff --git a/yoga/node/Node.h b/yoga/node/Node.h index 1eea46f8..ec28f2db 100644 --- a/yoga/node/Node.h +++ b/yoga/node/Node.h @@ -7,8 +7,8 @@ #pragma once -#include #include +#include #include #include @@ -34,7 +34,7 @@ class YG_EXPORT Node : public ::YGNode { Node(); explicit Node(const Config* config); - Node(Node&&); + Node(Node&& node) noexcept; // Does not expose true value semantics, as children are not cloned eagerly. // Should we remove this? @@ -65,7 +65,11 @@ class YG_EXPORT Node : public ::YGNode { return measureFunc_ != nullptr; } - YGSize measure(float, MeasureMode, float, MeasureMode); + YGSize measure( + float width, + MeasureMode widthMode, + float height, + MeasureMode heightMode); bool hasBaselineFunc() const noexcept { return baselineFunc_ != nullptr; @@ -73,9 +77,9 @@ class YG_EXPORT Node : public ::YGNode { float baseline(float width, float height) const; - float dimensionWithMargin(const FlexDirection axis, const float widthSize); + float dimensionWithMargin(FlexDirection axis, float widthSize); - bool isLayoutDimensionDefined(const FlexDirection axis); + bool isLayoutDimensionDefined(FlexDirection axis); /** * Whether the node has a "definite length" along the given axis. @@ -214,7 +218,7 @@ class YG_EXPORT Node : public ::YGNode { void setDirty(bool isDirty); void setLayoutLastOwnerDirection(Direction direction); - void setLayoutComputedFlexBasis(const FloatOptional computedFlexBasis); + void setLayoutComputedFlexBasis(FloatOptional computedFlexBasis); void setLayoutComputedFlexBasisGeneration( uint32_t computedFlexBasisGeneration); void setLayoutMeasuredDimension(float measuredDimension, Dimension dimension); @@ -226,15 +230,15 @@ class YG_EXPORT Node : public ::YGNode { void setLayoutPadding(float padding, PhysicalEdge edge); void setLayoutPosition(float position, PhysicalEdge edge); void setPosition( - const Direction direction, - const float mainSize, - const float crossSize, - const float ownerWidth); + Direction direction, + float mainSize, + float crossSize, + float ownerWidth); // Other methods Style::Length resolveFlexBasisPtr() const; void resolveDimension(); - Direction resolveDirection(const Direction ownerDirection); + Direction resolveDirection(Direction ownerDirection); void clearChildren(); /// Replaces the occurrences of oldChild with newChild void replaceChild(Node* oldChild, Node* newChild); @@ -253,12 +257,12 @@ class YG_EXPORT Node : public ::YGNode { private: // Used to allow resetting the node - Node& operator=(Node&&) = default; + Node& operator=(Node&&) noexcept = default; float relativePosition( FlexDirection axis, Direction direction, - const float axisSize) const; + float axisSize) const; void useWebDefaults() { style_.setFlexDirection(FlexDirection::Row); diff --git a/yoga/style/SmallValueBuffer.h b/yoga/style/SmallValueBuffer.h index 2860a420..8d78a54d 100644 --- a/yoga/style/SmallValueBuffer.h +++ b/yoga/style/SmallValueBuffer.h @@ -26,7 +26,7 @@ class SmallValueBuffer { SmallValueBuffer(const SmallValueBuffer& other) { *this = other; } - SmallValueBuffer(SmallValueBuffer&& other) = default; + SmallValueBuffer(SmallValueBuffer&& other) noexcept = default; // Add a new element to the buffer, returning the index of the element uint16_t push(uint32_t value) { @@ -116,7 +116,7 @@ class SmallValueBuffer { return *this; } - SmallValueBuffer& operator=(SmallValueBuffer&& other) = default; + SmallValueBuffer& operator=(SmallValueBuffer&& other) noexcept = default; private: struct Overflow { @@ -125,7 +125,7 @@ class SmallValueBuffer { }; uint16_t count_{0}; - std::array buffer_; + std::array buffer_{}; std::bitset wideElements_; std::unique_ptr overflow_; }; diff --git a/yoga/style/StyleValuePool.h b/yoga/style/StyleValuePool.h index f8ee93e4..3b177254 100644 --- a/yoga/style/StyleValuePool.h +++ b/yoga/style/StyleValuePool.h @@ -101,7 +101,7 @@ class StyleValuePool { static constexpr bool isIntegerPackable(float f) { constexpr uint16_t kMaxInlineAbsValue = (1 << 11) - 1; - int32_t i = static_cast(f); + auto i = static_cast(f); return static_cast(i) == f && i >= -kMaxInlineAbsValue && i <= +kMaxInlineAbsValue; } @@ -110,7 +110,7 @@ class StyleValuePool { uint16_t isNegative = value < 0 ? 1 : 0; return static_cast( (isNegative << 11) | - (static_cast(value) * (isNegative ? -1 : 1))); + (static_cast(value) * (isNegative != 0u ? -1 : 1))); } static constexpr float unpackInlineInteger(uint16_t value) { -- 2.50.1.windows.1