// minimizeAnyOf tries to find common children of given node of AnyOf pattern
// it searches for common children from left and from right
// if any common children are found – then it returns new optimized ast tree
// else it returns nil
345087
func minimizeTreeAnyOf(tree *ast.Node) *ast.Node {
	if !areOfSameKind(tree.Children, ast.KindPattern) {
		return nil
	}

	commonLeft, commonRight := commonChildren(tree.Children)
	commonLeftCount, commonRightCount := len(commonLeft), len(commonRight)
	if commonLeftCount == 0 && commonRightCount == 0 { // there are no common parts
		return nil
	}

	var result []*ast.Node
	if commonLeftCount > 0 {
		result = append(result, ast.NewNode(ast.KindPattern, nil, commonLeft...))
	}

	var anyOf []*ast.Node
	for _, child := range tree.Children {
		reuse := child.Children[commonLeftCount : len(child.Children)-commonRightCount]
		var node *ast.Node
		if len(reuse) == 0 {
			// this pattern is completely reduced by commonLeft and commonRight patterns
			// so it become nothing
			node = ast.NewNode(ast.KindNothing, nil)
		} else {
			node = ast.NewNode(ast.KindPattern, nil, reuse...)
		}
		anyOf = appendIfUnique(anyOf, node)
	}
	switch {
	case len(anyOf) == 1 && anyOf[0].Kind != ast.KindNothing:
		result = append(result, anyOf[0])
	case len(anyOf) > 1:
		result = append(result, ast.NewNode(ast.KindAnyOf, nil, anyOf...))
	}

	if commonRightCount > 0 {
		result = append(result, ast.NewNode(ast.KindPattern, nil, commonRight...))
	}

	return ast.NewNode(ast.KindPattern, nil, result...)
}
915390
func (sfn *specialFileNode) WrapChild(child libkbfs.Node) libkbfs.Node {
	child = sfn.Node.WrapChild(child)
	name := child.GetBasename()
	if !perTlfWrappedNodeNames[name] {
		if child.EntryType() == data.Dir {
			// Wrap this child too, so we can look up special files in
			// subdirectories of this node as well.
			return &specialFileNode{
				Node:   child,
				config: sfn.config,
				log:    sfn.log,
			}
		}
		return child
	}

	switch name {
	case StatusFileName:
		return &statusFileNode{
			Node:   &libkbfs.ReadonlyNode{Node: child},
			fb:     sfn.GetFolderBranch(),
			config: sfn.config,
			log:    sfn.log,
		}
	default:
		panic(fmt.Sprintf("Name %s was in map, but not in switch", name))
	}
}
593588
func (m *tree) deleteLeftmost() (*tree, *tree) {
	if m.isLeaf() {
		return m, nilMap
	}

	for i, t := range m.children {
		if t != nilMap {
			deleted, child := t.deleteLeftmost()
			newMap := m.clone()
			newMap.children[i] = child
			recalculateCount(newMap)
			return deleted, newMap
		}
	}
	panic("Tree isn't a leaf but also had no children. How does that happen?")
}
70653
func (manager *configManager) EnumerateNodeConf() (*NodesConfig, error) {
	keys, err := manager.kv.Keys(filepath.Join(baseKey, nodeKey), "/")
	if err != nil {
		return nil, fmt.Errorf("kvdb.Keys() returned error: " + err.Error())
	}

	nodesConfig := new(NodesConfig)
	*nodesConfig = make([]*NodeConfig, len(keys))
	for i, key := range keys {
		key := key
		nodeConfig, err := manager.GetNodeConf(key)
		if err != nil {
			return nil, err
		}
		(*nodesConfig)[i] = nodeConfig
	}

	return nodesConfig, nil
}
390883
func (this *ExpressionTree) collapse() {
	ncs := make([]*ExpressionTree, 0)
	for _, c := range this.Children {
		c.collapse()
		if c.Name == "" && c.Value == -1 {
			for _, gc := range c.Children {
				ncs = append(ncs, gc)
			}
		} else {
			ncs = append(ncs, c)
		}
	}
	this.Children = ncs
}
705206
func min(n *node) Item {
	if n == nil {
		return nil
	}
	for len(n.children) > 0 {
		n = n.children[0]
	}
	if len(n.items) == 0 {
		return nil
	}
	return n.items[0]
}
686490
func (tree *MutableTree) rotateLeft(node *Node) (*Node, *Node) {
	version := tree.version + 1

	// TODO: optimize balance & rotate.
	node = node.clone(version)
	orphaned := node.getRightNode(tree.ImmutableTree)
	newNode := orphaned.clone(version)

	newNodelHash, newNodelCached := newNode.leftHash, newNode.leftNode
	newNode.leftHash, newNode.leftNode = node.hash, node
	node.rightHash, node.rightNode = newNodelHash, newNodelCached

	node.calcHeightAndSize(tree.ImmutableTree)
	newNode.calcHeightAndSize(tree.ImmutableTree)

	return newNode, orphaned
}
257562
func (nc *NumberConstraint) MultipleOf(n float64) *NumberConstraint {
	nc.applyMultipleOf = true
	nc.multipleOf = n
	return nc
}
1044324
func (n *regexNode) reduceConcatenation() *regexNode {
	// Eliminate empties and concat adjacent strings/chars

	var optionsLast RegexOptions
	var optionsAt RegexOptions
	var i, j int

	if len(n.children) == 0 {
		return newRegexNode(ntEmpty, n.options)
	}

	wasLastString := false

	for i, j = 0, 0; i < len(n.children); i, j = i+1, j+1 {
		var at, prev *regexNode

		at = n.children[i]

		if j < i {
			n.children[j] = at
		}

		if at.t == ntConcatenate &&
			((at.options & RightToLeft) == (n.options & RightToLeft)) {
			for k := 0; k < len(at.children); k++ {
				at.children[k].next = n
			}

			//insert at.children at i+1 index in n.children
			n.insertChildren(i+1, at.children)

			j--
		} else if at.t == ntMulti || at.t == ntOne {
			// Cannot merge strings if L or I options differ
			optionsAt = at.options & (RightToLeft | IgnoreCase)

			if !wasLastString || optionsLast != optionsAt {
				wasLastString = true
				optionsLast = optionsAt
				continue
			}

			j--
			prev = n.children[j]

			if prev.t == ntOne {
				prev.t = ntMulti
				prev.str = []rune{prev.ch}
			}

			if (optionsAt & RightToLeft) == 0 {
				if at.t == ntOne {
					prev.str = append(prev.str, at.ch)
				} else {
					prev.str = append(prev.str, at.str...)
				}
			} else {
				if at.t == ntOne {
					// insert at the front by expanding our slice, copying the data over, and then setting the value
					prev.str = append(prev.str, 0)
					copy(prev.str[1:], prev.str)
					prev.str[0] = at.ch
				} else {
					//insert at the front...this one we'll make a new slice and copy both into it
					merge := make([]rune, len(prev.str)+len(at.str))
					copy(merge, at.str)
					copy(merge[len(at.str):], prev.str)
					prev.str = merge
				}
			}
		} else if at.t == ntEmpty {
			j--
		} else {
			wasLastString = false
		}
	}

	if j < i {
		// remove indices j through i from the children
		n.removeChildren(j, i)
	}

	return n.stripEnation(ntEmpty)
}
733441
func (v *PVector) Nth(i int) interface{} {
	node := v.arrayFor(i)
	return node[i&indexMask]
}
664782
func (n *node) findFirst(f func(fn *node) (bool, error)) (*node, error) {
	hasFound, err := f(n)
	if err != nil {
		return nil, errors.Annotate(err, ErrNodeFindFirst, errorMessages)
	}
	if hasFound {
		return n, nil
	}
	for _, child := range n.children {
		found, err := child.findFirst(f)
		if err != nil && !IsNodeNotFoundError(err) {
			return nil, errors.Annotate(err, ErrNodeFindFirst, errorMessages)
		}
		if found != nil {
			return found, nil
		}
	}
	return nil, errors.New(ErrNodeNotFound, errorMessages)
}
75575
func (n *regexNode) reduceRep() *regexNode {

	u := n
	t := n.t
	min := n.m
	max := n.n

	for {
		if len(u.children) == 0 {
			break
		}

		child := u.children[0]

		// multiply reps of the same type only
		if child.t != t {
			childType := child.t

			if !(childType >= ntOneloop && childType <= ntSetloop && t == ntLoop ||
				childType >= ntOnelazy && childType <= ntSetlazy && t == ntLazyloop) {
				break
			}
		}

		// child can be too lumpy to blur, e.g., (a {100,105}) {3} or (a {2,})?
		// [but things like (a {2,})+ are not too lumpy...]
		if u.m == 0 && child.m > 1 || child.n < child.m*2 {
			break
		}

		u = child
		if u.m > 0 {
			if (math.MaxInt32-1)/u.m < min {
				u.m = math.MaxInt32
			} else {
				u.m = u.m * min
			}
		}
		if u.n > 0 {
			if (math.MaxInt32-1)/u.n < max {
				u.n = math.MaxInt32
			} else {
				u.n = u.n * max
			}
		}
	}

	if math.MaxInt32 == min {
		return newRegexNode(ntNothing, n.options)
	}
	return u

}
66167
func (f FunctionNameList) Less(i, j int) bool {
	if f[i].Str == "" && f[j].Str != "" {
		return true
	}
	if f[i].Str != "" && f[j].Str == "" {
		return false
	}
	if f[i].Str != "" && f[j].Str != "" {
		if f[i].Str > f[j].Str {
			return true
		} else if f[i].Str < f[j].Str {
			return false
		}
	}
	return f[i].Name < f[j].Name
}
889404
func (n *node) findAll(f func(fn *node) (bool, error)) ([]*node, error) {
	var allFound []*node
	hasFound, err := f(n)
	if err != nil {
		return nil, errors.Annotate(err, ErrNodeFindAll, errorMessages)
	}
	if hasFound {
		allFound = append(allFound, n)
	}
	for _, child := range n.children {
		found, err := child.findAll(f)
		if err != nil {
			return nil, errors.Annotate(err, ErrNodeFindAll, errorMessages)
		}
		if found != nil {
			allFound = append(allFound, found...)
		}
	}
	return allFound, nil
}
961036
func MatchAnyOf(matchers ...EventMatcher) EventMatcher {
	return func(e Event) bool {
		for _, m := range matchers {
			if m(e) {
				return true
			}
		}
		return false
	}
}
954629
func (t *Tree) nextNonSpace() (token item) {
	for {
		token = t.next()
		if token.typ != itemIdent && token.typ != itemEndL && token.typ != itemEmptyLine {
			break
		}
	}
	// fmt.Println("\t\tnextNonSpace", token.val)
	return token
}
572020
func (t *Tree) Seek(k generic.T) (e *Enumerator, ok bool) {
	q := t.r
	if q == nil {
		e = &Enumerator{nil, false, 0, k, nil, t, t.ver}
		return
	}

	for {
		var i int
		if i, ok = t.find(q, k); ok {
			switch x := q.(type) {
			case *x:
				e = &Enumerator{nil, ok, 0, k, x.x[i].sep, t, t.ver}
				return
			case *d:
				e = &Enumerator{nil, ok, i, k, x, t, t.ver}
				return
			}
		}
		switch x := q.(type) {
		case *x:
			q = x.x[i].ch
		case *d:
			e = &Enumerator{nil, ok, i, k, x, t, t.ver}
			return
		}
	}
}