Class: Preprocessor

Inherits:
Object show all
Defined in:
ext/rubypp.rb

Instance Method Summary collapse

Constructor Details

#initialize(input, output, filename) ⇒ Preprocessor

Returns a new instance of Preprocessor.



2
3
4
5
6
7
# File 'ext/rubypp.rb', line 2

def initialize(input, output, filename)
  @input = input
  @output = output
  @filename = filename
  @linenum = 1
end

Instance Method Details

#evaluate(str, linenum) ⇒ Object



61
62
63
64
65
# File 'ext/rubypp.rb', line 61

def evaluate(str, linenum)
  result = eval(str, TOPLEVEL_BINDING, @filename, linenum)
  success = true
  return result
end

#getlineObject



9
10
11
12
13
# File 'ext/rubypp.rb', line 9

def getline
  line = @input.gets
  @linenum += 1 if not line.nil?
  return line
end

#preprocessObject



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
# File 'ext/rubypp.rb', line 15

def preprocess
  success = false
  begin
    loop do
      line = getline
      break if line.nil?
      case line
      when /(.*[^\\]|^)\#\{(.*?)\}(.*)/
        puts "#{$1}#{evaluate($2, @linenum)}#{$3}"
      when /^\#ruby\s+<<(.*)/
        marker = $1
        str = ''
        evalstart = @linenum
        loop do
          line = getline
          if line.nil? then
            raise "End of input without #{marker}"
          end
          break if line.chomp == marker
          str << line
        end
        result = evaluate(str, evalstart)
        puts result if not result.nil?
      when /^\#ruby\s+(.*)/
        str = line = $1
        while line[-1] == ?\\
          str.chop!
          line = getline
          break if line.nil?
          line.chomp!
          str << line
        end
        result = evaluate(str, @linenum)
        puts result if not result.nil?
      else
        puts line
      end
    end
    success = true
  ensure
    if not success then
      $stderr.puts "Error on line #{@linenum}:"
    end
  end
end

#puts(line) ⇒ Object



67
68
69
# File 'ext/rubypp.rb', line 67

def puts(line)
  @output.puts(line)
end