Skip to content

Instantly share code, notes, and snippets.

@takehiko
Created April 24, 2014 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takehiko/11269137 to your computer and use it in GitHub Desktop.
Save takehiko/11269137 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
# Makes a "Hello, world!" program that has no literals.
class HelloWorldGenerator1
def initialize(s = "Hello, world!")
@message = s.chomp + "\n"
end
def start
binfile = "hw"
srcfile = binfile + ".c"
open(srcfile, "w") do |f_out|
f_out.puts <<'EOS'
#include <stdio.h>
int c;
main(void)
{
EOS
c = 0
@message.each_char do |chr|
new_c = chr.ord
if new_c > c
(new_c - c).times { f_out.puts " c++;"}
elsif new_c < c
(c - new_c).times { f_out.puts " c--;"}
end
f_out.puts " putchar(c);"
c = new_c
end
f_out.puts <<'EOS'
}
EOS
end
command = "cc -o #{binfile} #{srcfile}"
puts command
system(command)
command = "./#{binfile}"
puts command
system(command)
end
end
class HelloWorldGenerator2
def initialize(s = "Hello, world!")
@message = s.chomp
end
def start
binfile = "hw"
srcfile = binfile + ".c"
open(srcfile, "w") do |f_out|
f_out.puts <<'EOS'
#include <stdio.h>
int o;
int a, b, c, d, e, f, g, h;
int main(void)
{
h++;
g = h + h;
f = g + g;
e = f + f;
d = e + e;
c = d + d;
b = c + c;
a = b + b;
EOS
vars = "abcdefgh".split(//)
@message.each_char do |chr|
expr = ("%08b" % chr.ord).
split(//).zip(vars).map {|b, v| b == "1" ? v : nil}.
compact.join(" + ")
expr = "o" if expr.empty?
f_out.puts " putchar(#{expr});"
end
f_out.puts <<'EOS'
puts((char *)&o);
return o;
}
EOS
end
command = "cc -o #{binfile} #{srcfile}"
puts command
system(command)
command = "./#{binfile}"
puts command
system(command)
end
end
class HelloWorldGenerator < HelloWorldGenerator2; end
if __FILE__ == $0
HelloWorldGenerator.new(ARGV.shift || "Hello, world!").start
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment