forked from gotnospirit/messageformat
-
Notifications
You must be signed in to change notification settings - Fork 2
/
literal.go
94 lines (79 loc) · 1.56 KB
/
literal.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
package messageformat
import (
"bytes"
"fmt"
)
// LiteralExpr represents a string literal
type LiteralExpr struct {
Values []string
}
func (f *formatter) formatLiteral(expr Expression, ptr_output *bytes.Buffer, pound string) error {
literal, ok := expr.(LiteralExpr)
if !ok {
return fmt.Errorf("InvalidExprType: want LiteralExpr, got: %T", expr)
}
for _, val := range literal.Values {
if val != "" {
ptr_output.WriteString(val)
} else if pound != "" {
ptr_output.WriteString(pound)
} else {
ptr_output.WriteRune(PoundChar)
}
}
return nil
}
func (p *parser) parseLiteral(start, end int, ptr_input *[]rune) LiteralExpr {
var items []int
input := *ptr_input
escaped := false
s, e := start, start
gap := 0
for i := start; i < end; i++ {
c := input[i]
if EscapeChar == c {
gap++
e++
escaped = true
} else {
switch c {
default:
e++
case OpenChar, CloseChar, PoundChar:
if escaped {
if i-s > gap {
if gap > 1 {
items = append(items, s, i)
} else {
items = append(items, s, i-1)
}
}
s = i
} else {
if s != e {
items = append(items, s, e, i, i)
} else if s != i {
items = append(items, s, i, i, i)
} else {
items = append(items, i, i)
}
s = i + 1
}
e = s
}
escaped = false
gap = 0
}
}
if s < end {
items = append(items, s, end)
}
n := len(items)
expr := LiteralExpr{
Values: make([]string, n/2),
}
for i := 0; i < n; i += 2 {
expr.Values[i/2] = string(input[items[i]:items[i+1]])
}
return expr
}