On Sat, Dec 17, 2011 at 7:31 AM, Marc Heiler <shevegen / linuxmail.org> wrote:

> Hi.
>
> Say I write something in Ruby. Then I want to translate this code
> into C.
>
> I do not aim for 100% translation. 60% is sufficiently well.
>
> For instance, think you are using only classes, and "def method"
> in those classes. No metaprogramming, no blocks etc...
>
> You use only a small subset of Ruby.
>
> And now you want to translate this into C. (Pure C, not Ruby-C).
>
> I can do this by hand (if given enough time), but I want to reduce
> this amount spent.
>
> The language C is just an example. You can insert any-other language
> into this.
>
> My question is - how to approach this goal?
>
> My most simple way would be via using readlines of the .rb file
> and then analyzing it. And then inserting what seems appropriate.
>
> But I could do this without the use of a scanner.
>
> Do I have to use a scanner though and tokenize the stream?
>
> --
> Posted via http://www.ruby-forum.com/.
>
>
You'd probably need to build a lexer/parser that can understand this subset
of C. I've never successfully built a parser, it's hard, but check out gems
like Treetop and Citrus. They should allow you to build an abstract syntax
tree that represents the code. Then you'll probably have to analyze the AST
to do some sort of type determining (ie if I pass it a string, then I know
its argument has type of string) check out
http://en.wikipedia.org/wiki/Hindley%E2%80%93Milner for that purpose. Once
you've got all of that, just write it back out, only when writing it out,
use the C syntax instead of the Ruby syntax.

Other thoughts:
* Racc might also be useful, but looked pretty formidable to me when I
tried to play with it.
* There is an ebook
http://gilesbowkett.blogspot.com/2010/07/review-create-your-own-freaking-awesome.htmlthat
might help. I wasn't able to figure out how to do anything more
complex than the provided example, though.
* This (http://www.bayfronttechnologies.com/mc_tutorial.html) also looked
promising to me, it was recommended in a talk by Alan Kay, but I haven't
tried to go through it yet.