Skip to content

Commit

Permalink
Merge pull request #58 from AjayBrahmakshatriya/master
Browse files Browse the repository at this point in the history
Added support for defer init for dyn_var
  • Loading branch information
AjayBrahmakshatriya authored Dec 8, 2023
2 parents 39e1807 + 5dd99a4 commit 5d2ffd2
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 0 deletions.
20 changes: 20 additions & 0 deletions include/builder/dyn_var.h
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,13 @@ struct with_name {
with_name(const std::string &n, bool wd = false) : name(n), with_decl(wd) {}
};

// constructor helper to defer the initialization of dyn_var
// This allows declaring dyn_var outside the context, but initialize
// them later
struct defer_init {
// No members
};

template <typename T>
class dyn_var_impl : public var {
public:
Expand Down Expand Up @@ -226,6 +233,19 @@ class dyn_var_impl : public var {
block_var->preferred_name = "";
var_name = v.name;
}

dyn_var_impl(const defer_init&) {
// Do nothing here
}
// The function to actually initialize a dyn_var, if it
// has been deferred. It is OKAY to call this even if defer_init
// is not used, but is not adviced. This can definitely be called multiple
// times and will produce the same dyn_var based on the static tag at the
// time of this call
// Currently we don't support init val, but can be added if needed
void deferred_init(void) {
create_dyn_var(false);
}
dyn_var_impl(const dyn_var_sentinel_type &a, std::string name = "") {
create_dyn_var(true);
if (name != "") {
Expand Down
10 changes: 10 additions & 0 deletions samples/outputs.var_names/sample53
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
void foo (void) {
int obj_0;
int x_1 = 0;
if (x_1) {
obj_0 = 1;
} else {
obj_0 = 2;
}
}

10 changes: 10 additions & 0 deletions samples/outputs/sample53
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
void foo (void) {
int var0;
int var1 = 0;
if (var1) {
var0 = 1;
} else {
var0 = 2;
}
}

36 changes: 36 additions & 0 deletions samples/sample53.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Include the headers
#include "blocks/c_code_generator.h"
#include "builder/dyn_var.h"
#include "builder/lib/utils.h"
#include "builder/static_var.h"
#include <iostream>

// Include the BuildIt types
using builder::dyn_var;
using builder::static_var;


struct external_object_t {
dyn_var<int> member = builder::defer_init();
};

static void foo(external_object_t &obj) {
// Init not
obj.member.deferred_init();

dyn_var<int> x = 0;
if (x) {
obj.member = 1;
} else {
obj.member = 2;
}
}

int main(int argc, char *argv[]) {

external_object_t obj;

builder::builder_context context;
block::c_code_generator::generate_code(context.extract_function_ast(foo, "foo", obj), std::cout, 0);
return 0;
}

0 comments on commit 5d2ffd2

Please sign in to comment.