Click here to Skip to main content
15,880,725 members
Articles / Programming Languages / C++

Wave: a Standard conformant C++ preprocessor library

Rate me:
Please Sign up or sign in to vote.
4.96/5 (58 votes)
10 Jan 200413 min read 394.4K   4.4K   81  
Describes a free and fully Standard conformant C++ preprocessor library
/*=============================================================================
    Wave: A Standard compliant C++ preprocessor

    Copyright (c) 2001-2003 Hartmut Kaiser
    http://spirit.sourceforge.net/

    Permission to copy, use, modify, sell and distribute this software
    is granted provided this copyright notice appears in all copies.
    This software is provided "as is" without express or implied
    warranty, and with no claim as to its suitability for any purpose.

    See Copyright.txt for full copyright notices and acknowledgements.
=============================================================================*/

#if !defined(INTERPRET_PRAGMA_HPP_B1F2315E_C5CE_4ED1_A343_0EF548B7942A_INCLUDED)
#define INTERPRET_PRAGMA_HPP_B1F2315E_C5CE_4ED1_A343_0EF548B7942A_INCLUDED

#include <cstdlib>
#include <cstdio>
#include <string>
#include <list>

#include <boost/spirit/core.hpp>

#include "wave/util/pattern_parser.hpp"
#include "wave/util/macro_helpers.hpp"
#include "wave/cpplexer/cpp_token_ids.hpp"
#include "wave/cpp_exceptions.hpp"
#include "wave/cpp_iteration_context.hpp"
#include "wave/language_support.hpp"

///////////////////////////////////////////////////////////////////////////////
namespace wave {
namespace util {

///////////////////////////////////////////////////////////////////////////////
//
//  The function interpret_pragma interprets the given token sequence as the
//  body of a #pragma directive (or parameter to the _Pragma operator) and 
//  executes the actions associated with recognized Wave specific options.
//
///////////////////////////////////////////////////////////////////////////////
template <typename ContextT, typename IteratorT, typename ContainerT>
inline bool 
interpret_pragma(ContextT &ctx, typename ContextT::token_t const &act_token,
    IteratorT it, IteratorT const &end, ContainerT &pending,
    wave::language_support language)
{
    typedef typename ContextT::token_t token_t;
    typedef typename token_t::string_t string_t;
    
    using namespace cpplexer;
    if (T_IDENTIFIER == token_id(*it) && "wave" == (*it).get_value()) {
    //  this is a wave specific option, it should have the form:
    //      #pragma wave option(value)
    //  where '(value)' is required only for some pragma directives
    //
    //  supported #pragma directives so far:
    //      wave trace(enable) or wave trace(1)
    //      wave trace(disable) or wave trace(0)
    //      wave stop(errormessage)
    //      wave system(command)
    
        using namespace boost::spirit;
        token_t option;
        ContainerT values;
        
        if (!parse (++it, end, 
                        ch_p(T_IDENTIFIER)[assign(option)] 
                    >> !(   ch_p(T_LEFTPAREN) 
                        >>  lexeme_d[
                                *(anychar_p[append(values)] - ch_p(T_RIGHTPAREN))
                            ]
                        >>  ch_p(T_RIGHTPAREN)
                        ),
                pattern_p(WhiteSpaceTokenType, TokenTypeMask)).hit)
        {
            return false;
        }
    
    // remove the falsely matched closing paren
        if (values.size() > 0) {
            if (T_RIGHTPAREN == values.back()) {
            typename ContainerT::reverse_iterator rit = values.rbegin();
            
                values.erase((++rit).base());
            }
            else {
                CPP_THROW(preprocess_exception, ill_formed_pragma_option,
                    "missing matching ')'", act_token.get_position());
            }
        }
            
    // decode the option
        if (option.get_value() == "trace") {
        // enable/disable tracing option
        bool valid_option = false;
        
            if (1 == values.size()) {
            token_t const &value = values.front();
            
                if (value.get_value() == "enable" || 
                    value.get_value() == "1") 
                {
                    ctx.enable_tracing(true);
                    valid_option = true;
                }
                else if (value.get_value() == "disable" || 
                    value.get_value() == "0") 
                {
                    ctx.enable_tracing(false);
                    valid_option = true;
                }
            }
            if (!valid_option) {
            // unknown option value
            string_t option_str ("trace");

                if (values.size() > 0) {
                    option_str += "(";
                    option_str += impl::as_string(values);
                    option_str += ")";
                }
                CPP_THROW(preprocess_exception, ill_formed_pragma_option,
                    option_str, act_token.get_position());
            }
        }
        else if (option.get_value() == "stop") {
        // stop the execution and output the argument
            CPP_THROW(preprocess_exception, error_directive,
                impl::as_string(values), act_token.get_position());
        }
        else if (option.get_value() == "system") {
        // try to spawn the given argument as a system command and return the
        // std::cout of this process as the replacement of this _Pragma
            if (0 == values.size()) {
                CPP_THROW(preprocess_exception, ill_formed_pragma_option,
                    "system", act_token.get_position());
            }
            
        string_t stdout_file(std::tmpnam(0));
        string_t stderr_file(std::tmpnam(0));
        string_t system_str(impl::as_string(values));
        string_t native_cmd(system_str);
        
            system_str += " >" + stdout_file + " 2>" + stderr_file;
            if (0 != std::system(system_str.c_str())) {
            // unable to spawn the command
            string_t error_str("unable to spawn command: ");
            
                error_str += native_cmd;
                CPP_THROW(preprocess_exception, ill_formed_pragma_option,
                    error_str, act_token.get_position());
            }
            
        // rescan the content of the stdout_file and insert it as the 
        // _Pragma replacement
            typedef typename ContextT::lex_t lex_t;
            typedef 
                wave::iteration_context<lex_t, typename ContextT::input_policy_t>
                iteration_context_t;

        iteration_context_t iter_ctx(stdout_file.c_str(), 
            act_token.get_position(), language);
        ContainerT pragma;

            for (/**/; iter_ctx.first != iter_ctx.last; ++iter_ctx.first) 
                pragma.push_back(*iter_ctx.first);

        // prepend the newly generated token sequence to the 'pending' container
            pending.splice(pending.begin(), pragma);

        // erase the created tempfiles
            std::remove(stdout_file.c_str());
            std::remove(stderr_file.c_str());
        }
        else {
        // unknown #pragma option 
        string_t option_str (option.get_value());

            if (values.size() > 0) {
                option_str += "(";
                option_str += impl::as_string(values);
                option_str += ")";
            }
            CPP_THROW(preprocess_exception, ill_formed_pragma_option,
                option_str, act_token.get_position());
        }
        return true;
    }
    return false;
}

///////////////////////////////////////////////////////////////////////////////
}   // namespace util
}   // namespace wave

#endif // !defined(INTERPRET_PRAGMA_HPP_B1F2315E_C5CE_4ED1_A343_0EF548B7942A_INCLUDED)

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
Actively involved in Boost and the development of the Spirit parser construction framework.

Comments and Discussions