Variáveis locais e globais: crie local, crie global e apague a variável
- Blocos novos em Variáveis: "crie variável local [] com valor ()", "crie variável global [] com valor ()" e "apague a variável []". - O armazenamento das variáveis foi para o core (tinyblocks/tb_vars.h), com escopos: uma cópia só, mesmo com a library carregada como .so. - Editor: cada script tem as suas locais (somem quando ele termina) e cada chamada de "Meus Blocos" também (vê as globais, não as de quem chamou). mude/adicione alteram onde a variável existir; se não existir, criam global. - A API tb_variables_* (monitores, salvar projeto) olha as globais. - make test-vars: escopos e os blocos novos. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d9449a568e
commit
0c73e81c1a
8 files changed
+428
-79
No files matched your search
@@ -68,6 +68,7 @@ SRCS := src/tinyblocks.c \
|
|||||||
src/tb_renderable_block.c \
|
src/tb_renderable_block.c \
|
||||||
src/tb_stage.c \
|
src/tb_stage.c \
|
||||||
src/tb_input.c \
|
src/tb_input.c \
|
||||||
|
src/tb_vars.c \
|
||||||
src/tb_json_block.c \
|
src/tb_json_block.c \
|
||||||
src/tb_image.c \
|
src/tb_image.c \
|
||||||
src/tb_meta.c
|
src/tb_meta.c
|
||||||
@@ -98,7 +99,7 @@ LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \
|
|||||||
editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend test-editor \
|
editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend test-editor \
|
||||||
appdir appimage run-appimage icon \
|
appdir appimage run-appimage icon \
|
||||||
test-toml test-plugin test-blueprint test-base64 test-curves test-meta test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \
|
test-toml test-plugin test-blueprint test-base64 test-curves test-meta test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \
|
||||||
test-syntax test-os test-scratchblocks test-input test-stdlib test-regex test-markdown test-opentype \
|
test-syntax test-os test-vars test-scratchblocks test-input test-stdlib test-regex test-markdown test-opentype \
|
||||||
category-libs category-sos libs \
|
category-libs category-sos libs \
|
||||||
lib-events lib-control lib-input lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \
|
lib-events lib-control lib-input lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \
|
||||||
lib-environ \
|
lib-environ \
|
||||||
@@ -625,6 +626,15 @@ $(BUILD)/os_fs_test: tests/os_fs_test.c $(FS_DIR)/src/tb_fs.c $(LIBDIR)/tinybloc
|
|||||||
test-os: $(BUILD)/os_fs_test ## Roda o teste de tinyblocks-os + pastas do tinyblocks-fs (ASan/UBSan)
|
test-os: $(BUILD)/os_fs_test ## Roda o teste de tinyblocks-os + pastas do tinyblocks-fs (ASan/UBSan)
|
||||||
./$(BUILD)/os_fs_test
|
./$(BUILD)/os_fs_test
|
||||||
|
|
||||||
|
$(BUILD)/vars_test: tests/vars_test.c $(LIBDIR)/tinyblocks-variables/src/tb_variables.c static
|
||||||
|
@mkdir -p $(BUILD)
|
||||||
|
$(CC) $(CFLAGS_DBG) -I$(LIBDIR)/tinyblocks-variables/include \
|
||||||
|
$(LIBDIR)/tinyblocks-variables/src/tb_variables.c tests/vars_test.c \
|
||||||
|
-o $@ -Wl,--start-group $(LIB_A) -Wl,--end-group -lm $(EXTRA_TEST_LIBS)
|
||||||
|
|
||||||
|
test-vars: $(BUILD)/vars_test ## Roda o teste das variáveis com escopos (ASan/UBSan)
|
||||||
|
./$(BUILD)/vars_test
|
||||||
|
|
||||||
$(BUILD)/scratchblocks_test: tests/scratchblocks_test.c $(SB_DIR)/src/tb_scratchblocks.c $(BP_LIB_SRCS)
|
$(BUILD)/scratchblocks_test: tests/scratchblocks_test.c $(SB_DIR)/src/tb_scratchblocks.c $(BP_LIB_SRCS)
|
||||||
@mkdir -p $(BUILD)
|
@mkdir -p $(BUILD)
|
||||||
$(CC) $(CFLAGS_DBG) -I$(SB_DIR)/include -I$(BP_DIR)/include \
|
$(CC) $(CFLAGS_DBG) -I$(SB_DIR)/include -I$(BP_DIR)/include \
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tb_vars.h
|
||||||
|
* Armazenamento das variaveis (nome = valor) com escopos.
|
||||||
|
*
|
||||||
|
* Fica no core para existir uma copia so, mesmo com as libraries carregadas
|
||||||
|
* como .so (a tinyblocks-variables so tem os blocos). Ha as globais e
|
||||||
|
* escopos locais: quem executa (o editor) cria um escopo por script e por
|
||||||
|
* chamada de "Meus Blocos" e o torna o atual enquanto aquele codigo roda.
|
||||||
|
* Ler/escrever procura do escopo atual para o global.
|
||||||
|
*/
|
||||||
|
#ifndef TINYBLOCKS_TB_VARS_H
|
||||||
|
#define TINYBLOCKS_TB_VARS_H
|
||||||
|
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <tinyblocks/tinyblocks.h>
|
||||||
|
|
||||||
|
typedef struct TbVarScope TbVarScope;
|
||||||
|
|
||||||
|
/* -- Escopos -- */
|
||||||
|
/* parent: escopo de fora visivel daqui (NULL = so as globais) */
|
||||||
|
TB_API TbVarScope* tb_vars_scope_new(TbVarScope* parent);
|
||||||
|
TB_API void tb_vars_scope_free(TbVarScope* s); /* se era o atual, volta para NULL */
|
||||||
|
TB_API TbVarScope* tb_vars_scope_current(void);
|
||||||
|
TB_API void tb_vars_scope_set(TbVarScope* s); /* NULL = so as globais */
|
||||||
|
|
||||||
|
/* -- Valores (procuram do escopo atual ate o global) -- */
|
||||||
|
TB_API const TinyBlocks_Value* tb_vars_get(const char* name); /* emprestado; NULL = nao existe */
|
||||||
|
TB_API bool tb_vars_exists(const char* name);
|
||||||
|
/* muda onde a variavel existir; se nao existir, cria global. Clona o valor. */
|
||||||
|
TB_API void tb_vars_set(const char* name, TinyBlocks_Value v);
|
||||||
|
/* cria (ou reinicia) no escopo atual; sem escopo atual, vira global */
|
||||||
|
TB_API void tb_vars_declare_local(const char* name, TinyBlocks_Value v);
|
||||||
|
TB_API void tb_vars_declare_global(const char* name, TinyBlocks_Value v);
|
||||||
|
/* apaga a mais interna com esse nome; false se nao existia */
|
||||||
|
TB_API bool tb_vars_delete(const char* name);
|
||||||
|
|
||||||
|
/* -- Globais (monitores, salvar projeto) -- */
|
||||||
|
TB_API int tb_vars_global_count(void);
|
||||||
|
TB_API const char* tb_vars_global_name(int i);
|
||||||
|
TB_API const TinyBlocks_Value* tb_vars_global_value(int i);
|
||||||
|
TB_API void tb_vars_clear(void); /* apaga as globais */
|
||||||
|
TB_API void tb_vars_reset_blocks(void); /* zera valores BLOCK em todos os escopos */
|
||||||
|
|
||||||
|
#endif /* TINYBLOCKS_TB_VARS_H */
|
||||||
@@ -20,6 +20,7 @@
|
|||||||
#include <tb_graphics.h>
|
#include <tb_graphics.h>
|
||||||
#include <tinyblocks/tb_stage.h>
|
#include <tinyblocks/tb_stage.h>
|
||||||
#include <tinyblocks/tb_input.h>
|
#include <tinyblocks/tb_input.h>
|
||||||
|
#include <tinyblocks/tb_vars.h>
|
||||||
#include <tb_variables.h>
|
#include <tb_variables.h>
|
||||||
#include <tb_blueprint.h>
|
#include <tb_blueprint.h>
|
||||||
#include <tb_api.h>
|
#include <tb_api.h>
|
||||||
@@ -318,6 +319,9 @@ static const BlockSpec s_specs[] = {
|
|||||||
{"Variables.Set", "mude %1 para %2", "x|0"},
|
{"Variables.Set", "mude %1 para %2", "x|0"},
|
||||||
{"Variables.Change", "adicione %2 a %1", "x|1"},
|
{"Variables.Change", "adicione %2 a %1", "x|1"},
|
||||||
{"Variables.Get", "%1", "x"},
|
{"Variables.Get", "%1", "x"},
|
||||||
|
{"Variables.DeclareLocal", "crie variável local %1 com valor %2", "contador|0"},
|
||||||
|
{"Variables.DeclareGlobal", "crie variável global %1 com valor %2", "placar|0"},
|
||||||
|
{"Variables.Delete", "apague a variável %1", "contador"},
|
||||||
{"IO.Print", "escreva %1 %2", "Olá!|"},
|
{"IO.Print", "escreva %1 %2", "Olá!|"},
|
||||||
{"IO.PrintInt", "escreva o número %1", NULL},
|
{"IO.PrintInt", "escreva o número %1", NULL},
|
||||||
{"Port.In", "parâmetro %1", "x"},
|
{"Port.In", "parâmetro %1", "x"},
|
||||||
@@ -648,8 +652,9 @@ typedef struct {
|
|||||||
#define VM_STACK 64
|
#define VM_STACK 64
|
||||||
#define VM_THREADS 32
|
#define VM_THREADS 32
|
||||||
typedef struct {
|
typedef struct {
|
||||||
VmFrame st[VM_STACK];
|
VmFrame st[VM_STACK];
|
||||||
int sp;
|
int sp;
|
||||||
|
TbVarScope* scope; /* variaveis locais deste script */
|
||||||
} VmThread;
|
} VmThread;
|
||||||
|
|
||||||
/* Cache das arvores do runtime por (aba, bloco, profundidade de chamada):
|
/* Cache das arvores do runtime por (aba, bloco, profundidade de chamada):
|
||||||
|
|||||||
@@ -816,7 +816,10 @@ static bool slot_is_var_name(const TinyBlocks_TypeBlock* t, int s) {
|
|||||||
const char* n = t->type_name;
|
const char* n = t->type_name;
|
||||||
return strcmp(n, "Variables.Get") == 0 ||
|
return strcmp(n, "Variables.Get") == 0 ||
|
||||||
strcmp(n, "Variables.Set") == 0 ||
|
strcmp(n, "Variables.Set") == 0 ||
|
||||||
strcmp(n, "Variables.Change") == 0;
|
strcmp(n, "Variables.Change") == 0 ||
|
||||||
|
strcmp(n, "Variables.DeclareLocal") == 0 ||
|
||||||
|
strcmp(n, "Variables.DeclareGlobal") == 0 ||
|
||||||
|
strcmp(n, "Variables.Delete") == 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void draw_slot(TinyBlocks_RenderableBlock* rb, const EdBlock* b, int s,
|
static void draw_slot(TinyBlocks_RenderableBlock* rb, const EdBlock* b, int s,
|
||||||
@@ -974,6 +977,8 @@ static void clear_live(Tab* T) {
|
|||||||
|
|
||||||
/* Destrói as instâncias do runtime da execução anterior (e para os scripts) */
|
/* Destrói as instâncias do runtime da execução anterior (e para os scripts) */
|
||||||
static void run_reset(Ed* ed) {
|
static void run_reset(Ed* ed) {
|
||||||
|
for (int i = 0; i < ed->vm_n; i++) { tb_vars_scope_free(ed->vm[i].scope); ed->vm[i].scope = NULL; }
|
||||||
|
tb_vars_scope_set(NULL);
|
||||||
ed->vm_n = 0;
|
ed->vm_n = 0;
|
||||||
ed->vm_running = false;
|
ed->vm_running = false;
|
||||||
ed->rt_cache_n = 0;
|
ed->rt_cache_n = 0;
|
||||||
@@ -1147,6 +1152,7 @@ static void vm_start(Ed* ed, Tab* T, int head) {
|
|||||||
if (ed->vm_n >= VM_THREADS) return;
|
if (ed->vm_n >= VM_THREADS) return;
|
||||||
VmThread* th = &ed->vm[ed->vm_n++];
|
VmThread* th = &ed->vm[ed->vm_n++];
|
||||||
th->sp = 0;
|
th->sp = 0;
|
||||||
|
th->scope = tb_vars_scope_new(NULL); /* variaveis locais deste script */
|
||||||
vm_push(ed, th, T, head, VF_CHAIN, 0);
|
vm_push(ed, th, T, head, VF_CHAIN, 0);
|
||||||
ed->vm_running = true;
|
ed->vm_running = true;
|
||||||
}
|
}
|
||||||
@@ -1277,8 +1283,14 @@ static void vm_frame(Ed* ed) {
|
|||||||
bool alive;
|
bool alive;
|
||||||
do {
|
do {
|
||||||
alive = false;
|
alive = false;
|
||||||
for (int i = 0; i < ed->vm_n && !ed->abort; i++)
|
for (int i = 0; i < ed->vm_n && !ed->abort; i++) {
|
||||||
if (ed->vm[i].sp > 0 && vm_step(ed, &ed->vm[i])) alive = true;
|
VmThread* th = &ed->vm[i];
|
||||||
|
if (th->sp <= 0) continue;
|
||||||
|
tb_vars_scope_set(th->scope);
|
||||||
|
if (vm_step(ed, th)) alive = true;
|
||||||
|
else { tb_vars_scope_set(NULL); tb_vars_scope_free(th->scope); th->scope = NULL; }
|
||||||
|
tb_vars_scope_set(NULL);
|
||||||
|
}
|
||||||
} while (alive && !ed->abort && !ed->redraw_req && now_ms() - t0 < VM_FRAME_MS);
|
} while (alive && !ed->abort && !ed->redraw_req && now_ms() - t0 < VM_FRAME_MS);
|
||||||
cap_end(ed);
|
cap_end(ed);
|
||||||
if (!alive || ed->abort) {
|
if (!alive || ed->abort) {
|
||||||
@@ -1493,6 +1505,9 @@ static void eval_composite(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|||||||
CallFrame* f = &ed->frames[ed->frame_n++];
|
CallFrame* f = &ed->frames[ed->frame_n++];
|
||||||
memset(f, 0, sizeof(*f));
|
memset(f, 0, sizeof(*f));
|
||||||
f->def = def;
|
f->def = def;
|
||||||
|
TbVarScope* outer = tb_vars_scope_current();
|
||||||
|
TbVarScope* local = tb_vars_scope_new(NULL); /* locais da chamada: nao veem as de quem chamou */
|
||||||
|
tb_vars_scope_set(local);
|
||||||
for (int i = 0; i < def->input_count; i++)
|
for (int i = 0; i < def->input_count; i++)
|
||||||
f->in[i] = tb_value_clone(tb_block_get_input(self, rt, (uint32_t)i));
|
f->in[i] = tb_value_clone(tb_block_get_input(self, rt, (uint32_t)i));
|
||||||
|
|
||||||
@@ -1513,6 +1528,8 @@ static void eval_composite(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|||||||
f->out[i] = tb_value_none();
|
f->out[i] = tb_value_none();
|
||||||
}
|
}
|
||||||
for (int i = 0; i < def->input_count; i++) tb_value_free(&f->in[i]);
|
for (int i = 0; i < def->input_count; i++) tb_value_free(&f->in[i]);
|
||||||
|
tb_vars_scope_set(outer);
|
||||||
|
tb_vars_scope_free(local);
|
||||||
ed->frame_n--;
|
ed->frame_n--;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
/*
|
/*
|
||||||
* TinyBlocks - tb_variables.h
|
* TinyBlocks - tb_variables.h
|
||||||
* Library da categoria "Variáveis". Ela é dona do armazenamento (nome=valor);
|
* Library da categoria "Variáveis" (blocos). O armazenamento, com escopos
|
||||||
* UIs, como o editor, consultam a lista para desenhar monitores.
|
* locais, fica no core (tinyblocks/tb_vars.h); esta API olha as globais,
|
||||||
|
* que UIs como o editor usam para desenhar monitores e salvar o projeto.
|
||||||
*/
|
*/
|
||||||
#ifndef TINYBLOCKS_VARIABLES_H
|
#ifndef TINYBLOCKS_VARIABLES_H
|
||||||
#define TINYBLOCKS_VARIABLES_H
|
#define TINYBLOCKS_VARIABLES_H
|
||||||
|
|||||||
@@ -1,32 +1,22 @@
|
|||||||
/*
|
/*
|
||||||
* TinyBlocks - tb_variables.c
|
* TinyBlocks - tb_variables.c
|
||||||
* Categoria "Variáveis": mude / adicione / valor de <variável>.
|
* Categoria "Variáveis": mude / adicione / valor de <variável>, crie
|
||||||
* A library é dona do armazenamento de variáveis e o expõe para monitores.
|
* variável local / global e apague a variável.
|
||||||
|
*
|
||||||
|
* O armazenamento fica no core (tinyblocks/tb_vars.h), com escopos: assim
|
||||||
|
* existe uma copia so mesmo com esta library carregada como .so, e quem
|
||||||
|
* executa (o editor) pode dar a cada script e a cada chamada de "Meus
|
||||||
|
* Blocos" as suas variaveis locais. A API tb_variables_* (monitores do
|
||||||
|
* editor, salvar projeto) olha as globais.
|
||||||
*/
|
*/
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
#include <tinyblocks/tinyblocks.h>
|
#include <tinyblocks/tinyblocks.h>
|
||||||
|
#include <tinyblocks/tb_vars.h>
|
||||||
#include "tb_variables.h"
|
#include "tb_variables.h"
|
||||||
|
|
||||||
#define MAX_VARS 64
|
|
||||||
|
|
||||||
typedef struct { char name[32]; TinyBlocks_Value val; } Var;
|
|
||||||
|
|
||||||
static Var s_vars[MAX_VARS];
|
|
||||||
static int s_n = 0;
|
|
||||||
|
|
||||||
static int var_find(const char* n, bool create) {
|
|
||||||
for (int i = 0; i < s_n; i++)
|
|
||||||
if (strcmp(s_vars[i].name, n) == 0) return i;
|
|
||||||
if (!create || s_n >= MAX_VARS) return -1;
|
|
||||||
int i = s_n++;
|
|
||||||
strncpy(s_vars[i].name, n, 31); s_vars[i].name[31] = 0;
|
|
||||||
s_vars[i].val = tb_value_integer(0);
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void input_name(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i,
|
static void input_name(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i,
|
||||||
char* out, size_t cap) {
|
char* out, size_t cap) {
|
||||||
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
|
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
|
||||||
@@ -41,81 +31,81 @@ static void input_name(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i,
|
|||||||
|
|
||||||
static void eval_var_get(TinyBlocks_Block* self, TinyBlocks* rt) {
|
static void eval_var_get(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||||
char name[64]; input_name(self, rt, 0, name, sizeof(name));
|
char name[64]; input_name(self, rt, 0, name, sizeof(name));
|
||||||
int i = var_find(name, false);
|
const TinyBlocks_Value* v = tb_vars_get(name);
|
||||||
tb_block_set_output(self, 0, i >= 0 ? tb_value_clone(s_vars[i].val)
|
tb_block_set_output(self, 0, v ? tb_value_clone(*v) : tb_value_integer(0));
|
||||||
: tb_value_integer(0));
|
|
||||||
self->dirty = false;
|
self->dirty = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void eval_var_set(TinyBlocks_Block* self, TinyBlocks* rt) {
|
static void eval_var_set(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||||
char name[64]; input_name(self, rt, 0, name, sizeof(name));
|
char name[64]; input_name(self, rt, 0, name, sizeof(name));
|
||||||
int i = var_find(name, true);
|
tb_vars_set(name, tb_block_get_input(self, rt, 1));
|
||||||
if (i >= 0) {
|
|
||||||
TinyBlocks_Value v = tb_block_get_input(self, rt, 1);
|
|
||||||
tb_value_free(&s_vars[i].val);
|
|
||||||
s_vars[i].val = tb_value_clone(v);
|
|
||||||
}
|
|
||||||
self->dirty = false;
|
self->dirty = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static double as_num(const TinyBlocks_Value* v) {
|
||||||
|
if (!v) return 0;
|
||||||
|
if (v->kind == TB_VALUE_INTEGER) return (double)v->as.integer;
|
||||||
|
if (v->kind == TB_VALUE_REAL) return v->as.real;
|
||||||
|
if (v->kind == TB_VALUE_TEXT && v->as.text) return strtod(v->as.text, NULL);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
static void eval_var_change(TinyBlocks_Block* self, TinyBlocks* rt) {
|
static void eval_var_change(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||||
char name[64]; input_name(self, rt, 0, name, sizeof(name));
|
char name[64]; input_name(self, rt, 0, name, sizeof(name));
|
||||||
int i = var_find(name, true);
|
TinyBlocks_Value by = tb_block_get_input(self, rt, 1);
|
||||||
if (i >= 0) {
|
double a = as_num(tb_vars_get(name)), d = as_num(&by);
|
||||||
TinyBlocks_Value by = tb_block_get_input(self, rt, 1);
|
TinyBlocks_Value nv = (a == floor(a) && d == floor(d))
|
||||||
TinyBlocks_Value* cur = &s_vars[i].val;
|
? tb_value_integer((long long)llround(a + d))
|
||||||
double a = 0, d = 0;
|
: tb_value_real(a + d);
|
||||||
if (cur->kind == TB_VALUE_INTEGER) a = (double)cur->as.integer;
|
tb_vars_set(name, nv);
|
||||||
else if (cur->kind == TB_VALUE_REAL) a = cur->as.real;
|
tb_value_free(&nv);
|
||||||
else if (cur->kind == TB_VALUE_TEXT && cur->as.text) a = strtod(cur->as.text, NULL);
|
|
||||||
if (by.kind == TB_VALUE_INTEGER) d = (double)by.as.integer;
|
|
||||||
else if (by.kind == TB_VALUE_REAL) d = by.as.real;
|
|
||||||
else if (by.kind == TB_VALUE_TEXT && by.as.text) d = strtod(by.as.text, NULL);
|
|
||||||
TinyBlocks_Value nv = (a == floor(a) && d == floor(d))
|
|
||||||
? tb_value_integer((long long)llround(a + d))
|
|
||||||
: tb_value_real(a + d);
|
|
||||||
tb_value_free(cur);
|
|
||||||
*cur = nv;
|
|
||||||
}
|
|
||||||
self->dirty = false;
|
self->dirty = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* == API de enumeração === */
|
/* "crie variável local [x] com valor (v)": so deste script/chamada */
|
||||||
int tb_variables_count(void) { return s_n; }
|
static void eval_var_local(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||||
|
char name[64]; input_name(self, rt, 0, name, sizeof(name));
|
||||||
const char* tb_variables_name(int i) {
|
TinyBlocks_Value v = tb_block_get_input(self, rt, 1);
|
||||||
return (i >= 0 && i < s_n) ? s_vars[i].name : "";
|
tb_vars_declare_local(name, v.kind == TB_VALUE_NONE ? tb_value_integer(0) : v);
|
||||||
|
self->dirty = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const TinyBlocks_Value* tb_variables_value(int i) {
|
/* "crie variável global [x] com valor (v)": visivel em todo lugar */
|
||||||
return (i >= 0 && i < s_n) ? &s_vars[i].val : NULL;
|
static void eval_var_global(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||||
|
char name[64]; input_name(self, rt, 0, name, sizeof(name));
|
||||||
|
TinyBlocks_Value v = tb_block_get_input(self, rt, 1);
|
||||||
|
tb_vars_declare_global(name, v.kind == TB_VALUE_NONE ? tb_value_integer(0) : v);
|
||||||
|
self->dirty = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
void tb_variables_reset_blocks(void) {
|
/* "apague a variável [x]": a mais interna com esse nome */
|
||||||
for (int v = 0; v < s_n; v++)
|
static void eval_var_delete(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||||
if (s_vars[v].val.kind == TB_VALUE_BLOCK) {
|
char name[64]; input_name(self, rt, 0, name, sizeof(name));
|
||||||
tb_value_free(&s_vars[v].val);
|
if (!tb_vars_delete(name) && name[0])
|
||||||
s_vars[v].val = tb_value_integer(0);
|
tinyblocks_set_error(rt, "variável '%s' não existe", name);
|
||||||
}
|
self->dirty = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
void tb_variables_clear(void) {
|
/* == API (globais) === */
|
||||||
for (int i = 0; i < s_n; i++) tb_value_free(&s_vars[i].val);
|
int tb_variables_count(void) { return tb_vars_global_count(); }
|
||||||
s_n = 0;
|
const char* tb_variables_name(int i) { return tb_vars_global_name(i); }
|
||||||
}
|
const TinyBlocks_Value* tb_variables_value(int i) { return tb_vars_global_value(i); }
|
||||||
|
void tb_variables_reset_blocks(void) { tb_vars_reset_blocks(); }
|
||||||
|
void tb_variables_clear(void) { tb_vars_clear(); }
|
||||||
|
|
||||||
void tb_variables_set_text(const char* name, const char* value) {
|
void tb_variables_set_text(const char* name, const char* value) {
|
||||||
if (!name || !name[0]) return;
|
if (!name || !name[0]) return;
|
||||||
int i = var_find(name, true);
|
|
||||||
if (i < 0) return;
|
|
||||||
tb_value_free(&s_vars[i].val);
|
|
||||||
const char* s = value ? value : "";
|
const char* s = value ? value : "";
|
||||||
char* end = NULL;
|
char* end = NULL;
|
||||||
|
TinyBlocks_Value v;
|
||||||
long long iv = strtoll(s, &end, 10);
|
long long iv = strtoll(s, &end, 10);
|
||||||
if (end && *end == 0 && end != s) { s_vars[i].val = tb_value_integer(iv); return; }
|
if (end && *end == 0 && end != s) v = tb_value_integer(iv);
|
||||||
double dv = strtod(s, &end);
|
else {
|
||||||
if (end && *end == 0 && end != s) { s_vars[i].val = tb_value_real(dv); return; }
|
double dv = strtod(s, &end);
|
||||||
s_vars[i].val = tb_value_text(s);
|
v = (end && *end == 0 && end != s) ? tb_value_real(dv) : tb_value_text(s);
|
||||||
|
}
|
||||||
|
tb_vars_declare_global(name, v);
|
||||||
|
tb_value_free(&v);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* == Registro === */
|
/* == Registro === */
|
||||||
@@ -134,6 +124,12 @@ static bool variables_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
|||||||
"Altera (incrementa) o valor de uma variavel");
|
"Altera (incrementa) o valor de uma variavel");
|
||||||
TB_BLOCK_META("Variables.Get", "eval_var_get",
|
TB_BLOCK_META("Variables.Get", "eval_var_get",
|
||||||
"Le o valor de uma variavel");
|
"Le o valor de uma variavel");
|
||||||
|
TB_BLOCK_META("Variables.DeclareLocal", "eval_var_local",
|
||||||
|
"Cria uma variavel que so existe neste script (ou nesta chamada de Meus Blocos)");
|
||||||
|
TB_BLOCK_META("Variables.DeclareGlobal", "eval_var_global",
|
||||||
|
"Cria uma variavel visivel em todos os scripts");
|
||||||
|
TB_BLOCK_META("Variables.Delete", "eval_var_delete",
|
||||||
|
"Apaga a variavel (a local, se houver; senao a global)");
|
||||||
|
|
||||||
static const TinyBlocks_SlotDesc var_in[] = {{"variável", TB_VALUE_TEXT}};
|
static const TinyBlocks_SlotDesc var_in[] = {{"variável", TB_VALUE_TEXT}};
|
||||||
static const TinyBlocks_SlotDesc var_set[] = {{"variável", TB_VALUE_TEXT}, {"valor", TB_VALUE_NONE}};
|
static const TinyBlocks_SlotDesc var_set[] = {{"variável", TB_VALUE_TEXT}, {"valor", TB_VALUE_NONE}};
|
||||||
@@ -146,13 +142,18 @@ static bool variables_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
|||||||
if (!t || !tb_library_add(lib, &t->base)) return false;
|
if (!t || !tb_library_add(lib, &t->base)) return false;
|
||||||
t = tb_type_block_create(rt, "Variables.Get", var_in, 1, any_out, 1, eval_var_get);
|
t = tb_type_block_create(rt, "Variables.Get", var_in, 1, any_out, 1, eval_var_get);
|
||||||
if (!t || !tb_library_add(lib, &t->base)) return false;
|
if (!t || !tb_library_add(lib, &t->base)) return false;
|
||||||
|
t = tb_type_block_create(rt, "Variables.DeclareLocal", var_set, 2, NULL, 0, eval_var_local);
|
||||||
|
if (!t || !tb_library_add(lib, &t->base)) return false;
|
||||||
|
t = tb_type_block_create(rt, "Variables.DeclareGlobal", var_set, 2, NULL, 0, eval_var_global);
|
||||||
|
if (!t || !tb_library_add(lib, &t->base)) return false;
|
||||||
|
t = tb_type_block_create(rt, "Variables.Delete", var_in, 1, NULL, 0, eval_var_delete);
|
||||||
|
if (!t || !tb_library_add(lib, &t->base)) return false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void variables_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
static void variables_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||||
(void)rt; (void)lib;
|
(void)rt; (void)lib;
|
||||||
for (int i = 0; i < s_n; i++) tb_value_free(&s_vars[i].val);
|
tb_vars_clear();
|
||||||
s_n = 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
TINYBLOCKS_DEFINE_LIBRARY(variables,
|
TINYBLOCKS_DEFINE_LIBRARY(variables,
|
||||||
|
|||||||
+164
@@ -0,0 +1,164 @@
|
|||||||
|
/*
|
||||||
|
* TinyBlocks - tb_vars.c
|
||||||
|
* Variaveis com escopos (ver tb_vars.h).
|
||||||
|
*/
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "tinyblocks/tb_vars.h"
|
||||||
|
|
||||||
|
typedef struct { char* name; TinyBlocks_Value val; } Var;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
Var* v;
|
||||||
|
int n, cap;
|
||||||
|
} VarTable;
|
||||||
|
|
||||||
|
struct TbVarScope {
|
||||||
|
VarTable t;
|
||||||
|
TbVarScope* parent;
|
||||||
|
TbVarScope* next_live; /* lista de todos os escopos vivos */
|
||||||
|
};
|
||||||
|
|
||||||
|
static VarTable s_global;
|
||||||
|
static TbVarScope* s_cur = NULL;
|
||||||
|
static TbVarScope* s_live = NULL;
|
||||||
|
|
||||||
|
/* -- Tabela ---------------------------------------------------------------- */
|
||||||
|
|
||||||
|
static int table_find(const VarTable* t, const char* name) {
|
||||||
|
for (int i = 0; i < t->n; i++) if (!strcmp(t->v[i].name, name)) return i;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Var* table_put(VarTable* t, const char* name, TinyBlocks_Value v) {
|
||||||
|
int i = table_find(t, name);
|
||||||
|
if (i >= 0) {
|
||||||
|
tb_value_free(&t->v[i].val);
|
||||||
|
t->v[i].val = tb_value_clone(v);
|
||||||
|
return &t->v[i];
|
||||||
|
}
|
||||||
|
if (t->n == t->cap) {
|
||||||
|
int nc = t->cap ? t->cap * 2 : 16;
|
||||||
|
Var* nv = realloc(t->v, (size_t)nc * sizeof(Var));
|
||||||
|
if (!nv) return NULL;
|
||||||
|
t->v = nv; t->cap = nc;
|
||||||
|
}
|
||||||
|
size_t len = strlen(name);
|
||||||
|
char* nm = malloc(len + 1);
|
||||||
|
if (!nm) return NULL;
|
||||||
|
memcpy(nm, name, len + 1);
|
||||||
|
Var* x = &t->v[t->n++];
|
||||||
|
x->name = nm;
|
||||||
|
x->val = tb_value_clone(v);
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void table_remove(VarTable* t, int i) {
|
||||||
|
free(t->v[i].name);
|
||||||
|
tb_value_free(&t->v[i].val);
|
||||||
|
memmove(&t->v[i], &t->v[i + 1], (size_t)(t->n - i - 1) * sizeof(Var));
|
||||||
|
t->n--;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void table_clear(VarTable* t) {
|
||||||
|
while (t->n > 0) table_remove(t, t->n - 1);
|
||||||
|
free(t->v);
|
||||||
|
t->v = NULL; t->cap = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tabela onde `name` existe, do escopo atual para fora; NULL se nenhuma */
|
||||||
|
static VarTable* where(const char* name, int* idx) {
|
||||||
|
for (TbVarScope* s = s_cur; s; s = s->parent) {
|
||||||
|
int i = table_find(&s->t, name);
|
||||||
|
if (i >= 0) { *idx = i; return &s->t; }
|
||||||
|
}
|
||||||
|
int i = table_find(&s_global, name);
|
||||||
|
if (i >= 0) { *idx = i; return &s_global; }
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -- Escopos --------------------------------------------------------------- */
|
||||||
|
|
||||||
|
TbVarScope* tb_vars_scope_new(TbVarScope* parent) {
|
||||||
|
TbVarScope* s = calloc(1, sizeof(TbVarScope));
|
||||||
|
if (!s) return NULL;
|
||||||
|
s->parent = parent;
|
||||||
|
s->next_live = s_live;
|
||||||
|
s_live = s;
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
void tb_vars_scope_free(TbVarScope* s) {
|
||||||
|
if (!s) return;
|
||||||
|
for (TbVarScope** pp = &s_live; *pp; pp = &(*pp)->next_live)
|
||||||
|
if (*pp == s) { *pp = s->next_live; break; }
|
||||||
|
for (TbVarScope* o = s_live; o; o = o->next_live) /* filhos perdem o pai */
|
||||||
|
if (o->parent == s) o->parent = NULL;
|
||||||
|
if (s_cur == s) s_cur = NULL;
|
||||||
|
table_clear(&s->t);
|
||||||
|
free(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
TbVarScope* tb_vars_scope_current(void) { return s_cur; }
|
||||||
|
void tb_vars_scope_set(TbVarScope* s) { s_cur = s; }
|
||||||
|
|
||||||
|
/* -- Valores --------------------------------------------------------------- */
|
||||||
|
|
||||||
|
const TinyBlocks_Value* tb_vars_get(const char* name) {
|
||||||
|
if (!name || !name[0]) return NULL;
|
||||||
|
int i;
|
||||||
|
VarTable* t = where(name, &i);
|
||||||
|
return t ? &t->v[i].val : NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool tb_vars_exists(const char* name) { return tb_vars_get(name) != NULL; }
|
||||||
|
|
||||||
|
void tb_vars_set(const char* name, TinyBlocks_Value v) {
|
||||||
|
if (!name || !name[0]) return;
|
||||||
|
int i;
|
||||||
|
VarTable* t = where(name, &i);
|
||||||
|
table_put(t ? t : &s_global, name, v);
|
||||||
|
}
|
||||||
|
|
||||||
|
void tb_vars_declare_local(const char* name, TinyBlocks_Value v) {
|
||||||
|
if (!name || !name[0]) return;
|
||||||
|
table_put(s_cur ? &s_cur->t : &s_global, name, v);
|
||||||
|
}
|
||||||
|
|
||||||
|
void tb_vars_declare_global(const char* name, TinyBlocks_Value v) {
|
||||||
|
if (!name || !name[0]) return;
|
||||||
|
table_put(&s_global, name, v);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool tb_vars_delete(const char* name) {
|
||||||
|
if (!name || !name[0]) return false;
|
||||||
|
int i;
|
||||||
|
VarTable* t = where(name, &i);
|
||||||
|
if (!t) return false;
|
||||||
|
table_remove(t, i);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -- Globais --------------------------------------------------------------- */
|
||||||
|
|
||||||
|
int tb_vars_global_count(void) { return s_global.n; }
|
||||||
|
const char* tb_vars_global_name(int i) { return (i >= 0 && i < s_global.n) ? s_global.v[i].name : ""; }
|
||||||
|
const TinyBlocks_Value* tb_vars_global_value(int i) {
|
||||||
|
return (i >= 0 && i < s_global.n) ? &s_global.v[i].val : NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
void tb_vars_clear(void) { table_clear(&s_global); }
|
||||||
|
|
||||||
|
static void reset_blocks_in(VarTable* t) {
|
||||||
|
for (int i = 0; i < t->n; i++)
|
||||||
|
if (t->v[i].val.kind == TB_VALUE_BLOCK) {
|
||||||
|
tb_value_free(&t->v[i].val);
|
||||||
|
t->v[i].val = tb_value_integer(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void tb_vars_reset_blocks(void) {
|
||||||
|
reset_blocks_in(&s_global);
|
||||||
|
for (TbVarScope* s = s_live; s; s = s->next_live) reset_blocks_in(&s->t);
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
/*
|
||||||
|
* vars_test.c - testa as variaveis com escopos do core (tb_vars) e os blocos
|
||||||
|
* da tinyblocks-variables (crie local/global, apague, mude, adicione).
|
||||||
|
*/
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <tinyblocks/tinyblocks.h>
|
||||||
|
#include <tinyblocks/tb_vars.h>
|
||||||
|
#include <tb_variables.h>
|
||||||
|
|
||||||
|
static int fails = 0;
|
||||||
|
#define CHECK(c, m) do { if (c) printf("ok %s\n", m); else { printf("FAIL %s\n", m); fails++; } } while (0)
|
||||||
|
|
||||||
|
static TinyBlocks* rt;
|
||||||
|
|
||||||
|
static void run(const char* type, const char* name, long long v, bool with_v) {
|
||||||
|
TinyBlocks_Block* b = tb_block_create(rt, tb_rt_find_type(rt, type));
|
||||||
|
TinyBlocks_Value n = tb_value_text(name);
|
||||||
|
tb_block_set_default(b, 0, n);
|
||||||
|
tb_value_free(&n);
|
||||||
|
if (with_v) { TinyBlocks_Value x = tb_value_integer(v); tb_block_set_default(b, 1, x); }
|
||||||
|
tb_block_eval(b, rt);
|
||||||
|
tb_block_destroy(b, rt);
|
||||||
|
}
|
||||||
|
|
||||||
|
static long long get(const char* name) {
|
||||||
|
TinyBlocks_Block* b = tb_block_create(rt, tb_rt_find_type(rt, "Variables.Get"));
|
||||||
|
TinyBlocks_Value n = tb_value_text(name);
|
||||||
|
tb_block_set_default(b, 0, n);
|
||||||
|
tb_value_free(&n);
|
||||||
|
tb_block_eval(b, rt);
|
||||||
|
long long r = b->outputs[0].kind == TB_VALUE_INTEGER ? b->outputs[0].as.integer : -999;
|
||||||
|
tb_block_destroy(b, rt);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
tinyblocks_init(&rt, NULL);
|
||||||
|
tb_library_register(rt, tb_variables_get_library());
|
||||||
|
CHECK(tb_rt_find_type(rt, "Variables.DeclareLocal") && tb_rt_find_type(rt, "Variables.DeclareGlobal") &&
|
||||||
|
tb_rt_find_type(rt, "Variables.Delete"), "blocos crie local / crie global / apague registrados");
|
||||||
|
|
||||||
|
run("Variables.DeclareGlobal", "placar", 10, true);
|
||||||
|
CHECK(get("placar") == 10 && tb_variables_count() == 1, "crie variável global aparece nas globais");
|
||||||
|
|
||||||
|
/* script A com uma local */
|
||||||
|
TbVarScope* a = tb_vars_scope_new(NULL);
|
||||||
|
tb_vars_scope_set(a);
|
||||||
|
run("Variables.DeclareLocal", "c", 1, true);
|
||||||
|
run("Variables.Change", "c", 5, true);
|
||||||
|
run("Variables.Change", "placar", 1, true);
|
||||||
|
CHECK(get("c") == 6, "local criada e alterada dentro do script");
|
||||||
|
CHECK(tb_variables_count() == 1, "local não entra nas globais (monitores)");
|
||||||
|
|
||||||
|
/* script B: não vê a local de A; a dele tem o mesmo nome */
|
||||||
|
TbVarScope* b = tb_vars_scope_new(NULL);
|
||||||
|
tb_vars_scope_set(b);
|
||||||
|
CHECK(get("c") == 0 && get("placar") == 11, "outro script não vê a local, mas vê a global");
|
||||||
|
run("Variables.DeclareLocal", "c", 100, true);
|
||||||
|
tb_vars_scope_set(a);
|
||||||
|
CHECK(get("c") == 6, "locais de mesmo nome em scripts diferentes são independentes");
|
||||||
|
|
||||||
|
/* local com o mesmo nome de uma global a esconde; mude escreve na local */
|
||||||
|
run("Variables.DeclareLocal", "placar", 0, true);
|
||||||
|
run("Variables.Set", "placar", 3, true);
|
||||||
|
CHECK(get("placar") == 3, "local esconde a global de mesmo nome");
|
||||||
|
tb_vars_scope_set(NULL);
|
||||||
|
CHECK(get("placar") == 11, "a global continua com o valor dela");
|
||||||
|
|
||||||
|
/* apague: a mais interna primeiro */
|
||||||
|
tb_vars_scope_set(a);
|
||||||
|
run("Variables.Delete", "placar", 0, false);
|
||||||
|
CHECK(get("placar") == 11, "apagar remove a local e a global volta a aparecer");
|
||||||
|
run("Variables.Delete", "c", 0, false);
|
||||||
|
CHECK(!tb_vars_exists("c"), "apague a variável local");
|
||||||
|
|
||||||
|
/* mude numa variável que não existe cria global */
|
||||||
|
run("Variables.Set", "nova", 7, true);
|
||||||
|
tb_vars_scope_set(NULL);
|
||||||
|
CHECK(get("nova") == 7, "mude em variável inexistente cria global");
|
||||||
|
|
||||||
|
/* escopo acaba: as locais somem */
|
||||||
|
tb_vars_scope_set(b);
|
||||||
|
tb_vars_scope_free(b);
|
||||||
|
CHECK(tb_vars_scope_current() == NULL, "liberar o escopo atual volta para as globais");
|
||||||
|
CHECK(get("c") == 0, "locais do script somem quando ele termina");
|
||||||
|
|
||||||
|
/* chamada de Meus Blocos: escopo sem pai não vê as locais de quem chamou */
|
||||||
|
tb_vars_scope_set(a);
|
||||||
|
run("Variables.DeclareLocal", "segredo", 42, true);
|
||||||
|
TbVarScope* call = tb_vars_scope_new(NULL);
|
||||||
|
tb_vars_scope_set(call);
|
||||||
|
CHECK(get("segredo") == 0 && get("placar") == 11, "chamada não vê as locais de quem chamou");
|
||||||
|
tb_vars_scope_set(a);
|
||||||
|
tb_vars_scope_free(call);
|
||||||
|
CHECK(get("segredo") == 42, "de volta ao script, a local continua lá");
|
||||||
|
tb_vars_scope_set(NULL);
|
||||||
|
tb_vars_scope_free(a);
|
||||||
|
|
||||||
|
run("Variables.Delete", "placar", 0, false);
|
||||||
|
CHECK(!tb_vars_exists("placar"), "apague a variável global");
|
||||||
|
tinyblocks_deinit(&rt);
|
||||||
|
if (fails) printf("\n%d FALHA(S)\n", fails);
|
||||||
|
else printf("\nTUDO OK\n");
|
||||||
|
return fails != 0;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user