Class: Basic101::Program

Inherits:
Object
  • Object
show all
Includes:
Identity, Enumerable
Defined in:
lib/basic101/program.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Identity

#==

Constructor Details

#initialize(lines = []) ⇒ Program

Returns a new instance of Program.



32
33
34
35
36
37
38
39
40
41
# File 'lib/basic101/program.rb', line 32

def initialize(lines = [])
  @statements = []
  @line_number_index = {}
  lines.each do |line|
    @line_number_index[line.line_number] = @statements.size
    @statements += line.statements
  end
  set_statement_indices
  link_if_statements
end

Instance Attribute Details

#statementsObject (readonly)

Returns the value of attribute statements.



11
12
13
# File 'lib/basic101/program.rb', line 11

def statements
  @statements
end

Class Method Details

.load(source_file) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/basic101/program.rb', line 19

def self.load(source_file)
  source = source_file.read
  parser = Parser.new
  transform = Transform.new
  tree = parser.parse(source)
  transform.apply(tree)
rescue Parslet::ParseFailed => error
  line_number, column_number =
    error.cause.source.line_and_column(error.cause.pos)
  line = source.lines[line_number - 1]
  raise SyntaxError.new(line, line_number, column_number, error.message)
end

.load_file(source_path) ⇒ Object



13
14
15
16
17
# File 'lib/basic101/program.rb', line 13

def self.load_file(source_path)
  File.open(source_path, 'r') do |file|
    load(file)
  end
end

Instance Method Details

#[](i) ⇒ Object



47
48
49
# File 'lib/basic101/program.rb', line 47

def [](i)
  @statements[i]
end

#data_items(starting_line_number = nil) ⇒ Object



59
60
61
62
63
64
65
66
67
68
# File 'lib/basic101/program.rb', line 59

def data_items(starting_line_number = nil)
  if starting_line_number
    statements = @statements.select do |statement|
      statement.line_number >= starting_line_number
    end
  else
    statements = @statements
  end
  statements.flat_map(&:data_items)
end

#index_of_line(line_number) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/basic101/program.rb', line 51

def index_of_line(line_number)
  index = @line_number_index[line_number]
  unless index
    raise UndefinedLineNumberError, "Undefined line number #{line_number}"
  end
  index
end

#statement_countObject



43
44
45
# File 'lib/basic101/program.rb', line 43

def statement_count
  @statements.size
end