// parseExpr parses a single expression, returning the result, and the
// number of bytes consumed.
172913
func parseExpr(in []byte) (Q, int, error) {
	b := in[:]
	var expr Q
	for len(b) > 0 && isSpace(b[0]) {
		b = b[1:]
	}

	tok, err := nextToken(b)
	if err != nil {
		return nil, 0, err
	}
	if tok == nil {
		return nil, 0, nil
	}
	b = b[len(tok.Input):]

	text := string(tok.Text)
	switch tok.Type {
	case tokCase:
		switch text {
		case "yes":
		case "no":
		case "auto":
		default:
			return nil, 0, fmt.Errorf("query: unknown case argument %q, want {yes,no,auto}", text)
		}
		expr = &caseQ{text}
	case tokRepo:
		expr = &Repo{Pattern: text}
	case tokBranch:
		expr = &Branch{Pattern: text}
	case tokText, tokRegex:
		q, err := regexpQuery(text, false, false)
		if err != nil {
			return nil, 0, err
		}
		expr = q
	case tokFile:
		q, err := regexpQuery(text, false, true)
		if err != nil {
			return nil, 0, err
		}
		expr = q

	case tokContent:
		q, err := regexpQuery(text, true, false)
		if err != nil {
			return nil, 0, err
		}
		expr = q
	case tokLang:
		expr = &Language{Language: text}

	case tokSym:
		if text == "" {
			return nil, 0, fmt.Errorf("the sym: atom must have an argument")
		}
		expr = &Symbol{&Substring{Pattern: text}}

	case tokParenClose:
		// Caller must consume paren.
		expr = nil

	case tokParenOpen:
		qs, n, err := parseExprList(b)
		b = b[n:]
		if err != nil {
			return nil, 0, err
		}

		pTok, err := nextToken(b)
		if err != nil {
			return nil, 0, err
		}
		if pTok == nil || pTok.Type != tokParenClose {
			return nil, 0, fmt.Errorf("query: missing close paren, got token %v", pTok)
		}

		b = b[len(pTok.Input):]
		expr, err = parseOperators(qs)
		if err != nil {
			return nil, 0, err
		}
	case tokNegate:
		subQ, n, err := parseExpr(b)
		if err != nil {
			return nil, 0, err
		}
		b = b[n:]
		expr = &Not{subQ}

	}

	return expr, len(in) - len(b), nil
}
361197
func (p *parser) parseExpr(expr interface{}) (interface{}, bool) {

	p.ExprCnt++
	if p.ExprCnt > p.maxExprCnt {
		panic(errMaxExprCnt)
	}

	var val interface{}
	var ok bool
	switch expr := expr.(type) {
	case *actionExpr:
		val, ok = p.parseActionExpr(expr)
	case *andCodeExpr:
		val, ok = p.parseAndCodeExpr(expr)
	case *andExpr:
		val, ok = p.parseAndExpr(expr)
	case *anyMatcher:
		val, ok = p.parseAnyMatcher(expr)
	case *charClassMatcher:
		val, ok = p.parseCharClassMatcher(expr)
	case *choiceExpr:
		val, ok = p.parseChoiceExpr(expr)
	case *labeledExpr:
		val, ok = p.parseLabeledExpr(expr)
	case *litMatcher:
		val, ok = p.parseLitMatcher(expr)
	case *notCodeExpr:
		val, ok = p.parseNotCodeExpr(expr)
	case *notExpr:
		val, ok = p.parseNotExpr(expr)
	case *oneOrMoreExpr:
		val, ok = p.parseOneOrMoreExpr(expr)
	case *recoveryExpr:
		val, ok = p.parseRecoveryExpr(expr)
	case *ruleRefExpr:
		val, ok = p.parseRuleRefExpr(expr)
	case *seqExpr:
		val, ok = p.parseSeqExpr(expr)
	case *throwExpr:
		val, ok = p.parseThrowExpr(expr)
	case *zeroOrMoreExpr:
		val, ok = p.parseZeroOrMoreExpr(expr)
	case *zeroOrOneExpr:
		val, ok = p.parseZeroOrOneExpr(expr)
	default:
		panic(fmt.Sprintf("unknown expression type %T", expr))
	}
	return val, ok
}
459477
func MustParseExpr(input string) *Expr {
	parsed, err := ParseExpr(input)
	if err != nil {
		panic(err)
	}
	return parsed
}
86207
func MakeRegexpArray(str string) ([]*regexp.Regexp, error) {
	parts := strings.Split(str, ",")
	result := make([]*regexp.Regexp, len(parts))
	for ix := range parts {
		re, err := regexp.Compile(parts[ix])
		if err != nil {
			return nil, err
		}
		result[ix] = re
	}
	return result, nil
}
937244
func parseExpression(expr string) (node ast.ExprNode, err error) {
	expr = fmt.Sprintf("select %s", expr)
	charset, collation := charset.GetDefaultCharsetAndCollate()
	stmts, _, err := parser.New().Parse(expr, charset, collation)
	if err == nil {
		node = stmts[0].(*ast.SelectStmt).Fields.Fields[0].Expr
	}
	return node, util.SyntaxError(err)
}
506274
func (t *Tree) parseInnerExpr() (Expr, error) {
	switch tok := t.nextNonSpace(); tok.tokenType {
	case tokenEOF:
		return nil, newUnexpectedEOFError(tok)

	case tokenOperator:
		op, ok := unaryOperators[tok.value]
		if !ok {
			return nil, newUnexpectedTokenError(tok)
		}
		expr, err := t.parseExpr()
		if err != nil {
			return nil, err
		}
		return NewUnaryExpr(op.Operator(), expr, tok.Pos), nil

	case tokenParensOpen:
		inner, err := t.parseExpr()
		if err != nil {
			return nil, err
		}
		_, err = t.expect(tokenParensClose)
		if err != nil {
			return nil, err
		}
		return NewGroupExpr(inner, tok.Pos), nil

	case tokenHashOpen:
		els := []*KeyValueExpr{}
		for {
			nxt := t.peek()
			if nxt.tokenType == tokenHashClose {
				t.next()
				break
			}
			keyExpr, err := t.parseExpr()
			if err != nil {
				return nil, err
			}
			_, err = t.expectValue(tokenPunctuation, delimHashKeyValue)
			if err != nil {
				return nil, err
			}
			valExpr, err := t.parseExpr()
			if err != nil {
				return nil, err
			}
			els = append(els, NewKeyValueExpr(keyExpr, valExpr, nxt.Pos))
			nxt = t.peek()
			if nxt.tokenType == tokenPunctuation {
				_, err := t.expectValue(tokenPunctuation, ",")
				if err != nil {
					return nil, err
				}
			}
		}
		return NewHashExpr(tok.Pos, els...), nil

	case tokenArrayOpen:
		els := []Expr{}
		for {
			nxt := t.peek()
			if nxt.tokenType == tokenArrayClose {
				t.next()
				break
			}
			expr, err := t.parseExpr()
			if err != nil {
				return nil, err
			}
			els = append(els, expr)
			nxt = t.peek()
			if nxt.tokenType == tokenPunctuation {
				_, err := t.expectValue(tokenPunctuation, ",")
				if err != nil {
					return nil, err
				}
			}
		}
		return NewArrayExpr(tok.Pos, els...), nil

	case tokenNumber:
		nxt := t.peek()
		val := tok.value
		if nxt.tokenType == tokenPunctuation && nxt.value == "." {
			val = val + "."
			t.next()
			nxt, err := t.expect(tokenNumber)
			if err != nil {
				return nil, err
			}
			val = val + nxt.value
		}
		return NewNumberExpr(val, tok.Pos), nil

	case tokenName:
		switch tok.value {
		case "null", "NULL", "none", "NONE":
			return NewNullExpr(tok.Pos), nil
		case "true", "TRUE":
			return NewBoolExpr(true, tok.Pos), nil
		case "false", "FALSE":
			return NewBoolExpr(false, tok.Pos), nil
		}
		name := NewNameExpr(tok.value, tok.Pos)
		nt := t.nextNonSpace()
		if nt.tokenType == tokenParensOpen {
			// TODO: This duplicates some code in parseOuterExpr, are both necessary?
			return t.parseFunc(name)
		}
		t.backup()
		return name, nil

	case tokenStringOpen:
		var exprs []Expr
		for {
			nxt, err := t.expect(tokenText, tokenInterpolateOpen, tokenStringClose)
			if err != nil {
				return nil, err
			}
			switch nxt.tokenType {
			case tokenText:
				exprs = append(exprs, NewStringExpr(nxt.value, nxt.Pos))
			case tokenInterpolateOpen:
				exp, err := t.parseExpr()
				if err != nil {
					return nil, err
				}
				_, err = t.expect(tokenInterpolateClose)
				if err != nil {
					return nil, err
				}
				exprs = append(exprs, exp)
			case tokenStringClose:
				ln := len(exprs)
				if ln > 1 {
					var res *BinaryExpr
					for i := 1; i < ln; i++ {
						if res == nil {
							res = NewBinaryExpr(exprs[i-1], OpBinaryConcat, exprs[i], exprs[i-1].Start())
							continue
						}
						res = NewBinaryExpr(res, OpBinaryConcat, exprs[i], res.Pos)
					}
					return res, nil
				}
				return exprs[0], nil
			}
		}

	default:
		return nil, newUnexpectedTokenError(tok)
	}
}
184095
func (v *evalVisitor) curExpr() *ast.Expression {
	if len(v.exprs) == 0 {
		return nil
	}

	return v.exprs[len(v.exprs)-1]
}
1145893
func (p *Decoder) parseEvent() (nextChunkType, error) {
	var err error

	// <delta-time> is stored as a variable-length quantity. It represents
	// the amount of time before the following event. If the first event in
	// a track occurs at the very beginning of a track, or if two
	// events occur simultaineously, a delta-time of zero is used.
	// Delta-times are always present. (Not storing delta-times of 0
	// requires at least two bytes for any other value, and most
	// delta-times aren't zero.) Delta-time is in some fraction of a beat
	// (or a second, for recording a track with SMPTE times), as specified
	// in the header chunk.
	timeDelta, readBytes, err := p.VarLen()
	if err != nil {
		return eventChunk, err
	}

	// status byte give us the msg type and channel.
	statusByte, err := p.ReadByte()
	if err != nil {
		return eventChunk, err
	}
	readBytes++

	e := &Event{TimeDelta: timeDelta}
	e.MsgType = (statusByte & 0xF0) >> 4
	e.MsgChan = statusByte & 0x0F

	nextChunk := eventChunk

	// Extract values based on message type
	switch e.MsgType {

	// unknown but found in the wild (seems to come with 1 data bytes)
	case 0x2, 0x3, 0x4, 0x5, 0x6:
		if _, err := p.ReadByte(); err != nil {
			return eventChunk, err
		}

	// Note Off
	// This message is sent when a note is released (ended)
	case 0x8:
		if e.Note, err = p.Uint7(); err != nil {
			return eventChunk, err
		}
		if e.Velocity, err = p.Uint7(); err != nil {
			return eventChunk, err
		}

	// Note On
	// This message is sent when a note is depressed (start)
	case 0x9:
		if e.Note, err = p.Uint7(); err != nil {
			return eventChunk, err
		}
		if e.Velocity, err = p.Uint7(); err != nil {
			return eventChunk, err
		}

	// Polyphonic Key Pressure (aftertouch)
	// This message is most often sent by pressing down on the key after it "bottoms out".
	case 0xA:
		if e.Note, err = p.Uint7(); err != nil {
			return eventChunk, err
		}
		// aftertouch value
		if e.Velocity, err = p.Uint7(); err != nil {
			return eventChunk, err
		}

	// Control Change / Channel Mode
	// This message is sent when a controller value changes.
	// Controllers include devices such as pedals and levers.
	// Controller numbers 120-127 are reserved as "Channel Mode Messages".
	// The controller number is between 0-119.
	// The new controller value is between 0-127.
	case 0xB:
		if e.Controller, err = p.Uint7(); err != nil {
			return eventChunk, err
		}
		if e.NewValue, err = p.Uint7(); err != nil {
			return eventChunk, err
		}

	/*
		channel mode messages
		Documented, not technically exposed

		This the same code as the Control Change, but implements Mode control and
		special message by using reserved controller numbers 120-127. The commands are:

		All Sound Off
		c = 120, v = 0
		When All Sound Off is received all oscillators will turn off,
		and their volume envelopes are set to zero as soon as possible.

		Reset All Controllers
		c = 121, v = x
		When Reset All Controllers is received, all controller values are reset to their default values.
		Value must only be zero unless otherwise allowed in a specific Recommended Practice.

		Local Control.
		c = 122, v = 0: Local Control Off
		c = 122, v = 127: Local Control On
		When Local Control is Off, all devices on a given channel will respond only to data received over MIDI.
		Played data, etc. will be ignored. Local Control On restores the functions of the normal controllers.

		All Notes Off.
		c = 123, v = 0: All Notes Off (See text for description of actual mode commands.)
		c = 124, v = 0: Omni Mode Off
		c = 125, v = 0: Omni Mode On
		c = 126, v = M: Mono Mode On (Poly Off) where M is the number of channels (Omni Off) or 0 (Omni On)
		c = 127, v = 0: Poly Mode On (Mono Off) (Note: These four messages also cause All Notes Off)
		When an All Notes Off is received, all oscillators will turn off.
		Program Change
				This message sent when the patch number changes. Value is the new program number.
	*/
	case 0xC:
		if e.NewProgram, err = p.Uint7(); err != nil {
			return eventChunk, err
		}
		if e.NewValue, err = p.Uint7(); err != nil {
			return eventChunk, err
		}

	// Channel Pressure (Aftertouch)
	// This message is most often sent by pressing down on the key after it "bottoms out".
	// This message is different from polyphonic after-touch.
	// Use this message to send the single greatest pressure value (of all the current depressed keys).
	// Value is the pressure value.
	// Most MIDI controllers don't generate Polyphonic Key AfterTouch because that requires a pressure sensor for each individual key
	// on a MIDI keyboard, and this is an expensive feature to implement.
	// For this reason, many cheaper units implement Channel Pressure instead of Aftertouch, as the former only requires
	// one sensor for the entire keyboard's pressure.
	case 0xD:
		if e.Pressure, err = p.Uint7(); err != nil {
			return eventChunk, err
		}

	// Pitch Bend Change.
	// This message is sent to indicate a change in the pitch bender (wheel or lever, typically).
	// The pitch bender is measured by a fourteen bit value. Center (no pitch change) is 2000H.
	// Sensitivity is a function of the transmitter.
	// Last 7 bits of the first byte are the least significant 7 bits.
	// Last 7 bits of the second byte are the most significant 7 bits.
	case 0xE:
		var b0, b1 byte
		if b0, err = p.ReadByte(); err != nil {
			return eventChunk, err
		}
		if b1, err = p.ReadByte(); err != nil {
			return eventChunk, err
		}

		// Absolute (unsigned) pitch bend value.
		e.AbsPitchBend = uint16(b1) & 0x7f << 7
		e.AbsPitchBend |= uint16(b0) & 0x7f

		// Relative signed value where 2000H is the center.
		e.RelPitchBend = int16(e.AbsPitchBend) - 0x2000

	//  Meta
	// All meta-events start with FF followed by the command (xx), the length,
	// or number of bytes that will contain data (nn), and the actual data (dd).
	case 0xF:
		var ok bool
		nextChunk, ok, err = p.parseMetaMsg(e)
		// early exit without adding the event to the track
		if err != nil || !ok {
			return nextChunk, err
		}

	default:
		fmt.Printf("skipped %#X - %s - %#X\n", statusByte, string(statusByte), e.MsgType)
		return eventChunk, nil
	}

	track := p.CurrentTrack()
	if track != nil {
		track.Events = append(track.Events, e)
	}

	return nextChunk, err
}
1120473
func (p *printer) expr(x ast.Expr, multiLine *bool) {
	const depth = 1
	p.expr1(x, token.LowestPrec, depth, multiLine)
}
20788
func (p *parser) parseFilterExpr(n node) node {
	opnd := p.parsePrimaryExpr(n)
	if p.r.typ == itemLBracket {
		opnd = newFilterNode(opnd, p.parsePredicate(opnd))
	}
	return opnd
}
978160
func (t *Tree) parseExpr() (Expr, error) {
	expr, err := t.parseInnerExpr()
	if err != nil {
		return nil, err
	}

	return t.parseOuterExpr(expr)
}
906559
func (e *Expr) parse(s string) error {
	if s == "" {
		return nil
	}
	node, err := parser.ParseExpr(s)
	if err != nil {
		return err
	}
	e.root = node

	v := &visitor{pool: e.pool}
	ast.Walk(v, e.root)
	return v.err
}
747756
func (p *parser) parsePathExpr(n node) node {
	var opnd node
	if isPrimaryExpr(p.r) {
		opnd = p.parseFilterExpr(n)
		switch p.r.typ {
		case itemSlash:
			p.next()
			opnd = p.parseRelativeLocationPath(opnd)
		case itemSlashSlash:
			p.next()
			opnd = p.parseRelativeLocationPath(newAxisNode("descendant-or-self", "", "", "", opnd))
		}
	} else {
		opnd = p.parseLocationPath(nil)
	}
	return opnd
}
88432
func (p *parser) parseOrExpr(n node) node {
	opnd := p.parseAndExpr(n)
	for {
		if !testOp(p.r, "or") {
			break
		}
		p.next()
		opnd = newOperatorNode("or", opnd, p.parseAndExpr(n))
	}
	return opnd
}
752471
func parseCapacity(b []byte, r *regexp.Regexp) (uint64, error) {
	matches := r.FindSubmatch(b)
	if len(matches) != 2 {
		return 0, fmt.Errorf("failed to match regexp in output: %q", string(b))
	}
	m, err := strconv.ParseUint(string(matches[1]), 10, 64)
	if err != nil {
		return 0, err
	}

	// Convert to bytes.
	return m * 1024, err
}
318358
func (p *parser) parseExpression(tok *lexer.Token) *ast.Expression {
	result := ast.NewExpression(tok.Pos, tok.Line)

	// helperName
	result.Path = p.parseHelperName()

	// param* hash?
	result.Params, result.Hash = p.parseExpressionParamsHash()

	return result
}
708422
func parsePrefixAsIdd(iddPattern *regexp.Regexp, number *builder.Builder) bool {
	numStr := number.String()
	ind := iddPattern.FindStringIndex(numStr)
	if len(ind) == 0 || ind[0] != 0 {
		return false
	}
	matchEnd := ind[1] // ind is a two element slice
	// Only strip this if the first digit after the match is not
	// a 0, since country calling codes cannot begin with 0.
	find := CAPTURING_DIGIT_PATTERN.FindAllString(numStr[matchEnd:], -1)
	if len(find) > 0 {
		if NormalizeDigitsOnly(find[0]) == "0" {
			return false
		}
	}

	numBytes := []byte(numStr)
	number.ResetWith(numBytes[matchEnd:])
	return true
}