Sunday, November 29, 2015

[IDL 2 CPP] Implement Variable Definitions

Since IDL (Interactive Data Language) is a kind of dynamic typed language (dynamic language for short), it doesn't have variable declarations. So we have to add declarations in translated C++ source code.

The basic method of adding declarations is by using mid-rules in Bison grammar file.

As following, initialize a data structure that could store variable names, and then each time the parse meets an assignment statement, store the variable name for future use. The following code show the way of recording variable names. But its not accurate, because unary_expression doesn't equal to variable name, sometimes it's an element of an array or some other ting. So here we need more complex code logic to accomplish it. But I won't put these code here because here is just a show of high level of structure of the method.

assignment_statement:
unary_expression '=' expression
{printf("bison got assign statement: %s = %s\n", $1, $3);
VariableNameSet_TryAdd($1);
$$ = AllocBuff();
sprintf_s($$, TEXT_BUFFER_LEN, "%s = %s;", $1, $3);
}
;

And at last, when composing the C++ function, put the variable declarations at the beginning of the function.

function_definition:
KEY_FUNCTION identifier parameter_list_line
{
VariableNameSet_Init();
}
statement_list KEY_END end_of_line
{
char *buf = AllocBuff();
IncreaseTab($5, buf);

$$ = AllocBuff();

char *var_decl_buf = AllocBuff();
VariableNameSet_DecleareVariables(var_decl_buf);

char *var_decl_buf_tabbed = AllocBuff();
IncreaseTab(var_decl_buf, var_decl_buf_tabbed);

sprintf_s($$, TEXT_BUFFER_LEN, "Variant %s%s{\n%s%s}%s\n", $2, $3, var_decl_buf_tabbed, buf, $7);
printf("IDL function: [%s]\n", $$);
}
;




Post a Comment