2024-02-26 00:22:09 +03:00
|
|
|
package pp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Preprocessor struct {
|
2024-02-26 21:04:47 +03:00
|
|
|
evaler Evaler
|
2024-02-26 00:22:09 +03:00
|
|
|
tags [2]string
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get the new preprocessor with default options.
|
2024-02-26 21:04:47 +03:00
|
|
|
func NewPp(evaler Evaler) *Preprocessor {
|
2024-02-26 00:22:09 +03:00
|
|
|
pp := &Preprocessor{
|
2024-02-26 21:04:47 +03:00
|
|
|
tags: evaler.Tags(),
|
2024-02-26 00:22:09 +03:00
|
|
|
}
|
2024-02-26 21:04:47 +03:00
|
|
|
pp.evaler = evaler
|
2024-02-26 00:22:09 +03:00
|
|
|
return pp
|
|
|
|
}
|
|
|
|
|
2024-02-26 21:04:47 +03:00
|
|
|
func (pp *Preprocessor) Process(filePath string, data string) (string, error) {
|
2024-02-26 00:22:09 +03:00
|
|
|
var b strings.Builder
|
|
|
|
last := 0
|
2024-02-26 20:16:12 +03:00
|
|
|
texts := []string{}
|
|
|
|
codes := []string{}
|
2024-02-26 00:22:09 +03:00
|
|
|
for {
|
|
|
|
idxStart := strings.Index(data[last:], pp.tags[0])
|
|
|
|
idxEnd := strings.Index(data[last:], pp.tags[1])
|
|
|
|
//fmt.Printf("cock %d %d %d\n", last, idxStart, idxEnd)
|
|
|
|
if idxStart < 0 {
|
|
|
|
if idxEnd >= 0 {
|
|
|
|
return "", UnexpectedError{
|
|
|
|
What: "end tag",
|
|
|
|
}
|
|
|
|
}
|
2024-02-26 20:16:12 +03:00
|
|
|
texts = append(texts, data[last:])
|
2024-02-26 00:22:09 +03:00
|
|
|
break
|
|
|
|
} else if idxEnd < 0 {
|
|
|
|
return "", UnexpectedError{
|
|
|
|
What: "start tag",
|
|
|
|
}
|
|
|
|
}
|
2024-02-26 20:16:12 +03:00
|
|
|
text := data[last:idxStart]
|
|
|
|
texts = append(texts, text)
|
|
|
|
|
2024-02-26 00:22:09 +03:00
|
|
|
code := data[idxStart+len(pp.tags[0]):idxEnd]
|
2024-02-26 20:16:12 +03:00
|
|
|
codes = append(codes, code)
|
|
|
|
|
|
|
|
data = data[idxEnd + len(pp.tags[1]):]
|
|
|
|
/*if len(data) > 0 && data[0] == '\n' {
|
|
|
|
data = data[1:]
|
|
|
|
}*/
|
|
|
|
}
|
2024-02-26 21:04:47 +03:00
|
|
|
codeRets, err := pp.evaler.Eval(filePath, codes)
|
2024-02-26 20:16:12 +03:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
for i, codeRet := range codeRets {
|
|
|
|
fmt.Fprint(&b, texts[i])
|
|
|
|
fmt.Fprintf(&b, codeRet)
|
2024-02-26 00:22:09 +03:00
|
|
|
}
|
2024-02-26 20:16:12 +03:00
|
|
|
fmt.Fprint(&b, texts[len(codeRets)])
|
2024-02-26 00:22:09 +03:00
|
|
|
|
|
|
|
return b.String(), nil
|
|
|
|
}
|
|
|
|
|