I need to convert a string into an object (AST like) obeying rules from a specific grammar.
I basically have 3 types of expressions ('@', '$' and '#'
). The expressions of type '#' are written as #something
while the other two are written as @something==somethingelse
and $something==somethingelse
.
These expressions can be grouped using conjunctions ('and', 'or'
) and the order to operations can be modified using parenthesis.
Here is an example of a complete expression:
const expression =
`#buy
&& (@car == white || @bike == blue)
&& $user==authenticated`;
I'm looking for a way to convert that into the object (AST like) bellow using javascript or a tool based in javascript (will use in a React project).
const ast = {
type: 'expression',
conjunction: 'null',
expressions: [{
type: 'expression',
conjunction: null,
expressions: [{
type: '#',
left: 'buy',
operator: null,
right: null
}]
},
{
type: 'expression',
conjunction: '&&',
expressions: [{
type: 'expression',
conjunction: 'null',
expressions: [{
type: '@',
left: 'car',
operator: '==',
right: 'white'
}]
},
{
type: 'expression',
conjunction: '||',
expressions: [{
type: '@',
left: 'bike',
operator: '==',
right: 'blue'
}]
}
]
},
{
type: 'expression',
conjunction: '&&',
expressions: [{
type: '$',
left: 'user',
operator: '==',
right: 'authenticaded'
}]
}
]
};