Created
March 13, 2010 23:46
-
-
Save ybakos/331634 to your computer and use it in GitHub Desktop.
Parser example: from lines in a file to a structured array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Parser | |
| # Gets ready to parse the input file | |
| def initialize(filename) | |
| generate_command_array(filename) # | |
| @index = 0 | |
| end | |
| # ... | |
| private | |
| # Place each line into a nested array. For example, push constant 3 becomes | |
| # ['push', 'constant', '3'] and add becomes ['add']. The entire instructions | |
| # array becomes nested [ ['push', 'constant', '3'], ['push', 'constant', '5'], ['add']] | |
| def generate_command_array(filename) | |
| begin | |
| raise TranslatorException.new("Could not read #{filename}.") unless File.readable?(filename) | |
| # Read each line in the file and remove comments and all extra whitespace | |
| vmfile = File.open(filename, 'r') do |f| | |
| @instructions = f.readlines | |
| @instructions.each {|i| i.gsub! /\/\/.*/, ''; i.strip!; i.squeeze!(' ')} | |
| @instructions.delete('') | |
| end | |
| rescue => e | |
| abort(e.message) | |
| end | |
| # Take each instruction string and split them into a 2d array | |
| @instructions.each_with_index do |cmd, i| | |
| cmd_array = cmd.split | |
| @instructions[i] = cmd_array | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment