Class: MixCompiler

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby/compiler.rb

Overview

Copyright © 2011-2012 Jesse Sielaff

Instance Method Summary collapse

Constructor Details

#initializeMixCompiler

Returns a new instance of MixCompiler.



7
8
9
10
11
12
# File 'lib/ruby/compiler.rb', line 7

def initialize
  @precompiler = MixPrecompiler.new
  @tokenizer = MixTokenizer.new
  @parser = MixParser.new
  @translator = MixTranslator.new
end

Instance Method Details

#combine_strings(js_string, ast_string, symbol_string) ⇒ Object



14
15
16
17
18
# File 'lib/ruby/compiler.rb', line 14

def combine_strings (js_string, ast_string, symbol_string)
  js_string
    .sub(%%'...Replace with AST nodes...'%, ast_string)
    .sub(%%'...Replace with symbol table...'%, symbol_string)
end

#compile_to_file(absolute_mix_path) ⇒ Object



20
21
22
23
# File 'lib/ruby/compiler.rb', line 20

def compile_to_file (absolute_mix_path)
  js_output_string = compile_to_string(absolute_mix_path)
  write_js_file(absolute_mix_path, js_output_string)
end

#compile_to_string(absolute_mix_path) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/ruby/compiler.rb', line 25

def compile_to_string (absolute_mix_path)
  mix_files, js_string = precompile_js(absolute_mix_path)
  mix_tokens = tokenize_mix_files(mix_files)
  mix_node = parse_token_stream(mix_tokens)
  ast_string, symbol_string = translate_to_js(mix_node)
  js_output_string = combine_strings(js_string, ast_string, symbol_string)
  
  return js_output_string
  
rescue SyntaxError => e
  "window.onload = function () { if (console && console.log) console.log(\"SyntaxError: #{e.message}\"); };"
end

#parse_token_stream(mix_tokens) ⇒ Object



38
39
40
# File 'lib/ruby/compiler.rb', line 38

def parse_token_stream (mix_tokens)
  @parser.parse(mix_tokens)
end

#precompile_js(absolute_mix_path) ⇒ Object



42
43
44
# File 'lib/ruby/compiler.rb', line 42

def precompile_js (absolute_mix_path)
  @precompiler.precompile(absolute_mix_path)
end

#tokenize_mix_files(mix_files) ⇒ Object



46
47
48
49
50
# File 'lib/ruby/compiler.rb', line 46

def tokenize_mix_files (mix_files)
  mix_files.each_with_object([]) do |(filename, script), tokens|
    @tokenizer.tokenize(filename, script, tokens)
  end
end

#translate_to_js(node) ⇒ Object



52
53
54
# File 'lib/ruby/compiler.rb', line 52

def translate_to_js (node)
  @translator.translate(node)
end

#write_js_file(absolute_mix_path, js_output_string) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/ruby/compiler.rb', line 56

def write_js_file (absolute_mix_path, js_output_string)
  filename = File.basename(absolute_mix_path, '.mix') + '.js'
  absolute_js_path = File.expand_path(filename, File.dirname(absolute_mix_path))
  
  File.open(absolute_js_path, 'w') {|f| f.write(js_output_string) }
  puts "Writing to #{filename}"
end