Created
March 11, 2018 15:28
-
-
Save willamesoares/a913d81bed8c2df650ab8d1ac7f82004 to your computer and use it in GitHub Desktop.
Compilers - Recursive Predictive Parser in Ruby
This file contains 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
#!/usr/bin/env ruby | |
require 'pry' | |
require 'terminal-table' | |
DELIM = '$' | |
def get_next_token(input) | |
@token = input[@counter] | |
@counter += 1 | |
end | |
def raise_error_msg() | |
raise "ERRO" | |
end | |
def raise_success_msg() | |
@rows << [@formated_input, "SUCESSO"] | |
end | |
def analyze_string(input) | |
get_next_token(input) | |
if @token === 'x' | |
get_next_token(input) | |
elsif @token === '(' | |
loop do | |
# reconhecer soma | |
analyze_string(input) | |
break if @token != '+' | |
end | |
if @token === ')' | |
get_next_token(input) | |
else | |
raise_error_msg() | |
end | |
else | |
raise_error_msg() | |
end | |
end | |
def check_final_token() | |
if @token === DELIM | |
raise_success_msg() | |
else | |
raise_error_msg() | |
end | |
end | |
def add_final_token(tokens_array, character) | |
tokens_array.push(character) | |
end | |
def extract_tokens(input) | |
temp = input.scan(/[\w+,'+','(',')']/) | |
temp = add_final_token(temp, DELIM) | |
return temp | |
end | |
def setup | |
@counter = 0 | |
@input_array = [] | |
if(ARGV.length > 0) | |
file = File.new ARGV[0], "r" | |
while line = file.gets | |
@input_array.push(extract_tokens(line)) | |
end | |
else | |
print "Digite cadeia a ser analisada: " | |
input_string = gets.chomp | |
@input_array.push(extract_tokens(input_string)) | |
end | |
end | |
def create_table() | |
table = Terminal::Table.new title: "ASD Preditiva Recursiva", headings: [{value: 'CADEIA', alignment: :center},{value: 'STATUS', alignment: :center}], rows: @rows | |
table.align_column(0, :right) | |
return table | |
end | |
def main | |
@alphabet = ["(", ")", "x", "+"] | |
# initialize table container | |
@rows = [] | |
setup() | |
# binding.pry | |
@input_array.each do |input| | |
begin | |
@formated_input = "" | |
input.each {|l| @formated_input += l unless l === '$'} | |
@counter = 0 | |
analyze_string(input) | |
check_final_token() | |
rescue RuntimeError => e | |
@rows << [@formated_input, e.message] | |
end | |
end | |
table = create_table() | |
puts table | |
end | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment