Skip to content

Instantly share code, notes, and snippets.

@aaronryank
Last active February 28, 2018 01:46
Show Gist options
  • Save aaronryank/49d093f64fa152bff9b89258a891e810 to your computer and use it in GitHub Desktop.
Save aaronryank/49d093f64fa152bff9b89258a891e810 to your computer and use it in GitHub Desktop.
INCOMPLETE RK TO C COMPILER - usage: perl rk.pl < input.rk > output.c
use Text::ParseWords;
print "typedef void *UNTYPED;\n";
print "#define ARGS UNTYPED args[]\n";
print "#define INT __uint128_t\n";
print "#define STR char *\n\n";
my @variables;
my $variable_count = 0;
my @code;
my $lines = 0;
my $cur_func;
while (<>) {
# prerequisites:
# - copy `ex VAR NAME` inside function `FUNC` to `VAR FUNC_NAME` at top of file
# - replace `ex VAR NAME` inside function `FUNC` with `VAR FUNC_NAME`
# - append space to each line
# - append newline
########################
# complex replacements #
########################
s/(?<=\*)(.*?)(?=\n)//g; s/\*/ /g; # remove comments
s/ +$//g; # remove trailing spaces
s/(\w+)\:start/UNTYPED $1(ARGS) {/g; # replace func:start with "UNTYPED func(ARGS) {"
if (length($1 // '')) {
$cur_func = $1;
}
s/(\w+)\:end/}/g; # replace func:end with }
s/\s*(\$)\s*/$1/g; # replace x $ y with x$y
s/(\w)\$(\w)/$1\[$2\]/g; # replace x$y with x[y]
s/(\w):(\w)/$1_$2/g; # globals:foo -> globals_foo
#############
# functions #
#############
while ($_ =~ /(.*?):\s+(.*)/g) {
s/(.*?):\s+(.*)/$1($2)/g;
}
sub remove_sp {
join ", ", quotewords('\s+', 1, shift);
}
s/(\([^)]*\))/remove_sp($1)/eg;
#########################
# variable modification #
#########################
s/int /INT /g;
s/str /STR /g;
s/chr /CHR /g;
s/var /UNTYPED /g;
####################
# global variables #
####################
s/ex (\w+) (\w+)/$cur_func\_$2/g;
if (length($1 // '') && (length($2 // ''))) {
$variables[$variable_count++] = $1 . ' ' . $cur_func . '_' . $2 . ";\n";
}
#############################
# basic syntax modification #
#############################
s/while /while (/g;
s/done/}/g;
s/ do/) {/g;
###########
# cleanup #
###########
s/ +$//g; # remove trailing spaces
s/$/;/; # append semicolons to generate valid C
} continue {
$code[$lines++] = $_;
}
print @variables;
print "\n";
print @code;
print "int main(int argc, char **argv) {\n";
print " return (int) rk(argv);\n";
print "}\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment