Bug 1272203 (part 1) - Add mozilla::NotNull to MFBT. r=froydnj.

This patch implements mozilla::NotNull, which is similar but not identicial to
gsl::not_null.

The current draft(?) implementation of gsl::not_null is at
https://github.com/Microsoft/GSL/blob/master/include/gsl.h.

The main difference is that not_null allows implicit conversion from T to
not_null<T>. In contrast, NotNull only allows explicit conversion from T to
NotNull<T> via WrapNotNull().

The rationale for this is that when converting from a less-constrained type to
a more constrained type, implicit conversion is undesirable. For example, if I
changed a function f from this:

  f(int* aPtr);

to this:

  f(gsl::not_null<int*> aPtr);

no call sites would have to be modified. But if I changed it to this:

  f(mozilla::NotNull<int*> aPtr);

call sites *would* need to be modified. This is a good thing! It forces the
author to audit the call sites for non-nullness, and encourages them to
back-propagate NotNull throughout the code.

The other difference between not_null and NotNull is that not_null disables
pointer arithmetic, which means it cannot be used with array pointers. I have
not implemented this restriction for NotNull because it seems arbitrary and
unnecessary.
This commit is contained in:
Nicholas Nethercote 2016-05-12 14:21:16 +10:00
Родитель 39cdd7f4f6
Коммит b3d842431f
4 изменённых файлов: 521 добавлений и 0 удалений

209
mfbt/NotNull.h Normal file
Просмотреть файл

@ -0,0 +1,209 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef mozilla_NotNull_h
#define mozilla_NotNull_h
// It's often unclear if a particular pointer, be it raw (T*) or smart
// (RefPtr<T>, nsCOMPtr<T>, etc.) can be null. This leads to missing null
// checks (which can cause crashes) and unnecessary null checks (which clutter
// the code).
//
// C++ has a built-in alternative that avoids these problems: references. This
// module defines another alternative, NotNull, which can be used in cases
// where references are not suitable.
//
// In the comments below we use the word "handle" to cover all varieties of
// pointers and references.
//
// References
// ----------
// References are always non-null. (You can do |T& r = *p;| where |p| is null,
// but that's undefined behaviour. C++ doesn't provide any built-in, ironclad
// guarantee of non-nullness.)
//
// A reference works well when you need a temporary handle to an existing
// single object, e.g. for passing a handle to a function, or as a local handle
// within another object. (In Rust parlance, this is a "borrow".)
//
// A reference is less appropriate in the following cases.
//
// - As a primary handle to an object. E.g. code such as this is possible but
// strange: |T& t = *new T(); ...; delete &t;|
//
// - As a handle to an array. It's common for |T*| to refer to either a single
// |T| or an array of |T|, but |T&| cannot refer to an array of |T| because
// you can't index off a reference (at least, not without first converting it
// to a pointer).
//
// - When the handle identity is meaningful, e.g. if you have a hashtable of
// handles, because you have to use |&| on the reference to convert it to a
// pointer.
//
// - Some people don't like using non-const references as function parameters,
// because it is not clear at the call site that the argument might be
// modified.
//
// - When you need "smart" behaviour. E.g. we lack reference equivalents to
// RefPtr and nsCOMPtr.
//
// - When interfacing with code that uses pointers a lot, sometimes using a
// reference just feels like an odd fit.
//
// Furthermore, a reference is impossible in the following cases.
//
// - When the handle is rebound to another object. References don't allow this.
//
// - When the handle has type |void|. |void&| is not allowed.
//
// NotNull is an alternative that can be used in any of the above cases except
// for the last one, where the handle type is |void|. See below.
#include "mozilla/Assertions.h"
namespace mozilla {
// NotNull can be used to wrap a "base" pointer (raw or smart) to indicate it
// is not null. Some examples:
//
// - NotNull<char*>
// - NotNull<RefPtr<Event>>
// - NotNull<nsCOMPtr<Event>>
//
// NotNull has the following notable properties.
//
// - It has zero space overhead.
//
// - It must be initialized explicitly. There is no default initialization.
//
// - It auto-converts to the base pointer type.
//
// - It does not auto-convert from a base pointer. Implicit conversion from a
// less-constrained type (e.g. T*) to a more-constrained type (e.g.
// NotNull<T*>) is dangerous. Creation and assignment from a base pointer can
// only be done with WrapNotNull(), which makes them impossible to overlook,
// both when writing and reading code.
//
// - When initialized (or assigned) it is checked, and if it is null we abort.
// This guarantees that it cannot be null.
//
// - |operator bool()| is deleted. This means you cannot check a NotNull in a
// boolean context, which eliminates the possibility of unnecessary null
// checks.
//
// NotNull currently doesn't work with UniquePtr. See
// https://github.com/Microsoft/GSL/issues/89 for some discussion.
//
template <typename T>
class NotNull
{
template <typename U> friend NotNull<U> WrapNotNull(U aBasePtr);
T mBasePtr;
// This constructor is only used by WrapNotNull().
template <typename U>
explicit NotNull(U aBasePtr) : mBasePtr(aBasePtr) {}
public:
// Disallow default construction.
NotNull() = delete;
// Construct/assign from another NotNull with a compatible base pointer type.
template <typename U>
MOZ_IMPLICIT NotNull(const NotNull<U>& aOther) : mBasePtr(aOther.get()) {}
// Default copy/move construction and assignment.
NotNull(const NotNull<T>&) = default;
NotNull<T>& operator=(const NotNull<T>&) = default;
NotNull(NotNull<T>&&) = default;
NotNull<T>& operator=(NotNull<T>&&) = default;
// Disallow null checks, which are unnecessary for this type.
explicit operator bool() const = delete;
// Explicit conversion to a base pointer. Use only to resolve ambiguity or to
// get a castable pointer.
const T& get() const { return mBasePtr; }
// Implicit conversion to a base pointer. Preferable to get().
operator const T&() const { return get(); }
// Dereference operators.
const T& operator->() const { return get(); }
decltype(*mBasePtr) operator*() const { return *mBasePtr; }
};
template <typename T>
NotNull<T>
WrapNotNull(const T aBasePtr)
{
NotNull<T> notNull(aBasePtr);
MOZ_RELEASE_ASSERT(aBasePtr);
return notNull;
}
// Compare two NotNulls.
template <typename T, typename U>
inline bool
operator==(const NotNull<T>& aLhs, const NotNull<U>& aRhs)
{
return aLhs.get() == aRhs.get();
}
template <typename T, typename U>
inline bool
operator!=(const NotNull<T>& aLhs, const NotNull<U>& aRhs)
{
return aLhs.get() != aRhs.get();
}
// Compare a NotNull to a base pointer.
template <typename T, typename U>
inline bool
operator==(const NotNull<T>& aLhs, const U& aRhs)
{
return aLhs.get() == aRhs;
}
template <typename T, typename U>
inline bool
operator!=(const NotNull<T>& aLhs, const U& aRhs)
{
return aLhs.get() != aRhs;
}
// Compare a base pointer to a NotNull.
template <typename T, typename U>
inline bool
operator==(const T& aLhs, const NotNull<U>& aRhs)
{
return aLhs == aRhs.get();
}
template <typename T, typename U>
inline bool
operator!=(const T& aLhs, const NotNull<U>& aRhs)
{
return aLhs != aRhs.get();
}
// Disallow comparing a NotNull to a nullptr.
template <typename T>
bool
operator==(const NotNull<T>&, decltype(nullptr)) = delete;
template <typename T>
bool
operator!=(const NotNull<T>&, decltype(nullptr)) = delete;
// Disallow comparing a nullptr to a NotNull.
template <typename T>
bool
operator==(decltype(nullptr), const NotNull<T>&) = delete;
template <typename T>
bool
operator!=(decltype(nullptr), const NotNull<T>&) = delete;
} // namespace mozilla
#endif /* mozilla_NotNull_h */

Просмотреть файл

@ -60,6 +60,7 @@ EXPORTS.mozilla = [
'MemoryChecking.h',
'MemoryReporting.h',
'Move.h',
'NotNull.h',
'NullPtr.h',
'NumericLimits.h',
'Opaque.h',

310
mfbt/tests/TestNotNull.cpp Normal file
Просмотреть файл

@ -0,0 +1,310 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/NotNull.h"
#include "mozilla/RefPtr.h"
#include "mozilla/UniquePtr.h"
using mozilla::WrapNotNull;
using mozilla::MakeUnique;
using mozilla::NotNull;
using mozilla::UniquePtr;
#define CHECK MOZ_RELEASE_ASSERT
class Blah
{
public:
Blah() : mX(0) {}
void blah() {};
int mX;
};
// A simple smart pointer that implicity converts to and from T*.
template <typename T>
class MyPtr
{
T* mRawPtr;
public:
MyPtr() : mRawPtr(nullptr) {}
MOZ_IMPLICIT MyPtr(T* aRawPtr) : mRawPtr(aRawPtr) {}
T* get() const { return mRawPtr; }
operator T*() const { return get(); }
T* operator->() const { return get(); }
};
// A simple class that works with RefPtr. It keeps track of the maximum
// refcount value for testing purposes.
class MyRefType
{
int mExpectedMaxRefCnt;
int mMaxRefCnt;
int mRefCnt;
public:
explicit MyRefType(int aExpectedMaxRefCnt)
: mExpectedMaxRefCnt(aExpectedMaxRefCnt)
, mMaxRefCnt(0)
, mRefCnt(0)
{}
~MyRefType() {
CHECK(mMaxRefCnt == mExpectedMaxRefCnt);
}
uint32_t AddRef() {
mRefCnt++;
if (mRefCnt > mMaxRefCnt) {
mMaxRefCnt = mRefCnt;
}
return mRefCnt;
}
uint32_t Release() {
CHECK(mRefCnt > 0);
if (mRefCnt == 1) {
delete this;
}
mRefCnt--;
return mRefCnt;
}
};
void f_i(int* aPtr) {}
void f_my(MyPtr<int> aPtr) {}
void f_nni(NotNull<int*> aPtr) {}
void f_nnmy(NotNull<MyPtr<int>> aPtr) {}
void
TestNotNullWithMyPtr()
{
int i4 = 4;
int i5 = 5;
MyPtr<int> my4 = &i4;
MyPtr<int> my5 = &i5;
NotNull<int*> nni4 = WrapNotNull(&i4);
NotNull<int*> nni5 = WrapNotNull(&i5);
NotNull<MyPtr<int>> nnmy4 = WrapNotNull(my4);
//WrapNotNull(nullptr); // no wrapping from nullptr
//WrapNotNull(0); // no wrapping from zero
// NotNull<int*> construction combinations
//NotNull<int*> nni4a; // no default
//NotNull<int*> nni4a(nullptr); // no nullptr
//NotNull<int*> nni4a(0); // no zero
//NotNull<int*> nni4a(&i4); // no int*
//NotNull<int*> nni4a(my4); // no MyPtr<int>
NotNull<int*> nni4b(WrapNotNull(&i4)); // WrapNotNull(int*)
NotNull<int*> nni4c(WrapNotNull(my4)); // WrapNotNull(MyPtr<int>)
NotNull<int*> nni4d(nni4); // NotNull<int*>
NotNull<int*> nni4e(nnmy4); // NotNull<MyPtr<int>>
CHECK(*nni4b == 4);
CHECK(*nni4c == 4);
CHECK(*nni4d == 4);
CHECK(*nni4e == 4);
// NotNull<MyPtr<int>> construction combinations
//NotNull<MyPtr<int>> nnmy4a; // no default
//NotNull<MyPtr<int>> nnmy4a(nullptr); // no nullptr
//NotNull<MyPtr<int>> nnmy4a(0); // no zero
//NotNull<MyPtr<int>> nnmy4a(&i4); // no int*
//NotNull<MyPtr<int>> nnmy4a(my4); // no MyPtr<int>
NotNull<MyPtr<int>> nnmy4b(WrapNotNull(&i4)); // WrapNotNull(int*)
NotNull<MyPtr<int>> nnmy4c(WrapNotNull(my4)); // WrapNotNull(MyPtr<int>)
NotNull<MyPtr<int>> nnmy4d(nni4); // NotNull<int*>
NotNull<MyPtr<int>> nnmy4e(nnmy4); // NotNull<MyPtr<int>>
CHECK(*nnmy4b == 4);
CHECK(*nnmy4c == 4);
CHECK(*nnmy4d == 4);
CHECK(*nnmy4e == 4);
// NotNull<int*> assignment combinations
//nni4b = nullptr; // no nullptr
//nni4b = 0; // no zero
//nni4a = &i4; // no int*
//nni4a = my4; // no MyPtr<int>
nni4b = WrapNotNull(&i4); // WrapNotNull(int*)
nni4c = WrapNotNull(my4); // WrapNotNull(MyPtr<int>)
nni4d = nni4; // NotNull<int*>
nni4e = nnmy4; // NotNull<MyPtr<int>>
CHECK(*nni4b == 4);
CHECK(*nni4c == 4);
CHECK(*nni4d == 4);
CHECK(*nni4e == 4);
// NotNull<MyPtr<int>> assignment combinations
//nnmy4a = nullptr; // no nullptr
//nnmy4a = 0; // no zero
//nnmy4a = &i4; // no int*
//nnmy4a = my4; // no MyPtr<int>
nnmy4b = WrapNotNull(&i4); // WrapNotNull(int*)
nnmy4c = WrapNotNull(my4); // WrapNotNull(MyPtr<int>)
nnmy4d = nni4; // NotNull<int*>
nnmy4e = nnmy4; // NotNull<MyPtr<int>>
CHECK(*nnmy4b == 4);
CHECK(*nnmy4c == 4);
CHECK(*nnmy4d == 4);
CHECK(*nnmy4e == 4);
NotNull<MyPtr<int>> nnmy5 = WrapNotNull(&i5);
CHECK(*nnmy5 == 5);
CHECK(nnmy5 == &i5); // NotNull<MyPtr<int>> == int*
CHECK(nnmy5 == my5); // NotNull<MyPtr<int>> == MyPtr<int>
CHECK(nnmy5 == nni5); // NotNull<MyPtr<int>> == NotNull<int*>
CHECK(nnmy5 == nnmy5); // NotNull<MyPtr<int>> == NotNull<MyPtr<int>>
CHECK(&i5 == nnmy5); // int* == NotNull<MyPtr<int>>
CHECK(my5 == nnmy5); // MyPtr<int> == NotNull<MyPtr<int>>
CHECK(nni5 == nnmy5); // NotNull<int*> == NotNull<MyPtr<int>>
CHECK(nnmy5 == nnmy5); // NotNull<MyPtr<int>> == NotNull<MyPtr<int>>
//CHECK(nni5 == nullptr); // no comparisons with nullptr
//CHECK(nullptr == nni5); // no comparisons with nullptr
//CHECK(nni5 == 0); // no comparisons with zero
//CHECK(0 == nni5); // no comparisons with zero
CHECK(*nnmy5 == 5);
CHECK(nnmy5 != &i4); // NotNull<MyPtr<int>> != int*
CHECK(nnmy5 != my4); // NotNull<MyPtr<int>> != MyPtr<int>
CHECK(nnmy5 != nni4); // NotNull<MyPtr<int>> != NotNull<int*>
CHECK(nnmy5 != nnmy4); // NotNull<MyPtr<int>> != NotNull<MyPtr<int>>
CHECK(&i4 != nnmy5); // int* != NotNull<MyPtr<int>>
CHECK(my4 != nnmy5); // MyPtr<int> != NotNull<MyPtr<int>>
CHECK(nni4 != nnmy5); // NotNull<int*> != NotNull<MyPtr<int>>
CHECK(nnmy4 != nnmy5); // NotNull<MyPtr<int>> != NotNull<MyPtr<int>>
//CHECK(nni4 != nullptr); // no comparisons with nullptr
//CHECK(nullptr != nni4); // no comparisons with nullptr
//CHECK(nni4 != 0); // no comparisons with zero
//CHECK(0 != nni4); // no comparisons with zero
// int* parameter
f_i(&i4); // identity int* --> int*
f_i(my4); // implicit MyPtr<int> --> int*
f_i(my4.get()); // explicit MyPtr<int> --> int*
f_i(nni4); // implicit NotNull<int*> --> int*
f_i(nni4.get()); // explicit NotNull<int*> --> int*
//f_i(nnmy4); // no implicit NotNull<MyPtr<int>> --> int*
f_i(nnmy4.get()); // explicit NotNull<MyPtr<int>> --> int*
f_i(nnmy4.get().get());// doubly-explicit NotNull<MyPtr<int>> --> int*
// MyPtr<int> parameter
f_my(&i4); // implicit int* --> MyPtr<int>
f_my(my4); // identity MyPtr<int> --> MyPtr<int>
f_my(my4.get()); // explicit MyPtr<int> --> MyPtr<int>
//f_my(nni4); // no implicit NotNull<int*> --> MyPtr<int>
f_my(nni4.get()); // explicit NotNull<int*> --> MyPtr<int>
f_my(nnmy4); // implicit NotNull<MyPtr<int>> --> MyPtr<int>
f_my(nnmy4.get()); // explicit NotNull<MyPtr<int>> --> MyPtr<int>
f_my(nnmy4.get().get());// doubly-explicit NotNull<MyPtr<int>> --> MyPtr<int>
// NotNull<int*> parameter
f_nni(nni4); // identity NotNull<int*> --> NotNull<int*>
f_nni(nnmy4); // implicit NotNull<MyPtr<int>> --> NotNull<int*>
// NotNull<MyPtr<int>> parameter
f_nnmy(nni4); // implicit NotNull<int*> --> NotNull<MyPtr<int>>
f_nnmy(nnmy4); // identity NotNull<MyPtr<int>> --> NotNull<MyPtr<int>>
//CHECK(nni4); // disallow boolean conversion / unary expression usage
//CHECK(nnmy4); // ditto
// '->' dereferencing.
Blah blah;
MyPtr<Blah> myblah = &blah;
NotNull<Blah*> nnblah = WrapNotNull(&blah);
NotNull<MyPtr<Blah>> nnmyblah = WrapNotNull(myblah);
(&blah)->blah(); // int*
myblah->blah(); // MyPtr<int>
nnblah->blah(); // NotNull<int*>
nnmyblah->blah(); // NotNull<MyPtr<int>>
(&blah)->mX = 1;
CHECK((&blah)->mX == 1);
myblah->mX = 2;
CHECK(myblah->mX == 2);
nnblah->mX = 3;
CHECK(nnblah->mX == 3);
nnmyblah->mX = 4;
CHECK(nnmyblah->mX == 4);
// '*' dereferencing (lvalues and rvalues)
*(&i4) = 7; // int*
CHECK(*(&i4) == 7);
*my4 = 6; // MyPtr<int>
CHECK(*my4 == 6);
*nni4 = 5; // NotNull<int*>
CHECK(*nni4 == 5);
*nnmy4 = 4; // NotNull<MyPtr<int>>
CHECK(*nnmy4 == 4);
// Non-null arrays.
static const int N = 20;
int a[N];
NotNull<int*> nna = WrapNotNull(a);
for (int i = 0; i < N; i++) {
nna[i] = i;
}
for (int i = 0; i < N; i++) {
nna[i] *= 2;
}
for (int i = 0; i < N; i++) {
CHECK(nna[i] == i * 2);
}
}
void f_ref(NotNull<MyRefType*> aR)
{
NotNull<RefPtr<MyRefType>> r = aR;
}
void
TestNotNullWithRefPtr()
{
// This MyRefType object will have a maximum refcount of 5.
NotNull<RefPtr<MyRefType>> r1 = WrapNotNull(new MyRefType(5));
// At this point the refcount is 1.
NotNull<RefPtr<MyRefType>> r2 = r1;
// At this point the refcount is 2.
NotNull<MyRefType*> r3 = r2;
(void)r3;
// At this point the refcount is still 2.
RefPtr<MyRefType> r4 = r2;
// At this point the refcount is 3.
RefPtr<MyRefType> r5 = r3.get();
// At this point the refcount is 4.
// No change to the refcount occurs because of the argument passing. Within
// f_ref() the refcount temporarily hits 5, due to the local RefPtr.
f_ref(r2);
// At this point the refcount is 4.
// At function's end all RefPtrs are destroyed and the refcount drops to 0
// and the MyRefType is destroyed.
}
int
main()
{
TestNotNullWithMyPtr();
TestNotNullWithRefPtr();
return 0;
}

Просмотреть файл

@ -29,6 +29,7 @@ CppUnitTests([
'TestMacroForEach',
'TestMathAlgorithms',
'TestMaybe',
'TestNotNull',
'TestPair',
'TestRefPtr',
'TestRollingMean',