From 393b783549e1247dfed5b86f098fb10d1eaf6659 Mon Sep 17 00:00:00 2001 From: Philip Herron Date: Tue, 20 Apr 2021 15:19:33 +0100 Subject: Reuse fold-const.c from GCC to enforce const array capacities Rust allows for constant eval for cases like array capacity, the initial version of this code forced the programmer to only use literals which was not correct but got the type system off the ground. This now takes advantage of the GCC backend object to offer 3 helpers. 1. check for constant Bexpression* are equal 2. extract a size_t constant value from the Bexpression* 3. to string the Bexpression constant We can get away with the extraction of the value here because we know its going to be a usize for array capacity but some thought is needed if these methods are to be reused in other cases. There is a new ConstFold namespace which should be extensible for const functions later on and const generics. Fixes: #296 --- gcc/rust/backend/rust-compile-context.h | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) (limited to 'gcc/rust/backend/rust-compile-context.h') diff --git a/gcc/rust/backend/rust-compile-context.h b/gcc/rust/backend/rust-compile-context.h index 8866575..226cec6 100644 --- a/gcc/rust/backend/rust-compile-context.h +++ b/gcc/rust/backend/rust-compile-context.h @@ -27,6 +27,7 @@ #include "rust-compile-tyty.h" #include "rust-ast-full.h" #include "rust-hir-full.h" +#include "rust-hir-const-fold-ctx.h" namespace Rust { namespace Compile { @@ -43,7 +44,8 @@ public: Context (::Backend *backend) : backend (backend), resolver (Resolver::Resolver::get ()), tyctx (Resolver::TypeCheckContext::get ()), - mappings (Analysis::Mappings::get ()) + mappings (Analysis::Mappings::get ()), + const_ctx (ConstFold::Context::get ()) { // insert the builtins auto builtins = resolver->get_builtin_types (); @@ -104,6 +106,7 @@ public: Resolver::Resolver *get_resolver () { return resolver; } Resolver::TypeCheckContext *get_tyctx () { return tyctx; } Analysis::Mappings *get_mappings () { return mappings; } + ConstFold::Context *get_const_ctx () { return const_ctx; } void push_block (Bblock *scope) { @@ -260,6 +263,7 @@ private: Resolver::Resolver *resolver; Resolver::TypeCheckContext *tyctx; Analysis::Mappings *mappings; + ConstFold::Context *const_ctx; // state std::vector fn_stack; @@ -420,16 +424,10 @@ public: void visit (TyTy::ArrayType &type) override { - mpz_t ival; - mpz_init_set_ui (ival, type.get_capacity ()); - - Btype *capacity_type = ctx->get_backend ()->integer_type (true, 32); - Bexpression *length - = ctx->get_backend ()->integer_constant_expression (capacity_type, ival); - Btype *element_type = TyTyResolveCompile::compile (ctx, type.get_element_type ()); - translated = ctx->get_backend ()->array_type (element_type, length); + translated + = ctx->get_backend ()->array_type (element_type, type.get_capacity ()); } void visit (TyTy::BoolType &type) override -- cgit v1.1