Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

C compiler ... in Perl

by rje (Deacon)
on Jan 05, 2004 at 22:43 UTC ( [id://318966]=perlquestion: print w/replies, xml ) Need Help??

rje has asked for the wisdom of the Perl Monks concerning the following question:

I had the idle thought that it would be possible to write a C compiler in Perl. Or even a C interpreter... now that's a scary thought. I didn't notice any modules like that on CPAN, however. But that seems like the kind of sick, twisted exercise that some perl hacker out there would have already tried... any info, anyone?

Replies are listed 'Best First'.
Re: C compiler ... in Perl
by samtregar (Abbot) on Jan 06, 2004 at 00:04 UTC
    Check out Inline::ASM. It should be no big deal to parse C code and use it to generate assembly. I mean, if the authors of GCC can do it, why not you?

    You might also be interested in HTML::Template::JIT. It's a just-in-time compiler that generates C code from HTML::Template templates. It uses Inline::C to compile the C code on the fly. The result is the fastest templating system known to (this) man.

    -sam

Re: C compiler ... in Perl
by jdtoronto (Prior) on Jan 06, 2004 at 03:24 UTC
    Sick and twisted? Nah! Just lots and lots of fun.

    It is a dream, and a wonderful challenge. Back in the early days (I am 50 now) in mid-1974 I heard about the Intel 8080 and set about acquiring a chip. In the meantime, from the early Intel documents I wrote a cross assembler to produce code for it on an Interdata 70 mini.

    Go and find some books on compiler design and get into it!

    My current favourite hobby project is replicating the Interdata using an Altera EPF10K250A EPLD device. It is about 95% functional, we are just finishing the interface to an original 8k word core memory plane. Using static memory with battery keep-alive we have been able to run our 1974 8080 cross-assembler and produce runnable code that executed on an 8080 emulator.

    It may not be efficient, but projects like this are great learning tools. Good luck and have lots of fun!

    jdtoronto

Re: C compiler ... in Perl
by Corion (Patriarch) on Jan 06, 2004 at 07:37 UTC

    I'm currently embarking on a similar twisted path, by creating a parser/compiler for Javascript. It is actually easy to do with the tools that Perl provides, as long as you're not afraid to use Parse::Yapp, a yacc for Perl.

    A yacc grammar for C should be found in every corner, the rest is where the fun is...

    perl -MHTTP::Daemon -MHTTP::Response -MLWP::Simple -e ' ; # The $d = new HTTP::Daemon and fork and getprint $d->url and exit;#spider ($c = $d->accept())->get_request(); $c->send_response( new #in the HTTP::Response(200,$_,$_,qq(Just another Perl hacker\n))); ' # web
Re: C compiler ... in Perl
by liz (Monsignor) on Jan 05, 2004 at 23:48 UTC
    If you're looking to be able to run C-programs like you run Perl, i.e. you change the code and then just execute the "script", you might want to have a look at Inline::C. I recall it even having a special script that you could use as a shebang in your script, but I somehow can't find that anymore.

    But since you can eval C-code at runtime, that shouldn't be too hard a feat to do yourself.

    Liz

Re: C compiler ... in Perl
by exussum0 (Vicar) on Jan 05, 2004 at 23:41 UTC
    Hmm... well.. even a c style script interpreter isn't hard. Every type would map to a composite type that has a value, or null.. all the functions are easy to map. Then you take said interpreter and make it write out byte code in a 2-pass fashion, write out the ASM. It'd be easier than writing it in ASM, but a hella lot slower :)

    Take a class in compiler construction.


    Play that funky music white boy..
Re: C compiler ... in Perl
by jonadab (Parson) on Jan 06, 2004 at 13:59 UTC

    If you want to do this the insane twisted way, start by writing a C => Perl translator and running gcc through it. The result will be a horrific mess (though if your translator is right it should actually work, albeit quite inefficiently), which you can then proceed to attempt to clean up by hand, a little at a time. The disadvantages of this approach should be obvious; the advantage is that, although your compiler will be slow, its output will be just fine.

    Doing a project like this will not only teach you a lot, it will also get you a lot of strange looks when you tell people about it.


    $;=sub{$/};@;=map{my($a,$b)=($_,$;);$;=sub{$a.$b->()}} split//,".rekcah lreP rehtona tsuJ";$\=$ ;->();print$/
Re: C compiler ... in Perl
by ambrus (Abbot) on Jan 06, 2004 at 10:57 UTC
    Consider looking very small (and incomplete) C compilers at http://www.ioccc.org. There's an interpreter, and a real (i386) compiler.
Re: C compiler ... in Perl
by Tommy (Chaplain) on Jan 06, 2004 at 00:08 UTC
    oh, wow. that _is_ sick and twisted ;-)
    --
    Tommy Butler, a.k.a. TOMMY
    

      No, sick and twisted would be if he wanted to implement a C interpreter in Unlambda or PostScript. Implementing it in Perl is actually fairly sensible.


      $;=sub{$/};@;=map{my($a,$b)=($_,$;);$;=sub{$a.$b->()}} split//,".rekcah lreP rehtona tsuJ";$\=$ ;->();print$/

        (Maybe someone should translate TeX to PostScript, then you could just send TeX input to a PostScript printer, and it would do all the work of typesetting.)

Re: C compiler ... in Perl
by melora (Scribe) on Jan 06, 2004 at 17:37 UTC
    I have recently written in Perl an interpreter for Another Language (an old process control language). The original interpreter runs on old dec hardware, and I wanted to write a version that would allow for testing code on a PC. By the way, it runs so much faster under FreeBSD than Win98 that I had to check to make sure it was really doing it. Yeah, the "went by me so fast I got out to see why I stopped" joke really applies. It is not an exact thing; it uses files to hold the states of variables and of I/Os and timers, so you couldn't really run a plant with it, but it allows testing code (and snippets of code). I did have to confront the nested parentheses, etc., and I did use eval(). My code would probably look very ugly to a real Perl practitioner, but it seems to work well enough, and I can understand it enough to maintain it.
    So I think there are reasons to write a compiler or interpreter in Perl. I must agree that there isn't really a *need* for another C compiler. But writing it for a learning experience is justification for it, in my opinion.
Re: C compiler ... in Perl
by Abigail-II (Bishop) on Jan 05, 2004 at 23:01 UTC
    It's certainly possible. But I don't think anyone tried. It seems like a lot of work without a very useful result.

    Abigail

      The knowledge that comes with writing a compiler seems to be a very useful result. Having a compiler written in a very high level language that allows more people to understand how compilers work seems like a very useful result. Starting a possibly successful large-scale project in Perl seems like a very useful result.

      Discouraging someone from doing something useful doesn't seem like a very useful result. So what's the point of your comment?

        So why not write a Java compiler? Or a brainfuck compiler? There are easier ways to learn about writing compilers. Writing yet another C compiler doesn't seem that useful even if you learn something about writing compilers. You want to see a compiler written in a high level language take a look at D.
        I agree completely. I've been toying off and on (lately on) with my own language that has a syntax between Perl and Lisp. It has scalars, lists and hashes.

        Writing the parser has been quite challenging. Figuring out how to create the parse tree, optimize it (constant folding, etc) has been good for keeping my skills sharp and looking at problems in a different light.

        Sure I could have started with a book on compilers and read up on lex and yacc, but solving it from the ground up, in my mind, has taught me a lot more than just following some book. Not to say there is anything wrong with that. When I get it to a more stable state, I'll probably do exactly that. Go back and see what was done right and what things I didn' figure out.

        -Lee

        "To be civilized is to deny one's nature."
      A potential benefit could be that a C-compiler isn't necessary to compile Perl's C modules (kind of Escherlike, eh?). But of course there are freely available C compilers for most platforms (I had temporarily forgotten about the beauty of Cygwin), so oh well...
Re: C compiler ... in Perl
by dominix (Deacon) on Jan 06, 2004 at 11:21 UTC
      How come? Parrot seems to be a runtime environment targeted at dynamic languages. C is a lot, but it's not dynamic, it's quite static.

      Abigail

        well, you're right, but parrot already have a BASICcompiler/interpreter, so why not C.
        --
        dominix
Re: C compiler ... in Perl
by gmpassos (Priest) on Jan 07, 2004 at 00:11 UTC
    See Parrot, actually, make a C parser for Parrot. Will be very interesting to have C interpreted by Parrot, since there isn't any plans for that yet.

    But I'm thinking, how you will handle alredy compiled codes, specially libraries? C is used not only because it can be compiled in any OS, but because we can use a lot of libraries/includes that are already done and because it can work directly with the OS, soo we can do anything with it. (and you will need to rewrite a lot of code... Argh!)

    But I understand that for now your idea has an educational purpose, and I give you the best luck with it. Maybe we will have the 1st real C interpreted (not a fake C ok!). ;-P

    About Parrot, take a look, we can do anything with it (or will), since it has an great architecture and it's a really good VM.

    http://www.parrotcode.org/ (Get involved!)

    And don't forget that one of the plans of Parrot is to can convert a code to another through Parrot Assembly Code. Soo, from a C code I can automatically convert it to Perl, Java, etc... Or from Perl to C!

    Thinking now, adding a C interpreted to Parrot will open an option to can automatically convert Perl codes to C and then use this to compile it as a normal C code. But this will only be possible if you keep your C interpreter compatible with gcc definitions!

    Graciliano M. P.
    "Creativity is the expression of the liberty".

Re: C compiler ... in Perl
by Roger (Parson) on Jan 05, 2004 at 22:56 UTC
    Did you have a look at the B:: suite of modules?

      Did you have a look at them? They have nothing to do with building a C compiler!

      -sam

        Yes I have not only looked at but also used them.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://318966]
Approved by Roger
Front-paged by broquaint
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (3)
As of 2024-04-25 10:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found