How to add qi::symbols in grammar?

后端 未结 1 1926
生来不讨喜
生来不讨喜 2020-12-11 10:24

I am trying to use Boost.Spirit (V. 2.5) library to create a mini-calculator. Features I want to implement : - basic calculus (+,-,/,*), that works - some functions (like m

1条回答
  •  轮回少年
    2020-12-11 11:05

    Huh, I've never actually added symbols from directly inside Semantic Actions myself (I prefer to build ASTs, and then traverse those).

    The fact that you wrote it like this and the absence of a SSCCE had me blindsided for a moment. Turns out, I should just have ignored the circumstantial 'evidence' and went straight for the docs + win:

    var_decl =
        qi::as_string [ lexeme [ ( ( alpha >> *( alnum | '_' ) ) - vars ) ] ]
            [ phx::bind(vars.add, _1) ];
    

    or

    var_decl =
         lexeme [ qi::raw [  ( alpha >> *( alnum | '_' ) ) - vars  ] ]
            [ phx::bind(vars.add, _1) ];
    

    and some similar incantations will apply

    Edit Here is the complete source, compiled on MSVC 2010, with boost 1.47:

    • https://gist.github.com/1582163

    Output:

    T:\>cl /EHsc /I "c:\Program Files (x86)\boost\boost_1_47" test.cpp
    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.30319.01 for 80x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    test.cpp
    Microsoft (R) Incremental Linker Version 10.00.30319.01
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /out:test.exe
    test.obj
    
    T:\>.\test.exe
    **********************************************************
    *                                                        *
    *          Command interface for VideoTraction4          *
    *                                                        *
    **********************************************************
    
    Type an expression...or [q or Q] to quit
    
    3*4+7
    -------------------------
    Parsing succeeded
    result = 19
    -------------------------
    

    On a slightly unrelated note: it looks kind-a funny that the exposed attribute of the var_decl rule appears to be char?

    You might want to read up on auto-rules and the %= operator; Without %=, the presence of a Semantic Action will suppress all automatic attribute propagation. That is helpful in case the required customization points do not exist. As written, the exposed attribute will always be unassigned-to.

    0 讨论(0)
提交回复
热议问题