Path: blob/main/vendor/golang.org/x/text/language/match.go
2880 views
// Copyright 2013 The Go Authors. All rights reserved.1// Use of this source code is governed by a BSD-style2// license that can be found in the LICENSE file.34package language56import (7"errors"8"strings"910"golang.org/x/text/internal/language"11)1213// A MatchOption configures a Matcher.14type MatchOption func(*matcher)1516// PreferSameScript will, in the absence of a match, result in the first17// preferred tag with the same script as a supported tag to match this supported18// tag. The default is currently true, but this may change in the future.19func PreferSameScript(preferSame bool) MatchOption {20return func(m *matcher) { m.preferSameScript = preferSame }21}2223// TODO(v1.0.0): consider making Matcher a concrete type, instead of interface.24// There doesn't seem to be too much need for multiple types.25// Making it a concrete type allows MatchStrings to be a method, which will26// improve its discoverability.2728// MatchStrings parses and matches the given strings until one of them matches29// the language in the Matcher. A string may be an Accept-Language header as30// handled by ParseAcceptLanguage. The default language is returned if no31// other language matched.32func MatchStrings(m Matcher, lang ...string) (tag Tag, index int) {33for _, accept := range lang {34desired, _, err := ParseAcceptLanguage(accept)35if err != nil {36continue37}38if tag, index, conf := m.Match(desired...); conf != No {39return tag, index40}41}42tag, index, _ = m.Match()43return44}4546// Matcher is the interface that wraps the Match method.47//48// Match returns the best match for any of the given tags, along with49// a unique index associated with the returned tag and a confidence50// score.51type Matcher interface {52Match(t ...Tag) (tag Tag, index int, c Confidence)53}5455// Comprehends reports the confidence score for a speaker of a given language56// to being able to comprehend the written form of an alternative language.57func Comprehends(speaker, alternative Tag) Confidence {58_, _, c := NewMatcher([]Tag{alternative}).Match(speaker)59return c60}6162// NewMatcher returns a Matcher that matches an ordered list of preferred tags63// against a list of supported tags based on written intelligibility, closeness64// of dialect, equivalence of subtags and various other rules. It is initialized65// with the list of supported tags. The first element is used as the default66// value in case no match is found.67//68// Its Match method matches the first of the given Tags to reach a certain69// confidence threshold. The tags passed to Match should therefore be specified70// in order of preference. Extensions are ignored for matching.71//72// The index returned by the Match method corresponds to the index of the73// matched tag in t, but is augmented with the Unicode extension ('u')of the74// corresponding preferred tag. This allows user locale options to be passed75// transparently.76func NewMatcher(t []Tag, options ...MatchOption) Matcher {77return newMatcher(t, options)78}7980func (m *matcher) Match(want ...Tag) (t Tag, index int, c Confidence) {81var tt language.Tag82match, w, c := m.getBest(want...)83if match != nil {84tt, index = match.tag, match.index85} else {86// TODO: this should be an option87tt = m.default_.tag88if m.preferSameScript {89outer:90for _, w := range want {91script, _ := w.Script()92if script.scriptID == 0 {93// Don't do anything if there is no script, such as with94// private subtags.95continue96}97for i, h := range m.supported {98if script.scriptID == h.maxScript {99tt, index = h.tag, i100break outer101}102}103}104}105// TODO: select first language tag based on script.106}107if w.RegionID != tt.RegionID && w.RegionID != 0 {108if w.RegionID != 0 && tt.RegionID != 0 && tt.RegionID.Contains(w.RegionID) {109tt.RegionID = w.RegionID110tt.RemakeString()111} else if r := w.RegionID.String(); len(r) == 2 {112// TODO: also filter macro and deprecated.113tt, _ = tt.SetTypeForKey("rg", strings.ToLower(r)+"zzzz")114}115}116// Copy options from the user-provided tag into the result tag. This is hard117// to do after the fact, so we do it here.118// TODO: add in alternative variants to -u-va-.119// TODO: add preferred region to -u-rg-.120if e := w.Extensions(); len(e) > 0 {121b := language.Builder{}122b.SetTag(tt)123for _, e := range e {124b.AddExt(e)125}126tt = b.Make()127}128return makeTag(tt), index, c129}130131// ErrMissingLikelyTagsData indicates no information was available132// to compute likely values of missing tags.133var ErrMissingLikelyTagsData = errors.New("missing likely tags data")134135// func (t *Tag) setTagsFrom(id Tag) {136// t.LangID = id.LangID137// t.ScriptID = id.ScriptID138// t.RegionID = id.RegionID139// }140141// Tag Matching142// CLDR defines an algorithm for finding the best match between two sets of language143// tags. The basic algorithm defines how to score a possible match and then find144// the match with the best score145// (see https://www.unicode.org/reports/tr35/#LanguageMatching).146// Using scoring has several disadvantages. The scoring obfuscates the importance of147// the various factors considered, making the algorithm harder to understand. Using148// scoring also requires the full score to be computed for each pair of tags.149//150// We will use a different algorithm which aims to have the following properties:151// - clarity on the precedence of the various selection factors, and152// - improved performance by allowing early termination of a comparison.153//154// Matching algorithm (overview)155// Input:156// - supported: a set of supported tags157// - default: the default tag to return in case there is no match158// - desired: list of desired tags, ordered by preference, starting with159// the most-preferred.160//161// Algorithm:162// 1) Set the best match to the lowest confidence level163// 2) For each tag in "desired":164// a) For each tag in "supported":165// 1) compute the match between the two tags.166// 2) if the match is better than the previous best match, replace it167// with the new match. (see next section)168// b) if the current best match is Exact and pin is true the result will be169// frozen to the language found thusfar, although better matches may170// still be found for the same language.171// 3) If the best match so far is below a certain threshold, return "default".172//173// Ranking:174// We use two phases to determine whether one pair of tags are a better match175// than another pair of tags. First, we determine a rough confidence level. If the176// levels are different, the one with the highest confidence wins.177// Second, if the rough confidence levels are identical, we use a set of tie-breaker178// rules.179//180// The confidence level of matching a pair of tags is determined by finding the181// lowest confidence level of any matches of the corresponding subtags (the182// result is deemed as good as its weakest link).183// We define the following levels:184// Exact - An exact match of a subtag, before adding likely subtags.185// MaxExact - An exact match of a subtag, after adding likely subtags.186// [See Note 2].187// High - High level of mutual intelligibility between different subtag188// variants.189// Low - Low level of mutual intelligibility between different subtag190// variants.191// No - No mutual intelligibility.192//193// The following levels can occur for each type of subtag:194// Base: Exact, MaxExact, High, Low, No195// Script: Exact, MaxExact [see Note 3], Low, No196// Region: Exact, MaxExact, High197// Variant: Exact, High198// Private: Exact, No199//200// Any result with a confidence level of Low or higher is deemed a possible match.201// Once a desired tag matches any of the supported tags with a level of MaxExact202// or higher, the next desired tag is not considered (see Step 2.b).203// Note that CLDR provides languageMatching data that defines close equivalence204// classes for base languages, scripts and regions.205//206// Tie-breaking207// If we get the same confidence level for two matches, we apply a sequence of208// tie-breaking rules. The first that succeeds defines the result. The rules are209// applied in the following order.210// 1) Original language was defined and was identical.211// 2) Original region was defined and was identical.212// 3) Distance between two maximized regions was the smallest.213// 4) Original script was defined and was identical.214// 5) Distance from want tag to have tag using the parent relation [see Note 5.]215// If there is still no winner after these rules are applied, the first match216// found wins.217//218// Notes:219// [2] In practice, as matching of Exact is done in a separate phase from220// matching the other levels, we reuse the Exact level to mean MaxExact in221// the second phase. As a consequence, we only need the levels defined by222// the Confidence type. The MaxExact confidence level is mapped to High in223// the public API.224// [3] We do not differentiate between maximized script values that were derived225// from suppressScript versus most likely tag data. We determined that in226// ranking the two, one ranks just after the other. Moreover, the two cannot227// occur concurrently. As a consequence, they are identical for practical228// purposes.229// [4] In case of deprecated, macro-equivalents and legacy mappings, we assign230// the MaxExact level to allow iw vs he to still be a closer match than231// en-AU vs en-US, for example.232// [5] In CLDR a locale inherits fields that are unspecified for this locale233// from its parent. Therefore, if a locale is a parent of another locale,234// it is a strong measure for closeness, especially when no other tie235// breaker rule applies. One could also argue it is inconsistent, for236// example, when pt-AO matches pt (which CLDR equates with pt-BR), even237// though its parent is pt-PT according to the inheritance rules.238//239// Implementation Details:240// There are several performance considerations worth pointing out. Most notably,241// we preprocess as much as possible (within reason) at the time of creation of a242// matcher. This includes:243// - creating a per-language map, which includes data for the raw base language244// and its canonicalized variant (if applicable),245// - expanding entries for the equivalence classes defined in CLDR's246// languageMatch data.247// The per-language map ensures that typically only a very small number of tags248// need to be considered. The pre-expansion of canonicalized subtags and249// equivalence classes reduces the amount of map lookups that need to be done at250// runtime.251252// matcher keeps a set of supported language tags, indexed by language.253type matcher struct {254default_ *haveTag255supported []*haveTag256index map[language.Language]*matchHeader257passSettings bool258preferSameScript bool259}260261// matchHeader has the lists of tags for exact matches and matches based on262// maximized and canonicalized tags for a given language.263type matchHeader struct {264haveTags []*haveTag265original bool266}267268// haveTag holds a supported Tag and its maximized script and region. The maximized269// or canonicalized language is not stored as it is not needed during matching.270type haveTag struct {271tag language.Tag272273// index of this tag in the original list of supported tags.274index int275276// conf is the maximum confidence that can result from matching this haveTag.277// When conf < Exact this means it was inserted after applying a CLDR equivalence rule.278conf Confidence279280// Maximized region and script.281maxRegion language.Region282maxScript language.Script283284// altScript may be checked as an alternative match to maxScript. If altScript285// matches, the confidence level for this match is Low. Theoretically there286// could be multiple alternative scripts. This does not occur in practice.287altScript language.Script288289// nextMax is the index of the next haveTag with the same maximized tags.290nextMax uint16291}292293func makeHaveTag(tag language.Tag, index int) (haveTag, language.Language) {294max := tag295if tag.LangID != 0 || tag.RegionID != 0 || tag.ScriptID != 0 {296max, _ = canonicalize(All, max)297max, _ = max.Maximize()298max.RemakeString()299}300return haveTag{tag, index, Exact, max.RegionID, max.ScriptID, altScript(max.LangID, max.ScriptID), 0}, max.LangID301}302303// altScript returns an alternative script that may match the given script with304// a low confidence. At the moment, the langMatch data allows for at most one305// script to map to another and we rely on this to keep the code simple.306func altScript(l language.Language, s language.Script) language.Script {307for _, alt := range matchScript {308// TODO: also match cases where language is not the same.309if (language.Language(alt.wantLang) == l || language.Language(alt.haveLang) == l) &&310language.Script(alt.haveScript) == s {311return language.Script(alt.wantScript)312}313}314return 0315}316317// addIfNew adds a haveTag to the list of tags only if it is a unique tag.318// Tags that have the same maximized values are linked by index.319func (h *matchHeader) addIfNew(n haveTag, exact bool) {320h.original = h.original || exact321// Don't add new exact matches.322for _, v := range h.haveTags {323if equalsRest(v.tag, n.tag) {324return325}326}327// Allow duplicate maximized tags, but create a linked list to allow quickly328// comparing the equivalents and bail out.329for i, v := range h.haveTags {330if v.maxScript == n.maxScript &&331v.maxRegion == n.maxRegion &&332v.tag.VariantOrPrivateUseTags() == n.tag.VariantOrPrivateUseTags() {333for h.haveTags[i].nextMax != 0 {334i = int(h.haveTags[i].nextMax)335}336h.haveTags[i].nextMax = uint16(len(h.haveTags))337break338}339}340h.haveTags = append(h.haveTags, &n)341}342343// header returns the matchHeader for the given language. It creates one if344// it doesn't already exist.345func (m *matcher) header(l language.Language) *matchHeader {346if h := m.index[l]; h != nil {347return h348}349h := &matchHeader{}350m.index[l] = h351return h352}353354func toConf(d uint8) Confidence {355if d <= 10 {356return High357}358if d < 30 {359return Low360}361return No362}363364// newMatcher builds an index for the given supported tags and returns it as365// a matcher. It also expands the index by considering various equivalence classes366// for a given tag.367func newMatcher(supported []Tag, options []MatchOption) *matcher {368m := &matcher{369index: make(map[language.Language]*matchHeader),370preferSameScript: true,371}372for _, o := range options {373o(m)374}375if len(supported) == 0 {376m.default_ = &haveTag{}377return m378}379// Add supported languages to the index. Add exact matches first to give380// them precedence.381for i, tag := range supported {382tt := tag.tag()383pair, _ := makeHaveTag(tt, i)384m.header(tt.LangID).addIfNew(pair, true)385m.supported = append(m.supported, &pair)386}387m.default_ = m.header(supported[0].lang()).haveTags[0]388// Keep these in two different loops to support the case that two equivalent389// languages are distinguished, such as iw and he.390for i, tag := range supported {391tt := tag.tag()392pair, max := makeHaveTag(tt, i)393if max != tt.LangID {394m.header(max).addIfNew(pair, true)395}396}397398// update is used to add indexes in the map for equivalent languages.399// update will only add entries to original indexes, thus not computing any400// transitive relations.401update := func(want, have uint16, conf Confidence) {402if hh := m.index[language.Language(have)]; hh != nil {403if !hh.original {404return405}406hw := m.header(language.Language(want))407for _, ht := range hh.haveTags {408v := *ht409if conf < v.conf {410v.conf = conf411}412v.nextMax = 0 // this value needs to be recomputed413if v.altScript != 0 {414v.altScript = altScript(language.Language(want), v.maxScript)415}416hw.addIfNew(v, conf == Exact && hh.original)417}418}419}420421// Add entries for languages with mutual intelligibility as defined by CLDR's422// languageMatch data.423for _, ml := range matchLang {424update(ml.want, ml.have, toConf(ml.distance))425if !ml.oneway {426update(ml.have, ml.want, toConf(ml.distance))427}428}429430// Add entries for possible canonicalizations. This is an optimization to431// ensure that only one map lookup needs to be done at runtime per desired tag.432// First we match deprecated equivalents. If they are perfect equivalents433// (their canonicalization simply substitutes a different language code, but434// nothing else), the match confidence is Exact, otherwise it is High.435for i, lm := range language.AliasMap {436// If deprecated codes match and there is no fiddling with the script437// or region, we consider it an exact match.438conf := Exact439if language.AliasTypes[i] != language.Macro {440if !isExactEquivalent(language.Language(lm.From)) {441conf = High442}443update(lm.To, lm.From, conf)444}445update(lm.From, lm.To, conf)446}447return m448}449450// getBest gets the best matching tag in m for any of the given tags, taking into451// account the order of preference of the given tags.452func (m *matcher) getBest(want ...Tag) (got *haveTag, orig language.Tag, c Confidence) {453best := bestMatch{}454for i, ww := range want {455w := ww.tag()456var max language.Tag457// Check for exact match first.458h := m.index[w.LangID]459if w.LangID != 0 {460if h == nil {461continue462}463// Base language is defined.464max, _ = canonicalize(Legacy|Deprecated|Macro, w)465// A region that is added through canonicalization is stronger than466// a maximized region: set it in the original (e.g. mo -> ro-MD).467if w.RegionID != max.RegionID {468w.RegionID = max.RegionID469}470// TODO: should we do the same for scripts?471// See test case: en, sr, nl ; sh ; sr472max, _ = max.Maximize()473} else {474// Base language is not defined.475if h != nil {476for i := range h.haveTags {477have := h.haveTags[i]478if equalsRest(have.tag, w) {479return have, w, Exact480}481}482}483if w.ScriptID == 0 && w.RegionID == 0 {484// We skip all tags matching und for approximate matching, including485// private tags.486continue487}488max, _ = w.Maximize()489if h = m.index[max.LangID]; h == nil {490continue491}492}493pin := true494for _, t := range want[i+1:] {495if w.LangID == t.lang() {496pin = false497break498}499}500// Check for match based on maximized tag.501for i := range h.haveTags {502have := h.haveTags[i]503best.update(have, w, max.ScriptID, max.RegionID, pin)504if best.conf == Exact {505for have.nextMax != 0 {506have = h.haveTags[have.nextMax]507best.update(have, w, max.ScriptID, max.RegionID, pin)508}509return best.have, best.want, best.conf510}511}512}513if best.conf <= No {514if len(want) != 0 {515return nil, want[0].tag(), No516}517return nil, language.Tag{}, No518}519return best.have, best.want, best.conf520}521522// bestMatch accumulates the best match so far.523type bestMatch struct {524have *haveTag525want language.Tag526conf Confidence527pinnedRegion language.Region528pinLanguage bool529sameRegionGroup bool530// Cached results from applying tie-breaking rules.531origLang bool532origReg bool533paradigmReg bool534regGroupDist uint8535origScript bool536}537538// update updates the existing best match if the new pair is considered to be a539// better match. To determine if the given pair is a better match, it first540// computes the rough confidence level. If this surpasses the current match, it541// will replace it and update the tie-breaker rule cache. If there is a tie, it542// proceeds with applying a series of tie-breaker rules. If there is no543// conclusive winner after applying the tie-breaker rules, it leaves the current544// match as the preferred match.545//546// If pin is true and have and tag are a strong match, it will henceforth only547// consider matches for this language. This corresponds to the idea that most548// users have a strong preference for the first defined language. A user can549// still prefer a second language over a dialect of the preferred language by550// explicitly specifying dialects, e.g. "en, nl, en-GB". In this case pin should551// be false.552func (m *bestMatch) update(have *haveTag, tag language.Tag, maxScript language.Script, maxRegion language.Region, pin bool) {553// Bail if the maximum attainable confidence is below that of the current best match.554c := have.conf555if c < m.conf {556return557}558// Don't change the language once we already have found an exact match.559if m.pinLanguage && tag.LangID != m.want.LangID {560return561}562// Pin the region group if we are comparing tags for the same language.563if tag.LangID == m.want.LangID && m.sameRegionGroup {564_, sameGroup := regionGroupDist(m.pinnedRegion, have.maxRegion, have.maxScript, m.want.LangID)565if !sameGroup {566return567}568}569if c == Exact && have.maxScript == maxScript {570// If there is another language and then another entry of this language,571// don't pin anything, otherwise pin the language.572m.pinLanguage = pin573}574if equalsRest(have.tag, tag) {575} else if have.maxScript != maxScript {576// There is usually very little comprehension between different scripts.577// In a few cases there may still be Low comprehension. This possibility578// is pre-computed and stored in have.altScript.579if Low < m.conf || have.altScript != maxScript {580return581}582c = Low583} else if have.maxRegion != maxRegion {584if High < c {585// There is usually a small difference between languages across regions.586c = High587}588}589590// We store the results of the computations of the tie-breaker rules along591// with the best match. There is no need to do the checks once we determine592// we have a winner, but we do still need to do the tie-breaker computations.593// We use "beaten" to keep track if we still need to do the checks.594beaten := false // true if the new pair defeats the current one.595if c != m.conf {596if c < m.conf {597return598}599beaten = true600}601602// Tie-breaker rules:603// We prefer if the pre-maximized language was specified and identical.604origLang := have.tag.LangID == tag.LangID && tag.LangID != 0605if !beaten && m.origLang != origLang {606if m.origLang {607return608}609beaten = true610}611612// We prefer if the pre-maximized region was specified and identical.613origReg := have.tag.RegionID == tag.RegionID && tag.RegionID != 0614if !beaten && m.origReg != origReg {615if m.origReg {616return617}618beaten = true619}620621regGroupDist, sameGroup := regionGroupDist(have.maxRegion, maxRegion, maxScript, tag.LangID)622if !beaten && m.regGroupDist != regGroupDist {623if regGroupDist > m.regGroupDist {624return625}626beaten = true627}628629paradigmReg := isParadigmLocale(tag.LangID, have.maxRegion)630if !beaten && m.paradigmReg != paradigmReg {631if !paradigmReg {632return633}634beaten = true635}636637// Next we prefer if the pre-maximized script was specified and identical.638origScript := have.tag.ScriptID == tag.ScriptID && tag.ScriptID != 0639if !beaten && m.origScript != origScript {640if m.origScript {641return642}643beaten = true644}645646// Update m to the newly found best match.647if beaten {648m.have = have649m.want = tag650m.conf = c651m.pinnedRegion = maxRegion652m.sameRegionGroup = sameGroup653m.origLang = origLang654m.origReg = origReg655m.paradigmReg = paradigmReg656m.origScript = origScript657m.regGroupDist = regGroupDist658}659}660661func isParadigmLocale(lang language.Language, r language.Region) bool {662for _, e := range paradigmLocales {663if language.Language(e[0]) == lang && (r == language.Region(e[1]) || r == language.Region(e[2])) {664return true665}666}667return false668}669670// regionGroupDist computes the distance between two regions based on their671// CLDR grouping.672func regionGroupDist(a, b language.Region, script language.Script, lang language.Language) (dist uint8, same bool) {673const defaultDistance = 4674675aGroup := uint(regionToGroups[a]) << 1676bGroup := uint(regionToGroups[b]) << 1677for _, ri := range matchRegion {678if language.Language(ri.lang) == lang && (ri.script == 0 || language.Script(ri.script) == script) {679group := uint(1 << (ri.group &^ 0x80))680if 0x80&ri.group == 0 {681if aGroup&bGroup&group != 0 { // Both regions are in the group.682return ri.distance, ri.distance == defaultDistance683}684} else {685if (aGroup|bGroup)&group == 0 { // Both regions are not in the group.686return ri.distance, ri.distance == defaultDistance687}688}689}690}691return defaultDistance, true692}693694// equalsRest compares everything except the language.695func equalsRest(a, b language.Tag) bool {696// TODO: don't include extensions in this comparison. To do this efficiently,697// though, we should handle private tags separately.698return a.ScriptID == b.ScriptID && a.RegionID == b.RegionID && a.VariantOrPrivateUseTags() == b.VariantOrPrivateUseTags()699}700701// isExactEquivalent returns true if canonicalizing the language will not alter702// the script or region of a tag.703func isExactEquivalent(l language.Language) bool {704for _, o := range notEquivalent {705if o == l {706return false707}708}709return true710}711712var notEquivalent []language.Language713714func init() {715// Create a list of all languages for which canonicalization may alter the716// script or region.717for _, lm := range language.AliasMap {718tag := language.Tag{LangID: language.Language(lm.From)}719if tag, _ = canonicalize(All, tag); tag.ScriptID != 0 || tag.RegionID != 0 {720notEquivalent = append(notEquivalent, language.Language(lm.From))721}722}723// Maximize undefined regions of paradigm locales.724for i, v := range paradigmLocales {725t := language.Tag{LangID: language.Language(v[0])}726max, _ := t.Maximize()727if v[1] == 0 {728paradigmLocales[i][1] = uint16(max.RegionID)729}730if v[2] == 0 {731paradigmLocales[i][2] = uint16(max.RegionID)732}733}734}735736737