2022-07-31 22:50:56 +00:00
|
|
|
package yqlib
|
|
|
|
|
|
|
|
import (
|
2022-10-28 03:16:46 +00:00
|
|
|
"bufio"
|
2022-07-31 22:50:56 +00:00
|
|
|
"bytes"
|
|
|
|
"container/list"
|
2022-10-28 03:16:46 +00:00
|
|
|
"strings"
|
2022-07-31 22:50:56 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type StringEvaluator interface {
|
2022-10-28 03:16:46 +00:00
|
|
|
Evaluate(expression string, input string, encoder Encoder, decoder Decoder) (string, error)
|
2024-03-07 01:02:40 +00:00
|
|
|
EvaluateAll(expression string, input string, encoder Encoder, decoder Decoder) (string, error)
|
2022-07-31 22:50:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type stringEvaluator struct {
|
|
|
|
treeNavigator DataTreeNavigator
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewStringEvaluator() StringEvaluator {
|
|
|
|
return &stringEvaluator{
|
|
|
|
treeNavigator: NewDataTreeNavigator(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-07 01:02:40 +00:00
|
|
|
func (s *stringEvaluator) EvaluateAll(expression string, input string, encoder Encoder, decoder Decoder) (string, error) {
|
|
|
|
reader := bufio.NewReader(strings.NewReader(input))
|
|
|
|
var documents *list.List
|
|
|
|
var results *list.List
|
|
|
|
var err error
|
|
|
|
|
|
|
|
if documents, err = ReadDocuments(reader, decoder); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
evaluator := NewAllAtOnceEvaluator()
|
|
|
|
if results, err = evaluator.EvaluateCandidateNodes(expression, documents); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
out := new(bytes.Buffer)
|
|
|
|
printer := NewPrinter(encoder, NewSinglePrinterWriter(out))
|
|
|
|
if err := printer.PrintResults(results); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return out.String(), nil
|
|
|
|
}
|
|
|
|
|
2022-10-28 03:16:46 +00:00
|
|
|
func (s *stringEvaluator) Evaluate(expression string, input string, encoder Encoder, decoder Decoder) (string, error) {
|
2022-07-31 22:50:56 +00:00
|
|
|
|
|
|
|
// Use bytes.Buffer for output of string
|
|
|
|
out := new(bytes.Buffer)
|
|
|
|
printer := NewPrinter(encoder, NewSinglePrinterWriter(out))
|
|
|
|
|
|
|
|
InitExpressionParser()
|
|
|
|
node, err := ExpressionParser.ParseExpression(expression)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2022-10-28 03:16:46 +00:00
|
|
|
reader := bufio.NewReader(strings.NewReader(input))
|
2024-03-07 01:02:40 +00:00
|
|
|
evaluator := NewStreamEvaluator()
|
|
|
|
if _, err := evaluator.Evaluate("", reader, node, printer, decoder); err != nil {
|
2022-07-31 22:50:56 +00:00
|
|
|
return "", err
|
|
|
|
}
|
2024-03-07 01:02:40 +00:00
|
|
|
return out.String(), nil
|
2022-07-31 22:50:56 +00:00
|
|
|
}
|