Writing ruby to [LANGUAGE] "compiler"

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?

Use a parser. There is ruby_parse gem, just perfect for the occasion.

I’ve once tried to create something similar:
https://github.com/MatmaRex/crude - examples included.

– Matma R.

On 12/17/2011 8:31 AM, Marc H. wrote:

You use only a small subset of Ruby.

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?

see

  1. ruby2c
  2. ruby2cextension

On 12/17/2011 8:31 AM, Marc H. wrote:

You use only a small subset of Ruby.

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?

also see
3) RubyToC

On Sat, Dec 17, 2011 at 6:35 PM, Reid T. [email protected]
wrote:

in those classes. No metaprogramming, no blocks etc…

  1. RubyToC
  1. cast_off

On Sat, Dec 17, 2011 at 7:31 AM, Marc H. [email protected]
wrote:

You use only a small subset of Ruby.

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–Milner 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:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs