helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! The event parser (`parserc.go`): turns the token stream into events and attaches the comments
//! the scanner collected to them.

use super::parser::Parser;
use super::scanner::Res;
use super::token::{ScalarStyle, TokenType};
use super::{Mark, YamlError};

/// The parser's states (`yaml_parser_state_t`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum State {
    StreamStart,
    ImplicitDocumentStart,
    DocumentStart,
    DocumentContent,
    DocumentEnd,
    BlockNode,
    BlockSequenceFirstEntry,
    BlockSequenceEntry,
    IndentlessSequenceEntry,
    BlockMappingFirstKey,
    BlockMappingKey,
    BlockMappingValue,
    FlowSequenceFirstEntry,
    FlowSequenceEntry,
    FlowSequenceEntryMappingKey,
    FlowSequenceEntryMappingValue,
    FlowSequenceEntryMappingEnd,
    FlowMappingFirstKey,
    FlowMappingKey,
    FlowMappingValue,
    FlowMappingEmptyValue,
    End,
}

/// The kinds of event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum EventType {
    None,
    StreamStart,
    StreamEnd,
    DocumentStart,
    DocumentEnd,
    Alias,
    Scalar,
    SequenceStart,
    SequenceEnd,
    MappingStart,
    MappingEnd,
}

/// An event.
#[derive(Debug, Clone)]
pub(super) struct Event {
    pub(super) typ: EventType,
    pub(super) start_mark: Mark,
    pub(super) anchor: Vec<u8>,
    pub(super) tag: Vec<u8>,
    pub(super) value: Vec<u8>,
    pub(super) style: ScalarStyle,
    pub(super) flow: bool,
    pub(super) head_comment: Vec<u8>,
    pub(super) line_comment: Vec<u8>,
    pub(super) foot_comment: Vec<u8>,
}

impl Event {
    pub(super) fn new(typ: EventType, start_mark: Mark) -> Self {
        Self {
            typ,
            start_mark,
            anchor: Vec::new(),
            tag: Vec::new(),
            value: Vec::new(),
            style: ScalarStyle::Plain,
            flow: false,
            head_comment: Vec::new(),
            line_comment: Vec::new(),
            foot_comment: Vec::new(),
        }
    }
}

impl Parser {
    pub(super) fn pop_state(&mut self) {
        self.state = self.states.pop().unwrap_or(State::End);
    }

    pub(super) fn set_event_comments(&mut self, event: &mut Event) {
        event.head_comment = std::mem::take(&mut self.head_comment);
        event.line_comment = std::mem::take(&mut self.line_comment);
        event.foot_comment = std::mem::take(&mut self.foot_comment);
        self.stem_comment = None;
    }

    /// `yaml_parser_parse`: the next event, `EventType::None` once the stream has ended.
    pub(super) fn next_event(&mut self) -> Res<Event> {
        if self.stream_end_produced || self.state == State::End {
            return Ok(Event::new(EventType::None, Mark::default()));
        }

        match self.state {
            State::StreamStart => self.parse_stream_start(),
            State::ImplicitDocumentStart => self.parse_document_start(true),
            State::DocumentStart => self.parse_document_start(false),
            State::DocumentContent => self.parse_document_content(),
            State::DocumentEnd => self.parse_document_end(),
            State::BlockNode => self.parse_node(true, false),
            State::BlockSequenceFirstEntry => self.parse_block_sequence_entry(true),
            State::BlockSequenceEntry => self.parse_block_sequence_entry(false),
            State::IndentlessSequenceEntry => self.parse_indentless_sequence_entry(),
            State::BlockMappingFirstKey => self.parse_block_mapping_key(true),
            State::BlockMappingKey => self.parse_block_mapping_key(false),
            State::BlockMappingValue => self.parse_block_mapping_value(),
            State::FlowSequenceFirstEntry => self.parse_flow_sequence_entry(true),
            State::FlowSequenceEntry => self.parse_flow_sequence_entry(false),
            State::FlowSequenceEntryMappingKey => self.parse_flow_sequence_entry_mapping_key(),
            State::FlowSequenceEntryMappingValue => self.parse_flow_sequence_entry_mapping_value(),
            State::FlowSequenceEntryMappingEnd => self.parse_flow_sequence_entry_mapping_end(),
            State::FlowMappingFirstKey => self.parse_flow_mapping_key(true),
            State::FlowMappingKey => self.parse_flow_mapping_key(false),
            State::FlowMappingValue => self.parse_flow_mapping_value(false),
            State::FlowMappingEmptyValue => self.parse_flow_mapping_value(true),
            State::End => Ok(Event::new(EventType::None, Mark::default())),
        }
    }

    pub(super) fn parse_stream_start(&mut self) -> Res<Event> {
        let token = self.peek_token()?;

        if token.typ != TokenType::StreamStart {
            return Err(YamlError::parser(
                Mark::default(),
                token.start_mark,
                "did not find expected <stream-start>",
            ));
        }

        self.state = State::ImplicitDocumentStart;
        self.skip_token();

        Ok(Event::new(EventType::StreamStart, token.start_mark))
    }

    pub(super) fn parse_document_start(&mut self, implicit: bool) -> Res<Event> {
        let mut token = self.peek_token()?;

        if !implicit {
            while token.typ == TokenType::DocumentEnd {
                self.skip_token();
                token = self.peek_token()?;
            }
        }

        let directive_or_start = matches!(
            token.typ,
            TokenType::VersionDirective
                | TokenType::TagDirective
                | TokenType::DocumentStart
                | TokenType::StreamEnd
        );

        if implicit && !directive_or_start {
            self.process_directives()?;
            self.states.push(State::DocumentEnd);
            self.state = State::BlockNode;

            let mut event = Event::new(EventType::DocumentStart, token.start_mark);

            event.head_comment = self.split_document_head_comment();

            return Ok(event);
        }

        if token.typ != TokenType::StreamEnd {
            let start_mark = token.start_mark;

            self.process_directives()?;
            token = self.peek_token()?;

            if token.typ != TokenType::DocumentStart {
                return Err(YamlError::parser(
                    Mark::default(),
                    token.start_mark,
                    "did not find expected <document start>",
                ));
            }

            self.states.push(State::DocumentEnd);
            self.state = State::DocumentContent;
            self.skip_token();

            return Ok(Event::new(EventType::DocumentStart, start_mark));
        }

        self.state = State::End;
        self.skip_token();

        Ok(Event::new(EventType::StreamEnd, token.start_mark))
    }

    pub(super) fn split_document_head_comment(&mut self) -> Vec<u8> {
        let head = &self.head_comment;

        for i in (1..head.len()).rev() {
            if head[i] != b'\n' {
                continue;
            }

            if i == head.len() - 1 {
                let event_head = head[..i].to_vec();

                self.head_comment = head[i + 1..].to_vec();

                return event_head;
            }

            if head[i - 1] == b'\n' {
                let event_head = head[..i - 1].to_vec();

                self.head_comment = head[i + 1..].to_vec();

                return event_head;
            }
        }

        Vec::new()
    }

    pub(super) fn parse_document_content(&mut self) -> Res<Event> {
        let token = self.peek_token()?;

        if matches!(
            token.typ,
            TokenType::VersionDirective
                | TokenType::TagDirective
                | TokenType::DocumentStart
                | TokenType::DocumentEnd
                | TokenType::StreamEnd
        ) {
            self.pop_state();

            return Ok(empty_scalar(token.start_mark));
        }

        self.parse_node(true, false)
    }

    pub(super) fn parse_document_end(&mut self) -> Res<Event> {
        let token = self.peek_token()?;

        if token.typ == TokenType::DocumentEnd {
            self.skip_token();
        }

        self.tag_directives.clear();
        self.state = State::DocumentStart;

        let mut event = Event::new(EventType::DocumentEnd, token.start_mark);

        self.set_event_comments(&mut event);

        if !event.head_comment.is_empty() && event.foot_comment.is_empty() {
            event.foot_comment = std::mem::take(&mut event.head_comment);
        }

        Ok(event)
    }

    pub(super) fn process_directives(&mut self) -> Res<()> {
        let mut token = self.peek_token()?;
        let mut seen_version = false;

        while matches!(
            token.typ,
            TokenType::VersionDirective | TokenType::TagDirective
        ) {
            if token.typ == TokenType::VersionDirective {
                if seen_version {
                    return Err(YamlError::parser(
                        Mark::default(),
                        token.start_mark,
                        "found duplicate %YAML directive",
                    ));
                }

                if token.major != 1 || token.minor != 1 {
                    return Err(YamlError::parser(
                        Mark::default(),
                        token.start_mark,
                        "found incompatible YAML document",
                    ));
                }

                seen_version = true;
            } else {
                self.append_tag_directive(&token.value, &token.prefix, false, token.start_mark)?;
            }

            self.skip_token();
            token = self.peek_token()?;
        }

        self.append_tag_directive(b"!", b"!", true, token.start_mark)?;
        self.append_tag_directive(b"!!", b"tag:yaml.org,2002:", true, token.start_mark)?;

        Ok(())
    }

    pub(super) fn append_tag_directive(
        &mut self,
        handle: &[u8],
        prefix: &[u8],
        allow_duplicates: bool,
        mark: Mark,
    ) -> Res<()> {
        if self.tag_directives.iter().any(|(known, _)| known == handle) {
            if allow_duplicates {
                return Ok(());
            }

            return Err(YamlError::parser(
                Mark::default(),
                mark,
                "found duplicate %TAG directive",
            ));
        }

        self.tag_directives.push((handle.to_vec(), prefix.to_vec()));

        Ok(())
    }
}

pub(super) fn empty_scalar(mark: Mark) -> Event {
    Event::new(EventType::Scalar, mark)
}

pub(super) fn collection_start(
    typ: EventType,
    mark: Mark,
    anchor: Vec<u8>,
    tag: Vec<u8>,
    flow: bool,
) -> Event {
    let mut event = Event::new(typ, mark);

    event.anchor = anchor;
    event.tag = tag;
    event.flow = flow;

    event
}