Skip to content

Instantly share code, notes, and snippets.

@koduki
Created August 20, 2008 22:15
Show Gist options
  • Save koduki/6457 to your computer and use it in GitHub Desktop.
Save koduki/6457 to your computer and use it in GitHub Desktop.
require "scanner.rb"
class ParseException < Exception
end
class Parser
def initialize input = nil
@sc = Scanner.new(input) unless input == nil
end
def tp tree
tree.each do |x|
if (x.class == Array) then
tp x
else
puts "#{x.type} :: #{x.value}"
end
end
end
def match? type
token = @sc.next
@sc.prev
token.type == type
end
def take type
token = @sc.next
raise ParseException unless token.type == type
token
end
def parse
b_program
end
def b_program
[take(:PROGRAM), b_ident,take(:SEMICOLON), take(:BEGIN), b_statlist, take(:END)
end
def b_statlist
result = []
until match?(:END)
result << [b_statement, take(:SEMICOLON)]
end
result
end
def b_statement
[b_ident,
take(:OPEN),
b_literal,
take(:CLOSE)]
end
def b_ident
take(:IDENT)
end
def b_literal
b_string
end
def b_string
take(:STRING)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment