1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
18 // RuleProcessor can be passed to Collator's Process method, which
19 // parses the rules and calls the respective method for each rule found.
20 type RuleProcessor interface {
21 Reset(anchor string, before int) error
22 Insert(level int, str, context, extend string) error
27 // cldrIndex is a Unicode-reserved sentinel value used to mark the start
28 // of a grouping within an index.
29 // We ignore any rule that starts with this rune.
30 // See http://unicode.org/reports/tr35/#Collation_Elements for details.
33 // specialAnchor is the format in which to represent logical reset positions,
34 // such as "first tertiary ignorable".
35 specialAnchor = "<%s/>"
38 // Process parses the rules for the tailorings of this collation
39 // and calls the respective methods of p for each rule found.
40 func (c Collation) Process(p RuleProcessor) (err error) {
43 return fmt.Errorf("multiple cr elements, want 0 or 1")
45 return processRules(p, c.Cr[0].Data())
47 if c.Rules.Any != nil {
48 return c.processXML(p)
50 return errors.New("no tailoring data")
53 // processRules parses rules in the Collation Rule Syntax defined in
54 // http://www.unicode.org/reports/tr35/tr35-collation.html#Collation_Tailorings.
55 func processRules(p RuleProcessor, s string) (err error) {
56 chk := func(s string, e error) string {
62 i := 0 // Save the line number for use after the loop.
63 scanner := bufio.NewScanner(strings.NewReader(s))
64 for ; scanner.Scan() && err == nil; i++ {
65 for s := skipSpace(scanner.Text()); s != "" && s[0] != '#'; s = skipSpace(s) {
68 switch ch, s = s[0], s[1:]; ch {
69 case '&': // followed by <anchor> or '[' <key> ']'
70 if s = skipSpace(s); consume(&s, '[') {
71 s = chk(parseSpecialAnchor(p, s))
73 s = chk(parseAnchor(p, 0, s))
75 case '<': // sort relation '<'{1,4}, optionally followed by '*'.
76 for level = 1; consume(&s, '<'); level++ {
79 err = fmt.Errorf("level %d > 4", level)
82 case '=': // identity relation, optionally followed by *.
84 s = chk(parseSequence(p, level, s))
86 s = chk(parseOrder(p, level, s))
89 chk("", fmt.Errorf("illegal operator %q", ch))
94 if chk("", scanner.Err()); err != nil {
95 return fmt.Errorf("%d: %v", i, err)
100 // parseSpecialAnchor parses the anchor syntax which is either of the form
101 // ['before' <level>] <anchor>
104 // The starting should already be consumed.
105 func parseSpecialAnchor(p RuleProcessor, s string) (tail string, err error) {
106 i := strings.IndexByte(s, ']')
108 return "", errors.New("unmatched bracket")
110 a := strings.TrimSpace(s[:i])
112 if strings.HasPrefix(a, "before ") {
113 l, err := strconv.ParseUint(skipSpace(a[len("before "):]), 10, 3)
117 return parseAnchor(p, int(l), s)
119 return s, p.Reset(fmt.Sprintf(specialAnchor, a), 0)
122 func parseAnchor(p RuleProcessor, level int, s string) (tail string, err error) {
123 anchor, s, err := scanString(s)
127 return s, p.Reset(anchor, level)
130 func parseOrder(p RuleProcessor, level int, s string) (tail string, err error) {
131 var value, context, extend string
132 if value, s, err = scanString(s); err != nil {
135 if strings.HasPrefix(value, cldrIndex) {
136 p.Index(value[len(cldrIndex):])
139 if consume(&s, '|') {
140 if context, s, err = scanString(s); err != nil {
141 return s, errors.New("missing string after context")
144 if consume(&s, '/') {
145 if extend, s, err = scanString(s); err != nil {
146 return s, errors.New("missing string after extension")
149 return s, p.Insert(level, value, context, extend)
152 // scanString scans a single input string.
153 func scanString(s string) (str, tail string, err error) {
154 if s = skipSpace(s); s == "" {
155 return s, s, errors.New("missing string")
157 buf := [16]byte{} // small but enough to hold most cases.
160 if consume(&s, '\'') {
161 i := strings.IndexByte(s, '\'')
163 return "", "", errors.New(`unmatched single quote`)
166 value = append(value, '\'')
168 value = append(value, s[:i]...)
173 r, sz := utf8.DecodeRuneInString(s)
174 if unicode.IsSpace(r) || strings.ContainsRune("&<=#", r) {
177 value = append(value, s[:sz]...)
180 return string(value), skipSpace(s), nil
183 func parseSequence(p RuleProcessor, level int, s string) (tail string, err error) {
184 if s = skipSpace(s); s == "" {
185 return s, errors.New("empty sequence")
189 r, sz := utf8.DecodeRuneInString(s)
193 // We have a range. The first element was already written.
195 return s, errors.New("range without starter value")
197 r, sz = utf8.DecodeRuneInString(s)
199 if r == utf8.RuneError || r < last {
200 return s, fmt.Errorf("invalid range %q-%q", last, r)
202 for i := last + 1; i <= r; i++ {
203 if err := p.Insert(level, string(i), "", ""); err != nil {
211 if unicode.IsSpace(r) || unicode.IsPunct(r) {
216 if err := p.Insert(level, string(r), "", ""); err != nil {
224 func skipSpace(s string) string {
225 return strings.TrimLeftFunc(s, unicode.IsSpace)
228 // consumes returns whether the next byte is ch. If so, it gobbles it by
230 func consume(s *string, ch byte) (ok bool) {
231 if *s == "" || (*s)[0] != ch {
238 // The following code parses Collation rules of CLDR version 24 and before.
240 var lmap = map[byte]int{
247 type rulesElem struct {
258 Value string `xml:",chardata"`
259 Before string `xml:"before,attr"`
266 var emptyValueError = errors.New("cldr: empty rule value")
268 func (r *rule) value() (string, error) {
269 // Convert hexadecimal Unicode codepoint notation to a string.
270 s := charRe.ReplaceAllStringFunc(r.Value, replaceUnicode)
274 return "", emptyValueError
276 r.Value = fmt.Sprintf(specialAnchor, r.Any[0].XMLName.Local)
278 } else if len(r.Any) != 0 {
279 return "", fmt.Errorf("cldr: XML elements found in collation rule: %v", r.Any)
284 func (r rule) process(p RuleProcessor, name, context, extend string) error {
290 case "p", "s", "t", "i":
291 if strings.HasPrefix(v, cldrIndex) {
292 p.Index(v[len(cldrIndex):])
295 if err := p.Insert(lmap[name[0]], v, context, extend); err != nil {
298 case "pc", "sc", "tc", "ic":
299 level := lmap[name[0]]
300 for _, s := range v {
301 if err := p.Insert(level, string(s), context, extend); err != nil {
306 return fmt.Errorf("cldr: unsupported tag: %q", name)
311 // processXML parses the format of CLDR versions 24 and older.
312 func (c Collation) processXML(p RuleProcessor) (err error) {
313 // Collation is generated and defined in xml.go.
315 for _, r := range c.Rules.Any {
316 switch r.XMLName.Local {
322 case "secondary", "2":
324 case "tertiary", "3":
328 return fmt.Errorf("cldr: unknown level %q", r.Before)
332 err = p.Reset(v, level)
335 var context, extend string
336 for _, r1 := range r.Any {
338 switch r1.XMLName.Local {
345 for _, r1 := range r.Any {
346 if t := r1.XMLName.Local; t == "context" || t == "extend" {
349 r1.rule.process(p, r1.XMLName.Local, context, extend)
352 err = r.rule.process(p, r.XMLName.Local, "", "")