I do not think that throwing a regex at the code string would be an especially good idea.The syntax of your input doesn't look too extraordinary, so we could just parse it with Marpa, using a grammar like
:default ::= action => [values]
:start ::= StatementList
:discard ~ ws
StatementList ::= <Expression>+ separator => <op semicolon> bless => Block
Expression ::=
('(') Expression (')') assoc => group action => ::first
| Number bless => Number
|| Ident bless => Var
|| Expression ('==') Expression bless => Numeric_eq
|| Expression ('=' ) Expression bless => Assign
|| Expression ('Or') Expression bless => Logical_or
|| Conditional
Conditional ::=
('If') Expression ('Then') Expression
bless => Cond
| ('If') Expression ('Then') Expression ('Else') Expression
bless => Cond
Ident ~ ident
Number ~ <number int> | <number rat>
word ~ [\w]+
ident ~ word | ident '.' word
<number int> ~ [\d]+
<number rat> ~ <number int> '.' <number int>
ws ~ [\s]+
<op semicolon> ~ ';'
Then:
use Marpa::R2;
my $grammar = Marpa::R2::Scanless::G->new({
bless_package => 'Ast',
source => \$the_grammar,
});
my $recce = Marpa::R2::Scanless::R->new({ grammar => $grammar });
$recce->read(\$the_string);
my $val = $recce->value // die "No parse found";
my $ast = $$val;
As soon as we have the AST, compiling it down to the C-like representation isn't overly complex. Factoring out the common assignment with an “optimization” pass can be done with a bit of thinking.
However, showing how this can be done is rather lengthy, so I put all the in-depth stuff into this blogpost. We can then define a method that recurses through the tree and emits the C-like code, e.g.
package Ast::Var;
...;
sub compile { my $self = shift; $self->name } # no modification needed
package Ast::Logical_Or;
...;
sub compile {
my $self = shift;
# C's "||" operator, plus parens to specify precedence
"(" . $self->l->compile . "||" . $self->r->compile . ")";
}
package Ast::Cond;
...;
sub compile {
my $self = shift;
return sprintf '(%s ? %s : %s)',
$self->cond->compile,
$self->then->compile,
$self->else->compile;
}
etc. for all the other AST node types.
my $a = 1 * ($val1 == 1 || $val2 == 1);
?1
or empty string for boolean