Você está na página 1de 19

import java.io.

IOException;
import java.util.*;

public class Main {


public static HashMap<Character, String> tokens = new HashMap<Character,
String>();
public static HashMap<String, String> tokensCompuestos = new HashMap<String,
String>();
public static HashMap<String, ArrayList<String>> primeros = new HashMap<String,
ArrayList<String>>();
public static HashMap<String, ArrayList<String>> siguientes = new
HashMap<String, ArrayList<String>>();
public static HashMap<ArrayList<String>, ArrayList<String>> prediccion = new
HashMap<>();
public static ArrayList<String> palabrasReservadas = new
ArrayList<String>(); // Create an ArrayList object
public static ArrayList<String> primitivos = new ArrayList<String>(); // Create
an ArrayList object
public static LinkedHashMap<String, String> ordenErrores = new
LinkedHashMap<>(); // Create an ArrayList object
public static int count;
public static ArrayList<ArrayList<String>> production = new
ArrayList<ArrayList<String>>();
public static Token tokenGeneral;
public static Lexico lexicoGeneral;

public static void inicializar() {


palabrasReservadas.add("funcion_principal");
palabrasReservadas.add("fin_principal");
palabrasReservadas.add("leer");
palabrasReservadas.add("imprimir");
palabrasReservadas.add("si");
palabrasReservadas.add("entonces");
palabrasReservadas.add("fin_si");
palabrasReservadas.add("si_no");
palabrasReservadas.add("mientras");
palabrasReservadas.add("hacer");
palabrasReservadas.add("fin_mientras");
palabrasReservadas.add("para");
palabrasReservadas.add("fin_para");
palabrasReservadas.add("seleccionar");
palabrasReservadas.add("entre");
palabrasReservadas.add("caso");
palabrasReservadas.add("romper");
palabrasReservadas.add("defecto");
palabrasReservadas.add("fin_seleccionar");
palabrasReservadas.add("estructura");
palabrasReservadas.add("fin_estructura");
palabrasReservadas.add("funcion");
palabrasReservadas.add("retornar");
palabrasReservadas.add("fin_funcion");
palabrasReservadas.add("verdadero");
palabrasReservadas.add("falso");
palabrasReservadas.add("entero");
palabrasReservadas.add("caracter");
palabrasReservadas.add("booleano");
palabrasReservadas.add("real");
palabrasReservadas.add("cadena");
palabrasReservadas.add("EOF");

ordenErrores.put("tk_mas","+");
ordenErrores.put("tk_menos", "-");
ordenErrores.put("tk_mult", "*");
ordenErrores.put("tk_div", "/");
ordenErrores.put("tk_mod", "%");
ordenErrores.put("tk_asig", "=");
ordenErrores.put("tk_menor", "<");
ordenErrores.put("tk_mayor", ">");
ordenErrores.put("tk_menor_igual","<=");
ordenErrores.put("tk_mayor_igual", ">=");
ordenErrores.put("tk_igual", "==");
ordenErrores.put("tk_y", "&&");
ordenErrores.put("tk_o", "||");
ordenErrores.put("tk_dif", "!=");
ordenErrores.put("tk_neg", "!");
ordenErrores.put("tk_dosp", ":");
ordenErrores.put("tk_pyc", ";");
ordenErrores.put("tk_coma", ",");
ordenErrores.put("tk_punto", ".");
ordenErrores.put("tk_par_izq", "(");
ordenErrores.put("tk_par_der", ")");
ordenErrores.put("id", "identificador");
ordenErrores.put("tk_entero", "valor_entero");
ordenErrores.put("tk_real", "valor_real");
ordenErrores.put("tk_caracter","valor_caracter");
ordenErrores.put("tk_cadena", "valor_cadena");
ordenErrores.put("funcion_principal","funcion_principal");
ordenErrores.put("fin_principal", "fin_principal");
ordenErrores.put("leer", "leer");
ordenErrores.put("imprimir", "imprimir");
ordenErrores.put("booleano", "booleano");
ordenErrores.put("caracter", "caracter");
ordenErrores.put("entero","entero");
ordenErrores.put("real", "real");
ordenErrores.put("cadena", "cadena");
ordenErrores.put("si", "si");
ordenErrores.put("entonces", "entonces");
ordenErrores.put("fin_si", "fin_si");
ordenErrores.put("si_no", "si_no");
ordenErrores.put("mientras", "mientras");
ordenErrores.put("hacer", "hacer");
ordenErrores.put("fin_mientras", "fin_mientras");
ordenErrores.put("para", "para");
ordenErrores.put("fin_para", "fin_para");
ordenErrores.put("seleccionar", "seleccionar");
ordenErrores.put("entre", "entre");
ordenErrores.put("caso", "caso");
ordenErrores.put("romper", "romper");
ordenErrores.put("defecto", "defecto");
ordenErrores.put("fin_seleccionar", "fin_seleccionar");
ordenErrores.put("estructura", "estructura");
ordenErrores.put("fin_estructura", "fin_estructura");
ordenErrores.put("funcion", "funcion");
ordenErrores.put("fin_funcion", "fin_funcion");
ordenErrores.put("retornar", "retornar");
ordenErrores.put("falso", "falso");
ordenErrores.put("verdadero", "verdadero");
ordenErrores.put("EOF", "EOF");

primitivos.add("tk_entero");
primitivos.add("tk_real");
primitivos.add("tk_cadena");
primitivos.add("tk_caracter");

tokens.put('+', "tk_mas");
tokens.put('-', "tk_menos");
tokens.put('*', "tk_mult");
tokens.put('/', "tk_div");
tokens.put('%', "tk_mod");
tokens.put('=', "tk_asig");
tokens.put('<', "tk_menor");
tokens.put('>', "tk_mayor");
tokens.put(':', "tk_dosp");
tokens.put(';', "tk_pyc");
tokens.put(',', "tk_coma");
tokens.put('.', "tk_punto");
tokens.put('(', "tk_par_izq");
tokens.put(')', "tk_par_der");
tokens.put('!', "tk_neg");

tokensCompuestos.put("<=", "tk_menor_igual");
tokensCompuestos.put(">=", "tk_mayor_igual");
tokensCompuestos.put("==", "tk_igual");
tokensCompuestos.put("!=", "tk_dif");
tokensCompuestos.put("&&", "tk_y");
tokensCompuestos.put("||", "tk_o");
}

public static void findfirst(String c) {


int j;
int sec = 2;
if (primeros.get(c) == null) {
ArrayList<String> temp = new ArrayList<>(); // Create an ArrayList
object
primeros.put(c, temp);
}
// The case where we
// encounter a Terminal

for (j = 0; j < count; j++) {


if (production.get(j).get(0).equals(c)) {
if (production.get(j).get(sec).equals("e")) {
primeros.get(c).add("e");
} else if (production.get(j).get(sec).equals("EOF")) {
primeros.get(c).add("EOF");
} else if (!
Character.isUpperCase(production.get(j).get(sec).charAt(0)) ||
palabrasReservadas.contains(production.get(j).get(sec)) ||
tokens.containsValue(production.get(j).get(sec)) ||
tokensCompuestos.containsValue(production.get(j).get(sec)) ||
primitivos.contains(production.get(j).get(sec))) {
//first.add(production.get(j).get(2));
primeros.get(c).add(production.get(j).get(sec));
} else {
if (primeros.get(production.get(j).get(sec)) == null) {
findfirst(production.get(j).get(sec));
}
//primeros.get(c).addAll( primeros.get(production.get(j).get(sec)));

quitarEpsilon(c, j, sec);
}
}
}
}

public static void quitarEpsilon(String c, int j, int sec) {


//ArrayList<String> temporal = primeros.get(production.get(j).get(2));
int pos = primeros.get(production.get(j).get(sec)).indexOf("e");
int pos2 = primeros.get(c).indexOf("e");
if (pos != -1 && pos2 == -1) {
tieneEpsilon(c, j, sec);
primeros.get(c).addAll(primeros.get(production.get(j).get(sec)));
primeros.get(c).remove("e");
} else if (pos != -1 && pos2 != -1) {
tieneEpsilon(c, j, sec);
primeros.get(c).remove("e");
primeros.get(c).addAll(primeros.get(production.get(j).get(sec)));
} else {
primeros.get(c).addAll(primeros.get(production.get(j).get(sec)));
}
}

private static void tieneEpsilon(String c, int j, int sec) {


if (sec + 1 <= production.get(j).size() - 1) {
if (!Character.isUpperCase(production.get(j).get(sec + 1).charAt(0)) ||
palabrasReservadas.contains(production.get(j).get(sec + 1)) ||
tokens.containsValue(production.get(j).get(sec + 1)) ||
tokensCompuestos.containsValue(production.get(j).get(sec + 1)) ||
primitivos.contains(production.get(j).get(sec + 1))) {
primeros.get(c).add(production.get(j).get(sec + 1));
} else if (primeros.get(production.get(j).get(sec + 1)) == null) {
findfirst(production.get(j).get(sec + 1));
quitarEpsilon(c, j, sec + 1);
//findfirst(production.get(j).get(sec+1));

//primeros.get(c).addAll(primeros.get(production.get(j).get(sec+1)));
} else {
quitarEpsilon(c, j, sec + 1);
}
}
}

public static ArrayList<String> removeDuplicates(ArrayList<String> list) {

// Create a new LinkedHashSet


Set<String> set = new LinkedHashSet<>();

// Add the elements to set


set.addAll(list);

// Clear the list


list.clear();

// add the elements of set


// with no duplicates to the list
list.addAll(set);

// return the list


return list;
}

public static void getPrimeros() {


String c;
count = production.size();
int kay;
String[] done = new String[count];
int ptr = -1;
int xxx;
for (int k = 0; k < count; k++) {
c = production.get(k).get(0);
xxx = 0;
// Checking if First of c has
// already been calculated
for (kay = 0; kay <= ptr; kay++)
if (c.equals(done[kay]))
xxx = 1;
if (xxx == 1)
continue;
// Function call
findfirst(c);
ptr += 1;
// Adding c to the calculated list
done[ptr] = c;
ArrayList<String> newList = removeDuplicates(primeros.get(c));
primeros.put(c, newList);
}
}

public static void findSiguiente(String c) {


if (siguientes.get(c) == null) {
ArrayList<String> temp = new ArrayList<>(); // Create an ArrayList
object
siguientes.put(c, temp);
}
if (c.equals(production.get(0).get(0))) {
siguientes.get(c).add("$");
}

for (int k = 0; k < count; k++) {


int tamano = production.get(k).size() - 1;
for (int j = 2; j <= tamano; j++) {
if (production.get(k).get(j).equals(c)) {
if (j != tamano) {
if (!Character.isUpperCase(production.get(k).get(j +
1).charAt(0)) || palabrasReservadas.contains(production.get(k).get(j + 1)) ||
tokens.containsValue(production.get(k).get(j + 1)) ||
tokensCompuestos.containsValue(production.get(k).get(j + 1)) ||
primitivos.contains(production.get(k).get(j + 1))) {
siguientes.get(c).add(production.get(k).get(j + 1));
} else {
if (j + 1 <= tamano) {
int sig = j+1;
if (production.get(k).get(sig).equals("e")) {
siguientes.get(c).addAll(siguientes.get(production.get(k).get(0)));
} else {
//ArrayList<String> temporal =
primeros.get(production.get(k).get(j + 1));
boolean pos =
primeros.get(production.get(k).get(sig)).contains("e");
boolean pos2 = siguientes.get(c).contains("e");

siguientes.get(c).addAll(primeros.get(production.get(k).get(sig)));
if (pos) {
siguientes.get(c).remove("e");
int sigT = sig;
while
(primeros.get(production.get(k).get(sigT)) != null &&
primeros.get(production.get(k).get(sigT)).contains("e")){
if(sigT != tamano){
sigT++;
if (!
Character.isUpperCase(production.get(k).get(sigT).charAt(0)) ||
palabrasReservadas.contains(production.get(k).get(sigT)) ||
tokens.containsValue(production.get(k).get(sigT)) ||
tokensCompuestos.containsValue(production.get(k).get(sigT)) ||
primitivos.contains(production.get(k).get(sigT))) {

siguientes.get(c).add(production.get(k).get(sigT));
}else{

siguientes.get(c).addAll(primeros.get(production.get(k).get(sigT)));
siguientes.get(c).remove("e");
}
}else{
metodoPrueba(c, k);
break;
}
}
}
}
}
}
} else {
metodoPrueba(c, k);
}
}
}
}
}

private static void metodoPrueba(String c, int k) {


if (!production.get(k).get(0).equals(c)) {
if (siguientes.get(production.get(k).get(0)) == null) {
findSiguiente(production.get(k).get(0));
}
siguientes.get(c).addAll(siguientes.get(production.get(k).get(0)));
}
}

public static void getSiguientes() {


count = production.size();
for (int i = 0; i < count; i++) {
String c = production.get(i).get(0);
if (siguientes.get(c) == null) {
findSiguiente(c);
}
ArrayList<String> newList = removeDuplicates(siguientes.get(c));
siguientes.put(c, newList);
}
}

public static void getConjuntoPrediccion() {


count = production.size();
for (int i = 0; i < count; i++) {
ArrayList<String> temp = new ArrayList<>();
ArrayList<String> c = production.get(i);
prediccion.put(c, temp);
for (int j = 2; j < production.get(i).size(); j++) {
if (production.get(i).get(j).equals("e")) {
prediccion.get(c).addAll(siguientes.get(c.get(0)));
} else if (!
Character.isUpperCase(production.get(i).get(j).charAt(0)) ||
palabrasReservadas.contains(production.get(i).get(j)) ||
tokens.containsValue(production.get(i).get(j)) ||
tokensCompuestos.containsValue(production.get(i).get(j)) ||
primitivos.contains(production.get(i).get(j))) {
prediccion.get(c).add(production.get(i).get(j));
break;
} else {
if (!primeros.get(production.get(i).get(j)).contains("e")) {

prediccion.get(c).addAll(primeros.get(production.get(i).get(j)));
break;
} else {

prediccion.get(c).addAll(primeros.get(production.get(i).get(j)));
prediccion.get(c).remove("e");
if (j == production.get(i).size() - 1) {

prediccion.get(c).addAll(siguientes.get(production.get(i).get(0)));
}
}
}
}
}
}

public static void analisisSintactico(String noTerminal) {


count = production.size();
boolean empa = false;
boolean error = true;
int f = 2;
ArrayList<String> predicciones = new ArrayList<>();
for (int i = 0; i < count; i++) {
if (production.get(i).get(0).equals(noTerminal)) {
ArrayList<String> predi = prediccion.get(production.get(i));
predicciones.addAll(predi);
//int tamano = predi.size();
for (String s : predi) {
if (tokenGeneral.tipo.equals(s)) {
error = false;
for (int k = 2; k < production.get(i).size(); k++) {
empa = true;
if (production.get(i).get(k).equals("e")) {

} else if (!
Character.isUpperCase(production.get(i).get(k).charAt(0)) ||
palabrasReservadas.contains(production.get(i).get(k)) ||
tokens.containsValue(production.get(i).get(k)) ||
tokensCompuestos.containsValue(production.get(i).get(k)) ||
primitivos.contains(production.get(i).get(k))) {
emparejar(production.get(i).get(k));
} else {
analisisSintactico(production.get(i).get(k));
}
}
}
}
if(empa){
break;
}
}
}
if(error){
errorSintactico(predicciones);
}
}

public static void emparejar(String token) {


if (tokenGeneral.tipo.equals(token)) {
if (lexicoGeneral.hasNext()) {
tokenGeneral = lexicoGeneral.getNextToken();
} else {
Token eof = new Token();
eof.fila = lexicoGeneral.fila;
eof.columna = 1;
eof.tipo = "EOF";
tokenGeneral = eof;
}
} else {
ArrayList<String> predicciones = new ArrayList<>();
predicciones.add(token);
errorSintactico(predicciones);
}
}

public static void errorSintactico(ArrayList<String> posibles) {


if(posibles.size() == 1 && posibles.get(0).equals("funcion_principal")){
System.out.print("Error sintactico: falta funcion_principal");
}else{
if(tokenGeneral.lexema.equals("")){
System.out.print("<" + tokenGeneral.fila + "," +
tokenGeneral.columna + "> Error sintactico: se encontro: \"" +
ordenErrores.get(tokenGeneral.tipo) + "\"; se esperaba: ");
}else{
System.out.print("<" + tokenGeneral.fila + "," +
tokenGeneral.columna + "> Error sintactico: se encontro: \"" + tokenGeneral.lexema
+ "\"; se esperaba: ");
}
for (Map.Entry<String, String> set : ordenErrores.entrySet()) {
if (posibles.contains(set.getKey())) {
if (posibles.size() == 1) {
System.out.print("\"" + set.getValue() + "\".");
break;
} else {
System.out.print("\"" + set.getValue() + "\", ");
}
posibles.remove(set.getKey());
}
}
}
System.exit(0);
}

public static void main(String[] args) throws IOException {

inicializar();

Scanner scanner = new Scanner("S = FUNC_ESTR MAIN FUNC_ESTR EOF\n" +


"FUNC_ESTR = ESTRUCT FUNC_ESTR\n" +
"FUNC_ESTR = FUNCTION FUNC_ESTR\n" +
"FUNC_ESTR = e\n" +
"ESTRUCT = estructura id ESTRUCT_BODY fin_estructura\n" +
"ESTRUCT_BODY = DECLARATIONE ESTRUCT_BODY\n" +
"ESTRUCT_BODY = e\n" +
"DECLARATIONE = TYPE id DECLARATIONE_ tk_pyc\n" +
"DECLARATIONE_ = tk_coma id DECLARATIONE_\n" +
"DECLARATIONE_ = e\n" +
"FUNCTION = funcion TIPO_FUN id tk_par_izq PARAMETERSF tk_par_der
hacer COMANDSF RETURN fin_funcion\n" +
"TIPO_FUN = PRIMITIVE\n" +
"TIPO_FUN = id\n" +
"RETURN = retornar VALOR tk_pyc\n" +
"PARAMETERSF = TIPO_FUN id PARAMETERSF_\n" +
"PARAMETERSF = e\n" +
"PARAMETERSF_ = tk_coma PARAMETERSF\n" +
"PARAMETERSF_ = e\n" +
"COMANDSF = COMANDF COMANDSF\n" +
"COMANDSF = e\n" +
"COMANDF = READ\n" +
"COMANDF = PRINT\n" +
"COMANDF = DECLARATION\n" +
"COMANDF = IF\n" +
"COMANDF = FUNC_ID\n" +
"COMANDF = WHILE\n" +
"COMANDF = DO_WHILE\n" +
"COMANDF = FOR\n" +
"COMANDF = SWITCH\n" +
"COMANDF = romper\n" +
"TYPE = id\n" +
"TYPE = PRIMITIVE\n" +
"PRIMITIVE = booleano\n" +
"PRIMITIVE = caracter\n" +
"PRIMITIVE = entero\n" +
"PRIMITIVE = real\n" +
"PRIMITIVE = cadena\n" +
"MAIN = funcion_principal COMANDSM fin_principal\n" +
"COMANDSM = COMANDM COMANDSM\n" +
"COMANDSM = e\n" +
"COMANDM = READ\n" +
"COMANDM = PRINT\n" +
"COMANDM = DECLARATION\n" +
"COMANDM = IF\n" +
"COMANDM = FUNC_ID\n" +
"COMANDM = WHILE\n" +
"COMANDM = DO_WHILE\n" +
"COMANDM = FOR\n" +
"COMANDM = SWITCH\n" +
"COMANDM = romper\n" +
"COMANDS = COMAND COMANDS\n" +
"COMANDS = e\n" +
"COMAND = READ\n" +
"COMAND = PRINT\n" +
"COMAND = DECLARATION\n" +
"COMAND = IF\n" +
"COMAND = FUNC_ID \n" +
"COMAND = WHILE\n" +
"COMAND = DO_WHILE\n" +
"COMAND = FOR\n" +
"COMAND = SWITCH\n" +
"READ = leer tk_par_izq IDR tk_par_der tk_pyc\n" +
"IDR = id IDR_\n" +
"IDR_ = tk_punto id IDR_ \n" +
"IDR_ = e\n" +
"PRINT = imprimir tk_par_izq PRINT_ tk_par_der tk_pyc\n" +
"PRINT_ = VALOR PRINT__\n" +
"PRINT__ = tk_coma PRINT_\n" +
"PRINT__ = e\n" +
"ID = id ID_ CALL_FUNCTION\n" +
"ID_ = tk_punto id ID_ \n" +
"ID_ = e\n" +
"CALL_FUNCTION = tk_par_izq CF tk_par_der\n" +
"CALL_FUNCTION = e\n" +
"CF = CF_ \n" +
"CF = e\n" +
"CF_ = VALOR F\n" +
"F = tk_coma CF_\n" +
"F = e\n" +
"DECLARATION = PRIMITIVE id DECLARATION_ tk_pyc\n" +
"DECLARATION_ = tk_coma id DECLARATION_\n" +
"DECLARATION_ = tk_asig VALOR DECLARATION_\n" +
"DECLARATION_ = e\n" +
"OPERATOR = tk_mas\n" +
"OPERATOR = tk_menos\n" +
"OPERATOR = tk_mult\n" +
"OPERATOR = tk_div\n" +
"OPERATOR = tk_mod\n" +
"OPERATOR = tk_menor\n" +
"OPERATOR = tk_mayor\n" +
"OPERATOR = tk_menor_igual\n" +
"OPERATOR = tk_mayor_igual\n" +
"OPERATOR = tk_igual\n" +
"OPERATOR = tk_dif\n" +
"OPERATOR = tk_y\n" +
"OPERATOR = tk_o\n" +
"IF = si tk_par_izq VALOR tk_par_der entonces COMANDS ELSE
fin_si\n" +
"VALOR = tk_par_izq VALOR tk_par_der VALOR_\n" +
"VALOR = OPERADORNEG VALOR\n" +
"VALOR = ID VALOR_\n" +
"VALOR = tk_entero VALOR_\n" +
"VALOR = tk_real VALOR_\n" +
"VALOR = tk_caracter VALOR_\n" +
"VALOR = tk_cadena VALOR_\n" +
"VALOR = falso VALOR_\n" +
"VALOR = verdadero VALOR_\n" +
"VALOR_ = OPERATOR VALOR VALOR_\n" +
"VALOR_ = e\n" +
"OPERADORNEG = tk_menos\n" +
"OPERADORNEG = tk_neg\n" +
"ELSE = si_no COMANDS\n" +
"ELSE = e\n" +
"FUNC_ID = id FUNC_ID_ tk_pyc\n" +
"FUNC_ID_ = tk_punto id FUNC_ID_ \n" +
"FUNC_ID_ = CALL_FUNCTION_M\n" +
"FUNC_ID_ = id\n" +
"FUNC_ID_ = ASIG_ID\n" +
"CALL_FUNCTION_M = tk_par_izq PAR_FUN tk_par_der\n" +
"PAR_FUN = PAR_FUN_\n" +
"PAR_FUN = e\n" +
"PAR_FUN_ = VALOR NEXT_P\n" +
"NEXT_P = tk_coma PAR_FUN_\n" +
"NEXT_P = e\n" +
"ASIG_ID = tk_asig VALOR\n" +
"FOR = para tk_par_izq PARA_INI tk_pyc VALOR tk_pyc VALOR
tk_par_der hacer COMANDS fin_para\n" +
"PARA_INI = DECLARATIONF\n" +
"DECLARATIONF = PRIMITIVE id tk_asig VALOR\n" +
"PARA_INI = FUNC_IDF\n" +
"FUNC_IDF = id tk_asig VALOR\n" +
"WHILE = mientras tk_par_izq VALOR tk_par_der hacer COMANDSW
fin_mientras\n" +
"COMANDSW = COMANDW COMANDSW\n" +
"COMANDSW = e\n" +
"COMANDW = READ\n" +
"COMANDW = PRINT\n" +
"COMANDW = DECLARATION\n" +
"COMANDW = IF\n" +
"COMANDW = FUNC_ID\n" +
"COMANDW = WHILE\n" +
"COMANDW = DO_WHILE\n" +
"COMANDW = FOR\n" +
"COMANDW = SWITCH\n" +
"COMANDW = romper\n" +
"DO_WHILE = hacer COMANDSDW VR_MNT tk_pyc\n" +
"VR_MNT = mientras tk_par_izq VALOR tk_par_der VER_MIENTRAS\n" +
"VER_MIENTRAS = hacer COMANDSW fin_mientras COMANDSDW VR_MNT\n" +
"VER_MIENTRAS = e\n" +
"COMANDSDW = COMANDDW COMANDSDW\n" +
"COMANDSDW = e\n" +
"COMANDDW = READ\n" +
"COMANDDW = PRINT\n" +
"COMANDDW = DECLARATION\n" +
"COMANDDW = IF\n" +
"COMANDDW = FUNC_ID\n" +
"COMANDDW = DO_WHILE\n" +
"COMANDDW = FOR \n" +
"COMANDDW = SWITCH\n" +
"COMANDDW = romper\n" +
"SWITCH = seleccionar tk_par_izq ID tk_par_der entre CASOS
fin_seleccionar\n" +
"CASOS = caso NUMS tk_dosp COMANDSSW B CASOS\n" +
"CASOS = defecto tk_dosp COMANDSSW B\n" +
"CASOS = e\n" +
"NUMS = NUM\n" +
"NUMS = OPERADOR_NEG NUM\n" +
"NUM = tk_entero\n" +
"NUM = tk_real\n" +
"NUM = tk_cadena\n" +
"NUM = tk_caracter\n" +
"NUM = verdadero\n" +
"NUM = false\n" +
"B = romper tk_pyc\n" +
"B = e\n" +
"COMANDSSW = COMANDSEL COMANDSSW\n" +
"COMANDSSW = e\n" +
"COMANDSEL = READ\n" +
"COMANDSEL = PRINT\n" +
"COMANDSEL = DECLARATION\n" +
"COMANDSEL = IF\n" +
"COMANDSEL = FUNC_ID \n" +
"COMANDSEL = WHILE\n" +
"COMANDSEL = DO_WHILE\n" +
"COMANDSEL = FOR\n" +
"COMANDSEL = SWITCH");

while (scanner.hasNextLine()) {
Scanner scanner2 = new Scanner(scanner.nextLine()).useDelimiter(" ");
ArrayList<String> palabras = new ArrayList<>();
while (scanner2.hasNext()) {
palabras.add(scanner2.next());
}
production.add(palabras);
}

getPrimeros();
//System.out.println(primeros);
getSiguientes();
//System.out.println(siguientes);
getConjuntoPrediccion();
//System.out.println(prediccion);
lexicoGeneral = new Lexico();
tokenGeneral = lexicoGeneral.getNextToken();
analisisSintactico("S");
System.out.print("El analisis sintactico ha finalizado exitosamente.");

}
}

class Lexico {
int fila = 1;
ArrayList<Token> allTokens = new ArrayList<Token>();

boolean comentario = false;

public Lexico() {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
generarTokens(scanner.nextLine() + ' ', this.fila);
this.fila++;
}
}

public Token getNextToken() {


return allTokens.remove(0);
}

public boolean hasNext() {


return allTokens.size() > 0;
}

public boolean esLetra(char i) {


int asci = (int) i;
if ((asci >= 65 && asci <= 90) || (asci >= 97 && asci <= 122)) {
return true;
}
return false;
}

public boolean esNumero(char i) {


int asci = (int) i;
if (asci >= 48 && asci <= 57) {
return true;
}
return false;
}

public void erroLexico(int linea, int columna) {


System.out.println(">>> Error lexico (linea: " + linea + ", posicion: " +
columna + ")");
System.exit(0);
}

public int delta(int estado, char c) {


switch (estado) {
case 0:
if (esLetra(c)) return 1;
else if (esNumero(c)) return 2;
else if (c == ' ') return 0;
else if (c == '<') return 5;
else if (c == '>') return 5;
else if (c == '=') return 9;
else if (c == '!') return 11;
else if (c == '/') return 13;
else if (c == '|') return 14;
else if (c == '*') return 15;
else if (c == '"') return 16;
else if (c == '\'') return 18;
else if (c == '\t') return 0;
else if (c == '&') return 23;
else if (Main.tokens.get(c) != null) return -1;
else return -11;
case 1:
if (esLetra(c) || esNumero(c) || c == '_') return 1;
else if (c == ' ') return -1;
else return -6;
case 2:
if (esNumero(c)) return 2;
else if (c == '.') return 3;
else return -5;
case 3:
if (esNumero(c)) return 24;
else return -12;
case 4:
if (c == '<') return 5;
else if (c == '>') return 5;
else if (c == '=') return 9;
else if (c == '!') return 11;
else if (c == '/') return 13;
else if (c == '|') return 14;
else if (c == '*') return 15;
else if (c == '"') return 16;
else if (c == '\'') return 18;
else return -1;
case 5:
if (c == '=') return -10;
else return -7;
case 6:
return -1;
//case 7: if(c == '=') return -10;
// else return -7;
case 8:
return -1;
case 9:
if (c == '=') return -10;
else return -7;
case 10:
return -1;
case 11:
if (c == '=') return -10;
else return -7;
case 12:
return -1;
case 13:
if (c == '/') return -2;
else if (c == '*') return -3;
else if (c == ' ') return -7;
else return -7;
case 14:
if (c == '|') return -10;
else return -11;
case 15:
if (c == '/') return -3;
else return -7;
case 16:
if (c == '"') return -4;
else if (esNumero(c) || esLetra(c) || c == '_' || c == ' ') return
16;
else if (c == '\\') return 17;
else return 0;
case 17:
if (c == 'n') return 16;
else return -11;
case 18:
if (esLetra(c) || esNumero(c) || c == '_' || c == ' ') return 19;
else if (c == '\\') return 20;
else return -11;
case 19:
if (c == '\'') return -8;
else return -11;
case 20:
if (c == 'n') return 19;
else return -11;
case 21:
if (c == '*') return 22;
else return 21;
case 22:
if (c == '/') return -3;
else return 21;
case 23:
if (c == '&') return -10;
else return -11;
case 24:
if (esNumero(c)) return 24;
else return -9;
}
return -1;
}

public void generarTokens(String linea, int fila) {


Scanner scanner = new Scanner(linea).useDelimiter("");
int estado = 0;
int columna = 1;
String word = "";
boolean verificar = false;
char character = ' ';

if (comentario) {
estado = 21;
}

while (scanner.hasNext()) {
if (!verificar) {

character = scanner.next().charAt(0);
} else {
verificar = false;
}

estado = delta(estado, character);


//System.out.println("estado: " + estado);

if (estado == -1) {
Token token = new Token();
token.fila = fila;
int largo = word.length();
token.columna = columna - largo;
if (Main.palabrasReservadas.contains(word)) {
token.tipo = word;
//System.out.println(token);
} else if (Main.tokens.get(character) != null) {
token.tipo = Main.tokens.get(character);
//System.out.println(token);
} else {
token.tipo = "id";
token.lexema = word;
//System.out.println(token);
}
allTokens.add(token);
word = "";
estado = 0;
} else if (estado == 0) {

} else if (estado == -2) {


break;
} else if (estado == -3) {
if (character == '*') {
comentario = true;
estado = 21;
} else if (character == '/') {
comentario = false;
word = "";
estado = 0;
}
} else if (estado == -4) {
word += character;
columna++;
Token token = new Token();
token.fila = fila;
int largo = word.length();
token.columna = columna - largo;

token.tipo = "tk_cadena";
token.lexema = word;
//System.out.println(token);

//verificar = true;
word = "";
estado = 0;
columna--;
allTokens.add(token);
} else if (estado == -5) {
Token token = new Token();
token.fila = fila;
int largo = word.length();
token.columna = columna - largo;

token.tipo = "tk_entero";
token.lexema = word;
//System.out.println(token);

verificar = true;
word = "";
estado = 0;
columna--;
allTokens.add(token);
} else if (estado == -6) {
Token token = new Token();
token.fila = fila;
int largo = word.length();
token.columna = columna - largo;
if (Main.palabrasReservadas.contains(word)) {
token.tipo = word;
} else {
token.tipo = "id";
token.lexema = word;
}
//System.out.println(token);

verificar = true;
word = "";
estado = 0;
columna--;
allTokens.add(token);
} else if (estado == -7) {
Token token = new Token();
token.fila = fila;
int largo = word.length();
token.columna = columna - largo;

token.tipo = Main.tokens.get(word.charAt(0));
//System.out.println(token);

verificar = true;
word = "";
estado = 0;
columna--;
allTokens.add(token);
} else if (estado == -8) {
word += character;
columna++;
Token token = new Token();
token.fila = fila;
int largo = word.length();
token.columna = columna - largo;

token.tipo = "tk_caracter";
token.lexema = word;
//System.out.println(token);

//verificar = true;
word = "";
estado = 0;
columna--;
allTokens.add(token);
} else if (estado == -9) {
Token token = new Token();
token.fila = fila;
int largo = word.length();
token.columna = columna - largo;

token.tipo = "tk_real";
token.lexema = word;
//System.out.println(token);

verificar = true;
word = "";
estado = 0;
columna--;
allTokens.add(token);
} else if (estado == -10) {
word += character;

Token token = new Token();


token.fila = fila;

//int largo = word.length();


token.columna = columna - 1;
token.tipo = Main.tokensCompuestos.get(word);
//System.out.println(token);

word = "";
estado = 0;
allTokens.add(token);
} else if (estado == -11) {
erroLexico(fila, columna - word.length());
} else if (estado == -12) {
Token token = new Token();
token.fila = fila;
int largo = word.length();
token.columna = columna - largo;

token.tipo = "tk_entero";
linea = character + linea.substring(columna);
scanner = new Scanner(linea).useDelimiter("");

character = word.substring(word.length() - 1).charAt(0);


token.lexema = word.substring(0, word.length() - 1);
//System.out.println(token);

verificar = true;
word = "";
estado = 0;
columna = columna - 2;
allTokens.add(token);
} else {
word += character;
//System.out.println("word: " + word);
}

columna++;
}
if (word.length() > 0 && (word.charAt(0) == '\'' || word.charAt(0) == '"'))
{
erroLexico(fila, columna - word.length());
}
}
}

class Token {
public int fila;
public int columna;

public String lexema = "";

public String tipo; //tipo es: ID, ENTERO, REAL ...

@Override
public String toString() {
if (!lexema.equals("")) {
return "<" + this.tipo + "," + this.lexema + "," + this.fila + "," +
this.columna + ">";
} else {
return "<" + this.tipo + "," + this.fila + "," + this.columna + ">";
}
}
}

Você também pode gostar