// ParseMIME reads a MIME document from the provided reader and parses it into
// tree of MIMEPart objects.
551689
func ParseMIME(reader *bufio.Reader) (MIMEPart, error) {
	tr := textproto.NewReader(reader)
	header, err := tr.ReadMIMEHeader()
	if err != nil {
		return nil, err
	}
	mediatype, params, err := mime.ParseMediaType(header.Get("Content-Type"))
	if err != nil {
		return nil, err
	}
	root := &memMIMEPart{header: header, contentType: mediatype}

	if strings.HasPrefix(mediatype, "multipart/") {
		boundary := params["boundary"]
		err = parseParts(root, reader, boundary)
		if err != nil {
			return nil, err
		}
	} else {
		// Content is text or data, decode it
		content, err := decodeSection(header.Get("Content-Transfer-Encoding"), reader)
		if err != nil {
			return nil, err
		}
		root.content = content
	}

	return root, nil
}
464469
func parseParts(parent MIMEPart, reader io.Reader, boundary string) error {
	var prevSibling MIMEPart

	// Loop over MIME parts
	mr := multipart.NewReader(reader, boundary)
	for {
		// mrp is golang's built in mime-part
		mrp, err := mr.NextPart()
		if err != nil {
			if err == io.EOF {
				// This is a clean end-of-message signal
				break
			}
			return err
		}
		if len(mrp.Header) == 0 {
			// Empty header probably means the part didn't using the correct trailing "--"
			// syntax to close its boundary.  We will let this slide if this this the
			// last MIME part.
			if _, err := mr.NextPart(); err != nil {
				if err == io.EOF || strings.HasSuffix(err.Error(), "EOF") {
					// This is what we were hoping for
					break
				} else {
					return fmt.Errorf("Error at boundary %v: %v", boundary, err)
				}
			}

			return fmt.Errorf("Empty header at boundary %v", boundary)
		}
		ctype := mrp.Header.Get("Content-Type")
		if ctype == "" {
			return fmt.Errorf("Missing Content-Type at boundary %v", boundary)
		}
		mediatype, mparams, err := mime.ParseMediaType(ctype)
		if err != nil {
			return err
		}

		// Insert ourselves into tree, p is enmime's MIME part
		p := NewMIMEPart(parent, mediatype)
		p.SetHeader(mrp.Header)
		if prevSibling != nil {
			prevSibling.SetNextSibling(p)
		} else {
			parent.SetFirstChild(p)
		}
		prevSibling = p

		// Determine content disposition, filename, character set
		disposition, dparams, err := mime.ParseMediaType(mrp.Header.Get("Content-Disposition"))
		if err == nil {
			// Disposition is optional
			p.SetDisposition(disposition)
			p.SetFileName(DecodeHeader(dparams["filename"]))
		}
		if p.FileName() == "" && mparams["name"] != "" {
			p.SetFileName(DecodeHeader(mparams["name"]))
		}
		if p.FileName() == "" && mparams["file"] != "" {
			p.SetFileName(DecodeHeader(mparams["file"]))
		}
		if p.Charset() == "" {
			p.SetCharset(mparams["charset"])
		}

		boundary := mparams["boundary"]
		if boundary != "" {
			// Content is another multipart
			err = parseParts(p, mrp, boundary)
			if err != nil {
				return err
			}
		} else {
			// Content is text or data, decode it
			data, err := decodeSection(mrp.Header.Get("Content-Transfer-Encoding"), mrp)
			if err != nil {
				return err
			}
			p.SetContent(data)
		}
	}

	return nil
}
805031
func ParseMessage(data []byte, sender net.Addr) (Message, error) {
	address, idx := ReadString(data)
	msg := Message{
		Address: address,
		Sender:  sender,
	}
	data = data[idx:]
	typetags, idx := ReadString(data)
	data = data[idx:]

	// Read all arguments.
	args, err := ReadArguments([]byte(typetags), data)
	if err != nil {
		return Message{}, errors.Wrap(err, "parse message")
	}
	msg.Arguments = args

	return msg, nil
}
295218
func insertMime(l []mime, e mime) []mime {
	for i, each := range l {
		// if current mime has lower quality then insert before
		if e.quality > each.quality {
			left := append([]mime{}, l[0:i]...)
			return append(append(left, e), l[i:]...)
		}
	}
	return append(l, e)
}
140898
func (t *Tree) Parse(text string) (err error) {
	defer t.recover(&err)
	t.startParse(lex(text))
	t.Text = text
	t.parse()
	t.stopParse()
	return nil
}
411591
func (buffer *BufferedReader) parseMLE16() ([]byte, int) {
	var messageLen uint16
	reader := bytes.NewReader(buffer.data[buffer.paramMLE:buffer.end])
	err := binary.Read(reader, buffer.encoding, &messageLen)
	if err != nil {
		return nil, -1 // ### return, malformed ###
	}
	return buffer.extractMessage(int(messageLen), buffer.paramMLE+2)
}
256282
func parseMultiPartBody(mailMsg *mail.Message, mimeMsg *MIMEBody) error {
	// Parse top-level multipart
	ctype := mailMsg.Header.Get("Content-Type")
	mediatype, params, err := mime.ParseMediaType(ctype)
	if err != nil {
		return fmt.Errorf("Unable to parse media type: %v", err)
	}
	if !strings.HasPrefix(mediatype, "multipart/") {
		return fmt.Errorf("Unknown mediatype: %v", mediatype)
	}
	boundary := params["boundary"]
	if boundary == "" {
		return fmt.Errorf("Unable to locate boundary param in Content-Type header")
	}
	// Root Node of our tree
	root := NewMIMEPart(nil, mediatype)
	mimeMsg.Root = root
	err = parseParts(root, mailMsg.Body, boundary)
	if err != nil {
		return err
	}

	// Locate text body
	if mediatype == "multipart/altern" {
		match := BreadthMatchFirst(root, func(p MIMEPart) bool {
			return p.ContentType() == "text/plain" && p.Disposition() != "attachment"
		})
		if match != nil {
			if match.Charset() != "" {
				newStr, err := ConvertToUTF8String(match.Charset(), match.Content())
				if err != nil {
					return err
				}
				mimeMsg.Text += newStr
			} else {
				mimeMsg.Text += string(match.Content())
			}
		}
	} else {
		// multipart is of a mixed type
		match := DepthMatchAll(root, func(p MIMEPart) bool {
			return p.ContentType() == "text/plain" && p.Disposition() != "attachment"
		})
		for i, m := range match {
			if i > 0 {
				mimeMsg.Text += "\n--\n"
			}
			if m.Charset() != "" {
				newStr, err := ConvertToUTF8String(m.Charset(), m.Content())
				if err != nil {
					return err
				}
				mimeMsg.Text += newStr
			} else {
				mimeMsg.Text += string(m.Content())
			}
		}
	}

	// Locate HTML body
	match := BreadthMatchFirst(root, func(p MIMEPart) bool {
		return p.ContentType() == "text/html" && p.Disposition() != "attachment"
	})
	if match != nil {
		if match.Charset() != "" {
			newStr, err := ConvertToUTF8String(match.Charset(), match.Content())
			if err != nil {
				return err
			}
			mimeMsg.HTML += newStr
		} else {
			mimeMsg.HTML = string(match.Content())
		}

	}

	// Locate attachments
	mimeMsg.Attachments = BreadthMatchAll(root, func(p MIMEPart) bool {
		return p.Disposition() == "attachment" || p.ContentType() == "application/octet-stream"
	})

	// Locate inlines
	mimeMsg.Inlines = BreadthMatchAll(root, func(p MIMEPart) bool {
		return p.Disposition() == "inline"
	})

	// Locate others parts not considered in attachments or inlines
	mimeMsg.OtherParts = BreadthMatchAll(root, func(p MIMEPart) bool {
		if strings.HasPrefix(p.ContentType(), "multipart/") {
			return false
		}
		if p.Disposition() != "" {
			return false
		}
		if p.ContentType() == "application/octet-stream" {
			return false
		}
		return p.ContentType() != "text/plain" && p.ContentType() != "text/html"
	})

	return nil
}
1059516
func Parse(r io.Reader) (*html.Node, error) {
	return html.Parse(r)
}
228973
func parseMetaGoImports(r io.Reader) (imports []metaImport, err error) {
	d := xml.NewDecoder(r)
	d.CharsetReader = charsetReader
	d.Strict = false
	var t xml.Token
	for {
		t, err = d.RawToken()
		if err != nil {
			if err == io.EOF || len(imports) > 0 {
				err = nil
			}
			return
		}
		if e, ok := t.(xml.StartElement); ok && strings.EqualFold(e.Name.Local, "body") {
			return
		}
		if e, ok := t.(xml.EndElement); ok && strings.EqualFold(e.Name.Local, "head") {
			return
		}
		e, ok := t.(xml.StartElement)
		if !ok || !strings.EqualFold(e.Name.Local, "meta") {
			continue
		}
		if attrValue(e.Attr, "name") != "go-import" {
			continue
		}
		if f := strings.Fields(attrValue(e.Attr, "content")); len(f) == 3 {
			imports = append(imports, metaImport{
				Prefix:   f[0],
				VCS:      f[1],
				RepoRoot: f[2],
			})
		}
	}
}
1364792
func NewMIMEPart(parent MIMEPart, contentType string) MIMEPart {
	return &memMIMEPart{parent: parent, contentType: contentType}
}
1325716
func MIMETypeFromReaderAt(ra io.ReaderAt) (mime string) {
	var buf [1024]byte
	n, _ := ra.ReadAt(buf[:], 0)
	return MIMEType(buf[:n])
}
1183463
func parseMessage(t *thing) (*Message, error) {
	m := &Message{}
	return m, mapstructure.Decode(t.Data, m)
}
56806
func Parse(data []byte, separator string) (Document, error) {
	var root interface{}
	err := json.Unmarshal(data, &root)
	if err != nil {
		return nil, errors.Annotate(err, ErrUnmarshalling, errorMessages)
	}
	return &document{
		separator: separator,
		root:      root,
	}, nil
}
641761
func (n *Name) Parse(reader io.ReadSeeker) error {
	err := encoding.Unmarshal(reader, &n.OffsetPrevString, Endianness)
	if err != nil {
		return err
	}
	err = encoding.Unmarshal(reader, &n.Hash, Endianness)
	if err != nil {
		return err
	}
	err = encoding.Unmarshal(reader, &n.Size, Endianness)
	if err != nil {
		return err
	}

	// No need to control size since it is uint16
	n.UTF16String = make([]uint16, n.Size+1)

	err = encoding.UnmarshaInitSlice(reader, &n.UTF16String, Endianness)
	return err
}
1151630
func (t *tree) parseMsgRawText(node *ast.RawTextNode) []ast.Node {
	var (
		r   []ast.Node
		txt = node.Text
		pos = node.Position()
	)
	for len(txt) > 0 {
		var start, end = len(txt), len(txt)
		var ii = htmlTagRegexp.FindSubmatchIndex(txt)
		if ii != nil {
			start, end = ii[0], ii[1]
		}

		if start > 0 {
			r = append(r, &ast.RawTextNode{pos, txt[:start]})
			pos += ast.Pos(start)
		}

		if end > start {
			r = append(r, &ast.MsgPlaceholderNode{pos, "", &ast.MsgHtmlTagNode{pos, txt[start:end]}})
			pos += ast.Pos(end - start)
		}

		txt = txt[end:]
	}
	return r
}
294049
func (res *Response) WriteMIME(w io.Writer) error {
	io.WriteString(w, "MIME-Version: 1.0\r\n")
	err := res.Header().Write(w)
	if err != nil {
		return err
	}
	_, err = io.WriteString(w, "\r\n")
	if err != nil {
		return err
	}
	_, err = w.Write(res.Body)
	if err != nil {
		return err
	}
	return nil
}
1336588
func ParseBytes(b []byte) (Sections, error) {
	tree, err := ParseASTBytes(b)
	if err != nil {
		return Sections{}, err
	}

	v := NewDefaultVisitor()
	if err = Walk(tree, v); err != nil {
		return Sections{}, err
	}

	return v.Sections, nil
}