A Simple Grammar
An example of a primitive translator, based on a true grammar. Converts an ariphmetic expression to a backward polish notation.
AI
AI Summary: This codebase represents a historical implementation of the logic described in the metadata. Our preservation engine analyzes the structure to provide context for modern developers.
Source Code
/* (c) Roman "Krishna" Bystritsky, 2001 */
/* file agram.cpp */
#include "string.hpp"
#include "iostream.h"
#include "stdio.h"
#include "agram.h"
/*
* Grammar:
*
* <formula> -> <term> { +/- <term> }
* <term> -> <element> { *\'/' <element> }
* <element> -> ( <formla> ) | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0
* +/- -> + | -
* * \ '/' -> * | /
**/
/* <formula> -> <term> { +/- <term> } */
int parseFormula( String& in, String& out, int& infix)
{
char cSign;
if(parseTerm(in,out, infix))
{
cout << "From parseFormula"<<endl;
return RET_ERR;
}
while( IsPM(cSign=in[infix]) )
{
infix++;
if(parseTerm(in,out,infix))
{
cout << "From parseFormula"<<endl;
return RET_ERR;
}
out += cSign;
out += ' ';
}
return RET_OK;
}
/* <term> -> <element> { *\'/' <element> } */
int parseTerm(String& in, String& out, int& infix)
{
char cSign;
if(parseElem(in,out,infix))
{
cout << "From parseTerm" << endl;
return RET_ERR;
}
while( IsMD(cSign=in[infix]) )
{
infix++;
if(parseElem(in,out,infix))
{
cout << "From parseTerm"<<endl;
return RET_ERR;
}
out += cSign;
out += ' ';
}
return RET_OK;
}
/* <element> -> ( <formla> ) | digit+*/
int parseElem(String& in, String& out, int& infix)
{
char cSign;
cSign = in[infix];
if(IsOB(cSign)) // case of ( formula )
{
infix ++;
if(parseFormula(in,out, infix))
{
cout << "from parseElem" << endl;
return RET_ERR;
}
cSign = in[infix];
infix++;
if(!IsCB(cSign))
{
cout << "parseElem: missing close brace c. " << infix+1 <<" "<<endl;
return RET_ERR;
}
} else
{
while(IsDigit(cSign))
{
out += cSign;
cSign= in[++infix];
}
if(cSign == '.' || cSign== ',')
{
out+='.';
cSign=in[++infix];
while(IsDigit(cSign))
{
out += cSign;
cSign= in[++infix];
}
}
out += ' ';
}
return RET_OK;
}
int parseExpression(String& in, String& out)
{
int infix = 0;
if(parseFormula(in, out, infix))
{
cout << "from parseExpression" << endl;
return RET_ERR;
}
if(infix != in.length())
{
cout << "parseExpression: Unknown symbol c. " << infix +1 << endl;
return RET_ERR;
}
return RET_OK;
}
Original Comments (3)
Recovered from Wayback Machine