How can I check if a variable has been declared (desenv. of a compiler in Java)

Asked

Viewed 177 times

1

I’m having trouble implementing a demonstration of a semantic analysis of the desenv. of a compiler in Java. I have a Jtextarea and put. ex type: int x; x = 'a', it must be an error since x is an integer and not a char. I can even take the substrings but I can’t go back to the Enum class and compare. Follow the code below and if you need to be clearer, let me know. Thank you.

import java.io.File;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import java.util.regex.Matcher;
java.util.regex.Pattern;

import javax.swing.JOptionPane;
import javax.swing.JTextArea;


public class Lex{

public static enum Simbolo
{        

        DIGITO("-?[0-9]+"),
        MODIFCADORDEACESSO("(private) | (protected) | (public)"),
        ESPACO("[ \t\f\r\n]+"), 
        OPLOG("(==)|(or)|(&&)|(>=)|(<=)|(>)|(<)|(!=)"), 
        OPMAT("[*/+-=]"),  OPBOLEANO("(true) | (false)"),
        SIMB("[(/# )}{]"),
        PALAVRARESERVADA("(if )|(else )|(for )|(while )|(case )|(Do ) |  (break ) | (return ) | (switch )|(assert) | (catch) | (finally) | (throw) | (throws) | (try)"),
        TIPOVAR("(int )|(float )|(String )|(double )|(Char )"), 
        MODIFICADORDECLASSESEMETODOS("(abstract ) | (class ) | (extends ) | (final )| (implements ) | (interface ) |"
                + " (native ) | (new ) | (static ) | (strictfp ) | (synchronized ) | (transient ) | (volatile ) | (void )"),
        VARIAVELDEREFERENCIA("(super ) | (this )"),
        VAR("-?[a-zA-Z0-9]+");


      public final String mod;

      private Simbolo(String modelo)
        {
           this.mod = modelo; //a variavel mod. recebe a string digitada para ser comparada no while.
        }
}//fim da classe simbolo.

public static class Simbol 
{
public Simbolo t; 
public String d; 

public Simbol(Simbolo pt, String pd)
{                                   
         this.t = pt;
         this.d = pd;
}
public String toString()
{
    return String.format("(%s %s)", t.name(), d);
}

}


public static ArrayList<Simbol> lex(String entr) { 

ArrayList<Simbol> vet = new ArrayList<Simbol>();

StringBuffer buffer = new StringBuffer();

for (Simbolo simb : Simbolo.values())



            buffer.append(String.format("|(?<%s>%s)", simb.name(),   simb.mod));

            Pattern pat = Pattern.compile(new String(buffer.substring(1)));


            Matcher mat = pat.matcher(entr);






      while (mat.find())
            {             


                if (mat.group(Simbolo.DIGITO.name()) != null) 
                {
                    vet.add(new Simbol(Simbolo.DIGITO,  mat.group(Simbolo.DIGITO.name())));

                    continue; 
                }
                else if  (mat.group(Simbolo.MODIFICADORDECLASSESEMETODOS.name()) != null) 
                {
                    vet.add(new Simbol(Simbolo.MODIFICADORDECLASSESEMETODOS,  mat.group(Simbolo.MODIFICADORDECLASSESEMETODOS.name())));
                    continue; 
                    } 
                else if (mat.group(Simbolo.VARIAVELDEREFERENCIA.name()) != null) 
                {
                    vet.add(new Simbol(Simbolo.VARIAVELDEREFERENCIA, mat.group(Simbolo.VARIAVELDEREFERENCIA.name())));
                    continue; } 



                else if (mat.group(Simbolo.OPMAT.name()) != null) 
                {
                    vet.add(new Simbol(Simbolo.OPMAT, mat.group(Simbolo.OPMAT.name())));
                    continue;
                    }
                else if (mat.group(Simbolo.MODIFCADORDEACESSO.name()) != null) 
                {
                    vet.add(new Simbol(Simbolo.MODIFCADORDEACESSO, mat.group(Simbolo.MODIFCADORDEACESSO.name())));
                    continue; } 



                else if (mat.group(Simbolo.OPLOG.name()) != null)
                {
                    vet.add(new Simbol(Simbolo.OPLOG, mat.group(Simbolo.OPLOG.name())));
                    continue; }
                else if (mat.group(Simbolo.OPBOLEANO.name()) != null) 
                {
                    vet.add(new Simbol(Simbolo.OPBOLEANO, mat.group(Simbolo.OPBOLEANO.name())));
                    continue; } 

                else if (mat.group(Simbolo.SIMB.name()) != null)
                {
                    vet.add(new Simbol(Simbolo.SIMB, mat.group(Simbolo.SIMB.name())));
                    continue;}

                else if (mat.group(Simbolo.VAR.name()) != null)
                {
                    vet.add(new Simbol(Simbolo.VAR, mat.group(Simbolo.VAR.name())));

                    continue;
                    }

                else if (mat.group(Simbolo.TIPOVAR.name()) != null) 
                {
                    vet.add(new Simbol(Simbolo.TIPOVAR, mat.group(Simbolo.TIPOVAR.name())));
                    continue; 
                    }


                else if (mat.group(Simbolo.PALAVRARESERVADA.name()) != null) 
                {
                    vet.add(new Simbol(Simbolo.PALAVRARESERVADA,        mat.group(Simbolo.PALAVRARESERVADA.name())));
                    continue; 
                } 

                else if (mat.group(Simbolo.ESPACO.name()) != null)
                    continue;



            }
      return vet;
}

public void verifica(JTextArea txtEntrada, JTextArea txtResultado, JTextArea   txtSintatico, JTextArea txtSemantico) 
{

                      StringBuffer buffer = new StringBuffer();

                      for (Simbolo simb : Simbolo.values())
                          buffer.append(String.format("|(?<%s>%s)",   simb.name(), simb.mod));//preenche o buffer com o conteudo da classe simbolo
                      String text = txtResultado.getText();//conteudo do  jtextArea

                      Pattern p = Pattern.compile(new  String(buffer.substring(1)));//compila o buffer

                      Matcher m = p.matcher(text);//percorre o jtextArea em busca do conteudo do pattern.

                      int flag=0;

                      String variavelDeclarada = null;

                      while(m.find()){//enquanto encontrar
                          if (m.group(Simbolo.TIPOVAR.name()) != null) {

                              //verificar o tipo de variavel e fazer um case.

                                   if(m.group(Simbolo.VAR.name())!= null)
                                        {
                                            variavelDeclarada = m.group(Simbolo.VAR.name());
                                            break;  
                                        }
                                    }
                          continue;
                        }




                      System.out.println("Variável declarada: " + variavelDeclarada);

                      String text2 = txtEntrada.getText();

                      System.out.println("Texto analisado: " + text2);              
}

1 answer

0

You can create your own functions for each object, an example :

 public static final boolean isEmpty(String x) {
            return (x == null || x.trim().equals(""));
        }
        public static final boolean isEmpty(Integer x) {
            return (x == null || x == 0);
        }
        public static final boolean isEmpty(Long x) {
            return (x == null || x == 0);
        }
        public static final boolean isEmpty(Collection<?> x) {
            return (x == null || x.size() == 0);
        }
        public static final boolean isEmpty(Map<?,?> x) {
            return (x == null || x.size() == 0);
        }
        public static final boolean isEmpty(Object[] x) {
            return (x == null || x.length == 0);
        }


  if(isEmpty(x)) 
    {
    JOptionPane.showMessageDialog(null,"A variável x foi declarada");
    }

Or you can try :

private int x;
private boolean x_was_touched = false;

public void setX (int newXvalue) {
    if (!x_was_touched) {
       x = newXvalue;
       x_was_touched = true;
    }
}

public int getX() {
    return x;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.