code_device/sdk/sane_opt_json/simple_logic.h

80 lines
1.8 KiB
C++

// simple_logic.h : include file for simple logical operation
//
// Purpose: to parse and execute a logical expression like 'b1 && !(b2 || b3) ^ b4 && b5'
//
// Date: 2023-09-03
//
// Author: gb
//
// Supporting opers: &&, ||, ^
//
// Priority: (&&, ^, ), (||)
#pragma once
#include <string>
#include <vector>
namespace string_util
{
// Function: find the ending position in str
//
// Parameter: str - the string beginning after the first letter 'head'
//
// head - the leading letter, can be emblaced
//
// tail - the ending letter
//
// Return: position at the ending letter, or '\0' in the string
int find_end_of_pair(const char* str, char head, char tail);
void skip_space(const char*& ptr, const char* space = " \t");
enum
{
TRIM_LEFT = 1,
TRIM_RIGHT,
TRIM_BOTH,
};
void trim(std::string& str, int type = TRIM_BOTH);
};
class simple_logic
{
int oper_;
bool not_;
std::string expr_;
simple_logic* l_;
simple_logic* r_;
void clear(void);
void copy(const simple_logic& r);
void set_not(bool notv);
bool parse_internal(const char* expr, int* end, void(*leaf)(const char*, void*), void* leaf_param);
simple_logic* make_binary(const std::vector<simple_logic*>& eles, const std::vector<int>& opers);
std::string to_string_internal(bool& single);
public:
simple_logic();
simple_logic(const simple_logic& r);
~simple_logic();
// && == ^ > ||
enum
{
LOGIC_OPER_NONE = 0,
LOGIC_OPER_LEAF,
LOGIC_OPER_OR,
LOGIC_OPER_AND,
LOGIC_OPER_XOR,
};
simple_logic& operator=(const simple_logic& r);
public:
bool parse(const char* expr, int *end_pos = nullptr, void(*leaf)(const char*, void*) = nullptr, void* leaf_param = nullptr); // leaf: callback for leaf notifying
bool value(bool(*simple_expr_value)(const char*, void*), void* param);
std::string to_expression(void);
};