Top Level Namespace

Defined Under Namespace

Modules: Generator, Lexer, Parser, SpecialGiggle

Instance Method Summary collapse

Instance Method Details

#mainObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/special-giggle/main.rb', line 7

def main
  ARGV << "-h" if ARGV.empty?

  options = Hash.new
  OptionParser.new do |opts|
    opts.banner = "Usage: ruby main.rb [options]"

    opts.separator ""
    opts.separator "Specific options:"

    opts.on("-f FILE", "--file", String, "Input from file (required)") do |f|
      options[:file] = f
    end

    opts.on("-t LANG", "--target", String, "Target language - C, Assembly (default C)") do |t|
      options[:lang] = t
    end

    opts.on("-o FILE", "--output", String, "Output to file (default: stdout)") do |o|
      options[:output] = o
    end

    opts.on_tail("-h", "--help","Show this message") do
      puts opts
      exit
    end
  end.parse!

  abort("Missing input file. Abort.") if options[:file].nil?
  abort("File not found. Abort.") unless File.file?(options[:file])

  options[:lang] ||= "C"
  lang = case options[:lang].downcase
         when "c"
           :C
         when "assembly"
           :S
         else
           abort("Language not supported. Abort.")
         end

  # Read program
  program = File.read(options[:file])

  # Lexing
  lexer = Lexer.new
  tokens = lexer.tokenize(program)

  # Parsing
  parser = Parser.new
  ast = parser.parse(tokens)

  # Code Generator
  generator = Generator.new
  code = generator.generate(ast, lang)

  if options[:output]
    File.write(options[:output], code)
  else
    puts code
  end
end