jueves, 14 de enero de 2010

Programa Libro

// **** analizlex.cpp **** \\

/* *********************** analizlex.c ****************************/
#include
#include
#include "global.h"
#include

int valcomplex = NINGUNO; /* valor del atributo del componente lexico */
int numlinea = 1;
extern entrada tablasimb[MAXSIMB]; /* tabla de simbolos */

char buflex[TAMBUFF];
//int numlinea = 1;
//int valcomplex = NINGUNO;

int analex() /* analizador lexico */
{
int t;
while(1) {
t = getchar();
if(t == ' ' || t == '\t')
; /* elimina espacios en blanco */
else if (t == '\n')
numlinea = numlinea + 1;
else if (isdigit(t)) { /* t es un digito */
ungetc(t, stdin);
scanf("%d", &valcomplex);
return NUM;
}
else if (isalpha(t)) { /* t es una letra */
int p, b=0;
while (isalnum(t)) { /* t es alfanumerico */
buflex[b] = t;
t = getchar();
b = b+1;
if (b >= TAMBUFF)
error("error de compilador");
}
buflex[b] = FDC;
if (t != EOF)
ungetc(t, stdin);
p = busca(buflex);
if (p == 0)
p = inserta(buflex, ID);
valcomplex = p;
return tablasimb[p].complex;
}
else if(t == EOF)
return FIN;
else {
valcomplex = NINGUNO;
return t;
}
}
}

// **** aanalizsint.cpp **** \\

#include
#include
#include
#include "global.h"

extern int valcomplex; /* valor del atributo del componente lexico */
extern int numlinea;
extern entrada tablasimb[MAXSIMB]; /* tabla de simbolos */

int preanalisis;
void analsint() /* analiza sintecticamente y traduce la lista de la expresion */
{
preanalisis = analex();
while (preanalisis != FIN) {
expr(); parea(';');
}
}
void expr()
{
int t;
termino();
while(1)
switch (preanalisis) {
case '+': case '-':
t = preanalisis;
parea (preanalisis); termino(); emite(t, NINGUNO);
continue;
default:
return;
}
}

void termino()
{
int t;
factor();
while(1)
switch(preanalisis) {
case '*': case '/': case DIV: case MOD:
t = preanalisis;
parea (preanalisis); factor(); emite(t, NINGUNO);
continue;
default:
return;
}
}
void factor()
{
switch(preanalisis) {
case '(':
parea('(');
        expr();
        parea(')');
        break;
case NUM:
emite(NUM, valcomplex); parea(NUM); break;
case ID:
emite(ID, valcomplex); parea(ID); break;
default:
error("error de sintaxis");
}
}
void parea (int t)
{
if(preanalisis == t)
preanalisis = analex();
else error ("error de sintaxis");
}

// **** emisor.cpp **** \\


#include
#include
#include
#include "global.h"
extern int valcomplex; /* valor del atributo del componente lexico */
extern int numlinea;
extern entrada tablasimb[MAXSIMB]; /* tabla de simbolos */

void emite (int t,int tval) /* genera la salida */
{
switch(t) {
case '+': case '-': case '*': case '/':
printf("%c\n",t); break;
case DIV:
printf("%DIV\n"); break;
case MOD:
printf("%MOD"); break;
case NUM:
printf("%d\n", tval); break;
case ID:
printf("%s\n", tablasimb[tval].aplex); break;
default:
printf("complex %d, valcomplex %d\n", t, tval);
}
}


// **** error.cpp **** \\


#include
#include
#include
#include "global.h"
extern int valcomplex; /* valor del atributo del componente lexico */
extern int numlinea;
extern entrada tablasimb[MAXSIMB]; /* tabla de simbolos */


void error(char *m) /* genera todos los mensajes de error */
{
fprintf(stderr, "linea %d: %s\n", numlinea, m);
exit(1); /* terminacion sin exito */
}


// **** inic.cpp **** \\


#include
#include
#include
#include "global.h"
extern int valcomplex; /* valor del atributo del componente lexico */
extern int numlinea;
extern entrada tablasimb[MAXSIMB]; /* tabla de simbolos */

struct _entrada palsclave[] = {
"div",DIV,"mod", MOD,0,0
};

void inic() /* carga las palabras clave en la tabla de simbolos */
{
        
struct _entrada *p = palsclave;
for (; p->complex; p++)
inserta(p->aplex, p->complex);
}


// **** principal.cpp **** \\

#include
#include
#include
#include "global.h"

extern int valcomplex;
extern int numlinea;
entrada tablasimb[MAXSIMB]; 

int main()
{
inic();
analsint();
exit(0); /* terminacion con exito */
}


// **** simbolos.cpp **** \\

#include
#include
#include "global.h"

extern int valcomplex; /* valor del atributo del componente lexico */
extern int numlinea;
extern entrada tablasimb[MAXSIMB]; /* tabla de simbolos */


char lexemas[MAXLEX];
int ultcar = -1; /* ultima posicion usada en los lexemas */

int ultent = 0; /* ultima posicion usada en tablasimb */


int busca(char *s)   /*debuelve la posicion del elemento de entrada de s */
{
int p;
for(p=ultent;p>0;p=p-1)
if(strcmp(tablasimb[p].aplex, s) == 0)
return p;
return 0;
}
int inserta(char *s, int clex) /* debuelve la posicion del elemento de entrada de s */
{
int lon;
lon = strlen(s); /* strlen evvalua la longitud de s */
if (ultent + 1 >= MAXSIMB)
error("tabla simbolos llena");
if (ultcar + lon + 1 >= MAXLEX)
error("matriz de lexema llena");
ultent = ultent + 1;
tablasimb[ultent].complex = clex;
tablasimb[ultent].aplex = &lexemas[ultcar + 1];
ultcar = ultcar + lon + 1;
strcpy(tablasimb[ultent].aplex, s);
return ultent;
}


// **** global.h **** \\

#include
#include
#include
#include

#define MAXLEX 999 /* tamano de la matriz de lexema */
#define MAXSIMB 100 /* tamano de la tabla de simbolos */

#define TAMBUFF 128
#define NINGUNO -1
#define FDC '\0'

#define NUM 256
#define DIV 257
#define MOD 258
#define ID 259
#define FIN 260

//int valcomplex = NINGUNO; /* valor del atributo del componente lexico */
//int numlinea = 1;



typedef struct _entrada { /* forma del elemento de entrada de la tabla de simbolos */
char *aplex;
int complex;
}entrada;
//entrada tablasimb[MAXSIMB]; /* tabla de simbolos */

//void analizsint();
int analex();
int busca(char *s);
void inic();
void error(char *m);
void emite (int t,int tval);
void analsint();
int inserta(char *s, int clex);
void expr();
//void expre();
void termino();
void factor();
void parea (int t);





Automata de Pila






   
Iníciales        
 E  ->  (, i
T  ->   (, i
F  ->   (, i
E'  ->  +, #
T'  ->  *, #                                                 

Seguidores


E -> $,)
T -> +, $,)
F -> *,+, $,)
E' -> $,)
T'-> +, $,)


Codigo

// **** Automata2.cpp **** \\



#include
#include "Pila.h"


using namespace std;


#define E1    -1
#define E2 -2
#define E3 0
#define Maximo   100


char *Prod[12] = { "T", "T'", "E", "E'", "F", "+", "*", "#", "I", "(", ")", "$" };


int tblAutomata[6][6]={
{0,99,99,0,99,99},
{99,1,99,99,2,2},
{3,99,99,3,99,99},
{99,5,4,99,5,5},
{6,99,99,7,99,99},
{99,99,99,99,99,100}};


enum Producciones { T, T_P, E, E_P, F, ADD, MUL, V, ID, PAR_A, PAR_C, FC };






CStack Pila( sLong(100) ); // DECLARACION DE LA PILA


int AutoTabla( const char* cadena );








void main()
{
   char cadena_ent[ Maximo ];
   
   cout << "*******AUTOMATA DE PILA**********"<<
     cout << "INCERTA CADENA: ";
     cin.getline( cadena_ent, Maximo);     
     strcat( cadena_ent,"$" ); //AGREGA SIMBOLO AL FINAL DE LA CADENA
     
     switch(AutoTabla(cadena_ent))
      {
        case E1: cout << "Error en la sintaxis" << endl; break;
        case E2: cout << "Caracter no valido" <
        case E3: cout << "ACEPTADA"<
      }
     
     Pila.sDelete();//ELIMINA LA PILA
}


int AutoTabla( const char *cadena )
{
   int i=0,tamCad=strlen(cadena);
   long elem, col=0,fil=0,pa=0;
   char *tmp;
   
   Pila.sPush( (long)&Prod[ FC ][ 0 ],NULL ); // INSERTA SIMBOLO DE FIN DE CADENA
   Pila.sPush( (long)&Prod[ E ][ 0 ], NULL ); // INSERTA INCIAL DE L APILA
   
   while(cadena[i])
    {
       Pila.sPeek( elem, NULL );
       tmp=(char*)elem;
       
       if(tmp[0]==cadena[i] || (isalpha(cadena[i]) && tmp[0]=='I'))
        {
          if( cadena[ i ] == '$' )
            if( !pa ) return E3;
else
return E1;
          
          if( cadena[ i ] == '(' )
 pa++;
          else 
 if( cadena[ i ] == ')' ) pa--;
           
          Pila.sPop( elem,NULL );
          i++; 
 continue;
        }
  
  
  
  
  
  
  ///////////////////////////////////////////////////////////////////////////////////////////////
  /////////////DA VALORES A FINA Y COLUMNA PARA RECORRER LA TABLA////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////
         
       if( !strcmp((char*)elem,Prod[E])) 
  fil = 0;   
       else 
  if( !strcmp( (char*)elem,Prod[E_P]) )
  fil = 1;
  else 
  if( !strcmp( (char*)elem,Prod[T]) ) 
  fil = 2;
  else 
  if( !strcmp( (char*)elem,Prod[T_P]) ) 
  fil = 3;
  else 
  if( !strcmp( (char*)elem,Prod[F]) ) 
  fil = 4;
  else
  if( !strcmp( (char*)elem,Prod[FC]) ) 
  fil = 5;
       
       if( isalpha( cadena[ i ] ) ) 
  col = 0;
       else
  if( cadena[ i ] == '+' ) 
  col = 1;
  else 
  if( cadena[ i ] == '*' ) 
  col = 2;
  else 
  if( cadena[ i ] == '(' ) 
  col = 3;
  else if( cadena[ i ] == ')' ) 
  col = 4;
  else 
  if( cadena[ i ] == '$' ) col = 5;


  else return E2;


  ///////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////






       switch( tblAutomata[fil][col] )//RECORRE LA TABLA
        {
          case 0:Pila.sPop( elem,NULL ); Pila.sPush( (long)&Prod[E_P][0],NULL );Pila.sPush( (long)&Prod[T][0],NULL ); 
            break;           
          case 1:Pila.sPop( elem,NULL);Pila.sPush( (long)&Prod[E_P][0],NULL );Pila.sPush( (long)&Prod[T][0],NULL );
 Pila.sPush( (long)&Prod[ADD][0],NULL );
            break;           
          case 2:Pila.sPop( elem,NULL );break;
 case 3:Pila.sPop( elem,NULL );Pila.sPush( (long)&Prod[T_P][0],NULL );Pila.sPush( (long)&Prod[F][0],NULL );
           break;           
          case 4:Pila.sPop( elem,NULL );Pila.sPush( (long)&Prod[T_P][0],NULL );Pila.sPush( (long)&Prod[F][0],NULL );
 Pila.sPush( (long)&Prod[MUL][0],NULL );
 break;
 case 5:Pila.sPop( elem,NULL );break;          
          case 6:Pila.sPop( elem,NULL );Pila.sPush( (long)&Prod[ID][0],NULL );break;           
          case 7:Pila.sPop( elem,NULL );Pila.sPush( (long)&Prod[PAR_C][0],NULL );Pila.sPush( (long)&Prod[E][0],NULL );
             Pila.sPush( (long)&Prod[PAR_A][0],NULL );break;           
          case 99: return E2;
          
          case 100: return E3;
        }




    }


   return E1;
}


// **** Pila.h **** \\

#ifndef STACK_CPP_H
#define STACK_CPP_H

#ifndef NULL
 #define NULL 0
#endif

  // constantes de excepciones
#define STACK_SUCCESS    0
#define STACK_EMPTY     -1
#define STACK_FULL      -2
#define STACK_ERR_MEM   -3
#define STACK_OUT_RANGE -4

#define sShort(code) (short)code
#define sLong(value) (long)value

typedef struct _STACK_SEGMENT // segmento de pila
{
  long dwData;
  void *vpAux;
  
} STACK_SEGMENT;
  
class CStack // clase manejadora de pila
{
   private:
    STACK_SEGMENT **sSegments;
    long dwSP;
    long dwSSize;
    short wExCod;
    
   public:
    CStack( long sMaxSize );
    CStack( short wCode ) : wExCod(wCode) { this-> sSegments = NULL; }
    ~CStack();
    
    const char* what() const throw();
    
    short sGetExCode();
    long GetSP();
    long GetStackMaxSize();
    long sPush( long dwData, const void** vpAux );
    long sPop( long& dwData, void** vpAux );
long sPeek( long& dwData, void** vpAux );
    long sDelete();
};
  // constructor
CStack::CStack( long sMaxSize )
  this-> dwSP      = -1;
  this-> wExCod    = 0;
  this-> dwSSize   = sMaxSize;
  this-> sSegments = NULL;
}

CStack::~CStack() { this-> sDelete(); } // Destructor

inline long CStack::GetSP() { return this-> dwSP; } // obtiene el puntero de pila

inline long CStack::GetStackMaxSize() { return this-> dwSSize;} // obtiene el tamaño maximo de pila

inline short CStack::sGetExCode() { return this-> wExCod; } // obtiene el codigo de excepcion

long CStack::sPush( long dwData, const void** vpAux ) // inserta un elemento en la pila
{
   STACK_SEGMENT **sAux;
   long i;
      // si la pila esta llena
   if( this-> dwSP >= this-> dwSSize-1 ) throw CStack( sShort(STACK_FULL) );

   this-> dwSP++;
   
   if( !this-> dwSP ) // si es el primer elemento
    {
      this-> sSegments = new STACK_SEGMENT* [this-> dwSP+1];
      if( !this-> sSegments ) throw CStack( sShort(STACK_ERR_MEM) );
      
      this-> sSegments[ this-> dwSP ] = new STACK_SEGMENT;
      if( !this-> sSegments[ this-> dwSP ] ) throw CStack( sShort(STACK_ERR_MEM) );
    }
   
   else // numero de elementos > 1
    {
      sAux = new STACK_SEGMENT* [this-> dwSP+1];
      if( !sAux ) throw CStack( sShort(STACK_ERR_MEM) );
      
      sAux[ this-> dwSP ] = new STACK_SEGMENT;
      if( !sAux[ this-> dwSP ] ) throw CStack( sShort(STACK_ERR_MEM) );
      
      for( i=0 ; i < this-> dwSP; i++ ) sAux[ i ] = this-> sSegments[ i ];
      
      delete[] this-> sSegments;
      
      this-> sSegments = sAux;
    }

   this-> sSegments[ this-> dwSP ]-> dwData = dwData;
   
   if( vpAux )
     this-> sSegments[ this-> dwSP ]-> vpAux  = (void*)*vpAux;
   else
     this-> sSegments[ this-> dwSP ]-> vpAux  = NULL;
   
   return this-> dwSP;
} // fin de sPush()

long CStack::sPop( long& dwData, void** vpAux ) // extrae un elemento de la pila
{
   STACK_SEGMENT **sAux;
   long i, tmpSP;
      // si la pila esta vacia
   if( this-> dwSP < 0 ) throw CStack( sShort(STACK_EMPTY) );
     
   dwData  = this-> sSegments[ this-> dwSP ]-> dwData;
   if( vpAux ) *vpAux = this-> sSegments[ this-> dwSP ]-> vpAux;
 
   if( !this-> dwSP ) // si hay un elemento
    {  
      delete this-> sSegments[ this-> dwSP ];
      delete[] this-> sSegments;
      
      this-> dwSP = -1;
    }
   
   else // si hay mas de 1 elemento
    { 
      sAux = new STACK_SEGMENT* [ this-> dwSP ];
      if( !sAux ) throw CStack( sShort(STACK_ERR_MEM) );
      
      delete this-> sSegments[ this-> dwSP ];
   
      this-> dwSP--;
 
      for( i=0; i <= this-> dwSP; i++ ) sAux[ i ] = this-> sSegments[ i ];
   
      delete[] this-> sSegments;
      
      this-> sSegments = sAux;
    }
    
   return this-> dwSP;
} // fin de sPop()
  // obtiene el elemeto en la cima sin extraerlo
long CStack::sPeek( long& dwData, void** vpAux )
{
   if( this-> dwSP < 0 ) throw CStack( sShort(STACK_EMPTY) );
   
   dwData = this-> sSegments[ this-> dwSP ]-> dwData;
   if( vpAux ) *vpAux  = this-> sSegments[ this-> dwSP ]-> vpAux;
   
   return this-> dwSP;
}

long CStack::sDelete() // Elimina la pila
{
   if( this-> sSegments )
    {
      for( ; this-> dwSP >= 0; this-> dwSP-- ) delete this-> sSegments[ this-> dwSP ];

      delete[] this-> sSegments;
    }
    
   return STACK_SUCCESS;
}

const char* CStack::what() const throw() // devuelve el texto de la excepcion
{
   switch( this-> wExCod )
    {
      case STACK_SUCCESS: return "Exito";
      case STACK_FULL:    return "Pila llena";
      case STACK_EMPTY:   return "Pila Vacia";
      case STACK_ERR_MEM: return "Error de asignacion de memoria";
    }
   
   return NULL;
}

#endif


                                                                                                                                           







Calculo De Iniciales

// ******************* Iniciales.cpp ******************* \\


#include "iniciales.h"

char NT[100];
char Terminales[100];

int main( int argc, char** argv )
{
   CIniciales calcIni;
   fstream Salida;
   char buffIni[100] = "";
   int i;
   cout<<"***** Calculo de Iniciales ***** "<
   cout<
  

         calcIni.SetFname( "Gramatica.txt" );//Archivo

if( calcIni.CargarGramatica() == NOABRE )
cout << "error al abrir la gramatica!" << endl;

 
 

   else
    {   char nt[ 100 ], alf[ 100 ], ini[ 100 ];
      
        for( i=0; i <= calcIni.NumProducciones(); i++ ) // Iniciales
         {
           calcIni.ObtenerProduccion( nt, alf, ini, i );
          
           if( !strlen( ini ) ) calcIni.CalcIniciales( i, buffIni );
         }
      
        Salida.open( SALIDA, ios::out );
      
        if( Salida.fail() ) cout << "Iniciales NO Guardados" << endl;
      
        else
         {
           for( i=0; i <= calcIni.NumProducciones(); i++ )
            {
              calcIni.ObtenerProduccion( nt, alf, ini, i );
              Salida << nt << " -> " << ini << endl;
 cout<< nt << " -> " << ini << endl;
            }
           cout<
 
cout << "Gonzalez Martinez David" << endl;
          cout<
 cout<



         }
    }

   if( argc > 1 ) cin.sync(), cin.get();
  
   cout << 0;
  
   return 0;
}

int BuscarTerminal( const char* T )
{
  int i;
 
  for( i=0; Terminales[ i ]; i++ ) if( Terminales[ i ] == T[0] ) return i;
 
  return ERROR_NO_ENCONTRADO;
}

CIniciales::CIniciales()
{
   this-> prod = NULL;
   this-> ultimaProd = -1;
}

CIniciales::~CIniciales()
{
   int i = this-> ultimaProd;
  
   if( this-> prod ) // si es distinto de NULL
    {
      for( ; i >= 0; i--)
       {
          delete[] this-> prod[ i ].Nterminal;
          delete[] this-> prod[ i ].Alfa;
          delete[] this-> prod[ i ].inicial;
       }
    
      delete[] this-> prod;
    }
}
  
inline int CIniciales::NumProducciones() { return this-> ultimaProd; }

inline int CIniciales::SetFname( const char* File )
{ strcpy( this-> archivo, File ); return 0; }

int CIniciales::CargarGramatica()
{
   char buffer[ MAX_BUFF ];
   char Nt[ 20 ], alf[ 100 ];
   char auxNt[ 20 ], auxAlfa[ 100 ], auxIni[ 3 ];
   int i = 0, j = 0, ind;
   fstream fgrama;
  
   fgrama.open( this-> archivo, ios::in );
   if( fgrama.fail() ) return NOABRE;
  
   fgrama.getline( buffer, MAX_BUFF );
  
   while( buffer[ i++ ] != '=' ) ;
  
   i++;
  
   while( buffer[ i ] ) // obtienes no terminales
    {
      if( buffer[ i ] != ' ' ) NT[ j++ ] = buffer[ i ];
      
      i++;
    }
      
   NT[ j ] = 0;
  
   fgrama.getline( buffer, MAX_BUFF );
      
   i = 0; j = 0;
  
   while( buffer[ i++ ] != '=' ) ;
  
   i++;
      
   while( buffer[ i ] ) // obtienes terminales
    {
      if( buffer[ i ] != ' ' && buffer[ i ] != ',' ) Terminales[ j++ ] = buffer[ i ];

      i++;
    }
      
   Terminales[ j ] = 0;
  
   while( !fgrama.eof() ) // carga las producciones
    {
       fgrama.getline( buffer, MAX_BUFF );
      
       if( !strlen( buffer ) ) continue;
      
       for( j=0, i=0; buffer[ i ]; i++ ) // obtiene el no terminal
        {
           if( buffer[ i ] == ' ' ) continue;

           if( buffer[ i ] != '-' && buffer[ i+1 ] != '>' )
            {
              Nt[ j++ ] = buffer[ i ];
              continue;
            }
          
           else
            {
              Nt[ j ] = 0;
              i += 2;
              break;
            }
        }
      
       for( j=0; buffer[ i ]; i++ )
        {
           if( buffer[ i ] == ' ' ) continue;
          
           alf[ j++ ] = buffer[ i ];
        }
      
       alf[ j ] = 0;
      
       ind = this-> BuscarProduccion( Nt ); // busca una produccion
      
       if( ind != ERROR_NO_ENCONTRADO )
        {
          this-> ObtenerProduccion( auxNt, auxAlfa, auxIni, ind );
        
          strcat( auxAlfa, "," ); strcat( auxAlfa, alf );
        
          this-> ModificarProduccion( Nt, auxAlfa, "", ind );
        }
      
       else  this-> AgregarProduccion( Nt, alf, "" );
      
    }
  
   fgrama.close();
  
   return 0;
}

int CIniciales::CalcIniciales( int indice, char* lista_ini )
{
   int i, j, tam, ind, k;
   char temp[ 5 ];
  
   tam = strlen( this-> prod[ indice ].Alfa );
   k = strlen( lista_ini );
  
   for( i=0, j=0, k=0; i < tam; i++ )
    {
      temp[ j ] = this-> prod[ indice ].Alfa[ i ];

      if( this-> prod[ indice ].Alfa[ i+1 ] == '\'' )
       {
         temp[ j++ ] = this-> prod[ indice ].Alfa[ i++ ];
       }
    
      temp[ ++j ] = 0;

      ind = BuscarTerminal( temp );
    
      if( ind != ERROR_NO_ENCONTRADO )
       {
         lista_ini[ k++ ] = Terminales[ ind ];
         lista_ini[ k++ ] = ',';
         lista_ini[ k ] = 0;
       }
      
      else
       {
         ind = this-> BuscarProduccion( temp );
        
         this-> CalcIniciales( ind, lista_ini );
         k = strlen( lista_ini );
       }
    
      for( i++; this-> prod[ indice ].Alfa[ i ]; i++ )
       {
         if( this-> prod[ indice ].Alfa[ i ] == ',' ) break;
       }
      
      j = 0;
    }
  
   if( this-> prod[indice].inicial ) delete[] this-> prod[ indice ].inicial;
  
   if( lista_ini[ k-1 ] == ',' ) lista_ini[ k-1 ] = 0;
  
   this-> prod[ indice ].inicial = new char[ strlen( lista_ini )+1 ];
   strcpy( this-> prod[ indice ].inicial, lista_ini );
  
   return 0;
}

int CIniciales::AgregarProduccion( const char* Nterm, const char* alfa, const char* Inicial )
{
   int i = 0;
   PRODUCCION *temp;
  
   this-> ultimaProd++;
  
   temp = new PRODUCCION[ this-> ultimaProd+1 ];
  
   if( !temp ) return ERROR_DE_ASIGNACION_DE_MEMORIA;
  
   for( ; i < this-> ultimaProd; i++ )
    {
      temp[ i ].Nterminal = this-> prod[ i ].Nterminal;
      temp[ i ].Alfa    = this-> prod[ i ].Alfa;
      temp[ i ].inicial = this-> prod[ i ].inicial;
    }
  
   delete[] this-> prod;
  
   temp[ i ].Nterminal = new char[ strlen( Nterm ) +1 ];
   temp[ i ].Alfa    = new char[ strlen( alfa ) +1 ];
   temp[ i ].inicial = new char[ strlen( Inicial ) +1 ];
  
   if( !temp[ i ].Nterminal || !temp[ i ].Alfa || !temp[ i ].inicial )
     return ERROR_DE_ASIGNACION_DE_MEMORIA;
    
   strcpy( temp[ i ].Nterminal, Nterm );
   strcpy( temp[ i ].Alfa, alfa );
   strcpy( temp[ i ].inicial, Inicial );
  
   this-> prod = temp;
  
   return this-> ultimaProd;
}

int CIniciales::BuscarProduccion( const char* Nterm )
{
   int i = 0;
  
   while( i <= this-> ultimaProd )
    {
      if( !strcmp( this-> prod[ i ].Nterminal, Nterm ) ) return i;
      i++;
    }
      
   return ERROR_NO_ENCONTRADO;
}

int CIniciales::ModificarProduccion( const char* Nterm, const char* alfa, const char* Inicial, int indice )
{
   if( indice < 0 || indice > this-> ultimaProd ) return ERROR_FUERA_DE_RANGO;
  
   delete[] this-> prod[ indice ].Nterminal;
   delete[] this-> prod[ indice ].Alfa;
   delete[] this-> prod[ indice ].inicial;
  
   this-> prod[ indice ].Nterminal = new char[ strlen( Nterm ) +1 ];
   this-> prod[ indice ].Alfa    = new char[ strlen( alfa ) +1 ];
   this-> prod[ indice ].inicial = new char[ strlen( Inicial ) +1 ];
  
   if( !prod[ indice ].Nterminal || !prod[ indice ].Alfa || !prod[ indice ].inicial )
      return ERROR_DE_ASIGNACION_DE_MEMORIA;
    
   strcpy( this-> prod[ indice ].Nterminal, Nterm );
   strcpy( this-> prod[ indice ].Alfa, alfa );
   strcpy( this-> prod[ indice ].inicial, Inicial );
  
   return indice;
}

int CIniciales::ObtenerProduccion( char* Nterm, char* alfa, char* Inicial, int indice )
{
   if( indice < 0 || indice > this-> ultimaProd ) return ERROR_FUERA_DE_RANGO;
  
   strcpy( Nterm, this-> prod[ indice ].Nterminal );
   strcpy( alfa, this-> prod[ indice ].Alfa );
   strcpy( Inicial, this-> prod[ indice ].inicial );
  
   return indice;
}
// ******************* Iniciales.h ******************* \\

#ifndef INICIALES_H
#define INICIALES_H

#include
#include
#include

using namespace std;

#ifndef MAX_PATH
#define MAX_PATH 256
#endif

#define MAX_BUFF 256

#define SALIDA "iniciales.txt"

#define ERROR_DE_ASIGNACION_DE_MEMORIA -1
#define NOABRE   -2
#define ERROR_NO_ENCONTRADO   -3
#define ERROR_FUERA_DE_RANGO           -4


typedef struct _PRODUCCION
{
   char *Nterminal;
   char *Alfa;
   char *inicial;
   
} PRODUCCION;

 // clase que se utilizan para el de archivos
class CIniciales
{
   private:
    PRODUCCION *prod;
    int  ultimaProd;
    char archivo[ MAX_PATH ];

   public:
    CIniciales();
    ~CIniciales();
    
    int SetFname( const char* File );
    int CalcIniciales( int indice, char* lista_ini );
    int NumProducciones();
    
    int CargarGramatica();
    int AgregarProduccion( const char* Nterm, const char* alfa, const char* Inicial );
    int BuscarProduccion( const char* Nterm );
    int ModificarProduccion( const char* Nterm, const char* alfa, const char* Inicial, int indice );
    int ObtenerProduccion( char* Nterm, char* alfa, char* Inicial, int indice );
};

int BuscarTerminal( const char* T );

#endif

// ******************* Iniciales.txt ******************* \\

E -> (,i
E' -> +,#
T -> (,i
T' -> *,#
F -> (,i

// ******************* Gramatica.txt ******************* \\

NT = E,E',T,T',F
T = +,*,(,),#,i


E  -> TE'
E' -> +TE'
E' -> #
T  -> FT'
T' -> *FT'
T' -> #
F  -> (E)
F  -> i



Doxygen

// ******************* FILTRO ******************* //
#include
#include
#include

using namespace std;
#define TAM 170

//definimos variables globales
char cad[TAM];
int cont_esp;
bool flag_coment=false,flag_pal=false,flag_pre=false,flag_class;
int cont=0;


//funcion principal
int main(int argc, char** argv)
{
ifstream entrada;
if(argc>=2)
{
entrada.open(argv[1], ios::in);
// cout<<"parametros"<
}
else
{
entrada.open("cod.txt");
// cout<<"sin parametros"<
}
fstream a;
a.open("funcion_cod.txt",ios::out);
// ofstream salida("procesado.h");
// salida.close();
flag_class=false;
//primero vemos si existe nuestro archivo
if(!entrada.fail())
{
a<<"class "<<"doxygen"<
a<<"public:"<
while(!entrada.eof())
{
entrada.getline(cad,TAM);
if(cad[0]=='/' && cad[1]=='/')
{
int o=1;
a<<"///";
while(cad[o]!=0)
{
a<
o++;
}
a<
}
else
{
if(cad[0]=='f' && cad[1]=='u' && cad[2]=='n' && cad[3]=='c' && cad[4]=='t' && cad[5]=='i' && cad[6]=='o'&& cad[7]=='n'&& cad[8]==' ')
{
cont=1;
int o = 9;
a<<"int";
while(cad[o]!='(')
{
a<
o++;
}
a<
o++;
a<<"int";
while(cad[o]!=0)
{
a<
o++;
}
a<<";"<
o=0;
}
}
}//while
a<<"};"<
}
//sino existe
else
cout<<"El archivo no fue encontrado"<
entrada.close();
// salida.close();
system("pause");
return 0;
}




// ******************** cod.txt *********************** //


// Comentarios Ehuporia //
// se inicia un if
if a >= 1 then
// se inicia otro if
if a >= 1 then
// declaro cero
cero = 0
// fin del if segundo
end if
// fin del primer if
end if
function david (c)
function suma (a)
function resta (a)


// ************************* funcion_cod *********************** //

class doxygen
{
public:
//// Comentarios Ehuporia //
//// se inicia un if
//// se inicia otro if
//// declaro cero
//// fin del if segundo
//// fin del primer if
intdavid (intc);
int suma (inta);
int resta (inta);
};

Ehuporia

// Programa //

#include
#include
#include
#include
#include


int ver(char cadena[20]);

int ver_linea(int linea[50],int tam,int l);
int ver_estructura(int linea[50],int tam);


char reservadas[11][9]=
{

{'i','f'},
{'w','h','i','l','e'},
{'f','o','r'},
{'e','n','d'},
{'t','h','e','n'},
{'f','u','n','c','t','i','o','n'},
{'i','n','t','e','g','e','r'},
{'r','e','t','u','r','n'},
{'d','o'},
{'b','y'},
{'t','o'},
};

int estructura_programa[6][8]=
{
{0, 0, 0, 0, 0, 0, 0, 0},
{2, 0, 3, 0, 4, 0, 1, 1},
{2, 5, 3, 0, 4, 0, 2, 2},
{2, 0, 3, 5, 4, 0, 3, 3},
{2, 0, 3, 0, 4, 5, 4, 4},
{2, 0, 3, 0, 4, 0, 5, 0},

};


char operadores_logicos[4]={'<','>','=','!'};
int op_log[5][4]=
{
{0, 0, 0, 0},
{2, 2, 4, 4},
{0, 0, 3, 0},
{0, 0, 0, 0},
{0, 0, 3, 0},
};
int ident[3][2]=
{
{0, 0},
{2, 0},
{2, 2},

};
int begin_if[7][5]=
{
{0, 0, 0, 0, 0},
{2, 0, 0, 0, 0},
{0, 3, 3, 0, 0},
{0, 0, 0, 4, 0},
{0, 5, 5, 0, 0},
{0, 0, 0, 0, 6},
{0, 0, 0, 0, 0},
};

int begin_while[7][5]=
{
{0, 0, 0, 0, 0},
{2, 0, 0, 0, 0},
{0, 3, 3, 0, 0},
{0, 0, 0, 4, 0},
{0, 5, 5, 0, 0},
{0, 0, 0, 0, 6},
{0, 0, 0, 0, 0},
};
int begin_function[8][6]=
{
{0, 0, 0, 0, 0, 0},
{2, 0, 0, 0, 0, 0},
{0, 3, 0, 0, 0, 0},
{0, 0, 4, 0, 0, 0},
{0, 0, 0, 5, 7, 0},
{0, 6, 0, 0, 0, 0},
{0, 0, 0, 0, 4, 7},
{0, 0, 0, 0, 0, 0},

};
int mate[6][4]=
{
{0, 0, 0, 0},
{2, 0, 0, 0},
{0, 3, 0, 0},
{4, 0, 4, 0},
{0, 0, 0, 5},
{4, 0, 4, 0},


};
int return1[4][3]=
{
{0, 0, 0},
{0, 0, 2},
{3, 3, 0},
{0, 0, 0},



};
int endif[4][2]=
{
{0, 0},
{0, 2},
{3, 0},
{0, 0},


};
int endwhile[4][2]=
{
{0, 0},
{0, 2},
{3, 0},
{0, 0},


};


char alfabeto[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char digitos[10]={'0','1','2','3','4','5','6','7','8','9'};








char opemat[4]={'+','-','*','/'};


char igual='=';
int errores_line=0;


char cadena[50][20];

char identificador[50][20];
int tipo_id[50];
int tipo=0;
int nido=0;
int tokens=0;
int linea_val[30];
int errores_lexico=0;
int main()
{
cout<<"***********ANALISIS LEXICO*********** "<
ifstream archivo("cod.txt", ios::in);
char var;
int x=0,y=0;
int lin=1;
int linea[50];
int tokens_linea[50][2];


while(!archivo.eof())
{
archivo.get(var);
if(var==' '||var=='\n')
{
x=0;
tokens_linea[y][0]=ver(cadena[y]);
if(tokens_linea[y][0]==0)
errores_lexico++;
tokens_linea[y][1]=lin;
cout<<" token "<
cout<
linea[y]=lin;
tokens++;
if(var=='\n')
{
lin++;



}
y++;

}
else
{

cadena[y][x]=var;
cout<
x++;
}
}
cout<
if(errores_lexico==0)
{
cout<<"!!presione cualquier tecla para continuara no se encontaron errores lexicos!!"<

}
else
{
cout<<" se encontraron "<
cout<<"verifique su codigo se encontaron errores el compilador no puede continuar"<
return 0;
}
getch();
system("cls");
int errores_line=0;
//cout<<"*********** ANALISIS SINTACTICO *************"<
cout<<" *Etapa 1 analisar la sintaxis de cada linea "<
cout<<" *Etapa 2 analisar de la estructura del programa "<
cout<<"********************************************************************************"<

cout<<" presione cualquier tecla para continuar"<
getch();
system("cls");
////////analiza linea
// cout<<"*********** ANALISIS SINTACTICO *************"<
cout<<"************ LEE LINEA x LINEA **************"<
int arre_struct[50];
errores_line=0;
int mains=0;
for(int da=0; da
{
int paquete1[50];
int tam=0;
for(int f=0; f
{
if(tokens_linea[f][1]==(da+1))
{
paquete1[tam]=tokens_linea[f][0];
tam++;
int tr=strlen(cadena[f]);
for(int lr=0; lr
{
cout<
}
cout<<" ";
}
}

cout<<" <===== ";

arre_struct[da]=ver_linea(paquete1,tam,da);
if(arre_struct[da]==0)
{
errores_line++;
mains=da+1;
}
cout<

}
if(errores_line==0)
{
cout<<"!!sin errores en las linea!!"<
}
if(errores_line>0)
{
cout<<" !! se encontraron "<
return 0;
}
cout<<" presione cualquier tecla para continuar"<
getch();
system("cls");
cout<
for(int matriz=0; matriz<600;matriz++)
{
cout<<"...espere analizando...no se ha siclado...";
}
cout<
system("cls");
cout<
cout<<"****************ETAPA 2 EVALUAR ESTRUCTURA*****************"<
int estatus=ver_estructura(arre_struct,lin);
if(estatus==0)
return 0;
getch();



for(int r=0; r
{


if(tipo_id[r]==1||tipo_id[r]==2)
{
cout<<" la variable " ;

int as=strlen(identificador[r]);
for(int f=0; f
{
cout<
}
cout<<" es de tipo ";
cout<
cout<
}
}







}
//funcion que renvia
int ver(char cadena[20])
{




//analisza palabras reservadas
int lon=strlen(cadena);
int q=0;
int x, y;
for( x=0; x<11; x++)
{
q=0;
for( y=0; y
{
if(cadena[y]==reservadas[x][y])
{
q++;
}
}
int as=strlen(reservadas[x]);
if(q==as)
{
cout<<" palabra reservada";

if(x==0||x==1||x==2||x==7)
{
cout<<"esta palabra es compatible con c++";

}

return x+1;
}

}

////analiza cadena
int pos=1,d=0;
if(cadena[0]=='"'&&cadena[lon-1]=='"')
{
for( x=1; x
{
for( y=0; y<26;y++)
{
if(alfabeto[y]==cadena[x])
{
d++;
}
}
for( int z=0; z<10;z++)
{
if(digitos[z]==cadena[x])
{
d++;
}
}
}

if(d==lon-2)
{
cout<<" cadena ";
return 20;
}
}



//analiza identificadores
pos=1,d=2;
for( x=0; x
{
d=2;
for( y=0; y<26;y++)
{
if(alfabeto[y]==cadena[x])
{
d=0;
}
}
for( int z=0; z<10;z++)
{
if(digitos[z]==cadena[x])
{
d=1;
}
}
if(d==2)
{
pos=0;
}
else
{
pos=ident[pos][d];
}
}

if(pos==2)
{
cout<<"Identificador ";
for(int gp=0; gp<2; gp++)
{
identificador[nido][gp]=cadena[gp];
}
nido++;



return 12;
}
//analiza si es numero
int jk=0;
for( x=0; x
{
for( y=0; y<10;y++)
{
if(cadena[x]==digitos[y])
{
jk++;
}
}
}

if(jk==lon)
{
cout<<" numero";
return 13;
}
//analiza si es un operador matematico
if(lon==1)
{
for( x=0; x<4; x++)
{

if(opemat[x]==cadena[0])
{
cout<<" opera. mat. ";
return 14;
}

}

//analiza si es una coma

if(cadena[0]==',')
{
cout<<" coma ";
return 15;
}
//analiza si es un igual

if(cadena[0]=='=')
{
cout<<" igual ";
return 16;
}
//analiza si es parentesis de apertura

if(cadena[0]=='(')
{
cout<<" parentesis A ";
return 17;
}
//analiza si es un parentesis de cerradura

if(cadena[0]==')')
{
cout<<" parentesis B ";
return 18;
}
}

//analiza si es un operador logico
int pp=1, dd=2;
for( x=0; x
{
dd=25;
for( y=0; y<4;y++)
{
if(operadores_logicos[y]==cadena[x])
{
dd=y;
}
}
if(dd==25)
{
pp=0;
}
else
{
pp=op_log[pp][dd];
}
}
if(pp==2||pp==3)
{
cout<<" operador logico ";
return 19;

}


cout<<"************************************************** ";

return 0;
}
////***********************************************************
int ver_linea(int linea[50],int tam,int l)
{

if(tam==3)
{
if(linea[0]==12)
if(linea[1]==16)
if(linea[2]==13)
{
cout<<"Es una declaracion de variable tipo interger";
tipo_id[tipo]=1;
tipo++;
return 9;
}
else
if(linea[2]==20)
{
cout<<"Es una declaracion de variable tipo string";
tipo_id[tipo]=2;
tipo++;
return 9;
}
else
if(linea[2]==12)
{
cout<<"Es Asignacion del valor de una variable";
tipo_id[tipo]=0;
tipo++;
tipo++;
return 9;

}


}

int estado=1;
int val_if[5]={1,12,13,19,5};

for(int c=0; c
{
for(int ro=0; ro<5; ro++)
{
if(linea[c]==val_if[ro])
{
estado=begin_if[estado][ro];
}
}
}
if(estado==6)
{
cout<<"la linea "<
tipo_id[tipo]=0;
tipo++;
return 1;

}

//fin del if

estado=1;
int val_endif[2]={1,4};



for(int ca=0; ca
{
for(int ro=0; ro<2; ro++)
{
if(linea[ca]==val_endif[ro])
{
estado=endif[estado][ro];
}
}
}
if(estado==3)
{
cout<<"la linea "<
return 2;
}

//inicio while
estado=1;
int val_while[5]={2,12,13,19,9};

for(int cu=0; cu
{
for(int ro=0; ro<5; ro++)
{
if(linea[cu]==val_while[ro])
{
estado=begin_while[estado][ro];
}
}
}
if(estado==6)
{
cout<<"la linea "<
tipo_id[tipo]=0;
tipo++;
return 3;

}
//fin del while
estado=1;
int val_endwhile[2]={2,4};



for(int ce=0; ce
{
for(int ro=0; ro<2; ro++)
{
if(linea[ce]==val_endwhile[ro])
{
estado=endwhile[estado][ro];
}
}
}
if(estado==3)
{
cout<<"la linea "<
return 4;
}
//inicio function
estado=1;
int val_function[6]={6,12,17,7,15,18};

for(int cd=0; cd
{
for(int ro=0; ro<6; ro++)
{
if(linea[cd]==val_function[ro])
{
estado=begin_function[estado][ro];
}
}
}
if(estado==7)
{
cout<<"la linea "<
tipo_id[tipo]=0;
tipo++;
return 5;

}
//fin de function
estado=1;
int val_endfunction[2]={6,4};



for(int cq=0; cq
{
for(int ro=0; ro<2; ro++)
{
if(linea[cq]==val_endfunction[ro])
{
estado=endwhile[estado][ro];
}
}
}
if(estado==3)
{
cout<<"la linea "<
return 6;
}

//operacion mate
estado=1;
int val_matema[4]={12,16,13,14};



for(int cl=0; cl
{
for(int ro=0; ro<4; ro++)
{
if(linea[cl]==val_matema[ro])
{
estado=mate[estado][ro];
}
}
}
if(estado==4)
{
cout<<"la linea "<
tipo_id[tipo]=0;
tipo++;
return 7;
}

//operacion return
estado=1;
int val_return[3]={12,13,8};



for(int ct=0; ct
{
for(int ro=0; ro<3; ro++)
{
if(linea[ct]==val_return[ro])
{
estado=return1[estado][ro];
}
}
}
if(estado==3)
{
cout<<"la linea "<
return 8;
}



cout<<"la linea "<
return 0;

}

///************************************************
int ver_estructura(int linea[50],int tam)
{
int estado=1;
int val_program[8]={1,2,3,4,5,6,7,8};
int num_if=0;
int num_whiles=0;
int num_function=0;







for(int c=0; c
{
cout<<"empiezo en el estado "<
for(int ro=0; ro<8; ro++)
{
if(linea[c]==val_program[ro])
{
if(estado==5)
{
if(val_program[ro]==2&&num_if>0)
{
estado=2;
}
if(val_program[ro]==4&&num_whiles>0)
{
estado=3;
}
if(val_program[ro]==6&&num_function>0)
{
estado=4;
}

}
estado=estructura_programa[estado][ro];
cout<<" con "<
if(val_program[ro]==1)
{
num_if++;
}
if(val_program[ro]==3)
{
num_whiles++;
}
if(val_program[ro]==5)
{
num_function++;
}
if(val_program[ro]==2)
{
num_if--;
}
if(val_program[ro]==4)
{
num_whiles--;
}
if(val_program[ro]==6)
{
num_function--;
}
}
}
}
if(estado==5&&num_if==0&& num_whiles==0&&num_function==0)
{
cout<>>>>>>>"<
return 1;
}
else
{
cout<<" error en la estructura"<
cout<
if(num_if>0)
{
cout<<"falta cerrar "<
}
if(num_whiles>0)
{
cout<<"falta cerrar "<
}
if(num_function>0)
{
cout<<"falta cerrar "<
}
return 0;
}
}




// ****************** Código En .txt que leo ******************** //

if a >= 1 then
if a >= 1 then
azu = b
end if
end if
while x > 0 do
a = 10 + 1
end while
b = a + 5
s = "hola"
d = 2