IvanRave / logic-tree

Build a JSON object from a logic expression string
14 stars 8 forks source link

Abstract syntax tree for logic expressions

Build an AST (JSON object) from a logic expression string

Input

    const logicExpression = 'a AND b OR c';

Processing

    const bracketTree = new BracketTree();
    bracketTree.applyExpression(expr) // handle errors
    const logicTree = new LogicTree(bracketTree.root)

Output

    console.log(logicTree.root);

    {
      name: 'node0',
      content: 'a AND b OR c',
      orParams: [{
        text: 'a AND b',
        andParams: [{ name: 'a' }, { name: 'b' }]
      }, {
        text: 'c',
        andParams: [{ name: 'c' }]
      }]
    }

Logical operators

Logical truth table

a b AND OR NAND NOR XOR XNOR
0 0 0 0 1 1 0 1
0 1 0 1 1 0 1 0
1 0 0 1 1 0 1 0
1 1 1 1 0 0 0 1

Different syntax in programming and natural languages

Language Negation Conjunction Disjunction XOR
C++ ! && || ^
Fortran .NOT. .AND. .OR. .XOR.
Java ! && || ^
Pascal not and or xor
PL/I ¬ & | ^
Prolog + , ;
Turbo Basic NOT AND OR XOR
SQL NOT AND OR
English not and or either
Russian не и или либо

https://en.wikipedia.org/wiki/Logical_connective

From boolean expression to logic tree

Input boolean expression: (true OR false) AND NOT(false) OR true OR false

1. Create a binary boolean expression tree

Binary boolean expression tree

2. Skip logical negation operator (NOT, ~)

3. Transform all binary logical operators to basic: conjunction and disjunction

4. Order of precedence (priority) for basic syntax operators

Syntax Precedence
parenthesis 1
NOT 2
AND 3
OR 4

5. Define own relations between basic logical binary operators

Logic tree relationship

6. Build an abstract syntax tree, using rules above

    // input
    (a OR b) AND NOT(c) OR d OR e

    // output
    {
      name: 'node0',
      content: '(a OR b) AND NOT(c) OR d OR e',
      orParams: [{
        text: '(a OR b) AND NOT(c)',
        andParams: [{
          name: 'node0',
          content: 'a OR b',
          orParams: [{
            text: 'a',
            andParams: [{ name: 'a' }]
          }, {
            text: 'b',
            andParams: [{ name: 'b' }]
          }]
        }, {
          name: 'c',
          isNegation: true
        }]
      }, {
        text: 'd',
        andParams: [{ name: 'd' }]
      }, {
        text: 'e',
        andParams: [{name: 'e' }]
      }]
    }

Where:

7. Use this logic tree for any business purposes