Phrase
public class Phrase : Equatable
Parse and evaluate a boolean expression.
Expressions consist of an expression string and a context
to set parameters/replace variables.
Example:
let expression = try Phrase("list != nil && list.count > 3")
expression.context = [
"list": [1,2,3,4,5]
]
if try expression.evaluate() {
...
} else {
...
}
-
Evaluation context, holding values for variable names
Example:
try Phrase("list.count > 3") expression.context = [ "list": [1,2,3,4,5] ]
Declaration
Swift
public var context: Context
-
Create a new instance of Phrase based on the given expression.
Evaluating an Abstract Syntax Tree (AST) consists of three steps:
- Finding the lexems (smallest known valid tokens) using a
Lexer
(eg. split by spaces), - Parse the tokens into tree nodes using a
Parser
(e.g.&&
means logicallyand
). - Evaluate the AST tree with optional variable values into a single boolean value using a
Evaluator
.
Algorithm runs linearly in
O(n)
.Throws
PhraseError
, if the expression is invalid and can not be parsedDeclaration
Swift
public init(_ expression: String) throws
Parameters
expression
Expression to be converted into a AST
- Finding the lexems (smallest known valid tokens) using a
-
Evaluates the Abstract Syntax Tree (AST) of this expression, using the current context.
Throws
if the evaluation fails, seeEvaluator.evaluate
for more details.Declaration
Swift
public func evaluate() throws -> Bool
Return Value
Boolean result value of the AST based on the current context.
-
Checks if two instances of
Phrase
equal.Declaration
Swift
public static func == (lhs: Phrase, rhs: Phrase) -> Bool
Parameters
lhs
One instance of
Phrase
rhs
Another instance of
Phrase
Return Value
true
if thetree
and thecontext
equal, otherwisefalse