Parsing conditions in a custom DSL using a tokenizer

286 views Asked by At

I am trying to parse a "rules string" provided over an API in PHP.

Given that I have an array of items such as

$items = [41, 42, 51, 54, 65, 12];

I wish to evaluate this expression

({41} AND {51}) OR ({31} AND {42})

In this instance it should return true, since the $items array has both the 41 and 51 items.

I started with creating a tokenizer using the https://github.com/nette/tokenizer library and currently have it parsing the string into an array of tokens.

array:25 [
  0 => array:3 [
    0 => "("
    1 => 0
    2 => 1
  ]
  1 => array:3 [
    0 => "{"
    1 => 1
    2 => 2
  ]
  2 => array:3 [
    0 => "41"
    1 => 2
    2 => 3
  ]
  3 => array:3 [
    0 => "}"
    1 => 4
    2 => 4
  ]
  4 => array:3 [
    0 => " "
    1 => 5
    2 => 8
  ]
  5 => array:3 [
    0 => "AND"
    1 => 6
    2 => 5
  ]
  6 => array:3 [
    0 => " "
    1 => 9
    2 => 8
  ]
  7 => array:3 [
    0 => "{"
    1 => 10
    2 => 2
  ]
  8 => array:3 [
    0 => "51"
    1 => 11
    2 => 3
  ]
  9 => array:3 [
    0 => "}"
    1 => 13
    2 => 4
  ]
  10 => array:3 [
    0 => ")"
    1 => 14
    2 => 7
  ]
  11 => array:3 [
    0 => " "
    1 => 15
    2 => 8
  ]
  12 => array:3 [
    0 => "OR"
    1 => 16
    2 => 6
  ]
  13 => array:3 [
    0 => " "
    1 => 18
    2 => 8
  ]
  14 => array:3 [
    0 => "("
    1 => 19
    2 => 1
  ]
  15 => array:3 [
    0 => "{"
    1 => 20
    2 => 2
  ]
  16 => array:3 [
    0 => "31"
    1 => 21
    2 => 3
  ]
  17 => array:3 [
    0 => "}"
    1 => 23
    2 => 4
  ]
  18 => array:3 [
    0 => " "
    1 => 24
    2 => 8
  ]
  19 => array:3 [
    0 => "AND"
    1 => 25
    2 => 5
  ]
  20 => array:3 [
    0 => " "
    1 => 28
    2 => 8
  ]
  21 => array:3 [
    0 => "{"
    1 => 29
    2 => 2
  ]
  22 => array:3 [
    0 => "42"
    1 => 30
    2 => 3
  ]
  23 => array:3 [
    0 => "}"
    1 => 32
    2 => 4
  ]
  24 => array:3 [
    0 => ")"
    1 => 33
    2 => 7
  ]
]

However this is where my talent runs out and I am not sure how to process the tokens so that I can run the condition against my $items array.

It could be that I am approaching this completely wrong.

0

There are 0 answers