/
print.go
100 lines (83 loc) · 2.08 KB
/
print.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package parse
import (
"bytes"
"fmt"
"io"
"github.com/inoxlang/inox/internal/utils"
)
type PrintConfig struct {
//Compact bool
KeepLeadingSpace bool
KeepTrailingSpace bool
CacheResult bool
}
// Print prints $node to $w and returns the number of written bytes.
func Print(node Node, chunk *Chunk, w io.Writer, config PrintConfig) (int, error) {
tokens := GetTokens(node, chunk, false)
singleSpace := []byte{' '}
totalN := 0
if len(tokens) == 0 {
return 0, nil
}
end := 0
isLeadingRegularSpacePrinted := false
isLeadingNewline := true
for i, token := range tokens {
if token.Type != NEWLINE {
isLeadingNewline = false
}
if config.KeepLeadingSpace && !isLeadingRegularSpacePrinted {
//print regular leading space.
isLeadingRegularSpacePrinted = true
spaceLength := int(token.Span.Start) - end
space := bytes.Repeat(singleSpace, int(spaceLength))
n, err := w.Write(space)
totalN += n
if err != nil {
return totalN, err
}
}
if i > 0 && !isLeadingNewline && (!config.KeepLeadingSpace || isLeadingRegularSpacePrinted) {
//print space before token.
spaceLength := int(token.Span.Start) - end
space := bytes.Repeat(singleSpace, int(spaceLength))
n, err := w.Write(space)
totalN += n
if err != nil {
return totalN, err
}
}
if token.Type == NEWLINE && isLeadingNewline && !config.KeepLeadingSpace {
//do not print leading newline.
end = int(token.Span.End)
continue
}
n, err := w.Write(utils.StringAsBytes(token.Str()))
totalN += n
if err != nil {
return totalN, err
}
end = int(token.Span.End)
}
// trailing space
defer func() {
if err := recover(); err != nil {
fmt.Println("!", node, end, tokens)
}
}()
if config.KeepTrailingSpace {
space := bytes.Repeat(singleSpace, int(node.Base().Span.End)-end)
n, err := w.Write(space)
totalN += n
if err != nil {
return totalN, err
}
}
return totalN, nil
}
// SPrint stringifies $node.
func SPrint(node Node, chunk *Chunk, config PrintConfig) string {
buff := bytes.Buffer{}
Print(node, chunk, &buff, config)
return buff.String()
}