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.



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

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.



9
10
11
# File 'lib/basic101/program.rb', line 9

def statements
  @statements
end

Class Method Details

.load(source_file) ⇒ Object



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

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



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

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

Instance Method Details

#[](i) ⇒ Object



45
46
47
# File 'lib/basic101/program.rb', line 45

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

#data_items(starting_line_number = nil) ⇒ Object



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

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



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

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



41
42
43
# File 'lib/basic101/program.rb', line 41

def statement_count
  @statements.size
end