///|
pub(all) struct DocumentStats {
  blocks : Int32
  sections : Int32
  definitions : Int32
  literal_blocks : Int32
  inline_runs : Int32
  visible_chars : Int32
  words : Int32
  link_spans : Int32
  unsafe_link_spans : Int32
  manual_references : Int32
  warnings : Int32
  errors : Int32
} derive(Eq, Debug)

///|
pub extend DocumentStats with Eq::{equal, not_equal}

///|
pub extend DocumentStats with @debug.Debug::{to_repr}

///|
/// Count bounded visible AST content, including definition terms, excluding metadata.
/// Words are whitespace-separated runs, not a language-specific tokenizer.
pub fn statistics(doc : Document) -> Result[DocumentStats, Diagnostic] {
  if validate_document(doc) is Err(d) {
    return Err(d)
  }
  let mut sections = 0
  let mut definitions = 0
  let mut literals = 0
  let mut runs = 0
  let mut chars = 0
  let mut words = 0
  for block in doc.blocks {
    let groups = match block.kind {
      Tagged(term) => {
        definitions = definitions + 1
        [term, block.inlines]
      }
      Heading(_) => {
        sections = sections + 1
        [block.inlines]
      }
      Literal => {
        literals = literals + 1
        [block.inlines]
      }
      _ => [block.inlines]
    }
    for group in groups {
      let mut inside_word = false
      for run in group {
        runs = runs + 1
        for c in run.text.iter() {
          chars = chars + 1
          if c.is_whitespace() {
            inside_word = false
          } else if !inside_word {
            words = words + 1
            inside_word = true
          }
        }
      }
    }
  }
  let targets = links(doc)
  let mut unsafe_links = 0
  for link in targets {
    if !link.safe {
      unsafe_links = unsafe_links + 1
    }
  }
  let mut warnings = 0
  let mut errors = 0
  for d in doc.diagnostics {
    match d.severity {
      Warning => warnings = warnings + 1
      Error => errors = errors + 1
    }
  }
  Ok({
    blocks: doc.blocks.length(),
    sections,
    definitions,
    literal_blocks: literals,
    inline_runs: runs,
    visible_chars: chars,
    words,
    link_spans: targets.length(),
    unsafe_link_spans: unsafe_links,
    manual_references: references(doc).length(),
    warnings,
    errors,
  })
}