Debian Codegraph @

unicode/cldr/resolve.go

raw
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.
4
5 package cldr
6
7 // This file implements the various inheritance constructs defined by LDML.
8 // See https://www.unicode.org/reports/tr35/#Inheritance_and_Validity
9 // for more details.
10
11 import (
12 "fmt"
13 "log"
14 "reflect"
15 "regexp"
16 "sort"
17 "strings"
18 )
19
20 // fieldIter iterates over fields in a struct. It includes
21 // fields of embedded structs.
22 type fieldIter struct {
23 v reflect.Value
24 index, n []int
25 }
26
27 func iter(v reflect.Value) fieldIter {
28 if v.Kind() != reflect.Struct {
29 log.Panicf("value %v must be a struct", v)
30 }
31 i := fieldIter{
32 v: v,
33 index: []int{0},
34 n: []int{v.NumField()},
35 }
36 i.descent()
37 return i
38 }
39
40 func (i *fieldIter) descent() {
41 for f := i.field(); f.Anonymous && f.Type.NumField() > 0; f = i.field() {
42 i.index = append(i.index, 0)
43 i.n = append(i.n, f.Type.NumField())
44 }
45 }
46
47 func (i *fieldIter) done() bool {
48 return len(i.index) == 1 && i.index[0] >= i.n[0]
49 }
50
51 func skip(f reflect.StructField) bool {
52 return !f.Anonymous && (f.Name[0] < 'A' || f.Name[0] > 'Z')
53 }
54
55 func (i *fieldIter) next() {
56 for {
57 k := len(i.index) - 1
58 i.index[k]++
59 if i.index[k] < i.n[k] {
60 if !skip(i.field()) {
61 break
62 }
63 } else {
64 if k == 0 {
65 return
66 }
67 i.index = i.index[:k]
68 i.n = i.n[:k]
69 }
70 }
71 i.descent()
72 }
73
74 func (i *fieldIter) value() reflect.Value {
75 return i.v.FieldByIndex(i.index)
76 }
77
78 func (i *fieldIter) field() reflect.StructField {
79 return i.v.Type().FieldByIndex(i.index)
80 }
81
82 type visitor func(v reflect.Value) error
83
84 var stopDescent = fmt.Errorf("do not recurse")
85
86 func (f visitor) visit(x interface{}) error {
87 return f.visitRec(reflect.ValueOf(x))
88 }
89
90 // visit recursively calls f on all nodes in v.
91 func (f visitor) visitRec(v reflect.Value) error {
92 if v.Kind() == reflect.Ptr {
93 if v.IsNil() {
94 return nil
95 }
96 return f.visitRec(v.Elem())
97 }
98 if err := f(v); err != nil {
99 if err == stopDescent {
100 return nil
101 }
102 return err
103 }
104 switch v.Kind() {
105 case reflect.Struct:
106 for i := iter(v); !i.done(); i.next() {
107 if err := f.visitRec(i.value()); err != nil {
108 return err
109 }
110 }
111 case reflect.Slice:
112 for i := 0; i < v.Len(); i++ {
113 if err := f.visitRec(v.Index(i)); err != nil {
114 return err
115 }
116 }
117 }
118 return nil
119 }
120
121 // getPath is used for error reporting purposes only.
122 func getPath(e Elem) string {
123 if e == nil {
124 return "<nil>"
125 }
126 if e.enclosing() == nil {
127 return e.GetCommon().name
128 }
129 if e.GetCommon().Type == "" {
130 return fmt.Sprintf("%s.%s", getPath(e.enclosing()), e.GetCommon().name)
131 }
132 return fmt.Sprintf("%s.%s[type=%s]", getPath(e.enclosing()), e.GetCommon().name, e.GetCommon().Type)
133 }
134
135 // xmlName returns the xml name of the element or attribute
136 func xmlName(f reflect.StructField) (name string, attr bool) {
137 tags := strings.Split(f.Tag.Get("xml"), ",")
138 for _, s := range tags {
139 attr = attr || s == "attr"
140 }
141 return tags[0], attr
142 }
143
144 func findField(v reflect.Value, key string) (reflect.Value, error) {
145 v = reflect.Indirect(v)
146 for i := iter(v); !i.done(); i.next() {
147 if n, _ := xmlName(i.field()); n == key {
148 return i.value(), nil
149 }
150 }
151 return reflect.Value{}, fmt.Errorf("cldr: no field %q in element %#v", key, v.Interface())
152 }
153
154 var xpathPart = regexp.MustCompile(`(\pL+)(?:\[@(\pL+)='([\w-]+)'\])?`)
155
156 func walkXPath(e Elem, path string) (res Elem, err error) {
157 for _, c := range strings.Split(path, "/") {
158 if c == ".." {
159 if e = e.enclosing(); e == nil {
160 panic("path ..")
161 }
162 continue
163 } else if c == "" {
164 continue
165 }
166 m := xpathPart.FindStringSubmatch(c)
167 if len(m) == 0 || len(m[0]) != len(c) {
168 return nil, fmt.Errorf("cldr: syntax error in path component %q", c)
169 }
170 v, err := findField(reflect.ValueOf(e), m[1])
171 if err != nil {
172 return nil, err
173 }
174 switch v.Kind() {
175 case reflect.Slice:
176 i := 0
177 if m[2] != "" || v.Len() > 1 {
178 if m[2] == "" {
179 m[2] = "type"
180 if m[3] = e.GetCommon().Default(); m[3] == "" {
181 return nil, fmt.Errorf("cldr: type selector or default value needed for element %s", m[1])
182 }
183 }
184 for ; i < v.Len(); i++ {
185 vi := v.Index(i)
186 key, err := findField(vi.Elem(), m[2])
187 if err != nil {
188 return nil, err
189 }
190 key = reflect.Indirect(key)
191 if key.Kind() == reflect.String && key.String() == m[3] {
192 break
193 }
194 }
195 }
196 if i == v.Len() || v.Index(i).IsNil() {
197 return nil, fmt.Errorf("no %s found with %s==%s", m[1], m[2], m[3])
198 }
199 e = v.Index(i).Interface().(Elem)
200 case reflect.Ptr:
201 if v.IsNil() {
202 return nil, fmt.Errorf("cldr: element %q not found within element %q", m[1], e.GetCommon().name)
203 }
204 var ok bool
205 if e, ok = v.Interface().(Elem); !ok {
206 return nil, fmt.Errorf("cldr: %q is not an XML element", m[1])
207 } else if m[2] != "" || m[3] != "" {
208 return nil, fmt.Errorf("cldr: no type selector allowed for element %s", m[1])
209 }
210 default:
211 return nil, fmt.Errorf("cldr: %q is not an XML element", m[1])
212 }
213 }
214 return e, nil
215 }
216
217 const absPrefix = "//ldml/"
218
219 func (cldr *CLDR) resolveAlias(e Elem, src, path string) (res Elem, err error) {
220 if src != "locale" {
221 if !strings.HasPrefix(path, absPrefix) {
222 return nil, fmt.Errorf("cldr: expected absolute path, found %q", path)
223 }
224 path = path[len(absPrefix):]
225 if e, err = cldr.resolve(src); err != nil {
226 return nil, err
227 }
228 }
229 return walkXPath(e, path)
230 }
231
232 func (cldr *CLDR) resolveAndMergeAlias(e Elem) error {
233 alias := e.GetCommon().Alias
234 if alias == nil {
235 return nil
236 }
237 a, err := cldr.resolveAlias(e, alias.Source, alias.Path)
238 if err != nil {
239 return fmt.Errorf("%v: error evaluating path %q: %v", getPath(e), alias.Path, err)
240 }
241 // Ensure alias node was already evaluated. TODO: avoid double evaluation.
242 err = cldr.resolveAndMergeAlias(a)
243 v := reflect.ValueOf(e).Elem()
244 for i := iter(reflect.ValueOf(a).Elem()); !i.done(); i.next() {
245 if vv := i.value(); vv.Kind() != reflect.Ptr || !vv.IsNil() {
246 if _, attr := xmlName(i.field()); !attr {
247 v.FieldByIndex(i.index).Set(vv)
248 }
249 }
250 }
251 return err
252 }
253
254 func (cldr *CLDR) aliasResolver() visitor {
255 return func(v reflect.Value) (err error) {
256 if e, ok := v.Addr().Interface().(Elem); ok {
257 err = cldr.resolveAndMergeAlias(e)
258 if err == nil && blocking[e.GetCommon().name] {
259 return stopDescent
260 }
261 }
262 return err
263 }
264 }
265
266 // elements within blocking elements do not inherit.
267 // Taken from CLDR's supplementalMetaData.xml.
268 var blocking = map[string]bool{
269 "identity": true,
270 "supplementalData": true,
271 "cldrTest": true,
272 "collation": true,
273 "transform": true,
274 }
275
276 // Distinguishing attributes affect inheritance; two elements with different
277 // distinguishing attributes are treated as different for purposes of inheritance,
278 // except when such attributes occur in the indicated elements.
279 // Taken from CLDR's supplementalMetaData.xml.
280 var distinguishing = map[string][]string{
281 "key": nil,
282 "request_id": nil,
283 "id": nil,
284 "registry": nil,
285 "alt": nil,
286 "iso4217": nil,
287 "iso3166": nil,
288 "mzone": nil,
289 "from": nil,
290 "to": nil,
291 "type": []string{
292 "abbreviationFallback",
293 "default",
294 "mapping",
295 "measurementSystem",
296 "preferenceOrdering",
297 },
298 "numberSystem": nil,
299 }
300
301 func in(set []string, s string) bool {
302 for _, v := range set {
303 if v == s {
304 return true
305 }
306 }
307 return false
308 }
309
310 // attrKey computes a key based on the distinguishable attributes of
311 // an element and its values.
312 func attrKey(v reflect.Value, exclude ...string) string {
313 parts := []string{}
314 ename := v.Interface().(Elem).GetCommon().name
315 v = v.Elem()
316 for i := iter(v); !i.done(); i.next() {
317 if name, attr := xmlName(i.field()); attr {
318 if except, ok := distinguishing[name]; ok && !in(exclude, name) && !in(except, ename) {
319 v := i.value()
320 if v.Kind() == reflect.Ptr {
321 v = v.Elem()
322 }
323 if v.IsValid() {
324 parts = append(parts, fmt.Sprintf("%s=%s", name, v.String()))
325 }
326 }
327 }
328 }
329 sort.Strings(parts)
330 return strings.Join(parts, ";")
331 }
332
333 // Key returns a key for e derived from all distinguishing attributes
334 // except those specified by exclude.
335 func Key(e Elem, exclude ...string) string {
336 return attrKey(reflect.ValueOf(e), exclude...)
337 }
338
339 // linkEnclosing sets the enclosing element as well as the name
340 // for all sub-elements of child, recursively.
341 func linkEnclosing(parent, child Elem) {
342 child.setEnclosing(parent)
343 v := reflect.ValueOf(child).Elem()
344 for i := iter(v); !i.done(); i.next() {
345 vf := i.value()
346 if vf.Kind() == reflect.Slice {
347 for j := 0; j < vf.Len(); j++ {
348 linkEnclosing(child, vf.Index(j).Interface().(Elem))
349 }
350 } else if vf.Kind() == reflect.Ptr && !vf.IsNil() && vf.Elem().Kind() == reflect.Struct {
351 linkEnclosing(child, vf.Interface().(Elem))
352 }
353 }
354 }
355
356 func setNames(e Elem, name string) {
357 e.setName(name)
358 v := reflect.ValueOf(e).Elem()
359 for i := iter(v); !i.done(); i.next() {
360 vf := i.value()
361 name, _ = xmlName(i.field())
362 if vf.Kind() == reflect.Slice {
363 for j := 0; j < vf.Len(); j++ {
364 setNames(vf.Index(j).Interface().(Elem), name)
365 }
366 } else if vf.Kind() == reflect.Ptr && !vf.IsNil() && vf.Elem().Kind() == reflect.Struct {
367 setNames(vf.Interface().(Elem), name)
368 }
369 }
370 }
371
372 // deepCopy copies elements of v recursively. All elements of v that may
373 // be modified by inheritance are explicitly copied.
374 func deepCopy(v reflect.Value) reflect.Value {
375 switch v.Kind() {
376 case reflect.Ptr:
377 if v.IsNil() || v.Elem().Kind() != reflect.Struct {
378 return v
379 }
380 nv := reflect.New(v.Elem().Type())
381 nv.Elem().Set(v.Elem())
382 deepCopyRec(nv.Elem(), v.Elem())
383 return nv
384 case reflect.Slice:
385 nv := reflect.MakeSlice(v.Type(), v.Len(), v.Len())
386 for i := 0; i < v.Len(); i++ {
387 deepCopyRec(nv.Index(i), v.Index(i))
388 }
389 return nv
390 }
391 panic("deepCopy: must be called with pointer or slice")
392 }
393
394 // deepCopyRec is only called by deepCopy.
395 func deepCopyRec(nv, v reflect.Value) {
396 if v.Kind() == reflect.Struct {
397 t := v.Type()
398 for i := 0; i < v.NumField(); i++ {
399 if name, attr := xmlName(t.Field(i)); name != "" && !attr {
400 deepCopyRec(nv.Field(i), v.Field(i))
401 }
402 }
403 } else {
404 nv.Set(deepCopy(v))
405 }
406 }
407
408 // newNode is used to insert a missing node during inheritance.
409 func (cldr *CLDR) newNode(v, enc reflect.Value) reflect.Value {
410 n := reflect.New(v.Type())
411 for i := iter(v); !i.done(); i.next() {
412 if name, attr := xmlName(i.field()); name == "" || attr {
413 n.Elem().FieldByIndex(i.index).Set(i.value())
414 }
415 }
416 n.Interface().(Elem).GetCommon().setEnclosing(enc.Addr().Interface().(Elem))
417 return n
418 }
419
420 // v, parent must be pointers to struct
421 func (cldr *CLDR) inheritFields(v, parent reflect.Value) (res reflect.Value, err error) {
422 t := v.Type()
423 nv := reflect.New(t)
424 nv.Elem().Set(v)
425 for i := iter(v); !i.done(); i.next() {
426 vf := i.value()
427 f := i.field()
428 name, attr := xmlName(f)
429 if name == "" || attr {
430 continue
431 }
432 pf := parent.FieldByIndex(i.index)
433 if blocking[name] {
434 if vf.IsNil() {
435 vf = pf
436 }
437 nv.Elem().FieldByIndex(i.index).Set(deepCopy(vf))
438 continue
439 }
440 switch f.Type.Kind() {
441 case reflect.Ptr:
442 if f.Type.Elem().Kind() == reflect.Struct {
443 if !vf.IsNil() {
444 if vf, err = cldr.inheritStructPtr(vf, pf); err != nil {
445 return reflect.Value{}, err
446 }
447 vf.Interface().(Elem).setEnclosing(nv.Interface().(Elem))
448 nv.Elem().FieldByIndex(i.index).Set(vf)
449 } else if !pf.IsNil() {
450 n := cldr.newNode(pf.Elem(), v)
451 if vf, err = cldr.inheritStructPtr(n, pf); err != nil {
452 return reflect.Value{}, err
453 }
454 vf.Interface().(Elem).setEnclosing(nv.Interface().(Elem))
455 nv.Elem().FieldByIndex(i.index).Set(vf)
456 }
457 }
458 case reflect.Slice:
459 vf, err := cldr.inheritSlice(nv.Elem(), vf, pf)
460 if err != nil {
461 return reflect.Zero(t), err
462 }
463 nv.Elem().FieldByIndex(i.index).Set(vf)
464 }
465 }
466 return nv, nil
467 }
468
469 func root(e Elem) *LDML {
470 for ; e.enclosing() != nil; e = e.enclosing() {
471 }
472 return e.(*LDML)
473 }
474
475 // inheritStructPtr first merges possible aliases in with v and then inherits
476 // any underspecified elements from parent.
477 func (cldr *CLDR) inheritStructPtr(v, parent reflect.Value) (r reflect.Value, err error) {
478 if !v.IsNil() {
479 e := v.Interface().(Elem).GetCommon()
480 alias := e.Alias
481 if alias == nil && !parent.IsNil() {
482 alias = parent.Interface().(Elem).GetCommon().Alias
483 }
484 if alias != nil {
485 a, err := cldr.resolveAlias(v.Interface().(Elem), alias.Source, alias.Path)
486 if a != nil {
487 if v, err = cldr.inheritFields(v.Elem(), reflect.ValueOf(a).Elem()); err != nil {
488 return reflect.Value{}, err
489 }
490 }
491 }
492 if !parent.IsNil() {
493 return cldr.inheritFields(v.Elem(), parent.Elem())
494 }
495 } else if parent.IsNil() {
496 panic("should not reach here")
497 }
498 return v, nil
499 }
500
501 // Must be slice of struct pointers.
502 func (cldr *CLDR) inheritSlice(enc, v, parent reflect.Value) (res reflect.Value, err error) {
503 t := v.Type()
504 index := make(map[string]reflect.Value)
505 if !v.IsNil() {
506 for i := 0; i < v.Len(); i++ {
507 vi := v.Index(i)
508 key := attrKey(vi)
509 index[key] = vi
510 }
511 }
512 if !parent.IsNil() {
513 for i := 0; i < parent.Len(); i++ {
514 vi := parent.Index(i)
515 key := attrKey(vi)
516 if w, ok := index[key]; ok {
517 index[key], err = cldr.inheritStructPtr(w, vi)
518 } else {
519 n := cldr.newNode(vi.Elem(), enc)
520 index[key], err = cldr.inheritStructPtr(n, vi)
521 }
522 index[key].Interface().(Elem).setEnclosing(enc.Addr().Interface().(Elem))
523 if err != nil {
524 return v, err
525 }
526 }
527 }
528 keys := make([]string, 0, len(index))
529 for k, _ := range index {
530 keys = append(keys, k)
531 }
532 sort.Strings(keys)
533 sl := reflect.MakeSlice(t, len(index), len(index))
534 for i, k := range keys {
535 sl.Index(i).Set(index[k])
536 }
537 return sl, nil
538 }
539
540 func parentLocale(loc string) string {
541 parts := strings.Split(loc, "_")
542 if len(parts) == 1 {
543 return "root"
544 }
545 parts = parts[:len(parts)-1]
546 key := strings.Join(parts, "_")
547 return key
548 }
549
550 func (cldr *CLDR) resolve(loc string) (res *LDML, err error) {
551 if r := cldr.resolved[loc]; r != nil {
552 return r, nil
553 }
554 x := cldr.RawLDML(loc)
555 if x == nil {
556 return nil, fmt.Errorf("cldr: unknown locale %q", loc)
557 }
558 var v reflect.Value
559 if loc == "root" {
560 x = deepCopy(reflect.ValueOf(x)).Interface().(*LDML)
561 linkEnclosing(nil, x)
562 err = cldr.aliasResolver().visit(x)
563 } else {
564 key := parentLocale(loc)
565 var parent *LDML
566 for ; cldr.locale[key] == nil; key = parentLocale(key) {
567 }
568 if parent, err = cldr.resolve(key); err != nil {
569 return nil, err
570 }
571 v, err = cldr.inheritFields(reflect.ValueOf(x).Elem(), reflect.ValueOf(parent).Elem())
572 x = v.Interface().(*LDML)
573 linkEnclosing(nil, x)
574 }
575 if err != nil {
576 return nil, err
577 }
578 cldr.resolved[loc] = x
579 return x, err
580 }
581
582 // finalize finalizes the initialization of the raw LDML structs. It also
583 // removed unwanted fields, as specified by filter, so that they will not
584 // be unnecessarily evaluated.
585 func (cldr *CLDR) finalize(filter []string) {
586 for _, x := range cldr.locale {
587 if filter != nil {
588 v := reflect.ValueOf(x).Elem()
589 t := v.Type()
590 for i := 0; i < v.NumField(); i++ {
591 f := t.Field(i)
592 name, _ := xmlName(f)
593 if name != "" && name != "identity" && !in(filter, name) {
594 v.Field(i).Set(reflect.Zero(f.Type))
595 }
596 }
597 }
598 linkEnclosing(nil, x) // for resolving aliases and paths
599 setNames(x, "ldml")
600 }
601 }