improve doxygen documentation of PFunction.* and PFunctionGrammar.h
All checks were successful
Build and Deploy Documentation / build-and-deploy (push) Successful in 18s

This commit is contained in:
2025-11-14 07:50:50 +01:00
parent f8a2d646dc
commit 40a797c0da
3 changed files with 463 additions and 109 deletions

View File

@@ -40,24 +40,34 @@
// Constructor
//--------------------------------------------------------------------------
/**
* <p>Constructor.
* \brief Constructor that initializes the function from a parsed AST.
*
* info is an abstract syntax tree (AST) generate by the spirit parse library
* (see http://spirit.sourceforge.net/distrib/spirit_1_8_5/libs/spirit/doc/trees.html).
* It contains a single parsed msr-function in an ascii representation.
* Here it takes the from
* This constructor performs the following steps:
* 1. Stores the AST generated by the Boost.Spirit parser
* 2. Extracts the function number from the function label (FUNx)
* 3. Converts the AST into an efficient evaluation tree structure
* 4. Generates a human-readable string representation of the function
*
* The input AST has the following structure:
* \verbatim
* assignment (root node)
* |_ 'FUNx'
* |_ '='
* |_ expression
* |_ ...
* |_ 'FUNx' (function label)
* |_ '=' (assignment operator)
* |_ expression (mathematical expression tree)
* |_ term
* |_ factor
* |_ ...
* \endverbatim
*
* <p>Since it would be inefficient to evaluate this AST directly it is transferred to
* a more efficient tree fFuncs here in the constructor.
* Direct evaluation of the AST would be inefficient due to its verbose structure.
* Therefore, it is converted to a more compact evaluation tree (fFunc) optimized
* for repeated evaluation with different parameter values during fitting.
*
* \param info AST parse tree holding a single parsed msr-function in an ascii representation
* \param info AST parse tree from Boost.Spirit containing a parsed msr-function
*
* \see SetFuncNo for function number extraction
* \see GenerateFuncEvalTree for AST to evaluation tree conversion
* \see EvalTreeForString for string representation generation
*/
PFunction::PFunction(tree_parse_info<> info) : fInfo(info)
{
@@ -80,7 +90,12 @@ PFunction::PFunction(tree_parse_info<> info) : fInfo(info)
// Destructor
//--------------------------------------------------------------------------
/**
* <p>Destructor.
* \brief Destructor that releases all resources.
*
* Cleans up:
* - Parameter vector
* - Map vector
* - Evaluation tree (recursively frees all nodes and their children)
*/
PFunction::~PFunction()
{
@@ -112,9 +127,14 @@ void PFunction::InitNode(PFuncTreeNode &node)
// SetFuncNo (protected)
//-------------------------------------------------------------
/**
* <p>Extracts the function number of the AST tree.
* \brief Extracts the function number from the AST tree.
*
* <b>return:</b> true if the function number (of FUNx, x being a number) could be extracted, otherwise false.
* Navigates to the function label node in the AST and parses the numeric
* identifier from the "FUNx" label. For example, "FUN3" yields 3.
*
* \return true if the function number was successfully extracted, false otherwise
*
* \note The function number is stored in the member variable fFuncNo
*/
Bool_t PFunction::SetFuncNo()
{
@@ -145,8 +165,15 @@ Bool_t PFunction::SetFuncNo()
// GenerateFuncEvalTree (protected)
//-------------------------------------------------------------
/**
* <p>Stub to generate the function evaluation tree from the AST tree. Needed for an efficient
* evaluation.
* \brief Initiates conversion of AST to evaluation tree.
*
* This function initializes the root node and triggers the recursive
* conversion process. The evaluation tree is a more efficient representation
* than the AST for repeated function evaluations during fitting.
*
* \return true (currently always successful)
*
* \see FillFuncEvalTree for the recursive conversion algorithm
*/
Bool_t PFunction::GenerateFuncEvalTree()
{
@@ -160,10 +187,23 @@ Bool_t PFunction::GenerateFuncEvalTree()
// FillFuncEvalTree (protected)
//-------------------------------------------------------------
/**
* <p>Recursive generation of the evaluation tree.
* \brief Recursively converts AST nodes to evaluation tree nodes.
*
* \param i iterator of the AST tree
* \param node of the evaluation tree
* This function traverses the AST and builds a corresponding evaluation tree.
* It handles all node types defined in PFunctionGrammar:
* - Leaf nodes: real numbers, constants (PI, GAMMA_MU, B, EN, T), parameters, maps
* - Operator nodes: arithmetic operations (+, -, *, /)
* - Function nodes: mathematical functions (cos, sin, exp, etc.)
* - Power nodes: POW(base, exponent)
* - Composite nodes: factors, terms, expressions
*
* The resulting tree structure is optimized for efficient evaluation.
*
* \param i Iterator pointing to the current AST node to process
* \param node Evaluation tree node to populate with data from the AST
*
* \see PFunctionGrammar for AST node type definitions
* \see EvalNode for the evaluation algorithm that uses this tree
*/
void PFunction::FillFuncEvalTree(iter_t const& i, PFuncTreeNode &node)
{
@@ -340,10 +380,17 @@ void PFunction::FillFuncEvalTree(iter_t const& i, PFuncTreeNode &node)
// CheckMapAndParamRange (public)
//-------------------------------------------------------------
/**
* <p>Stub the check map and fit parameter ranges.
* \brief Validates all map and parameter references in the function.
*
* \param mapSize size of the map vector
* \param paramSize size of the parameter vector
* Initiates a recursive traversal of the evaluation tree to verify that all
* MAP# and PAR# references fall within valid ranges. This prevents runtime
* errors during evaluation caused by out-of-bounds array access.
*
* \param mapSize Number of available map entries (MAP1 to MAP<mapSize>)
* \param paramSize Number of available fit parameters (PAR1 to PAR<paramSize>)
* \return true if all references are valid, false if any are out of range
*
* \see FindAndCheckMapAndParamRange for the recursive validation algorithm
*/
Bool_t PFunction::CheckMapAndParamRange(UInt_t mapSize, UInt_t paramSize)
{
@@ -354,11 +401,20 @@ Bool_t PFunction::CheckMapAndParamRange(UInt_t mapSize, UInt_t paramSize)
// FindAndCheckMapAndParamRange (protected)
//-------------------------------------------------------------
/**
* <p>Recursive checking of map and fit parameter ranges.
* \brief Recursively validates map and parameter references in the tree.
*
* \param node of the evaluation tree
* \param mapSize size of the map vector
* \param paramSize size of the fit parameter vector
* Traverses the evaluation tree depth-first, checking each node:
* - For parameter nodes (PAR#): verifies # <= paramSize
* - For map nodes (MAP#): verifies # <= mapSize
* - For other nodes: recursively checks all children
*
* The validation ensures that array indices will be valid during evaluation,
* preventing potential segmentation faults or undefined behavior.
*
* \param node Current evaluation tree node being checked
* \param mapSize Number of available map entries
* \param paramSize Number of available fit parameters
* \return true if this node and all descendants have valid references, false otherwise
*/
Bool_t PFunction::FindAndCheckMapAndParamRange(PFuncTreeNode &node, UInt_t mapSize, UInt_t paramSize)
{
@@ -416,11 +472,25 @@ Bool_t PFunction::FindAndCheckMapAndParamRange(PFuncTreeNode &node, UInt_t mapSi
// Eval (public)
//-------------------------------------------------------------
/**
* <p>Stub starting the evaluation of the evaluation tree.
* \brief Evaluates the function with given parameters and metadata.
*
* <b>return:</b> the value of the function call.
* This is the main evaluation entry point. It:
* 1. Stores the current parameter values and metadata
* 2. Initiates recursive evaluation of the tree
* 3. Returns the computed result
*
* \param param fit parameter vector
* The function can be evaluated multiple times with different parameter
* values without re-parsing or rebuilding the evaluation tree, making it
* efficient for iterative fitting algorithms.
*
* \param param Vector of fit parameter values (PAR1, PAR2, ...)
* \param metaData Experimental metadata (field, energy, temperature, etc.)
* \return Computed function value
*
* \see EvalNode for the recursive evaluation algorithm
*
* \warning Ensure CheckMapAndParamRange has been called before evaluation
* to prevent out-of-bounds access
*/
Double_t PFunction::Eval(std::vector<Double_t> param, PMetaData metaData)
{
@@ -434,9 +504,27 @@ Double_t PFunction::Eval(std::vector<Double_t> param, PMetaData metaData)
// EvalNode (protected)
//-------------------------------------------------------------
/**
* <p>Recursive evaluation of the evaluation tree.
* \brief Recursively evaluates an evaluation tree node.
*
* \param node of the evaluation tree
* This is the core evaluation algorithm that computes the function value
* by recursively processing the tree structure. Each node type is handled
* appropriately:
*
* - Leaf nodes (constants, parameters, maps): Return their values directly
* - Operator nodes (+, -, *, /): Evaluate children and apply operation
* - Function nodes (cos, sin, exp, etc.): Evaluate argument and apply function
* - Power nodes: Evaluate base and exponent, compute power
*
* Special handling:
* - Division by zero: Triggers an error and assertion
* - Negative bases in power: Takes absolute value if exponent is non-integer
* - Logarithms and square roots: Use absolute value to avoid complex numbers
* - Maps: Returns 0 if map value is 0, otherwise returns the mapped parameter
*
* \param node Current evaluation tree node to evaluate
* \return Computed value for this node
*
* \see Eval for the public evaluation entry point
*/
Double_t PFunction::EvalNode(PFuncTreeNode &node)
{
@@ -570,7 +658,12 @@ Double_t PFunction::EvalNode(PFuncTreeNode &node)
// CleanupFuncEvalTree (protected)
//-------------------------------------------------------------
/**
* <p>Stub to clean up the evaluation tree.
* \brief Initiates cleanup of the evaluation tree.
*
* Starts the recursive cleanup process from the root node to free all
* dynamically allocated child nodes in the tree.
*
* \see CleanupNode for the recursive cleanup algorithm
*/
void PFunction::CleanupFuncEvalTree()
{
@@ -582,9 +675,13 @@ void PFunction::CleanupFuncEvalTree()
// CleanupNode (protected)
//-------------------------------------------------------------
/**
* <p>Recursive clean up of the evaluation tree.
* \brief Recursively cleans up evaluation tree nodes and their children.
*
* \param node of the evaluation tree
* Performs depth-first traversal to clean up all child nodes before
* clearing the current node's children vector. This ensures proper
* resource deallocation and prevents memory leaks.
*
* \param node Current evaluation tree node to clean up
*/
void PFunction::CleanupNode(PFuncTreeNode &node)
{
@@ -600,9 +697,15 @@ void PFunction::CleanupNode(PFuncTreeNode &node)
// EvalTreeForString (private)
//-------------------------------------------------------------
/**
* <p>Stub to generate the function string (clean and tidy).
* \brief Initiates generation of human-readable function string from AST.
*
* \param info AST tree
* Creates a formatted, readable string representation of the function by
* traversing the AST. The resulting string is stored in fFuncString and
* can be used for display, logging, or debugging purposes.
*
* \param info AST parse tree to convert to string
*
* \see EvalTreeForStringExpression for the recursive string generation algorithm
*/
void PFunction::EvalTreeForString(tree_parse_info<> info)
{
@@ -614,9 +717,24 @@ void PFunction::EvalTreeForString(tree_parse_info<> info)
// EvalTreeForStringExpression (private)
//-------------------------------------------------------------
/**
* <p>Recursive generation of the function string (clean and tidy).
* \brief Recursively generates formatted function string from AST.
*
* \param i iterator of the AST tree
* Traverses the AST and builds a human-readable string representation.
* The function handles:
* - Proper parenthesization to maintain operator precedence
* - Formatting of constants (PI -> Pi, GAMMA_MU -> gamma_mu)
* - Proper spacing around operators
* - Special handling for division denominators (adds parentheses if needed)
* - Function call formatting with arguments
*
* The resulting string is formatted for readability while maintaining
* mathematical correctness.
*
* \param i Iterator pointing to current AST node
* \param funcFlag Flag indicating if currently processing inside a function argument
* (affects parenthesization rules)
*
* \note Uses a static variable termOp to track operator nesting depth
*/
void PFunction::EvalTreeForStringExpression(iter_t const& i, bool funcFlag)
{

View File

@@ -48,85 +48,256 @@
#include "PFunctionGrammar.h"
//----------------------------------------------------------------------------
#define OP_ADD 0
#define OP_SUB 1
#define OP_MUL 2
#define OP_DIV 3
// Operator tags for arithmetic operations
//----------------------------------------------------------------------------
#define OP_ADD 0 ///< Addition operator tag
#define OP_SUB 1 ///< Subtraction operator tag
#define OP_MUL 2 ///< Multiplication operator tag
#define OP_DIV 3 ///< Division operator tag
#define FUN_COS 0
#define FUN_SIN 1
#define FUN_TAN 2
#define FUN_COSH 3
#define FUN_SINH 4
#define FUN_TANH 5
#define FUN_ACOS 6
#define FUN_ASIN 7
#define FUN_ATAN 8
#define FUN_ACOSH 9
#define FUN_ASINH 10
#define FUN_ATANH 11
#define FUN_LOG 12
#define FUN_LN 13
#define FUN_EXP 14
#define FUN_SQRT 15
#define FUN_POW 16
//----------------------------------------------------------------------------
// Function tags for mathematical functions
//----------------------------------------------------------------------------
#define FUN_COS 0 ///< Cosine function tag
#define FUN_SIN 1 ///< Sine function tag
#define FUN_TAN 2 ///< Tangent function tag
#define FUN_COSH 3 ///< Hyperbolic cosine function tag
#define FUN_SINH 4 ///< Hyperbolic sine function tag
#define FUN_TANH 5 ///< Hyperbolic tangent function tag
#define FUN_ACOS 6 ///< Inverse cosine (arccos) function tag
#define FUN_ASIN 7 ///< Inverse sine (arcsin) function tag
#define FUN_ATAN 8 ///< Inverse tangent (arctan) function tag
#define FUN_ACOSH 9 ///< Inverse hyperbolic cosine function tag
#define FUN_ASINH 10 ///< Inverse hyperbolic sine function tag
#define FUN_ATANH 11 ///< Inverse hyperbolic tangent function tag
#define FUN_LOG 12 ///< Base-10 logarithm function tag
#define FUN_LN 13 ///< Natural logarithm function tag
#define FUN_EXP 14 ///< Exponential function tag
#define FUN_SQRT 15 ///< Square root function tag
#define FUN_POW 16 ///< Power function tag (base^exponent)
//----------------------------------------------------------------------------
/**
* <p>Structure needed to evaluate a function tree (see FUNCTIONS block of an msr-file).
* \brief Tree node structure for efficient function evaluation.
*
* This structure represents a node in the evaluation tree used to compute
* function values. The abstract syntax tree (AST) generated by the parser
* is converted into this more efficient tree structure for faster evaluation.
*
* Each node can represent:
* - A leaf node (constant, parameter, map reference)
* - An operator node (arithmetic operation)
* - A function node (mathematical function)
*
* The tree is evaluated recursively by traversing from the root to the leaves.
*
* \see PFunction::EvalNode for the recursive evaluation algorithm
*/
typedef struct func_tree_node {
Int_t fID; ///< tag showing what tree element this is
Int_t fOperatorTag; ///< tag for '+', '-', '*', '/'
Int_t fFunctionTag; ///< tag got "cos", "sin", ...
Int_t fIvalue; ///< for parameter numbers and maps
Bool_t fSign; ///< for sign, true means '-', false '+'
Double_t fDvalue; ///< for numbers
std::vector<func_tree_node> children; ///< holding sub-tree
Int_t fID; ///< Node type identifier (from PFunctionGrammar constants)
Int_t fOperatorTag; ///< Operator type: OP_ADD, OP_SUB, OP_MUL, OP_DIV
Int_t fFunctionTag; ///< Function type: FUN_COS, FUN_SIN, FUN_EXP, etc.
Int_t fIvalue; ///< Integer value for parameter numbers, map indices, or temperature indices
Bool_t fSign; ///< Sign flag: true for negative, false for positive
Double_t fDvalue; ///< Numeric value for constants and real number literals
std::vector<func_tree_node> children; ///< Child nodes forming the sub-tree
} PFuncTreeNode;
//----------------------------------------------------------------------------
/**
* <p>Class handling a function from the msr-file FUNCTIONS block.
* \brief Class for parsing and evaluating mathematical functions from msr-file FUNCTIONS blocks.
*
* This class handles the complete lifecycle of a function definition:
* 1. Parses the function string using PFunctionGrammar into an AST
* 2. Converts the AST into an efficient evaluation tree
* 3. Validates parameter and map references
* 4. Evaluates the function with given parameters and metadata
*
* Functions can reference:
* - Fit parameters (PAR1, PAR2, ...)
* - Map values (MAP1, MAP2, ...)
* - Constants (PI, GAMMA_MU)
* - Metadata (magnetic field B, energy EN, temperature T)
* - Other functions (FUN1, FUN2, ...)
*
* Example function definition:
* \code
* FUN1 = PAR1 * COS(2.0 * PI * GAMMA_MU * B * PAR2)
* \endcode
*
* \see PFunctionGrammar for the grammar definition
* \see PFuncTreeNode for the evaluation tree structure
*/
class PFunction {
public:
//------------------------------------------------------------------------
/**
* \brief Constructor that parses and prepares a function for evaluation.
*
* \param info Abstract syntax tree (AST) from parsing a function expression
*/
PFunction(tree_parse_info<> info);
//------------------------------------------------------------------------
/**
* \brief Destructor that cleans up the evaluation tree.
*/
virtual ~PFunction();
//------------------------------------------------------------------------
/**
* \brief Checks if the function was successfully parsed and initialized.
*
* \return true if the function is valid, false otherwise
*/
virtual Bool_t IsValid() { return fValid; }
//------------------------------------------------------------------------
/**
* \brief Returns the function number extracted from the function label.
*
* \return Function number (x from FUNx), or -1 if invalid
*/
virtual Int_t GetFuncNo() { return fFuncNo; }
//------------------------------------------------------------------------
/**
* \brief Validates that all parameter and map references are within valid ranges.
*
* \param mapSize Number of available map entries
* \param paramSize Number of available fit parameters
* \return true if all references are valid, false otherwise
*/
virtual Bool_t CheckMapAndParamRange(UInt_t mapSize, UInt_t paramSize);
//------------------------------------------------------------------------
/**
* \brief Evaluates the function with given parameters and metadata.
*
* \param param Vector of fit parameter values
* \param metaData Metadata containing field, energy, temperature, etc.
* \return Computed function value
*/
virtual Double_t Eval(std::vector<Double_t> param, PMetaData metaData);
//------------------------------------------------------------------------
/**
* \brief Sets the map vector for parameter indirection.
*
* Maps allow indirect parameter references. MAP# references fMap[#-1],
* which then indexes into the parameter vector.
*
* \param map Vector of parameter indices (1-based)
*/
virtual void SetMap(std::vector<Int_t> map) { fMap = map; }
//------------------------------------------------------------------------
/**
* \brief Returns the human-readable string representation of the function.
*
* \return Pointer to formatted function string
*/
virtual TString* GetFuncString() { return &fFuncString; }
protected:
//------------------------------------------------------------------------
/**
* \brief Initializes all fields of an evaluation tree node to default values.
*
* \param node Node to initialize
*/
virtual void InitNode(PFuncTreeNode &node);
//------------------------------------------------------------------------
/**
* \brief Extracts the function number from the AST.
*
* Parses the function label (FUN#) to extract the numeric identifier.
*
* \return true if successful, false otherwise
*/
virtual Bool_t SetFuncNo();
//------------------------------------------------------------------------
/**
* \brief Recursively validates parameter and map references in the tree.
*
* \param node Current node being checked
* \param mapSize Number of available map entries
* \param paramSize Number of available fit parameters
* \return true if all references are valid, false otherwise
*/
virtual Bool_t FindAndCheckMapAndParamRange(PFuncTreeNode &node, UInt_t mapSize, UInt_t paramSize);
//------------------------------------------------------------------------
/**
* \brief Initiates the conversion from AST to evaluation tree.
*
* \return true if successful, false otherwise
*/
virtual Bool_t GenerateFuncEvalTree();
//------------------------------------------------------------------------
/**
* \brief Recursively builds the evaluation tree from the AST.
*
* \param i Iterator pointing to current AST node
* \param node Evaluation tree node to fill
*/
virtual void FillFuncEvalTree(iter_t const& i, PFuncTreeNode &node);
//------------------------------------------------------------------------
/**
* \brief Recursively evaluates an evaluation tree node.
*
* \param node Node to evaluate
* \return Computed value for this node and its subtree
*/
virtual Double_t EvalNode(PFuncTreeNode &node);
//------------------------------------------------------------------------
/**
* \brief Initiates cleanup of the evaluation tree.
*/
virtual void CleanupFuncEvalTree();
//------------------------------------------------------------------------
/**
* \brief Recursively cleans up evaluation tree nodes and their children.
*
* \param node Node to clean up
*/
virtual void CleanupNode(PFuncTreeNode &node);
private:
tree_parse_info<> fInfo; ///< AST parse tree holding a single parsed msr-function in an ascii representation
std::vector<Double_t> fParam; ///< parameter vector (from the msr-file Fit Parameter block)
std::vector<Int_t> fMap; ///< map vector
PFuncTreeNode fFunc;
tree_parse_info<> fInfo; ///< AST parse tree from Boost.Spirit parser
std::vector<Double_t> fParam; ///< Current fit parameter values for evaluation
std::vector<Int_t> fMap; ///< Map vector for indirect parameter references
PFuncTreeNode fFunc; ///< Root node of the evaluation tree
Bool_t fValid; ///< flag showing if the function is valid
Int_t fFuncNo; ///< function number, i.e. FUNx with x the function number
Bool_t fValid; ///< Validity flag: true if function parsed and initialized successfully
Int_t fFuncNo; ///< Function number extracted from label (x in FUNx)
//------------------------------------------------------------------------
/**
* \brief Initiates generation of human-readable function string.
*
* \param info AST parse tree to convert to string
*/
virtual void EvalTreeForString(tree_parse_info<> info);
virtual void EvalTreeForStringExpression(iter_t const& i, bool funcFlag=false);
TString fFuncString; ///< text representation of the function
PMetaData fMetaData; ///< keeps meta data from data files (field, energy, temperature, ...)
//------------------------------------------------------------------------
/**
* \brief Recursively generates formatted function string from AST.
*
* \param i Iterator pointing to current AST node
* \param funcFlag Flag indicating if currently inside a function call
*/
virtual void EvalTreeForStringExpression(iter_t const& i, bool funcFlag=false);
TString fFuncString; ///< Formatted, human-readable function representation
PMetaData fMetaData; ///< Metadata from experimental data (field, energy, temperature, etc.)
};
#endif // _PFUNCTION_H_

View File

@@ -44,35 +44,91 @@
using namespace boost::spirit;
#endif
//--------------------------------------------------------------------------
/**
* \brief Iterator type for parsing characters.
*/
typedef char const* iterator_t;
//--------------------------------------------------------------------------
/**
* \brief Type for parse tree matching results.
*/
typedef tree_match<iterator_t> parse_tree_match_t;
//--------------------------------------------------------------------------
/**
* \brief Iterator type for traversing the parse tree.
*/
typedef parse_tree_match_t::tree_iterator iter_t;
//--------------------------------------------------------------------------
/**
* <p>EBNF like grammar definition of a function entry in the msr-file FUNCTION block.
* \brief EBNF-like grammar definition for parsing function entries in msr-file FUNCTION blocks.
*
* This grammar defines the syntax for parsing mathematical function expressions in msr-files.
* It supports:
* - Basic arithmetic operations (+, -, *, /)
* - Mathematical functions (trigonometric, hyperbolic, logarithmic, exponential, etc.)
* - Constants (PI, GAMMA_MU, field B, energy EN, temperature T)
* - Parameters (PAR) and maps (MAP)
* - Function references (FUN)
*
* The grammar follows an EBNF-like structure with the following hierarchy:
* \verbatim
* assignment = fun_label '=' expression
* expression = term { ('+' | '-') term }
* term = factor { ('*' | '/') factor }
* factor = real | constant | parameter | map | function | power | '(' expression ')'
* \endverbatim
*
* \see PFunction for the class that uses this grammar to evaluate parsed expressions
*/
struct PFunctionGrammar : public grammar<PFunctionGrammar>
{
static const int realID = 1;
static const int constPiID = 2;
static const int constGammaMuID = 3;
static const int constFieldID = 4;
static const int constEnergyID = 5;
static const int constTempID = 6;
static const int funLabelID = 7;
static const int parameterID = 8;
static const int mapID = 9;
static const int functionID = 10;
static const int powerID = 11;
static const int factorID = 12;
static const int termID = 13;
static const int expressionID = 14;
static const int assignmentID = 15;
static const int realID = 1; ///< Identifier for real number literals
static const int constPiID = 2; ///< Identifier for PI constant
static const int constGammaMuID = 3; ///< Identifier for GAMMA_MU constant (muon gyromagnetic ratio)
static const int constFieldID = 4; ///< Identifier for magnetic field constant (B or -B)
static const int constEnergyID = 5; ///< Identifier for energy constant (EN or -EN)
static const int constTempID = 6; ///< Identifier for temperature constant (T# or -T#)
static const int funLabelID = 7; ///< Identifier for function label (FUN#)
static const int parameterID = 8; ///< Identifier for parameter reference (PAR# or -PAR#)
static const int mapID = 9; ///< Identifier for map reference (MAP#)
static const int functionID = 10; ///< Identifier for mathematical functions (cos, sin, exp, etc.)
static const int powerID = 11; ///< Identifier for power function (POW)
static const int factorID = 12; ///< Identifier for factor in expression
static const int termID = 13; ///< Identifier for term in expression
static const int expressionID = 14; ///< Identifier for expression
static const int assignmentID = 15; ///< Identifier for assignment statement
//------------------------------------------------------------------------
/**
* \brief Inner template structure defining the grammar rules.
*
* This template structure contains the actual grammar rule definitions
* using Boost.Spirit syntax. It defines how the parser should recognize
* and build an abstract syntax tree (AST) for function expressions.
*
* \tparam ScannerT Scanner type used by Boost.Spirit for parsing
*/
template <typename ScannerT>
struct definition
{
//--------------------------------------------------------------------
/**
* \brief Constructor that defines all grammar rules.
*
* Sets up the complete grammar hierarchy for parsing function expressions:
* - Terminals: real numbers, constants (PI, GAMMA_MU, B, EN, T), parameters (PAR), maps (MAP)
* - Functions: trigonometric (cos, sin, tan), hyperbolic (cosh, sinh, tanh),
* inverse trigonometric (acos, asin, atan), inverse hyperbolic (acosh, asinh, atanh),
* logarithmic (log, ln), exponential (exp), square root (sqrt), power (pow)
* - Operators: addition (+), subtraction (-), multiplication (*), division (/)
* - Expressions: Hierarchical structure following operator precedence
*
* \param self Reference to the enclosing PFunctionGrammar (unused but required by Boost.Spirit)
*/
definition(PFunctionGrammar const& /*self*/)
{
// Start grammar definition
@@ -163,22 +219,31 @@ struct PFunctionGrammar : public grammar<PFunctionGrammar>
BOOST_SPIRIT_DEBUG_RULE(assignment);
}
rule<ScannerT, parser_context<>, parser_tag<assignmentID> > assignment;
rule<ScannerT, parser_context<>, parser_tag<expressionID> > expression;
rule<ScannerT, parser_context<>, parser_tag<termID> > term;
rule<ScannerT, parser_context<>, parser_tag<factorID> > factor;
rule<ScannerT, parser_context<>, parser_tag<functionID> > function;
rule<ScannerT, parser_context<>, parser_tag<powerID> > power;
rule<ScannerT, parser_context<>, parser_tag<mapID> > map;
rule<ScannerT, parser_context<>, parser_tag<parameterID> > parameter;
rule<ScannerT, parser_context<>, parser_tag<funLabelID> > fun_label;
rule<ScannerT, parser_context<>, parser_tag<constTempID> > const_temp;
rule<ScannerT, parser_context<>, parser_tag<constEnergyID> > const_energy;
rule<ScannerT, parser_context<>, parser_tag<constFieldID> > const_field;
rule<ScannerT, parser_context<>, parser_tag<constGammaMuID> > const_gamma_mu;
rule<ScannerT, parser_context<>, parser_tag<constPiID> > const_pi;
rule<ScannerT, parser_context<>, parser_tag<realID> > real;
rule<ScannerT, parser_context<>, parser_tag<assignmentID> > assignment; ///< Rule for assignment: FUN# = expression
rule<ScannerT, parser_context<>, parser_tag<expressionID> > expression; ///< Rule for expression: term { ('+' | '-') term }
rule<ScannerT, parser_context<>, parser_tag<termID> > term; ///< Rule for term: factor { ('*' | '/') factor }
rule<ScannerT, parser_context<>, parser_tag<factorID> > factor; ///< Rule for factor: operand or parenthesized expression
rule<ScannerT, parser_context<>, parser_tag<functionID> > function; ///< Rule for mathematical functions
rule<ScannerT, parser_context<>, parser_tag<powerID> > power; ///< Rule for power function POW(base, exponent)
rule<ScannerT, parser_context<>, parser_tag<mapID> > map; ///< Rule for map reference MAP#
rule<ScannerT, parser_context<>, parser_tag<parameterID> > parameter; ///< Rule for parameter reference PAR# or -PAR#
rule<ScannerT, parser_context<>, parser_tag<funLabelID> > fun_label; ///< Rule for function label FUN#
rule<ScannerT, parser_context<>, parser_tag<constTempID> > const_temp; ///< Rule for temperature constant T# or -T#
rule<ScannerT, parser_context<>, parser_tag<constEnergyID> > const_energy; ///< Rule for energy constant EN or -EN
rule<ScannerT, parser_context<>, parser_tag<constFieldID> > const_field; ///< Rule for field constant B or -B
rule<ScannerT, parser_context<>, parser_tag<constGammaMuID> > const_gamma_mu;///< Rule for muon gyromagnetic ratio constant
rule<ScannerT, parser_context<>, parser_tag<constPiID> > const_pi; ///< Rule for PI constant
rule<ScannerT, parser_context<>, parser_tag<realID> > real; ///< Rule for real number literals
//--------------------------------------------------------------------
/**
* \brief Returns the starting rule for the grammar.
*
* The parser begins by matching the assignment rule, which represents
* a complete function definition (e.g., FUN1 = PAR1 * cos(PAR2 * PI)).
*
* \return Reference to the assignment rule as the grammar entry point
*/
rule<ScannerT, parser_context<>, parser_tag<assignmentID> > const&
start() const { return assignment; }
};