Source File
language.go
Belonging Package
golang.org/x/text/language
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate go run gen.go -output tables.go
package language
// TODO: Remove above NOTE after:
// - verifying that tables are dropped correctly (most notably matcher tables).
import (
)
// Tag represents a BCP 47 language tag. It is used to specify an instance of a
// specific language or locale. All language tag values are guaranteed to be
// well-formed.
type Tag compact.Tag
func makeTag( language.Tag) ( Tag) {
return Tag(compact.Make())
}
func ( *Tag) () language.Tag {
return (*compact.Tag)().Tag()
}
func ( *Tag) () bool {
return (*compact.Tag)().IsCompact()
}
// TODO: improve performance.
func ( *Tag) () language.Language { return .tag().LangID }
func ( *Tag) () language.Region { return .tag().RegionID }
func ( *Tag) () language.Script { return .tag().ScriptID }
// Make is a convenience wrapper for Parse that omits the error.
// In case of an error, a sensible default is returned.
func ( string) Tag {
return Default.Make()
}
// Make is a convenience wrapper for c.Parse that omits the error.
// In case of an error, a sensible default is returned.
func ( CanonType) ( string) Tag {
, := .Parse()
return
}
// Raw returns the raw base language, script and region, without making an
// attempt to infer their values.
func ( Tag) () ( Base, Script, Region) {
:= .tag()
return Base{.LangID}, Script{.ScriptID}, Region{.RegionID}
}
// IsRoot returns true if t is equal to language "und".
func ( Tag) () bool {
return compact.Tag().IsRoot()
}
// CanonType can be used to enable or disable various types of canonicalization.
type CanonType int
const (
// Replace deprecated base languages with their preferred replacements.
DeprecatedBase CanonType = 1 << iota
// Replace deprecated scripts with their preferred replacements.
DeprecatedScript
// Replace deprecated regions with their preferred replacements.
DeprecatedRegion
// Remove redundant scripts.
SuppressScript
// Normalize legacy encodings. This includes legacy languages defined in
// CLDR as well as bibliographic codes defined in ISO-639.
Legacy
// Map the dominant language of a macro language group to the macro language
// subtag. For example cmn -> zh.
Macro
// The CLDR flag should be used if full compatibility with CLDR is required.
// There are a few cases where language.Tag may differ from CLDR. To follow all
// of CLDR's suggestions, use All|CLDR.
CLDR
// Raw can be used to Compose or Parse without Canonicalization.
Raw CanonType = 0
// Replace all deprecated tags with their preferred replacements.
Deprecated = DeprecatedBase | DeprecatedScript | DeprecatedRegion
// All canonicalizations recommended by BCP 47.
BCP47 = Deprecated | SuppressScript
// All canonicalizations.
All = BCP47 | Legacy | Macro
// Default is the canonicalization used by Parse, Make and Compose. To
// preserve as much information as possible, canonicalizations that remove
// potentially valuable information are not included. The Matcher is
// designed to recognize similar tags that would be the same if
// they were canonicalized using All.
Default = Deprecated | Legacy
canonLang = DeprecatedBase | Legacy | Macro
// TODO: LikelyScript, LikelyRegion: suppress similar to ICU.
)
// canonicalize returns the canonicalized equivalent of the tag and
// whether there was any change.
func canonicalize( CanonType, language.Tag) (language.Tag, bool) {
if == Raw {
return , false
}
:= false
if &SuppressScript != 0 {
if .LangID.SuppressScript() == .ScriptID {
.ScriptID = 0
= true
}
}
if &canonLang != 0 {
for {
if , := .LangID.Canonicalize(); != .LangID {
switch {
case language.Legacy:
if &Legacy != 0 {
if .LangID == _sh && .ScriptID == 0 {
.ScriptID = _Latn
}
.LangID =
= true
}
case language.Macro:
if &Macro != 0 {
// We deviate here from CLDR. The mapping "nb" -> "no"
// qualifies as a typical Macro language mapping. However,
// for legacy reasons, CLDR maps "no", the macro language
// code for Norwegian, to the dominant variant "nb". This
// change is currently under consideration for CLDR as well.
// See https://unicode.org/cldr/trac/ticket/2698 and also
// https://unicode.org/cldr/trac/ticket/1790 for some of the
// practical implications. TODO: this check could be removed
// if CLDR adopts this change.
if &CLDR == 0 || .LangID != _nb {
= true
.LangID =
}
}
case language.Deprecated:
if &DeprecatedBase != 0 {
if .LangID == _mo && .RegionID == 0 {
.RegionID = _MD
}
.LangID =
= true
// Other canonicalization types may still apply.
continue
}
}
} else if &Legacy != 0 && .LangID == _no && &CLDR != 0 {
.LangID = _nb
= true
}
break
}
}
if &DeprecatedScript != 0 {
if .ScriptID == _Qaai {
= true
.ScriptID = _Zinh
}
}
if &DeprecatedRegion != 0 {
if := .RegionID.Canonicalize(); != .RegionID {
= true
.RegionID =
}
}
return ,
}
// Canonicalize returns the canonicalized equivalent of the tag.
func ( CanonType) ( Tag) (Tag, error) {
// First try fast path.
if .isCompact() {
if , := canonicalize(, compact.Tag().Tag()); ! {
return , nil
}
}
// It is unlikely that one will canonicalize a tag after matching. So do
// a slow but simple approach here.
if , := canonicalize(, .tag()); {
.RemakeString()
return makeTag(), nil
}
return , nil
}
// Confidence indicates the level of certainty for a given return value.
// For example, Serbian may be written in Cyrillic or Latin script.
// The confidence level indicates whether a value was explicitly specified,
// whether it is typically the only possible value, or whether there is
// an ambiguity.
type Confidence int
const (
No Confidence = iota // full confidence that there was no match
Low // most likely value picked out of a set of alternatives
High // value is generally assumed to be the correct match
Exact // exact match or explicitly specified value
)
var confName = []string{"No", "Low", "High", "Exact"}
func ( Confidence) () string {
return confName[]
}
// String returns the canonical string representation of the language tag.
func ( Tag) () string {
return .tag().String()
}
// MarshalText implements encoding.TextMarshaler.
func ( Tag) () ( []byte, error) {
return .tag().MarshalText()
}
// UnmarshalText implements encoding.TextUnmarshaler.
func ( *Tag) ( []byte) error {
var language.Tag
:= .UnmarshalText()
* = makeTag()
return
}
// Base returns the base language of the language tag. If the base language is
// unspecified, an attempt will be made to infer it from the context.
// It uses a variant of CLDR's Add Likely Subtags algorithm. This is subject to change.
func ( Tag) () (Base, Confidence) {
if := .lang(); != 0 {
return Base{}, Exact
}
:= .tag()
:= High
if .ScriptID == 0 && !.RegionID.IsCountry() {
= Low
}
if , := .Maximize(); == nil && .LangID != 0 {
return Base{.LangID},
}
return Base{0}, No
}
// Script infers the script for the language tag. If it was not explicitly given, it will infer
// a most likely candidate.
// If more than one script is commonly used for a language, the most likely one
// is returned with a low confidence indication. For example, it returns (Cyrl, Low)
// for Serbian.
// If a script cannot be inferred (Zzzz, No) is returned. We do not use Zyyy (undetermined)
// as one would suspect from the IANA registry for BCP 47. In a Unicode context Zyyy marks
// common characters (like 1, 2, 3, '.', etc.) and is therefore more like multiple scripts.
// See https://www.unicode.org/reports/tr24/#Values for more details. Zzzz is also used for
// unknown value in CLDR. (Zzzz, Exact) is returned if Zzzz was explicitly specified.
// Note that an inferred script is never guaranteed to be the correct one. Latin is
// almost exclusively used for Afrikaans, but Arabic has been used for some texts
// in the past. Also, the script that is commonly used may change over time.
// It uses a variant of CLDR's Add Likely Subtags algorithm. This is subject to change.
func ( Tag) () (Script, Confidence) {
if := .script(); != 0 {
return Script{}, Exact
}
:= .tag()
, := language.Script(_Zzzz), No
if := .LangID.SuppressScript(); != 0 {
// Note: it is not always the case that a language with a suppress
// script value is only written in one script (e.g. kk, ms, pa).
if .RegionID == 0 {
return Script{}, High
}
, = , High
}
if , := .Maximize(); == nil {
if .ScriptID != {
, = .ScriptID, Low
}
} else {
, _ = canonicalize(Deprecated|Macro, )
if , := .Maximize(); == nil && .ScriptID != {
, = .ScriptID, Low
}
}
return Script{},
}
// Region returns the region for the language tag. If it was not explicitly given, it will
// infer a most likely candidate from the context.
// It uses a variant of CLDR's Add Likely Subtags algorithm. This is subject to change.
func ( Tag) () (Region, Confidence) {
if := .region(); != 0 {
return Region{}, Exact
}
:= .tag()
if , := .Maximize(); == nil {
return Region{.RegionID}, Low // TODO: differentiate between high and low.
}
, _ = canonicalize(Deprecated|Macro, )
if , := .Maximize(); == nil {
return Region{.RegionID}, Low
}
return Region{_ZZ}, No // TODO: return world instead of undetermined?
}
// Variants returns the variants specified explicitly for this language tag.
// or nil if no variant was specified.
func ( Tag) () []Variant {
if !compact.Tag().MayHaveVariants() {
return nil
}
:= []Variant{}
, := "", .tag().Variants()
for != "" {
, = nextToken()
= append(, Variant{})
}
return
}
// Parent returns the CLDR parent of t. In CLDR, missing fields in data for a
// specific language are substituted with fields from the parent language.
// The parent for a language may change for newer versions of CLDR.
//
// Parent returns a tag for a less specific language that is mutually
// intelligible or Und if there is no such language. This may not be the same as
// simply stripping the last BCP 47 subtag. For instance, the parent of "zh-TW"
// is "zh-Hant", and the parent of "zh-Hant" is "und".
func ( Tag) () Tag {
return Tag(compact.Tag().Parent())
}
// nextToken returns token t and the rest of the string.
func nextToken( string) (, string) {
:= strings.Index([1:], "-")
if == -1 {
return [1:], ""
}
++
return [1:], [:]
}
// Extension is a single BCP 47 extension.
type Extension struct {
s string
}
// String returns the string representation of the extension, including the
// type tag.
func ( Extension) () string {
return .s
}
// ParseExtension parses s as an extension and returns it on success.
func ( string) ( Extension, error) {
, := language.ParseExtension()
return Extension{},
}
// Type returns the one-byte extension type of e. It returns 0 for the zero
// exception.
func ( Extension) () byte {
if .s == "" {
return 0
}
return .s[0]
}
// Tokens returns the list of tokens of e.
func ( Extension) () []string {
return strings.Split(.s, "-")
}
// Extension returns the extension of type x for tag t. It will return
// false for ok if t does not have the requested extension. The returned
// extension will be invalid in this case.
func ( Tag) ( byte) ( Extension, bool) {
if !compact.Tag().MayHaveExtensions() {
return Extension{}, false
}
, := .tag().Extension()
return Extension{},
}
// Extensions returns all extensions of t.
func ( Tag) () []Extension {
if !compact.Tag().MayHaveExtensions() {
return nil
}
:= []Extension{}
for , := range .tag().Extensions() {
= append(, Extension{})
}
return
}
// TypeForKey returns the type associated with the given key, where key and type
// are of the allowed values defined for the Unicode locale extension ('u') in
// https://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers.
// TypeForKey will traverse the inheritance chain to get the correct value.
//
// If there are multiple types associated with a key, only the first will be
// returned. If there is no type associated with a key, it returns the empty
// string.
func ( Tag) ( string) string {
if !compact.Tag().MayHaveExtensions() {
if != "rg" && != "va" {
return ""
}
}
return .tag().TypeForKey()
}
// SetTypeForKey returns a new Tag with the key set to type, where key and type
// are of the allowed values defined for the Unicode locale extension ('u') in
// https://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers.
// An empty value removes an existing pair with the same key.
func ( Tag) (, string) (Tag, error) {
, := .tag().SetTypeForKey(, )
return makeTag(),
}
// NumCompactTags is the number of compact tags. The maximum tag is
// NumCompactTags-1.
const NumCompactTags = compact.NumCompactTags
// CompactIndex returns an index, where 0 <= index < NumCompactTags, for tags
// for which data exists in the text repository.The index will change over time
// and should not be stored in persistent storage. If t does not match a compact
// index, exact will be false and the compact index will be returned for the
// first match after repeatedly taking the Parent of t.
func ( Tag) ( int, bool) {
, := compact.LanguageID(compact.Tag())
return int(),
}
var root = language.Tag{}
// Base is an ISO 639 language code, used for encoding the base language
// of a language tag.
type Base struct {
langID language.Language
}
// ParseBase parses a 2- or 3-letter ISO 639 code.
// It returns a ValueError if s is a well-formed but unknown language identifier
// or another error if another error occurred.
func ( string) (Base, error) {
, := language.ParseBase()
return Base{},
}
// String returns the BCP 47 representation of the base language.
func ( Base) () string {
return .langID.String()
}
// ISO3 returns the ISO 639-3 language code.
func ( Base) () string {
return .langID.ISO3()
}
// IsPrivateUse reports whether this language code is reserved for private use.
func ( Base) () bool {
return .langID.IsPrivateUse()
}
// Script is a 4-letter ISO 15924 code for representing scripts.
// It is idiomatically represented in title case.
type Script struct {
scriptID language.Script
}
// ParseScript parses a 4-letter ISO 15924 code.
// It returns a ValueError if s is a well-formed but unknown script identifier
// or another error if another error occurred.
func ( string) (Script, error) {
, := language.ParseScript()
return Script{},
}
// String returns the script code in title case.
// It returns "Zzzz" for an unspecified script.
func ( Script) () string {
return .scriptID.String()
}
// IsPrivateUse reports whether this script code is reserved for private use.
func ( Script) () bool {
return .scriptID.IsPrivateUse()
}
// Region is an ISO 3166-1 or UN M.49 code for representing countries and regions.
type Region struct {
regionID language.Region
}
// EncodeM49 returns the Region for the given UN M.49 code.
// It returns an error if r is not a valid code.
func ( int) (Region, error) {
, := language.EncodeM49()
return Region{},
}
// ParseRegion parses a 2- or 3-letter ISO 3166-1 or a UN M.49 code.
// It returns a ValueError if s is a well-formed but unknown region identifier
// or another error if another error occurred.
func ( string) (Region, error) {
, := language.ParseRegion()
return Region{},
}
// String returns the BCP 47 representation for the region.
// It returns "ZZ" for an unspecified region.
func ( Region) () string {
return .regionID.String()
}
// ISO3 returns the 3-letter ISO code of r.
// Note that not all regions have a 3-letter ISO code.
// In such cases this method returns "ZZZ".
func ( Region) () string {
return .regionID.ISO3()
}
// M49 returns the UN M.49 encoding of r, or 0 if this encoding
// is not defined for r.
func ( Region) () int {
return .regionID.M49()
}
// IsPrivateUse reports whether r has the ISO 3166 User-assigned status. This
// may include private-use tags that are assigned by CLDR and used in this
// implementation. So IsPrivateUse and IsCountry can be simultaneously true.
func ( Region) () bool {
return .regionID.IsPrivateUse()
}
// IsCountry returns whether this region is a country or autonomous area. This
// includes non-standard definitions from CLDR.
func ( Region) () bool {
return .regionID.IsCountry()
}
// IsGroup returns whether this region defines a collection of regions. This
// includes non-standard definitions from CLDR.
func ( Region) () bool {
return .regionID.IsGroup()
}
// Contains returns whether Region c is contained by Region r. It returns true
// if c == r.
func ( Region) ( Region) bool {
return .regionID.Contains(.regionID)
}
// TLD returns the country code top-level domain (ccTLD). UK is returned for GB.
// In all other cases it returns either the region itself or an error.
//
// This method may return an error for a region for which there exists a
// canonical form with a ccTLD. To get that ccTLD canonicalize r first. The
// region will already be canonicalized it was obtained from a Tag that was
// obtained using any of the default methods.
func ( Region) () (Region, error) {
, := .regionID.TLD()
return Region{},
}
// Canonicalize returns the region or a possible replacement if the region is
// deprecated. It will not return a replacement for deprecated regions that
// are split into multiple regions.
func ( Region) () Region {
return Region{.regionID.Canonicalize()}
}
// Variant represents a registered variant of a language as defined by BCP 47.
type Variant struct {
variant string
}
// ParseVariant parses and returns a Variant. An error is returned if s is not
// a valid variant.
func ( string) (Variant, error) {
, := language.ParseVariant()
return Variant{.String()},
}
// String returns the string representation of the variant.
func ( Variant) () string {
return .variant
}
![]() |
The pages are generated with Golds v0.6.7. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds. |