Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Docs for the check and scope guard macros #1734

Merged
merged 3 commits into from
Apr 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions Doxyfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
PROJECT_NAME = "Particle Firmware"
PROJECT_NUMBER = "0.8.0-rc.11"
PROJECT_NUMBER = "1.0.1"

OUTPUT_DIRECTORY = docs/doxygen

Expand All @@ -12,12 +12,16 @@ EXCLUDE_PATTERNS = \
*/hal/src/photon/wiced/* \
*/hal/src/electron/rtos/* \
*/platform/MCU/STM32F1xx/CMSIS/* \
*/platform/MCU/STM32F2xx/CMSIS/*
*/platform/MCU/STM32F2xx/CMSIS/* \
*/user/tests/* \
*/communication/tests/* \
*/test/*

OPTIMIZE_OUTPUT_FOR_C = YES
HIDE_UNDOC_CLASSES = YES
HIDE_UNDOC_MEMBERS = YES
SHOW_INCLUDE_FILES = NO
MAX_INITIALIZER_LINES = 4
INLINE_INFO = NO
SOURCE_BROWSER = YES
GENERATE_LATEX = NO
139 changes: 129 additions & 10 deletions services/inc/check.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,108 @@
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/

/**
* @file check.h
*
* @section check_macros Check macros
*
* This header file defines a set of macros that simplify error handling in the Device OS code.
*
* Device OS doesn't use C++ exceptions, and, by convention, its internal and public API functions
* return a negative value in case of an error. All error codes are defined in the system_error.h
* file.
*
* Consider the following example:
* ```
* int foo() {
* void* buffer = malloc(1024);
* if (!buffer) {
* return SYSTEM_ERROR_NO_MEMORY; // -260
* }
* ...
* free(buffer);
* return 0; // No error
* }
* ```
* When invoking such a function, the calling function should properly handle all possible errors.
* In the most typical scenario, it simply forwards the error to its own calling function:
* ```
* int fooBarBaz() {
* int result = foo();
* if (result == 0) {
* result = bar();
* if (result == 0) {
* result = baz();
* }
* }
* return result;
* }
* ```
* When many functions are involved, writing the code like in the above example becomes tedious.
* Given that all the functions follow the convention, the code can be rewritten as follows using
* the `CHECK()` macro:
* ```
* int fooBarBaz() {
* // This macro makes fooBarBaz() return SYSTEM_ERROR_NO_MEMORY if foo() fails to allocate its
* // internal buffer
* CHECK(foo());
* CHECK(bar());
* CHECK(baz());
* return 0;
* }
* ```
* The `CHECK()` macro expands to a code that evaluates the expression passed to the macro. If the
* expression yields a negative value then the function that invokes the macro (`fooBarBaz()` in the
* above example) will return that value and thus finish its execution with an error. Non-negative
* values get passed back to the calling code as if the checked expression was evaluated directly:
* ```
* int parseStream(Stream* stream) {
* char buffer[128];
* size_t size = CHECK(stream->read(buffer, sizeof(buffer));
* LOG(TRACE, "Read %u bytes", (unsigned)size);
* ...
* return 0;
* }
* ```
* In the above example, it is safe to assume that the value returned by `Stream::read()`, which is
* wrapped into the `CHECK()` macro, is greater than or equal to 0, since, otherwise, `parseStream()`
* would have returned before the initialization of the `size` variable. Internally, this is
* implemented using GCC's statement expressions:
*
* https://gcc.gnu.org/onlinedocs/gcc-3.2.3/gcc/Statement-Exprs.html
*
* It is important to note that a Device OS function should never return a negative result code
* from a third party library as is, otherwise, it will be impossible to decode that error in the
* dependent code. The following code is incorrect:
* ```
* int receiveMessage(int socket) {
* char buffer[128];
* // It is an error to use non-Device OS functions with CHECK()
* size_t size = CHECK(lwip_read(socket, buffer, sizeof(buffer)));
* LOG(TRACE, "Read %u bytes", (unsigned)size);
* ...
* return 0;
* }
* ```
* This header file also defines the `CHECK_TRUE()` and `CHECK_FALSE()` macros, which can be used
zfields marked this conversation as resolved.
Show resolved Hide resolved
* with predicate expressions:
* ```
* int foo() {
* std::unique_ptr<char[]> buffer(new(std::nothrow) char[1024]);
* CHECK_TRUE(buffer, SYSTEM_ERROR_NO_MEMORY);
* ...
* return 0;
* }
*
* int bar(int value) {
* static Vector<int> values;
* CHECK_FALSE(values.contains(value), SYSTEM_ERROR_ALREADY_EXISTS);
* ...
* return 0;
* }
* ```
*/

#pragma once

#include "system_error.h"
Expand All @@ -31,16 +133,11 @@
#define _LOG_CHECKED_ERROR(_expr, _ret)
#endif

#define CHECK_RETURN(_expr, _val) \
({ \
const auto _ret = _expr; \
if (_ret < 0) { \
_LOG_CHECKED_ERROR(_expr, _ret); \
return _val; \
} \
_ret; \
})

/**
* Check the result of an expression.
*
* @see @ref check_macros
*/
#define CHECK(_expr) \
({ \
const auto _ret = _expr; \
Expand All @@ -51,6 +148,11 @@
_ret; \
})

/**
* Check the result of a predicate expression.
*
* @see @ref check_macros
*/
#define CHECK_TRUE(_expr, _ret) \
do { \
const bool _ok = (bool)(_expr); \
Expand All @@ -60,9 +162,26 @@
} \
} while (false)

/**
* Check the result of a predicate expression.
*
* @see @ref check_macros
*/
#define CHECK_FALSE(_expr, _ret) \
CHECK_TRUE(!(_expr), _ret)

// Deprecated
#define CHECK_RETURN(_expr, _val) \
({ \
const auto _ret = _expr; \
if (_ret < 0) { \
_LOG_CHECKED_ERROR(_expr, _ret); \
return _val; \
} \
_ret; \
})

// Deprecated
#define CHECK_TRUE_RETURN(_expr, _val) \
({ \
const auto _ret = _expr; \
Expand Down
108 changes: 108 additions & 0 deletions services/inc/scope_guard.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,124 @@
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/

/**
* @file scope_guard.h
*
* @section scope_guards Scope guards
*
* This header file defines a set of macros that simplify RAII-style resource management in the
* Device OS code.
*
* Consider the following example:
* ```
* int parseStream(Stream* stream) {
* // Allocate a buffer
* const size_t bufferSize = 1024;
* char* buffer = (char*)malloc(bufferSize);
* if (!buffer) {
* return SYSTEM_ERROR_NO_MEMORY;
* }
* // Read the first chunk of the data
* int result = stream->read(buffer, bufferSize);
* if (result < 0) {
* free(buffer);
* return result;
* }
* ...
* // Read the second chunk of the data
* result = stream->read(buffer, bufferSize);
* if (result < 0) {
* free(buffer);
* return result;
* }
* ...
* // Free the buffer
* free(buffer);
* return 0;
* }
* ```
* Using the `SCOPE_GUARD()` macro together with the @ref check_macros "check macros", the above
* code can be rewritten in a less error-prone way:
* ```
* int parseStream(Stream* stream) {
* // Allocate a buffer
* const size_t bufferSize = 1024;
* char* buffer = (char*)malloc(bufferSize);
* CHECK_TRUE(buffer, SYSTEM_ERROR_NO_MEMORY);
* // Declare a scope guard
* SCOPE_GUARD({
* free(buffer);
* });
* // Read the first chunk of the data
* CHECK(stream->read(buffer, bufferSize));
* ...
* // Read the second chunk of the data
* CHECK(stream->read(buffer, bufferSize));
* ...
* return 0;
* }
* ```
* Internally, `SCOPE_GUARD()` declares an object that schedules an arbitrary user-provided code
* for execution at the end of the enclosing scope of the object. In the above example, the buffer
* allocated via `malloc()` will be automatically freed by the scope guard when the function returns
* either successfully or with an error.
*
zfields marked this conversation as resolved.
Show resolved Hide resolved
* It is possible to assign a name to a scope guard object by using the `NAMED_SCOPE_GUARD()` macro.
* Named scope guards are useful when the ownership over a managed resource needs to be transferred
* to another function:
* ```
* int openResourceFile(lfs_t *lfs, lfs_file_t* file, const char* name) {
* // Open the resource file
* auto result = lfs_file_open(lfs, file, name, LFS_O_RDONLY);
* if (result < 0) {
* LOG(ERROR, "Unable to open resource file");
* return SYSTEM_ERROR_FILE;
* }
* // Declare a scope guard
* NAMED_SCOPE_GUARD(guard, {
* lfs_file_close(lfs, file);
* });
* // Check the header signature
* const headerSize = 3;
* char header[headerSize + 1] = {}; // Reserve one character for the term. null
* result = lfs_file_read(lfs, file, header, headerSize);
* if (result < 0) {
* LOG(ERROR, "Unable to read resource file");
* return SYSTEM_ERROR_IO;
* }
* if (result != headerSize || strcmp(header, "RES") != 0) {
* LOG(ERROR, "Invalid header signature");
* return SYSTEM_ERROR_BAD_DATA;
* }
* ...
* // Dismiss the scope guard and let the calling code read the remaining sections of the file
* // and manage the lifetime of the file descriptor
* guard.dismiss();
* return 0;
* }
* ```
*/

#pragma once

#include "preprocessor.h"

#include <utility>

/**
* Declare a scope guard.
*
* @see @ref scope_guards
*/
// TODO: Add a separate class for unnamed scope guards
#define SCOPE_GUARD(_func) \
NAMED_SCOPE_GUARD(PP_CAT(_scope_guard_, __COUNTER__), _func)

/**
* Declare a named scope guard.
*
* @see @ref scope_guards
*/
#define NAMED_SCOPE_GUARD(_name, _func) \
auto _name = ::particle::makeNamedScopeGuard([&] _func)

Expand Down