moo2coldc.gz

snippets · 4.8 KB · 2010-03-30

MOO to ColdC converter 2.0 in Perl.

Download   « Back to the snippets list

#!/usr/local/bin/perl
#
# todo: check var names against reserved words (like 'where')
#
##
## MOO -> ColdC convertor, version 2.0
##
## NOTE: THIS DOES NOT PRODUCE COMPLETE OUTPUT, it is intended that this
## be used as a tool to supplement conversion of MOO code to ColdC.
## Because of inherent differences in MOO and ColdC you must read over
## the output and tweak things appropriately.  Keep a close eye on
## object varaibles (MOO Properties).  Encapsulation in ColdC causes
## Conversion to be rather odd.  Commands are also not considered as of
## this release
##
##
## Syntax: moo2coldc file.moo
##
## will read from the .moo file, which should be in the MOO object @dump
## format.  Conversion notes will go to stdout, output will go to
## file.cdc
#
# This script was hacked together by a bored Brandon Gillespie
#     sometime around the beginning of September, 1995.
#
# Brandon Later revised it December 7 1997--at this rate we can expect
#     a decent convertor around the 3020
#

require 5.002;

$infile = $ARGV[0] || die("Syntax: $0 FILENAME\n");
$outfile = $infile;
$outfile =~ s/\.moo//;
$outfile .= ".cdc";
print <<END;
Input file:  $infile
Output file: $outfile
END
print "[RETURN TO CONTINUE]";
<STDIN>;
open(OUT, ">$outfile") || die("open('>$outfile'): $!\n");
open(INPUT, $infile) || die("open('$infile'): $!\n");
$objnum = "";
$infile =~ /^([a-z0-9_]+)/;
$objname = $1;
@wait = ();
$firstnum = 0;
$command_str = "";

sub cmsg {
   my $msg = $_[0];
   $msg =~ s/\"/'/g;
   print STDERR "$msg\n";
}
$cmsg = "  // CONVERSION NOTE:";

$verb = 0;
%objvars = ();
%props = ();
%prot = ("parameters", 1, "methods", 1, "code", 1);
%renamed = ();
%reserved = (
    "any" => 1,
    "arg" => 1,
    "break" => 1,
    "case" => 1,
    "catch" => 1,
    "continue" => 1,
    "default" => 1,
    "disallow_overrides" => 1,
    "else" => 1,
    "filter" => 1,
    "find" => 1,
    "for" => 1,
    "fork" => 1,
    "handler" => 1,
    "hash" => 1,
    "if" => 1,
    "in" => 1,
    "map" => 1,
    "pass" => 1,
    "return" => 1,
    "switch" => 1,
    "to" => 1,
    "var" => 1,
    "where" => 1,
    "while" => 1,
    "with" => 1);

%parents = ('$root_class', '$root');
%errors = ("none"      => "No error",
           "type"      => "Type mismatch",
           "div"       => "Division by zero",
           "perm"      => "Permission denied",
           "propnf"    => "Property not found",
           "verbnf"    => "Verb not found",
           "varnf"     => "Variable not found",
           "invind"    => "Invalid indirection",
           "recmove"   => "Recursive move",
           "maxrec"    => "Too many verb calls",
           "range"     => "Range error",
           "args"      => "Incorrect number of arguments",
           "nacc"      => "Move refused by destination",
           "invarg"    => "Invalid argument",
           "quota"     => "Resource limit exceeded");


while (<INPUT>) { 
    if (!$firstnum) {
        if (/(#[0-9]+)/) {
            $objnum = $1;
            $firstnum = 1;
            print STDERR "Found objnum $objnum, specify objname to use";
            if (length($objname)) {
                print " [\$$objname] ";
            } else {
                print ": ";
            }
            chomp($oname = <STDIN>);
            $oname =~ s/^\s+//;
            $oname =~ s/^\$//;
            $oname =~ tr/[A-Z]/[a-z]/;
            if (!$oname) {
                if (!length($objname)) {
                    die("You must specify the objname to use\n");
                }
                $oname = $objname;
            } else {
                $objname = $oname;
            }
            $oname =~ s/[^a-z0-9_]+//;
            if ($oname ne $objname) {
                die("Invalid objname '\$$objname'\n");
            }
            $objname = "\$$objname";
            s/$objnum/$objname/g;
        } else {
            push(@wait, $_);
            next;
        }
    } else {
        s/$objnum/$objname/g;
    }
    s/#([0-9]+)/#-$1/g;
    $inline = $_;

    while ($#wait != -1) {
        &process_line(shift(@wait));
    }

    &process_line($inline);
}

sub process_line {
    my $line = $_[0];
    $_ = $line;

    if (!$verb) {
        if (/^\@chmod\s+([#\$0-9a-z_]+):(.*)\s*([rxd]*)$/) {
            # command x=method, !x=command, r=['code], !r=[]
            $perms = $3;
            ($perms !~ /r/) && (delete($prot{code}));
        } elsif (/^\@args\s+([#\$0-9a-z_]+):(.*)/) {
            $obj = $1;
            $rest = $2;
            if ($rest =~ /"/) {
                if ($rest =~ /"([^"]+)"\s+(.*)$/) {
                    $name = $1;
                    $args = $2;
                } else {
                    die("Unable to figure \@arg syntax:\n\t'$rest'\n");
                }
            } else {
                if ($rest =~ /([^\s]+)\s+(.*)$/) {
                    $name = $1;
                    $args = $2;
                } else {
                    die("Unable to figure \@arg syntax:\n\t'$rest'\n");
                }
            }
            $name =~ s/\*/?/g;
            $name =~ s/\s+/|/g;
            if ($args =~ /^(any|none) (any|none) (any|none)$/) {
                $command_str = "$name <any>";
            } elsif ($args ne "this none this") {
                $args =~ s/([^ ]+) +([^ ]+) +([^ ]+)/<$1> $2 <$3>/g;
                $command_str = "$name $args";
            }
        } elsif (/^\@prop\s+([#\$0-9a-z_]+)\.\"([0-9a-z_]+)\"\s*([{}"0]+)\s*([rc]+)/) {
            $obj = $1;
            $param = $2;
            ($param =~ /_msg$/) && next;
            $data = &moo_2_coldc($3);
            $perms = $3;
            ($perms !~ /r/) && (delete($prot{parameters}));
            ($perms !~ /c/) && 1;   # dunno what to do
            print OUT "\@av $1,$2 $data\n";
        } elsif (/^\@create\s*(.*)/) {
            @words = split(/ /, $1);
            $parent = $words[0];
            if ($parents{$parent}) {
                $parent = $parents{$parent};
            }
            $name = join(" ",@words[2..$#words]);
            @name = split(/:/, $name);
            print OUT "\@spawn $parent named $objname\n";
            if (length($name[1])) {
                print OUT "\@rename $objname $name[1]\n";
            }
        } elsif (/^\;+([#\$0-9a-z_]+)\.\(\"([0-9a-z_]+)\"\)\s*=\s*(.*)/) {
            $obj = $1;
            $name = $2;
            ($name eq "aliases") && next;
            ($name eq "corified_as") && next;
            ($name eq "webhits") && next;
            ($name eq "object_size") && next;
            $val = &moo_2_coldc($3);
            $key = "$obj,$name";
            if (exists($obvars{$key})) {
                print STDERR "Collision: two obj vars, same name, eek\n";
            }
            $objvars{$key} = 1;
            print OUT "\@av ${obj},${name} = $val\n";
        } elsif (/^\@program\s*(.*)/) {
            if (/([#\$][0-9a-z_]+):(.*)/i) {
                $obj = $1;
                $meth = $2;
                $chng = $meth;
                $chng =~ s/-/_/g;
                $chng =~ s/\(old\)/__old/g;
                if ($chng =~ s/\@//g) {
                    $chng .= "_cmd";
                }
                if (length($command_str)) {
                    print OUT "\@ac \"$command_str\" $objname.$chng()\n";
                }
                $command_str = "";
                $chng =~ s/[^a-z0-9_]+//gi;
                print OUT "\n";
                if ($chng ne $meth) {
                    if (exists($renamed{$meth})) {
                        print STDERR "Collision: two verbs, same name, eek\n";
                    }
                    $renamed{$meth} = $chng;
                    &cmsg("Method name changed, was '$meth'");
                    $meth = $chng;
                }
                print OUT "\@program $obj.$meth\n";
            } else {
                &cmsg("Unable to handle method name, you fix it!");
                print OUT;
            }
            $verb++;
        } elsif (/^@([0-9a-z_]+)\s+([#\$0-9a-z_]+)\s+is\s+(.*)/) {
            print OUT ";$2.add_message('$1)\n";
            # eventually create a MOO->ColdC message converter
            print OUT ";$2.set_message('$1, $3, $2)\n";
        }
    } else {
        # D'oh, no more verb code.
        if (/^.$/) {
            $verb = 0;
            &convert_verb(*code);
            @code = ();
            print OUT ".\n";
            next;
        } else {
            @code = (@code, $_);
        }
    }
}

@code_lines = ();
sub convert_verb {
    local(*code) = @_;
    local(%vars, $line, $v, $count, $keys);

    # first pass...
    %vars = ("argstr" => 1);
    for (@code) {
        $line = $_;
        if ($line =~ /^\s*for\s+([a-z0-9_]+)\s+/) {
            $vars{$1} = 1;
        } else {
            while ($line =~ /([a-z_\*\.]+)\s+=\s+/i) {
                $v = $1;
                if ($v =~ /\./) {
                    $s = $v;
                    $s =~ s/\./,/;
                    $props{$v} = 1;
                } else {
                    $vars{$v} = 1;
                }
                $line =~ s/([a-z_\*\.]+)\s*=\s*//i;
            }
        }
    }

    %bad = ();
    $count = 0;

    print OUT "    arg args;\n    var " . join(", ", sort keys(%vars)) . ";\n";
     
    for (sort keys(%vars)) {
        if (exists($reserved{$_})) {
            $bad{$_} = 1;
        }
    }
    for (sort(keys(%bad))) {
       print OUT "$cmsg Local variable '$_' is a reserved word!\n";
    }
    print OUT "    argstr = join(args);\n";

    # line-by-line conversions
    @code_lines = ();
    for (@code) {
        chomp;
        push(@code_lines, &moo_2_coldc($_));
    }
    print OUT join("\n", @code_lines) . "\n";
}

sub moo_2_coldc {
    local($_) = @_;

    # get comments out of the way...
    if (/^(\s*)"(.*)";\s*$/) {
        $ind = $1;
        $msg = $2;
        $msg =~ s/^\s+//;
        return "$ind// $msg";
    }

    # error conversion
    if (s/E_([A-Z]+)/~$1/) {
        $error = $1;

        ## we need a throw..
        if (/^\s*return\s+~/) {
            # random things... see if the previous line was a 'tell'
            $error =~ tr/[A-Z]/[a-z]/;
            $prev = $code_lines[$#code_lines];
            /^(\s*)/;
            $ind = $1;

            if ($prev =~ /^\s*[#\$]?[a-z0-9_]+(\(\))?.tell\(([^\)]+)/i) {
                pop(@code_lines);
                $msg = $2;
                if (substr($msg, 0, 1) ne '"') {
                    $msg =~ s/, "/ + "/g;
                    $msg =~ s/", /" + /g;
                }
                return "${ind}throw(~$error, $msg);";
            } elsif (exists($errors{$error})) {
                return "${ind}throw(~$error, \"$errors{$error}\");";
            } else {
                return "${ind}throw(~$error, \"Unknown MOO translated error\");";
            }
        }
    }

    # oof, fix 'var = var + ..'
    if (/([a-z0-9_]+) = ([a-z0-9_]+) ([+*\/-]) /) {
        if ($1 eq $2) {
            s/([a-z0-9_]+) = ([a-z0-9_]+) ([+*\/-]) /$1 $3= /;
        }
    }

    # nasty ucky 'player' global
    s/player([.:])/user()$1/g;

    # Fix lists first...
    s/\{/[/g;
    s/\}/]/g;

    # if we know it will only match once, continue
    (s/^(\s*)else$/$1} else {/) && (return $_);
    (s/^(\s*)(endif|endfor|endwhile)/$1}/) && (return $_);

    # fix 'this'
    s/this:/./g;
    s/this\.//g;
    s/([^a-z_\*])this([^a-z_\*])/${1}this()${2}/g;

    # perms
    s/caller_perms\(\)\s*..?\s*owner/.perms(caller())/;

    # change obj:verb to obj.method; fix props by making them methods
    s/([#\$0-9a-z_)\]]+)\.([a-z_]+)/$1.$2()/gi;
    s/([#\$0-9a-z_)\]]+):([a-z_(]+)/$1.$2/gi;

    #############################
    # do common verb/method conversions

    ## handle tells and announces, hope there isn't anything too nested
    if (/.(tell|announce|announce_all)\(/) {
        $changed = 0;
        s/, "/ + "/g && $changed++;
        s/", /" + /g && $changed++;
        if ($changed) {
            push(@code_lines, "$cmsg the following line may have problems");
            push(@code_lines, "$cmsg ,..,.. was converted to +..+..");
        }
    }

    #############################
    #############################
    # do basic function conversions...
    s/(^|[^a-z0-9_])typeof\(/$1type\(/g;
    s/(^|[^a-z0-9_])tonum\(/$1toint\(/g;
    s/(^|[^a-z0-9_])length\((.*?)\)/$1$2.length()/g;
    s/(^|[^a-z0-9_])rindex\((.*?)\)/$1stridx($2, -1)/g;
    s/(^|[^a-z0-9_])index\((.*?)\)/$1stridx($2)/g;
    s/(^|[^a-z0-9_])match\(/$1match_regexp(/g;
    s/(^|[^a-z0-9_])rmatch\(/$1match_regexp(/g;
    s/(^|[^a-z0-9_.])substitute\((.*?),\s*(.*)\)/$1$2.regexp($3)/g;
    s/(^|[^a-z0-9_])listinsert\(/$1insert(/g;
    s/(^|[^a-z0-9_])listappend\((.*?),\s*(.*)\)/$1$2 + [$3]/g;
    s/(^|[^a-z0-9_])listdelete\(/$1delete(/g;
    s/(^|[^a-z0-9_])listset\(/$1replace(/g;
    s/(^|[^a-z0-9_])chparent\((.*?),\s*(.*)\)/$1$2.chparents($3)/g;
    s/(^|[^a-z0-9_])parent\((.*?)\)/$1$2.parents()/g;
    s/(^|[^a-z0-9_])children\((.*?)\)/$1$2.children()/g;
    s/(^|[^a-z0-9_])recycle\(/$1destroy(/g;
    s/(^|[^a-z0-9_])max_object\(/$1next_dbref(/g;
    s/(^|[^a-z0-9_])move\((.*?)\)/$1$2.move_to()/g;
    s/(^|[^a-z0-9_])properties\((.*)\)/$1.parameters()/g;
    s/(^|[^a-z0-9_])verbs\((.*)\)/$1.methods()/g;
    s/(^|[^a-z0-9_])verb_code\((.*?),\s*(.*)\)/$1$2.list_method($3)/g;
    s/(^|[^a-z0-9_])is_player\((.*)\)/$1.is(\$user)/g;

    ## nix any redundant/broken lib calls
    s/\$[a-z0-9_]+_utils\.([a-z0-9_]+)\./$1./g;

    ## ''rename'' any other util/lib calls
    s/\$(string|list)_utils\./\$$1./g;
    s/(\$[a-z]+)_utils\./$1_lib./g;

    ## *sigh*
    s/(^|[^a-z0-9_])connected_players\(\)/$1\$user_db.connected()/g;

    # structured statements
    s/^(\s*)if\s+\((.*)\)\s*/${1}if ($2) {/;
    s/^(\s*)elseif\s+\((.*)\)/${1}} else if ($2) {/;
    s/^(\s*)while\s+\((.*)\)\s*/${1}while ($2) {/;
    if (!s/^(\s*)for\s+([a-z0-9_]+)\s+in\s+(\(.*\))\s*$/$1for $2 in $3 {/ &&
        !s/^(\s*)for\s+([a-z0-9_]+)\s+in\s+(\[.*\])\s*$/$1for $2 in $3 {/) {
        # handle subrange syntax, this doesn't get assignment subranges
        s/([a-z0-9_]+)\[([^.]+)\.\.([^]]+)\]/${1}.subrange(${2}, ${3})/gi;
    }

    # fix property references on other objs,
    # just make them function calls
    s/([a-z0-9_]+|\)|\])\.([a-z0-9_]+)([^(a-z0-9_])/$1.$2()$3/g;

    ## try to get assign to subranges
    if (/^(\s*)([a-z0-9_]+)\[([^]]+)\] = (.*);\s*$/) {
        return "$1$2 = replace($2, $3, $4);";
    } else {
        return $_;
    }
}

%bad = ();
for (sort(keys(%objvars))) {
    if (exists($reserved{$_})) {
        $bad{$_} = 1;
    }
    if (exists($props{$_})) {
        delete($props{$_});
    }
}

@keys = keys(%props);
if ($#keys > -1) {
    &cmsg("Referenced and possibly undefined parameters:");
    for (sort @keys) {
        if (exists($reserved{$_})) {
            $bad{$_} = 1;
        }
        s/\./,/g;
        &cmsg("     $_");
    }
}

@keys = keys(%prot);
if ($#keys > -1) {
    &cmsg("Object Protection:");
    for (sort @keys) {
        &cmsg("     '$_");
    }
}

@keys = keys(%renamed);
if ($#keys > -1) {
    &cmsg("Renamed the following methods:");
    for (sort @keys) {
        &cmsg(sprintf("     :%-30s=> .$renamed{$_}", $_));
    }
}

close(OUT);
close(INPUT);

Site Stats

Snippets: 1791
Codebases: 571