Click here to Skip to main content
15,881,715 members
Articles / Programming Languages / ASM

Fast Polymorphic Math Parser

Rate me:
Please Sign up or sign in to vote.
4.97/5 (30 votes)
3 Dec 2009CPOL13 min read 75.5K   1.4K   67  
An article which describes how to implement a fast polymorphic math parser using machine code generation methods.
#include "MathGrammar.h"
#include "MathFormula.h"
#include <boost/spirit/include/classic.hpp>

#ifdef _MSC_VER
#   pragma warning( disable : 4355 )
#endif

using namespace BOOST_SPIRIT_CLASSIC_NS;

MathGrammar::MathGrammar( MathFormula *formula ) :
    _formula( formula ),
    _doAdd( this ),
    _doSub( this ),
    _doMul( this ),
    _doDiv( this ),
    _doArg( this ),
    _doConst( this )
{
}

MathGrammar::AddFunctor::AddFunctor( MathGrammar *grammar ) : 
    _grammar( grammar ) 
{
}

void MathGrammar::AddFunctor::operator()( const char*, const char* ) const
{
    if ( NULL != _grammar && NULL != _grammar->_formula )
        _grammar->_formula->emitAddition();
}

MathGrammar::SubFunctor::SubFunctor( MathGrammar *grammar ) : 
    _grammar( grammar )
{
}

void MathGrammar::SubFunctor::operator()( const char*, const char* ) const
{
    if ( NULL != _grammar && NULL != _grammar->_formula )
        _grammar->_formula->emitSubstraction();
}

MathGrammar::MulFunctor::MulFunctor( MathGrammar *grammar ) : 
    _grammar( grammar ) 
{
}

void MathGrammar::MulFunctor::operator()( const char*, const char* ) const
{
    if ( NULL != _grammar && NULL != _grammar->_formula )
        _grammar->_formula->emitMultiplication();
}

MathGrammar::DivFunctor::DivFunctor( MathGrammar *grammar ) : 
    _grammar( grammar ) 
{
}

void MathGrammar::DivFunctor::operator()( const char*, const char* ) const
{
    if ( NULL != _grammar && NULL != _grammar->_formula )
        _grammar->_formula->emitDivision();
}

MathGrammar::ArgFunctor::ArgFunctor( MathGrammar *grammar ) : 
    _grammar( grammar ) 
{
}

void MathGrammar::ArgFunctor::operator()( char ) const
{
    if ( NULL != _grammar && NULL != _grammar->_formula )
        _grammar->_formula->emitArg();
}

MathGrammar::ConstFunctor::ConstFunctor( MathGrammar *grammar ) : 
    _grammar( grammar ) 
{
}

void MathGrammar::ConstFunctor::operator()( double constant ) const
{
    if ( NULL != _grammar && NULL != _grammar->_formula )
        _grammar->_formula->emitConstant( (float)constant );
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Poland Poland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions