// parseMacro parses a macro definition.
//
// 	{% macro <name>([ arg [ , arg]) %}
//	Macro body
//	{% endmacro %}
4926
func parseMacro(t *Tree, start Pos) (Node, error) {
	tok, err := t.expect(tokenName)
	if err != nil {
		return nil, err
	}
	name := tok.value
	_, err = t.expect(tokenParensOpen)
	if err != nil {
		return nil, err
	}
	var args []string
	for {
		tok = t.nextNonSpace()
		switch tok.tokenType {
		case tokenEOF:
			return nil, newUnexpectedEOFError(tok)
		case tokenName:
			args = append(args, tok.value)
		case tokenPunctuation:
			if tok.value != "," {
				return nil, newUnexpectedValueError(tok, ",")
			}
		case tokenParensClose:
			_, err := t.expect(tokenTagClose)
			if err != nil {
				return nil, err
			}
			goto body
		default:
			return nil, newUnexpectedTokenError(tok)
		}
	}
body:
	body, err := t.parseUntilEndTag("macro", start)
	if err != nil {
		return nil, err
	}
	n := NewMacroNode(name, args, body, start)
	n.Origin = t.Name
	t.macros[name] = n
	return n, nil
}
131970
func parseGlob(t *Template, pattern string) (*Template, error) {
	filenames, err := filepath.Glob(pattern)
	if err != nil {
		return nil, err
	}
	if len(filenames) == 0 {
		return nil, fmt.Errorf("template: pattern matches no files: %#q", pattern)
	}
	return parseFiles(t, filenames...)
}
420121
func parseBSON(done <-chan struct{}, r io.Reader) (<-chan map[string]interface{}, <-chan error) {
	c := make(chan map[string]interface{})
	errc := make(chan error, 1)

	go func() {
		defer close(c)
		scanner := bsonScanner.New(r)
	scan:
		for scanner.Scan() {
			op := map[string]interface{}{}
			if err := bson.Unmarshal(scanner.Bytes(), &op); err != nil {
				errc <- err
				return
			}
			select {
			case c <- op:
			case <-done:
				break scan
			}
		}
		if err := scanner.Err(); err != nil {
			fmt.Println(err)
			errc <- err
		}
		errc <- nil
	}()
	return c, errc
}
1208091
func (t *tree) parsePrint(token item) ast.Node {
	var expr = t.parseExpr(0)
	var directives []*ast.PrintDirectiveNode
	for {
		switch tok := t.next(); tok.typ {
		case itemRightDelim:
			return &ast.PrintNode{token.pos, expr, directives}
		case itemPipe:
			// read the directive name and see if there are arguments
			var id = t.expect(itemIdent, "print directive")
			var args []ast.Node
			for {
				// each argument is preceeded by a colon (first arg) or comma (subsequent)
				switch next := t.next(); next.typ {
				case itemColon, itemComma:
					args = append(args, t.parseExpr(0))
					continue
				}
				t.backup()
				directives = append(directives, &ast.PrintDirectiveNode{tok.pos, id.val, args})
				break
			}
		default:
			t.unexpected(tok, "print. (expected '|' or '}')")
		}
	}
}
285810
func (a *MacroArguments) UnmarshalJSON(data []byte) error {
	type Alias MacroArguments
	aux := struct{ *Alias }{Alias: (*Alias)(a)}

	err := json.Unmarshal(data, &aux)
	if err != nil {
		return err
	}

	// Decode the polymorphic MacroArguments.Values field into the approriate struct
	switch aux.Type {
	case "constant":
		values, ok := aux.Values.([]interface{})
		if !ok {
			return fmt.Errorf("error parsing %v as MacroConstantArguments", aux.Values)
		}

		macroValues := make(MacroConstantValues, len(values))
		for i, v := range values {
			if _, ok := v.(string); !ok {
				return fmt.Errorf("expected macro constant value to be string but received %T", v)
			}
			macroValues[i] = v.(string)
		}

		a.Values = macroValues
	case "map":
		values, ok := aux.Values.(map[string]interface{})
		if !ok {
			return fmt.Errorf("error parsing %v as MacroMapArguments", aux.Values)
		}

		macroValues := MacroMapValues{}
		for k, v := range values {
			if _, ok := v.(string); !ok {
				return fmt.Errorf("expected macro map value to be string but received %T", v)
			}
			macroValues[k] = v.(string)
		}

		a.Values = macroValues
	case "query":
		values, ok := aux.Values.(map[string]interface{})
		if !ok {
			return fmt.Errorf("error parsing %v as MacroQueryArguments", aux.Values)
		}

		macroValues := MacroQueryValues{}

		query, prs := values["query"]
		if !prs {
			return fmt.Errorf("\"query\" key not present in MacroQueryArguments")
		}
		if _, ok := query.(string); !ok {
			return fmt.Errorf("expected \"query\" to be string but received %T", query)
		}

		language, prs := values["language"]
		if !prs {
			return fmt.Errorf("\"language\" key not present in MacroQueryArguments")
		}
		if _, ok := language.(string); !ok {
			return fmt.Errorf("expected \"language\" to be string but received %T", language)
		}

		macroValues.Query = query.(string)
		macroValues.Language = language.(string)
		a.Values = macroValues
	default:
		return fmt.Errorf("unknown MacroArguments type %s", aux.Type)
	}

	return nil
}
794537
func (operation *Operation) ParseParamComment(commentLine string) error {
	swaggerParameter := Parameter{}
	paramString := commentLine

	re := regexp.MustCompile(`([-\w]+)[\s]+([\w]+)[\s]+([\S.]+)[\s]+([\w]+)[\s]+"([^"]+)"`)

	if matches := re.FindStringSubmatch(paramString); len(matches) != 6 {
		return fmt.Errorf("Can not parse param comment \"%s\", skipped.", paramString)
	} else {
		typeName, err := operation.registerType(matches[3])
		if err != nil {
			return err
		}

		swaggerParameter.Name = matches[1]
		swaggerParameter.ParamType = matches[2]
		swaggerParameter.Type = typeName
		swaggerParameter.DataType = typeName
		requiredText := strings.ToLower(matches[4])
		swaggerParameter.Required = (requiredText == "true" || requiredText == "required")
		swaggerParameter.Description = matches[5]

		operation.Parameters = append(operation.Parameters, swaggerParameter)
	}

	return nil
}
89925
func parseSelection(parser *Parser) (interface{}, error) {
	if peek(parser, lexer.SPREAD) {
		return parseFragment(parser)
	}
	return parseField(parser)
}
969341
func parseFragmentDefinition(parser *Parser) (ast.Node, error) {
	start := parser.Token.Start
	_, err := expectKeyWord(parser, lexer.FRAGMENT)
	if err != nil {
		return nil, err
	}
	name, err := parseFragmentName(parser)
	if err != nil {
		return nil, err
	}
	_, err = expectKeyWord(parser, "on")
	if err != nil {
		return nil, err
	}
	typeCondition, err := parseNamed(parser)
	if err != nil {
		return nil, err
	}
	directives, err := parseDirectives(parser)
	if err != nil {
		return nil, err
	}
	selectionSet, err := parseSelectionSet(parser)
	if err != nil {
		return nil, err
	}
	return ast.NewFragmentDefinition(&ast.FragmentDefinition{
		Name:          name,
		TypeCondition: typeCondition,
		Directives:    directives,
		SelectionSet:  selectionSet,
		Loc:           loc(parser, start),
	}), nil
}
784510
func (obj *Doc) GetTextMacros(ctx context.Context) ([]*TextMacro, error) {
	result := &struct {
		Macros []*TextMacro	`json:"qMacros"`
	} {}
	err := obj.rpc(ctx, "GetTextMacros", result)
	return result.Macros, err 
}
542788
func (p *parser) parseMultiplicativeExpr(n node) node {
	opnd := p.parseUnaryExpr(n)
Loop:
	for {
		var op string
		if p.r.typ == itemStar {
			op = "*"
		} else if testOp(p.r, "div") || testOp(p.r, "mod") {
			op = p.r.name
		} else {
			break Loop
		}
		p.next()
		opnd = newOperatorNode(op, opnd, p.parseUnaryExpr(n))
	}
	return opnd
}
1114604
func (s *Service) CreateMacro(ctx context.Context, m *platform.Macro) error {
	op := OpPrefix + platform.OpCreateMacro
	m.ID = s.IDGenerator.ID()
	err := s.ReplaceMacro(ctx, m)
	if err != nil {
		return &platform.Error{
			Op:  op,
			Err: err,
		}
	}
	return nil
}
912460
func (p *Parser) parseField() (*Field, error) {
	f := &Field{}

	// Attempt to parse a regex.
	re, err := p.parseRegex()
	if err != nil {
		return nil, err
	} else if re != nil {
		f.Expr = re
	} else {
		_, pos, _ := p.ScanIgnoreWhitespace()
		p.Unscan()
		// Parse the expression first.
		expr, err := p.ParseExpr()
		if err != nil {
			return nil, err
		}
		var c validateField
		Walk(&c, expr)
		if c.foundInvalid {
			return nil, fmt.Errorf("invalid operator %s in SELECT clause at line %d, char %d; operator is intended for WHERE clause", c.badToken, pos.Line+1, pos.Char+1)
		}
		f.Expr = expr
	}

	// Parse the alias if the current and next tokens are "WS AS".
	alias, err := p.parseAlias()
	if err != nil {
		return nil, err
	}
	f.Alias = alias

	// Consume all trailing whitespace.
	p.consumeWhitespace()

	return f, nil
}
1205029
func (s *MacroService) FindMacros(ctx context.Context) ([]*platform.Macro, error) {
	url, err := newURL(s.Addr, macroPath)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("GET", url.String(), nil)
	if err != nil {
		return nil, err
	}

	SetToken(s.Token, req)
	hc := newClient(url.Scheme, s.InsecureSkipVerify)

	resp, err := hc.Do(req)
	if err != nil {
		return nil, err
	}

	if err := CheckError(resp, true); err != nil {
		return nil, err
	}

	var ms getMacrosResponse
	if err := json.NewDecoder(resp.Body).Decode(&ms); err != nil {
		return nil, err
	}

	macros := ms.ToPlatform()
	return macros, nil
}
286395
func ParseMAC(s string) (MAC, error) {
	ha, err := net.ParseMAC(s)
	if err != nil {
		return MAC{}, err
	}
	if len(ha) != 6 {
		return MAC{}, fmt.Errorf("invalid MAC address %s", s)
	}

	return MAC(ha), nil
}
633754
func parseJSON(rest string, d *Directive) (*Node, map[string]bool, error) {
	rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
	if !strings.HasPrefix(rest, "[") {
		return nil, nil, fmt.Errorf(`Error parsing "%s" as a JSON array`, rest)
	}

	var myJSON []interface{}
	if err := json.NewDecoder(strings.NewReader(rest)).Decode(&myJSON); err != nil {
		return nil, nil, err
	}

	var top, prev *Node
	for _, str := range myJSON {
		s, ok := str.(string)
		if !ok {
			return nil, nil, errDockerfileNotStringArray
		}

		node := &Node{Value: s}
		if prev == nil {
			top = node
		} else {
			prev.Next = node
		}
		prev = node
	}

	return top, map[string]bool{"json": true}, nil
}
692207
func NewMacroHandler() *MacroHandler {
	h := &MacroHandler{
		Router: NewRouter(),
		Logger: zap.NewNop(),
	}

	h.HandlerFunc("GET", "/api/v2/macros", h.handleGetMacros)
	h.HandlerFunc("POST", "/api/v2/macros", h.handlePostMacro)
	h.HandlerFunc("GET", "/api/v2/macros/:id", h.handleGetMacro)
	h.HandlerFunc("PATCH", "/api/v2/macros/:id", h.handlePatchMacro)
	h.HandlerFunc("PUT", "/api/v2/macros/:id", h.handlePutMacro)
	h.HandlerFunc("DELETE", "/api/v2/macros/:id", h.handleDeleteMacro)

	return h
}
1253388
func (c *Client) ReplaceMacro(ctx context.Context, macro *platform.Macro) error {
	op := getOp(platform.OpReplaceMacro)
	return c.db.Update(func(tx *bolt.Tx) error {
		if pe := c.putMacro(ctx, tx, macro); pe != nil {
			return &platform.Error{
				Op:  op,
				Err: pe,
			}
		}
		return nil
	})
}