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.
package yaml

import (
	
	
	
	
	
	
	
	
	
)
indirect walks down v allocating pointers as needed, until it gets to a non-pointer. if it encounters an Unmarshaler, indirect stops and returns that. if decodingNull is true, indirect stops at the last pointer so it can be set to nil.
If v is a named type and is addressable, start with its address, so that if the type has pointer methods, we find them.
	if .Kind() != reflect.Ptr && .Type().Name() != "" && .CanAddr() {
		 = .Addr()
	}
Load value from interface, but only if the result will be usefully addressable.
		if .Kind() == reflect.Interface && !.IsNil() {
			 := .Elem()
			if .Kind() == reflect.Ptr && !.IsNil() && (! || .Elem().Kind() == reflect.Ptr) {
				 = 
				continue
			}
		}

		if .Kind() != reflect.Ptr {
			break
		}

		if .Elem().Kind() != reflect.Ptr &&  && .CanSet() {
			break
		}
		if .IsNil() {
			if .CanSet() {
				.Set(reflect.New(.Type().Elem()))
			} else {
				 = reflect.New(.Type().Elem())
			}
		}
		if .Type().NumMethod() > 0 {
			if ,  := .Interface().(json.Unmarshaler);  {
				return , nil, reflect.Value{}
			}
			if ,  := .Interface().(encoding.TextUnmarshaler);  {
				return nil, , reflect.Value{}
			}
		}
		 = .Elem()
	}
	return nil, nil, 
}
A field represents a single field found in a struct.
type field struct {
	name      string
	nameBytes []byte                 // []byte(name)
	equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent

	tag       bool
	index     []int
	typ       reflect.Type
	omitEmpty bool
	quoted    bool
}

func ( field) field {
	.nameBytes = []byte(.name)
	.equalFold = foldFunc(.nameBytes)
	return 
}
byName sorts field by name, breaking ties with depth, then breaking ties with "name came from json tag", then breaking ties with index sequence.
type byName []field

func ( byName) () int { return len() }

func ( byName) (,  int) { [], [] = [], [] }

func ( byName) (,  int) bool {
	if [].name != [].name {
		return [].name < [].name
	}
	if len([].index) != len([].index) {
		return len([].index) < len([].index)
	}
	if [].tag != [].tag {
		return [].tag
	}
	return byIndex().Less(, )
}
byIndex sorts field by index sequence.
type byIndex []field

func ( byIndex) () int { return len() }

func ( byIndex) (,  int) { [], [] = [], [] }

func ( byIndex) (,  int) bool {
	for ,  := range [].index {
		if  >= len([].index) {
			return false
		}
		if  != [].index[] {
			return  < [].index[]
		}
	}
	return len([].index) < len([].index)
}
typeFields returns a list of fields that JSON should recognize for the given type. The algorithm is breadth-first search over the set of structs to include - the top struct and then any reachable anonymous structs.
Anonymous fields to explore at the current level and the next.
	 := []field{}
	 := []field{{typ: }}
Count of queued names for current level and the next.
	 := map[reflect.Type]int{}
	 := map[reflect.Type]int{}
Types already visited at an earlier level.
	 := map[reflect.Type]bool{}
Fields found.
	var  []field

	for len() > 0 {
		,  = , [:0]
		,  = , map[reflect.Type]int{}

		for ,  := range  {
			if [.typ] {
				continue
			}
			[.typ] = true
Scan f.typ for fields to include.
			for  := 0;  < .typ.NumField(); ++ {
				 := .typ.Field()
				if .PkgPath != "" { // unexported
					continue
				}
				 := .Tag.Get("json")
				if  == "-" {
					continue
				}
				,  := parseTag()
				if !isValidTag() {
					 = ""
				}
				 := make([]int, len(.index)+1)
				copy(, .index)
				[len(.index)] = 

				 := .Type
Follow pointer.
					 = .Elem()
				}
Record found field and index sequence.
				if  != "" || !.Anonymous || .Kind() != reflect.Struct {
					 :=  != ""
					if  == "" {
						 = .Name
					}
					 = append(, fillField(field{
						name:      ,
						tag:       ,
						index:     ,
						typ:       ,
						omitEmpty: .Contains("omitempty"),
						quoted:    .Contains("string"),
					}))
If there were multiple instances, add a second, so that the annihilation code will see a duplicate. It only cares about the distinction between 1 or 2, so don't bother generating any more copies.
						 = append(, [len()-1])
					}
					continue
				}
Record new anonymous struct to explore in next round.
				[]++
				if [] == 1 {
					 = append(, fillField(field{name: .Name(), index: , typ: }))
				}
			}
		}
	}

	sort.Sort(byName())
Delete all fields that are hidden by the Go rules for embedded fields, except that fields with JSON tags are promoted.
The fields are sorted in primary order of name, secondary order of field index length. Loop over names; for each name, delete hidden fields by choosing the one dominant field that survives.
	 := [:0]
One iteration per name. Find the sequence of fields with the name of this first field.
		 := []
		 := .name
		for  = 1; + < len(); ++ {
			 := [+]
			if .name !=  {
				break
			}
		}
		if  == 1 { // Only one field with this name
			 = append(, )
			continue
		}
		,  := dominantField([ : +])
		if  {
			 = append(, )
		}
	}

	 = 
	sort.Sort(byIndex())

	return 
}
dominantField looks through the fields, all of which are known to have the same name, to find the single field that dominates the others using Go's embedding rules, modified by the presence of JSON tags. If there are multiple top-level fields, the boolean will be false: This condition is an error in Go and we skip all the fields.
The fields are sorted in increasing index-length order. The winner must therefore be one with the shortest index length. Drop all longer entries, which is easy: just truncate the slice.
	 := len([0].index)
	 := -1 // Index of first tagged field.
	for ,  := range  {
		if len(.index) >  {
			 = [:]
			break
		}
		if .tag {
Multiple tagged fields at the same level: conflict. Return no field.
				return field{}, false
			}
			 = 
		}
	}
	if  >= 0 {
		return [], true
All remaining fields have the same length. If there's more than one, we have a conflict (two fields named "X" at the same level) and we return no field.
	if len() > 1 {
		return field{}, false
	}
	return [0], true
}

var fieldCache struct {
	sync.RWMutex
	m map[reflect.Type][]field
}
cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
func ( reflect.Type) []field {
	fieldCache.RLock()
	 := fieldCache.m[]
	fieldCache.RUnlock()
	if  != nil {
		return 
	}
Compute fields without lock. Might duplicate effort but won't hold other computations back.
	 = typeFields()
	if  == nil {
		 = []field{}
	}

	fieldCache.Lock()
	if fieldCache.m == nil {
		fieldCache.m = map[reflect.Type][]field{}
	}
	fieldCache.m[] = 
	fieldCache.Unlock()
	return 
}

func ( string) bool {
	if  == "" {
		return false
	}
	for ,  := range  {
		switch {
Backslash and quote chars are reserved, but otherwise any punctuation chars are allowed in a tag name.
		default:
			if !unicode.IsLetter() && !unicode.IsDigit() {
				return false
			}
		}
	}
	return true
}

const (
	caseMask     = ^byte(0x20) // Mask to ignore case in ASCII.
	kelvin       = '\u212a'
	smallLongEss = '\u017f'
)
foldFunc returns one of four different case folding equivalence functions, from most general (and slow) to fastest: 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S') 3) asciiEqualFold, no special, but includes non-letters (including _) 4) simpleLetterEqualFold, no specials, no non-letters. The letters S and K are special because they map to 3 runes, not just 2: * S maps to s and to U+017F 'ſ' Latin small letter long s * k maps to K and to U+212A 'K' Kelvin sign See http://play.golang.org/p/tTxjOc0OGo The returned function is specialized for matching against s and should only be given s. It's not curried for performance reasons.
func ( []byte) func(,  []byte) bool {
	 := false
	 := false // special letter
	for ,  := range  {
		if  >= utf8.RuneSelf {
			return bytes.EqualFold
		}
		 :=  & caseMask
		if  < 'A' ||  > 'Z' {
			 = true
See above for why these letters are special.
			 = true
		}
	}
	if  {
		return equalFoldRight
	}
	if  {
		return asciiEqualFold
	}
	return simpleLetterEqualFold
}
equalFoldRight is a specialization of bytes.EqualFold when s is known to be all ASCII (including punctuation), but contains an 's', 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t. See comments on foldFunc.
func (,  []byte) bool {
	for ,  := range  {
		if len() == 0 {
			return false
		}
		 := [0]
		if  < utf8.RuneSelf {
			if  !=  {
				 :=  & caseMask
				if 'A' <=  &&  <= 'Z' {
					if  != &caseMask {
						return false
					}
				} else {
					return false
				}
			}
			 = [1:]
			continue
sb is ASCII and t is not. t must be either kelvin sign or long s; sb must be s, S, k, or K.
		,  := utf8.DecodeRune()
		switch  {
		case 's', 'S':
			if  != smallLongEss {
				return false
			}
		case 'k', 'K':
			if  != kelvin {
				return false
			}
		default:
			return false
		}
		 = [:]

	}
	if len() > 0 {
		return false
	}
	return true
}
asciiEqualFold is a specialization of bytes.EqualFold for use when s is all ASCII (but may contain non-letters) and contains no special-folding letters. See comments on foldFunc.
func (,  []byte) bool {
	if len() != len() {
		return false
	}
	for ,  := range  {
		 := []
		if  ==  {
			continue
		}
		if ('a' <=  &&  <= 'z') || ('A' <=  &&  <= 'Z') {
			if &caseMask != &caseMask {
				return false
			}
		} else {
			return false
		}
	}
	return true
}
simpleLetterEqualFold is a specialization of bytes.EqualFold for use when s is all ASCII letters (no underscores, etc) and also doesn't contain 'k', 'K', 's', or 'S'. See comments on foldFunc.
func (,  []byte) bool {
	if len() != len() {
		return false
	}
	for ,  := range  {
		if &caseMask != []&caseMask {
			return false
		}
	}
	return true
}
tagOptions is the string following a comma in a struct field's "json" tag, or the empty string. It does not include the leading comma.
parseTag splits a struct field's json tag into its name and comma-separated options.
func ( string) (string, tagOptions) {
	if  := strings.Index(, ",");  != -1 {
		return [:], tagOptions([+1:])
	}
	return , tagOptions("")
}
Contains reports whether a comma-separated list of options contains a particular substr flag. substr must be surrounded by a string boundary or commas.
func ( tagOptions) ( string) bool {
	if len() == 0 {
		return false
	}
	 := string()
	for  != "" {
		var  string
		 := strings.Index(, ",")
		if  >= 0 {
			,  = [:], [+1:]
		}
		if  ==  {
			return true
		}
		 = 
	}
	return false