diff options
author | Philip Herron <philip.herron@embecosm.com> | 2021-04-20 15:19:33 +0100 |
---|---|---|
committer | Philip Herron <philip.herron@embecosm.com> | 2021-04-20 18:56:53 +0100 |
commit | 393b783549e1247dfed5b86f098fb10d1eaf6659 (patch) | |
tree | 628921f4b47bc83ab588fa3f7109ddfd7702bfd6 /gcc/rust/backend/rust-compile-expr.h | |
parent | ee5afc03f94e8a76c1b1b9306849cd932d5d9090 (diff) | |
download | gcc-393b783549e1247dfed5b86f098fb10d1eaf6659.zip gcc-393b783549e1247dfed5b86f098fb10d1eaf6659.tar.gz gcc-393b783549e1247dfed5b86f098fb10d1eaf6659.tar.bz2 |
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
Diffstat (limited to 'gcc/rust/backend/rust-compile-expr.h')
-rw-r--r-- | gcc/rust/backend/rust-compile-expr.h | 18 |
1 files changed, 15 insertions, 3 deletions
diff --git a/gcc/rust/backend/rust-compile-expr.h b/gcc/rust/backend/rust-compile-expr.h index f98ebc6..59ae815 100644 --- a/gcc/rust/backend/rust-compile-expr.h +++ b/gcc/rust/backend/rust-compile-expr.h @@ -275,7 +275,12 @@ public: return; } - Btype *array_type = TyTyResolveCompile::compile (ctx, tyty); + rust_assert (tyty->get_kind () == TyTy::TypeKind::ARRAY); + TyTy::ArrayType *array_tyty = static_cast<TyTy::ArrayType *> (tyty); + capacity_expr = array_tyty->get_capacity (); + + Btype *array_type = TyTyResolveCompile::compile (ctx, array_tyty); + rust_assert (array_type != nullptr); expr.get_internal_elements ()->accept_vis (*this); std::vector<unsigned long> indexes; @@ -302,7 +307,11 @@ public: Bexpression *translated_expr = CompileExpr::Compile (elems.get_elem_to_copy (), ctx); - for (size_t i = 0; i < elems.get_num_elements (); ++i) + size_t capacity; + bool ok = ctx->get_backend ()->const_size_cast (capacity_expr, &capacity); + rust_assert (ok); + + for (size_t i = 0; i < capacity; ++i) constructor.push_back (translated_expr); } @@ -786,9 +795,12 @@ public: } private: - CompileExpr (Context *ctx) : HIRCompileBase (ctx), translated (nullptr) {} + CompileExpr (Context *ctx) + : HIRCompileBase (ctx), translated (nullptr), capacity_expr (nullptr) + {} Bexpression *translated; + Bexpression *capacity_expr; std::vector<Bexpression *> constructor; }; |