Debian Codegraph @

debian/go/src/github.com/bep/golocales/internal/gen.go

raw
1 // Copyright 2026 Bjørn Erik Pedersen
2 // SPDX-License-Identifier: MIT
3
4 package internal
5
6 import (
7 "fmt"
8 "iter"
9 "log"
10 "reflect"
11 "slices"
12 "strings"
13
14 "golang.org/x/text/unicode/cldr"
15 )
16
17 var (
18 TestMode = false
19 // testModeLocales = []string{"en", "de", "fr", "zh", "no", "nb", "nb_NO", "nn", "nn_NO"}
20 testModeLocales = []string{"en", "de", "de_BE", "fr", "zh", "no", "nb", "nb_NO", "nn", "nn_NO"}
21 )
22
23 func Generate(dataPath string) iter.Seq2[string, LocaleConfig] {
24 return func(yeld func(string, LocaleConfig) bool) {
25 // load CLDR recourses
26 var decoder cldr.Decoder
27 decoder.SetDirFilter("main", "supplemental")
28
29 cldrData, err := decoder.DecodePath(dataPath)
30 if err != nil {
31 log.Fatal(err)
32 }
33
34 parentOverrides := BuildParentLocaleMap(cldrData)
35
36 for _, l := range cldrData.Locales() {
37 if TestMode && !slices.Contains(testModeLocales, l) {
38 continue
39 }
40 lcfg := ResolveLocale(l, cldrData, parentOverrides)
41 if !yeld(l, lcfg) {
42 return
43 }
44
45 }
46 }
47 }
48
49 // BuildMetazoneMap builds a map of IANA timezone name → metazone name
50 // from the CLDR supplemental metazoneInfo data.
51 // Only the current (no "to" date) mapping is used.
52 func BuildMetazoneMap(cldrData *cldr.CLDR) map[string]string {
53 m := make(map[string]string)
54 sup := cldrData.Supplemental()
55 if sup.MetaZones == nil || sup.MetaZones.MetazoneInfo == nil {
56 return m
57 }
58 for _, tz := range sup.MetaZones.MetazoneInfo.Timezone {
59 for _, umz := range tz.UsesMetazone {
60 if umz.To == "" {
61 // Current mapping (no end date).
62 m[tz.Type] = umz.Mzone
63 }
64 }
65 }
66 return m
67 }
68
69 // BuildParentLocaleMap builds a map of locale -> parent from the CLDR
70 // supplemental parentLocales data, falling back to the default algorithm
71 // (strip rightmost component, then "root").
72 func BuildParentLocaleMap(cldrData *cldr.CLDR) map[string]string {
73 m := make(map[string]string)
74 sup := cldrData.Supplemental()
75 if sup.ParentLocales != nil {
76 for _, pl := range sup.ParentLocales.ParentLocale {
77 for _, loc := range strings.Fields(pl.Locales) {
78 m[loc] = pl.Parent
79 }
80 }
81 }
82 return m
83 }
84
85 // parentLocale returns the parent of loc. It consults the explicit override
86 // map first, then falls back to stripping the rightmost component.
87 // Returns "" for "root".
88 func parentLocale(loc string, overrides map[string]string) string {
89 if loc == "root" {
90 return ""
91 }
92 if p, ok := overrides[loc]; ok {
93 return p
94 }
95 if i := strings.LastIndex(loc, "_"); i >= 0 {
96 return loc[:i]
97 }
98 return "root"
99 }
100
101 // mergeInto copies non-zero fields from src into dst where dst's field is
102 // the zero value. This works for any struct fields (slices, arrays, strings,
103 // etc.) and is the single place inheritance is applied — adding new fields
104 // to localeConfig automatically participates in inheritance.
105 // Map fields are merged key-by-key (parent keys fill gaps in child).
106 func mergeInto(dst, src *LocaleConfig) {
107 dv := reflect.ValueOf(dst).Elem()
108 sv := reflect.ValueOf(src).Elem()
109 for i := range dv.NumField() {
110 df := dv.Field(i)
111 sf := sv.Field(i)
112 if df.Kind() == reflect.Struct {
113 mergeStruct(df, sf)
114 } else if df.Kind() == reflect.Map {
115 mergeMap(df, sf)
116 } else if df.IsZero() && !sf.IsZero() {
117 df.Set(sf)
118 }
119 }
120 }
121
122 func mergeStruct(dst, src reflect.Value) {
123 for i := range dst.NumField() {
124 df := dst.Field(i)
125 sf := src.Field(i)
126 if df.Kind() == reflect.Map {
127 mergeMap(df, sf)
128 } else if df.Kind() == reflect.Array {
129 mergeArray(df, sf)
130 } else if df.IsZero() && !sf.IsZero() {
131 df.Set(sf)
132 }
133 }
134 }
135
136 func mergeArray(dst, src reflect.Value) {
137 for i := range dst.Len() {
138 de := dst.Index(i)
139 se := src.Index(i)
140 if de.IsZero() && !se.IsZero() {
141 de.Set(se)
142 }
143 }
144 }
145
146 func mergeMap(dst, src reflect.Value) {
147 if src.IsNil() {
148 return
149 }
150 if dst.IsNil() {
151 dst.Set(reflect.MakeMap(dst.Type()))
152 }
153 for _, k := range src.MapKeys() {
154 if dst.MapIndex(k).IsValid() {
155 continue // child already has this key
156 }
157 dst.SetMapIndex(k, src.MapIndex(k))
158 }
159 }
160
161 // extractFromLDML extracts locale data from a raw LDML into a localeConfig.
162 func extractFromLDML(ldml *cldr.LDML) LocaleConfig {
163 var lcfg LocaleConfig
164 if ldml == nil {
165 return lcfg
166 }
167 calendar := gregorianCalendar(ldml)
168 if calendar != nil {
169 extractMonths(calendar, &lcfg)
170 extractDays(calendar, &lcfg)
171 extractDateTimeFormats(calendar, &lcfg)
172 }
173 extractNumbers(ldml, &lcfg)
174 extractCurrencies(ldml, &lcfg)
175 extractTimeZoneNames(ldml, &lcfg)
176 return lcfg
177 }
178
179 func gregorianCalendar(ldml *cldr.LDML) *cldr.Calendar {
180 if ldml.Dates == nil || ldml.Dates.Calendars == nil {
181 return nil
182 }
183 for _, cal := range ldml.Dates.Calendars.Calendar {
184 if cal.Type == "gregorian" {
185 return cal
186 }
187 }
188 return nil
189 }
190
191 func extractMonths(calendar *cldr.Calendar, lcfg *LocaleConfig) {
192 if calendar.Months == nil {
193 return
194 }
195 for _, ctx := range calendar.Months.MonthContext {
196 if ctx.Type != "format" {
197 continue
198 }
199 for _, width := range ctx.MonthWidth {
200 var months Months
201 for _, m := range width.Month {
202 if m.Yeartype != "" {
203 continue
204 }
205 idx := 0
206 fmt.Sscanf(m.Type, "%d", &idx)
207 if idx >= 1 && idx <= 12 {
208 months[idx-1] = m.Data()
209 }
210 }
211 switch width.Type {
212 case "abbreviated":
213 lcfg.MonthsAbbreviated = months
214 case "narrow":
215 lcfg.MonthsNarrow = months
216 case "wide":
217 lcfg.MonthsWide = months
218 }
219 }
220 }
221 }
222
223 var dayIndex = map[string]int{
224 "sun": 0, "mon": 1, "tue": 2, "wed": 3,
225 "thu": 4, "fri": 5, "sat": 6,
226 }
227
228 func extractDays(calendar *cldr.Calendar, lcfg *LocaleConfig) {
229 if calendar.Days == nil {
230 return
231 }
232 for _, ctx := range calendar.Days.DayContext {
233 if ctx.Type != "format" {
234 continue
235 }
236 for _, width := range ctx.DayWidth {
237 var days Days
238 for _, d := range width.Day {
239 if i, ok := dayIndex[d.Type]; ok {
240 days[i] = d.Data()
241 }
242 }
243 switch width.Type {
244 case "abbreviated":
245 lcfg.WeekDaysAbbreviated = days
246 case "narrow":
247 lcfg.WeekDaysNarrow = days
248 case "short":
249 lcfg.WeekDaysShort = days
250 case "wide":
251 lcfg.WeekDaysWide = days
252 }
253 }
254 }
255 }
256
257 // normalizeDateShortYear replaces a standalone single 'y' in a short date pattern
258 // with 'yy' so that the formatter produces 2-digit years for short date formats.
259 func normalizeDateShortYear(pattern string) string {
260 // Find runs of 'y'. If there's exactly one 'y' (not 'yy' or more), replace with 'yy'.
261 i := 0
262 var result []byte
263 changed := false
264 for i < len(pattern) {
265 if pattern[i] == '\'' {
266 result = append(result, pattern[i])
267 i++
268 for i < len(pattern) && pattern[i] != '\'' {
269 result = append(result, pattern[i])
270 i++
271 }
272 if i < len(pattern) {
273 result = append(result, pattern[i])
274 i++
275 }
276 continue
277 }
278 if pattern[i] == 'y' {
279 start := i
280 for i < len(pattern) && pattern[i] == 'y' {
281 i++
282 }
283 if i-start == 1 {
284 result = append(result, 'y', 'y')
285 changed = true
286 } else {
287 result = append(result, pattern[start:i]...)
288 }
289 continue
290 }
291 result = append(result, pattern[i])
292 i++
293 }
294 if !changed {
295 return pattern
296 }
297 return string(result)
298 }
299
300 func extractDateTimeFormats(calendar *cldr.Calendar, lcfg *LocaleConfig) {
301 if calendar.DateFormats != nil {
302 for _, dfl := range calendar.DateFormats.DateFormatLength {
303 for _, df := range dfl.DateFormat {
304 for _, p := range df.Pattern {
305 if p.Alt != "" {
306 continue
307 }
308 switch dfl.Type {
309 case "full":
310 lcfg.DateFull = p.Data()
311 case "long":
312 lcfg.DateLong = p.Data()
313 case "medium":
314 lcfg.DateMedium = p.Data()
315 case "short":
316 lcfg.DateShort = normalizeDateShortYear(p.Data())
317 }
318 }
319 }
320 }
321 }
322 if calendar.TimeFormats != nil {
323 for _, tfl := range calendar.TimeFormats.TimeFormatLength {
324 for _, tf := range tfl.TimeFormat {
325 for _, p := range tf.Pattern {
326 if p.Alt != "" {
327 continue
328 }
329 switch tfl.Type {
330 case "full":
331 lcfg.TimeFull = p.Data()
332 case "long":
333 lcfg.TimeLong = p.Data()
334 case "medium":
335 lcfg.TimeMedium = p.Data()
336 case "short":
337 lcfg.TimeShort = p.Data()
338 }
339 }
340 }
341 }
342 }
343 }
344
345 func extractTimeZoneNames(ldml *cldr.LDML, lcfg *LocaleConfig) {
346 if ldml.Dates == nil || ldml.Dates.TimeZoneNames == nil {
347 return
348 }
349 tzn := ldml.Dates.TimeZoneNames
350 for _, mz := range tzn.Metazone {
351 if len(mz.Long) == 0 {
352 continue
353 }
354 long := mz.Long[0]
355 var standard, daylight string
356 if len(long.Standard) > 0 {
357 standard = long.Standard[0].Data()
358 }
359 if len(long.Daylight) > 0 {
360 daylight = long.Daylight[0].Data()
361 }
362 if standard == "" && daylight == "" {
363 continue
364 }
365 if lcfg.TZNames == nil {
366 lcfg.TZNames = make(TimeZoneNames)
367 }
368 lcfg.TZNames[mz.Type] = [2]string{standard, daylight}
369 }
370 }
371
372 func extractNumbers(ldml *cldr.LDML, lcfg *LocaleConfig) {
373 if ldml.Numbers == nil {
374 return
375 }
376 // Find symbols for the "latn" number system (or unspecified, which defaults to latn).
377 for _, sym := range ldml.Numbers.Symbols {
378 if sym.NumberSystem != "" && sym.NumberSystem != "latn" {
379 continue
380 }
381 if len(sym.Decimal) > 0 {
382 lcfg.Decimal = sym.Decimal[0].Data()
383 }
384 if len(sym.Group) > 0 {
385 lcfg.Group = sym.Group[0].Data()
386 }
387 if len(sym.MinusSign) > 0 {
388 lcfg.Minus = sym.MinusSign[0].Data()
389 }
390 if len(sym.PercentSign) > 0 {
391 lcfg.Percent = sym.PercentSign[0].Data()
392 }
393 if len(sym.PerMille) > 0 {
394 lcfg.PerMille = sym.PerMille[0].Data()
395 }
396 if len(sym.PlusSign) > 0 {
397 lcfg.Plus = sym.PlusSign[0].Data()
398 }
399 break
400 }
401
402 // Extract percent format pattern.
403 for _, pf := range ldml.Numbers.PercentFormats {
404 if pf.NumberSystem != "" && pf.NumberSystem != "latn" {
405 continue
406 }
407 for _, pfl := range pf.PercentFormatLength {
408 if pfl.Type != "" {
409 continue
410 }
411 for _, pfmt := range pfl.PercentFormat {
412 for _, p := range pfmt.Pattern {
413 if p.Alt != "" || p.Count != "" {
414 continue
415 }
416 lcfg.PercentPattern = p.Data()
417 }
418 }
419 }
420 break
421 }
422 }
423
424 func extractCurrencies(ldml *cldr.LDML, lcfg *LocaleConfig) {
425 if ldml.Numbers == nil {
426 return
427 }
428
429 // Extract accounting format pattern from latn currency formats.
430 for _, cf := range ldml.Numbers.CurrencyFormats {
431 if cf.NumberSystem != "" && cf.NumberSystem != "latn" {
432 continue
433 }
434 for _, cfl := range cf.CurrencyFormatLength {
435 if cfl.Type != "" {
436 continue // skip "short" etc., we want the default length
437 }
438 for _, cfmt := range cfl.CurrencyFormat {
439 for _, p := range cfmt.Pattern {
440 if p.Alt != "" || p.Count != "" {
441 continue
442 }
443 switch cfmt.Type {
444 case "standard":
445 lcfg.StandardPattern = p.Data()
446 case "accounting":
447 lcfg.AccountingPattern = p.Data()
448 }
449 }
450 }
451 }
452 break
453 }
454
455 // Extract currency symbols.
456 if ldml.Numbers.Currencies != nil {
457 for _, cur := range ldml.Numbers.Currencies.Currency {
458 if len(cur.Symbol) > 0 {
459 if lcfg.CurrencySymbols == nil {
460 lcfg.CurrencySymbols = make(map[string]string)
461 }
462 lcfg.CurrencySymbols[cur.Type] = cur.Symbol[0].Data()
463 }
464 }
465 }
466 }
467
468 // ResolveLocale builds a fully inherited localeConfig by walking up the
469 // parent chain (e.g. nn -> no -> root) and merging.
470 func ResolveLocale(loc string, cldrData *cldr.CLDR, parentOverrides map[string]string) LocaleConfig {
471 lcfg := extractFromLDML(cldrData.RawLDML(loc))
472 for p := parentLocale(loc, parentOverrides); p != ""; p = parentLocale(p, parentOverrides) {
473 parentCfg := extractFromLDML(cldrData.RawLDML(p))
474 mergeInto(&lcfg, &parentCfg)
475 }
476 return lcfg
477 }