From patchwork Tue Dec 6 10:13:56 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Arthur Cohen X-Patchwork-Id: 61515 Return-Path: X-Original-To: patchwork@sourceware.org Delivered-To: patchwork@sourceware.org Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id B887C3837F76 for ; Tue, 6 Dec 2022 10:19:35 +0000 (GMT) X-Original-To: gcc-patches@gcc.gnu.org Delivered-To: gcc-patches@gcc.gnu.org Received: from mail-wr1-x434.google.com (mail-wr1-x434.google.com [IPv6:2a00:1450:4864:20::434]) by sourceware.org (Postfix) with ESMTPS id 75A49395B421 for ; Tue, 6 Dec 2022 10:12:24 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.1 sourceware.org 75A49395B421 Authentication-Results: sourceware.org; dmarc=none (p=none dis=none) header.from=embecosm.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=embecosm.com Received: by mail-wr1-x434.google.com with SMTP id h12so22701094wrv.10 for ; Tue, 06 Dec 2022 02:12:24 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=embecosm.com; s=google; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to; bh=ps5pWT/Q9AyQXrvIoVSalBZnBTBshZesqQfr/9sahQc=; b=Qd5MxvrRcQ3KWf3hcLb9wvTBQ1FAqcjYSY0HYITaFB8phJjiDI075+4KxE06oAlWxO 2RguzW7t1J5avBytv0tFOEThx17kw9Z/EIXfLmoMgVl7SraUsNyc3xxHveCfghENNdqs 3GrFwB9jcXv/b/yUBU46QuUzwqF3E8XToz6/YwSM8jogRAmyvBXgkfh/gfECHFgsa5yp jdKVIBK7gSzpCIfO06qfEA/JZROknpI95wyI8y/cAb3bZbanaD0w4Y1FHMcVfL1Ngd1T YBAC5MAPVOdDX+aNYeNj4pRzwvOOlCUEzkKDzT2mzAtEfCfXM42064inbl259Zqd7UgO pP7g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=ps5pWT/Q9AyQXrvIoVSalBZnBTBshZesqQfr/9sahQc=; b=e73OJI16Seajk/DCudsmpN3V1A6Lg5931DYiI8eDm+JiZlXHJpETYyNaCoyseuC9ob p8zOPDklv92ZcNkkCaeipL94izdofLxciBkyFKv6k+/2mfUJerlnB2NBZnrEFq8ZYfWW fDYDqQYuYZrfL0zWaA2ZVB9KKOdjYaPv0xRmjk/LsA4QmV+aWuXgCUyIbN4zmCMVAzed WMJOG5ApX4UtM0dpkQ92hMQtLF21ZRdvyA5U7DyBxSVDUFvTRf3aIbpijBLc+/n+dX45 ohK+WfHUFsGhh/Vdu/VxGF2+YP46soZc7WJg2FRPBrZBqxFS8Q3dpR1e2jTj/H+1FGR7 vqeA== X-Gm-Message-State: ANoB5pkbZBgOqovjvk2gQ7+6NlBjV1Web3Amzm5IuImHgkSrnCxfJIx5 os8SLlLzyHM98RPb+Xm7LtULP6CDvKw27ZxxGw== X-Google-Smtp-Source: AA0mqf4myJ/6BC9qsSRcg08TEKG4qm2ySHtCr49nQUn7OAlEirmZhWbUuHtYg/aw8FYfYO0Sssp52Q== X-Received: by 2002:a5d:53c4:0:b0:242:1f22:df3b with SMTP id a4-20020a5d53c4000000b002421f22df3bmr20544458wrw.679.1670321543699; Tue, 06 Dec 2022 02:12:23 -0800 (PST) Received: from platypus.lan ([2001:861:5e4c:3bb0:6424:328a:1734:3249]) by smtp.googlemail.com with ESMTPSA id r10-20020a05600c458a00b003cfd4a50d5asm27052699wmo.34.2022.12.06.02.12.23 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 06 Dec 2022 02:12:23 -0800 (PST) From: arthur.cohen@embecosm.com To: gcc-patches@gcc.gnu.org Cc: gcc-rust@gcc.gnu.org, Arthur Cohen Subject: [PATCH Rust front-end v4 24/46] gccrs: Add implementation of Optional Date: Tue, 6 Dec 2022 11:13:56 +0100 Message-Id: <20221206101417.778807-25-arthur.cohen@embecosm.com> X-Mailer: git-send-email 2.38.1 In-Reply-To: <20221206101417.778807-1-arthur.cohen@embecosm.com> References: <20221206101417.778807-1-arthur.cohen@embecosm.com> MIME-Version: 1.0 X-Spam-Status: No, score=-19.8 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, GIT_PATCH_0, KAM_SHORT, RCVD_IN_DNSWL_NONE, SPF_HELO_NONE, SPF_PASS, TXREP autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org X-BeenThere: gcc-patches@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Gcc-patches mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Reply-To: arthur.cohen@embecosm.com Errors-To: gcc-patches-bounces+patchwork=sourceware.org@gcc.gnu.org Sender: "Gcc-patches" From: Arthur Cohen This adds an Optional class to improve error handling. --- gcc/rust/util/rust-optional-test.cc | 110 +++++++++++ gcc/rust/util/rust-optional.h | 278 ++++++++++++++++++++++++++++ 2 files changed, 388 insertions(+) create mode 100644 gcc/rust/util/rust-optional-test.cc create mode 100644 gcc/rust/util/rust-optional.h diff --git a/gcc/rust/util/rust-optional-test.cc b/gcc/rust/util/rust-optional-test.cc new file mode 100644 index 00000000000..43fa175fa40 --- /dev/null +++ b/gcc/rust/util/rust-optional-test.cc @@ -0,0 +1,110 @@ +// Copyright (C) 2020-2022 Free Software Foundation, Inc. + +// This file is part of GCC. + +// GCC is free software; you can redistribute it and/or modify it under +// the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 3, or (at your option) any later +// version. + +// GCC is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// for more details. + +// You should have received a copy of the GNU General Public License +// along with GCC; see the file COPYING3. If not see +// . + +#include "rust-system.h" +#include "rust-optional.h" +#include "selftest.h" + +#if CHECKING_P + +static void +rust_optional_create () +{ + auto opt = Rust::Optional::some (15); + + ASSERT_TRUE (opt.is_some ()); + ASSERT_EQ (opt.get (), 15); + + Rust::Optional const_opt = Rust::Optional::some (15); + const int &value = const_opt.get (); + + ASSERT_EQ (value, 15); +} + +static void +rust_optional_operators () +{ + auto opt = Rust::Optional::some (15); + + // as bool + ASSERT_TRUE (opt); + + // deref + ASSERT_EQ (*opt, 15); + + class Methodable + { + public: + int method () { return 15; } + }; + + auto m_opt = Rust::Optional::some (Methodable ()); + ASSERT_EQ (m_opt->method (), 15); +} + +static void +rust_optional_take () +{ + auto opt = Rust::Optional::some (15); + auto value = opt.take (); + + ASSERT_EQ (value, 15); + ASSERT_TRUE (opt.is_none ()); +} + +static void +rust_optional_map () +{ + auto opt = Rust::Optional::some (15); + auto twice = opt.map ([] (int value) { return value * 2; }); + + ASSERT_FALSE (opt); + ASSERT_TRUE (twice); + ASSERT_EQ (*twice, 30); +} + +static void +rust_optional_reference () +{ + auto value = std::vector (); + value.emplace_back ("rust"); + value.emplace_back ("+"); + value.emplace_back ("gcc"); + value.emplace_back ("="); + value.emplace_back ("<3"); + + auto opt = Rust::Optional &>::some (value); + + ASSERT_EQ (opt->at (0), "rust"); + ASSERT_EQ (opt->at (2), "gcc"); +} + +#endif /* #if CHECKING_P */ + +void +rust_optional_test () +{ +#if CHECKING_P + rust_optional_create (); + rust_optional_operators (); + rust_optional_take (); + rust_optional_map (); + rust_optional_reference (); + +#endif /* #if CHECKING_P */ +} diff --git a/gcc/rust/util/rust-optional.h b/gcc/rust/util/rust-optional.h new file mode 100644 index 00000000000..56465400250 --- /dev/null +++ b/gcc/rust/util/rust-optional.h @@ -0,0 +1,278 @@ +// Copyright (C) 2020-2022 Free Software Foundation, Inc. + +// This file is part of GCC. + +// GCC is free software; you can redistribute it and/or modify it under +// the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 3, or (at your option) any later +// version. + +// GCC is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// for more details. + +// You should have received a copy of the GNU General Public License +// along with GCC; see the file COPYING3. If not see +// . + +#ifndef RUST_OPTIONAL_H +#define RUST_OPTIONAL_H + +#include "config.h" +#include "rust-system.h" + +#include "selftest.h" + +namespace Rust { + +/** + * Tagged union to try and simulate a sum type. This is safer and more ergonomic + * than one of the two alternatives we're currently using in the compiler: + * + * 1. Storing a raw pointer, which can be `nullptr` or valid + * + * This is wildly unsafe, and usable in conjunction with local references, stack + * variables, or pointers managed elsewhere, which can cause crashes, hard to + * debug issues or undefined behavior. Likewise, if you do not check for the + * pointer's validity, this will cause a crash. + * + * 2. Storing an extra boolean alongside the object + * + * This causes implementors to use a "dummy object": Either an empty version or + * an error version. But what happens if what you really wanted to store was + * the empty or error version? You can also easily incorporate logic bugs if you + * forget to check for the associated boolean. + * + * The `Optional` type has the same "ergonomic" cost: You need to check + * whether your option is valid or not. However, the main advantage is that it + * is more restrictive: You can only acess the member it contains "safely". + * It is similar to storing a value + an associated boolean, but has the + * advantage of making up only one member in your class. + * You also benefit from some helper methods such as `map()`. + * + * You also get helper functions and operator overloading to "seamlessly" + * replace raw pointer alternatives. + * + * ```c++ + * MyType *raw_pointer = something_that_can_fail(); + * if (raw_pointer) + * raw_pointer->method(); + * + * // or + * + * Optional opt = something_that_can_fail2(); + * if (opt) + * opt->method(); + * + * // equivalent to + * + * if (opt.is_some()) + * opt.get().method(); + * ``` + */ +template class Optional +{ +private: + struct Empty + { + }; + + enum Kind + { + Some, + None + } kind; + + union Content + { + Empty empty; + T value; + + Content () = default; + } content; + + Optional (Kind kind, Content content) : kind (kind), content (content) {} + +public: + Optional (const Optional &other) = default; + Optional &operator= (const Optional &other) = default; + Optional (Optional &&other) = default; + + static Optional some (T value) + { + Content content; + content.value = value; + + return Optional (Kind::Some, content); + } + + static Optional none () + { + Content content; + content.empty = Empty (); + + return Optional (Kind::None, content); + } + + bool is_some () const { return kind == Kind::Some; } + bool is_none () const { return !is_some (); } + + /** + * Enable boolean-like comparisons. + */ + operator bool () { return is_some (); } + + /** + * Enables dereferencing to access the contained value + */ + T &operator* () { return get (); } + const T &operator* () const { return get (); } + T *operator-> () { return &get (); } + const T *operator-> () const { return &get (); } + + const T &get () const + { + rust_assert (is_some ()); + + return content.value; + } + + T &get () + { + rust_assert (is_some ()); + + return content.value; + } + + T take () + { + rust_assert (is_some ()); + + auto to_return = std::move (content.value); + + content.empty = Empty (); + kind = Kind::None; + + return to_return; + } + + template Optional map (std::function functor) + { + if (is_none ()) + return Optional::none (); + + auto value = functor (take ()); + + return Optional::some (value); + } +}; + +template class Optional +{ +private: + struct Empty + { + }; + + enum Kind + { + Some, + None + } kind; + + union Content + { + Empty empty; + T *value; + + Content () = default; + } content; + + Optional (Kind kind, Content content) : kind (kind), content (content) {} + +public: + Optional (const Optional &other) = default; + Optional (Optional &&other) = default; + + static Optional some (T &value) + { + Content content; + content.value = &value; + + return Optional (Kind::Some, content); + } + + static Optional none () + { + Content content; + content.empty = Empty (); + + return Optional (Kind::None, content); + } + + bool is_some () const { return kind == Kind::Some; } + bool is_none () const { return !is_some (); } + + // FIXME: Can we factor this in a single class? + + /** + * Enable boolean-like comparisons. + */ + operator bool () { return is_some (); } + + /** + * Enables dereferencing to access the contained value + */ + T &operator* () { return get (); } + const T &operator* () const { return get (); } + T *operator-> () { return &get (); } + const T *operator-> () const { return &get (); } + + const T &get () const + { + rust_assert (is_some ()); + + return *content.value; + } + + T &get () + { + rust_assert (is_some ()); + + return *content.value; + } + + T &take () + { + rust_assert (is_some ()); + + auto to_return = std::move (content.value); + + content.empty = Empty (); + kind = Kind::None; + + return *to_return; + } + + template Optional map (std::function functor) + { + if (is_none ()) + return Optional::none (); + + auto value = functor (take ()); + + return Optional::some (value); + } +}; + +} // namespace Rust + +#ifdef CHECKING_P + +void +rust_optional_test (); + +#endif // !CHECKING_P + +#endif // !RUST_OPTIONAL_H