///|
/// Mutable state is private to a single parse; no global macro environment exists.
priv struct Parser {
  options : Options
  mut metadata : Metadata
  blocks : Array[Block]
  diagnostics : Array[Diagnostic]
  mut current : Array[Inline]
  mut kind : BlockKind
  mut start_line : Int32
  mut last_line : Int32
  mut font : Font
  mut previous : Font
  mut continues : Bool
  mut indent : Int32
  indent_stack : Array[Int32]
  mut pending_tag : Bool
  mut literal_mode : String
  mut literal_lines : Int32
  mut literal_font : Font
  mut active_link : String?
  mut link_kind : String
  mut link_has_label : Bool
  mut retained : Int32
  mut fatal : Diagnostic?
  mut next_heading : Int32?
  mut one_line_font : Font?
}

///|
fn Parser::new(options : Options) -> Parser {
  {
    options,
    metadata: Metadata::empty(),
    blocks: [],
    diagnostics: [],
    current: [],
    kind: Paragraph,
    start_line: 1,
    last_line: 1,
    font: Roman,
    previous: Roman,
    continues: false,
    indent: 0,
    indent_stack: [],
    pending_tag: false,
    literal_mode: "",
    literal_lines: 0,
    literal_font: Roman,
    active_link: None,
    link_kind: "",
    link_has_label: false,
    retained: 0,
    fatal: None,
    next_heading: None,
    one_line_font: None,
  }
}

///|
fn joined_arguments(args : Array[String]) -> String {
  let out = StringBuilder()
  for i = 0; i < args.length(); i = i + 1 {
    if i > 0 {
      out.write_char(' ')
    }
    out.write_string(args[i])
  }
  out.to_string()
}

///|
fn Parser::warn(
  self : Parser,
  code : String,
  message : String,
  line : Int32,
) -> Unit {
  self.diagnostics.push(diagnostic(code, message, line))
}

///|
fn Parser::flush(self : Parser) -> Unit {
  if self.current.is_empty() {
    match self.kind {
      Tagged(term) if !term.is_empty() => ()
      _ => return
    }
  }
  if self.blocks.length() >= self.options.max_blocks {
    self.fatal = Some(
      diagnostic(
        "block-limit",
        "Document exceeds max_blocks",
        self.start_line,
        severity=Error,
      ),
    )
    return
  }
  self.blocks.push({
    kind: self.kind,
    inlines: self.current,
    indent: self.indent,
    span: {
      line: self.start_line,
      column: 1,
      end_line: self.last_line,
      end_column: 1,
    },
  })
  self.current = []
  self.kind = Paragraph
  self.continues = false
}

///|
fn Parser::begin(self : Parser, kind : BlockKind, line : Int32) -> Unit {
  self.flush()
  self.kind = kind
  self.start_line = line
  self.last_line = line
}

///|
fn Parser::retain(self : Parser, run : Inline, line : Int32) -> Unit {
  self.retained = self.retained + 1
  if self.retained > self.options.max_inlines {
    self.fatal = Some(
      diagnostic(
        "node-limit",
        "Document exceeds max_inlines",
        line,
        severity=Error,
      ),
    )
  } else {
    let linked = match self.active_link {
      Some(target) => {
        self.link_has_label = true
        { ..run, target: Some(target), }
      }
      None => run
    }
    self.current.push(linked)
  }
}

///|
fn Parser::append(
  self : Parser,
  text : String,
  line : Int32,
  join~ : Bool = true,
) -> Unit {
  if self.current.is_empty() {
    self.start_line = line
  }
  self.last_line = line
  let result = decode_inline(
    text,
    line~,
    initial_font=self.font,
    previous_font=self.previous,
    max_chars=self.options.max_line_chars,
  )
  match result {
    Err(d) => self.fatal = Some(d)
    Ok(value) => {
      if !value.inlines.is_empty() &&
        !self.current.is_empty() &&
        join &&
        !self.continues {
        self.retain(Inline::text(" "), line)
      }
      for d in value.diagnostics {
        self.diagnostics.push(d)
      }
      for run in value.inlines {
        self.retain(run, line)
      }
      self.font = value.end_font
      self.previous = value.previous_font
      self.continues = value.continues
    }
  }
}

///|
fn Parser::plain_arg(
  self : Parser,
  args : Array[String],
  index : Int32,
  line : Int32,
) -> String {
  if index >= args.length() {
    return ""
  }
  match
    decode_inline(args[index], line~, max_chars=self.options.max_line_chars) {
    Err(d) => {
      self.fatal = Some(d)
      ""
    }
    Ok(value) => {
      for d in value.diagnostics {
        self.diagnostics.push(d)
      }
      inline_text(value.inlines)
    }
  }
}

///|
fn Parser::core_request(
  self : Parser,
  name : String,
  args : Array[String],
  line : Int32,
) -> Bool {
  match name {
    "TH" => {
      self.flush()
      if args.length() < 2 {
        self.warn("missing-title", "TH requires title and section", line)
      }
      if self.metadata.title != "" {
        self.warn("repeated-title", "A later TH replaces metadata", line)
      }
      self.metadata = {
        title: self.plain_arg(args, 0, line),
        section: self.plain_arg(args, 1, line),
        date: self.plain_arg(args, 2, line),
        source: self.plain_arg(args, 3, line),
        manual: self.plain_arg(args, 4, line),
      }
      true
    }
    "SH" | "SS" => {
      self.flush()
      let level = if name == "SH" { 1 } else { 2 }
      self.font = Roman
      if args.is_empty() {
        self.next_heading = Some(level)
      } else {
        self.begin(Heading(level), line)
        self.append(joined_arguments(args), line)
        self.flush()
      }
      true
    }
    "PP" | "P" | "LP" => {
      self.flush()
      true
    }
    "br" => {
      if !self.current.is_empty() {
        self.retain(Inline::text("\n"), line)
      }
      self.continues = true
      true
    }
    "sp" => {
      self.flush()
      true
    }
    "" => true
    _ => false
  }
}

///|
fn Parser::feed(self : Parser, source : SourceLine) -> Unit {
  let line = source.span.line
  match source.kind {
    Comment => ()
    Blank =>
      if self.literal_mode != "" {
        self.literal_line("", line)
      } else {
        self.flush()
      }
    Text(text) =>
      if self.literal_mode != "" {
        self.literal_line(text, line)
      } else {
        match self.next_heading {
          Some(level) => {
            self.next_heading = None
            self.begin(Heading(level), line)
            self.append(text, line)
            self.flush()
          }
          None => {
            let saved = self.font
            if self.one_line_font is Some(font) {
              self.font = font
            }
            self.append(text, line)
            if self.one_line_font is Some(_) {
              self.font = saved
              self.one_line_font = None
            }
          }
        }
      }
    Request(name, raw) => {
      self.request_boundary(name, line)
      let args = tokenize_arguments(raw, line~)
      for d in args.diagnostics {
        self.diagnostics.push(d)
      }
      if !self.literal_request(name, line) &&
        !self.core_request(name, args.values, line) &&
        !self.font_request(name, args.values, line) &&
        !self.layout_request(name, args.values, line) &&
        !self.link_request(name, args.values, line) &&
        !self.synopsis_request(name, args.values, line) {
        let denied = name == "so" ||
          name == "mso" ||
          name == "sy" ||
          name == "pso" ||
          name == "open" ||
          name == "write" ||
          name == "de" ||
          name == "am"
        let severity = if denied || self.options.unknown_is_error {
          Error
        } else {
          Warning
        }
        let code = if denied { "unsafe-request" } else { "unsupported-request" }
        self.diagnostics.push(
          diagnostic(code, "Request is not evaluated: " + name, line, severity~),
        )
      }
    }
  }
  if self.next_heading is Some(level) {
    if !self.current.is_empty() {
      self.next_heading = None
      self.kind = Heading(level)
      self.flush()
    }
  }
  self.capture_tag()
}

///| Parse a semantic man(7) document. Hard resource failures return Err; recoverable

///|
/// unsupported requests are located in Document.diagnostics.
pub fn parse(
  source : String,
  options~ : Options = Options::default(),
) -> Result[Document, Diagnostic] {
  let lines = match scan(source, options~) {
    Ok(lines) => lines
    Err(d) => return Err(d)
  }
  let parser = Parser::new(options)
  for line in lines {
    if line.span.line == lines.length() &&
      line.kind == Blank &&
      source.has_suffix("\n") {
      break
    }
    parser.feed(line)
    if parser.fatal is Some(d) {
      return Err(d)
    }
  }
  if parser.active_link is Some(_) {
    parser.warn("unclosed-link", "Link has no closing macro", lines.length())
  }
  if parser.literal_mode != "" {
    parser.warn(
      "unclosed-literal",
      "Literal mode is not closed",
      lines.length(),
    )
  }
  if parser.pending_tag {
    parser.warn("missing-tag", "TP has no following tag", lines.length())
  }
  if !parser.indent_stack.is_empty() {
    parser.warn("unclosed-indent", "RS is missing RE", lines.length())
  }
  parser.flush()
  if parser.fatal is Some(d) {
    return Err(d)
  }
  if parser.next_heading is Some(_) {
    parser.warn(
      "missing-heading",
      "Heading macro has no following text",
      lines.length(),
    )
  }
  Ok({
    metadata: parser.metadata,
    blocks: parser.blocks,
    diagnostics: parser.diagnostics,
  })
}