///|
/// An immutable source line shared by an outer language and its embedded
/// readers. Offsets count UTF-16 units. A virtual start hides its prefix from
/// column and indentation, after tabs expand from the physical column zero.
pub struct Line {
  text : String
  start : Int32
  priv offset : Int32
  priv origin_column : Int32
  priv indentation_end : Int32
  priv columns : Columns
}

///|
priv struct Columns {
  text : String
  tab_size : Int32
  mut block_comments : (Int32, Map[Int32, Int32])?
  mut space_run : (Int32, Int32)
  mut searches : Map[(String, Bool), DelimiterHits]?
  mut backslashes : @sorted_map.SortedMap[Int32, Int32]?
  mut scanned : Int32
  // Physical offset after each tab and the extra width accumulated there.
  tabs : Array[(Int32, Int32)]
}

///|
/// Compute a physical column. A clipped or negative offset outside the line
/// has one column per additional code unit, as in an editor StringStream.
fn Columns::at(self : Columns, offset : Int32) -> Int32 {
  let end = offset.clamp(min=0, max=self.text.length())
  let size = if self.tab_size == 0 { 8 } else { self.tab_size }
  let mut extra = self.tabs.last().map(t => t.1).unwrap_or(0)
  if end > self.scanned {
    for i in self.scanned.. t.0.compare(end)) {
      Ok(i) => self.tabs[i].1
      Err(i) => if i == 0 { 0 } else { self.tabs[i - 1].1 }
    }
  }
  offset + extra
}

///|
/// The optional virtual start is a signed UTF-16 offset. Embedding modes
/// can place it outside a short line. Each unit beyond either end has width one.
pub fn Line::new(
  text : String,
  tab_size~ : Int32 = 8,
  start~ : Int32 = 0,
) -> Line {
  let columns : Columns = {
    text,
    tab_size,
    block_comments: None,
    space_run: (0, 0),
    searches: None,
    backslashes: None,
    scanned: 0,
    tabs: [],
  }
  {
    text,
    start,
    offset: 0,
    origin_column: columns.at(start),
    indentation_end: whitespace_end(text, 0),
    columns,
  }
}

///|
/// The visual width of this line's leading ECMAScript whitespace.
pub fn Line::indentation(self : Line) -> Int32 {
  self.columns.at(self.indentation_end) - self.origin_column
}

///|
fn Line::physical_offset(self : Line, offset : Int32) -> Int32 {
  self.offset + offset.clamp(min=-self.offset, max=self.text.length())
}

///|
/// The visual column of a UTF-16 offset. Embedded fragments share the physical
/// tab index, including when an outer mode alternates between virtual origins.
pub fn Line::column(self : Line, offset : Int32) -> Int32 {
  self.columns.at(self.physical_offset(offset)) - self.origin_column
}

///|
/// Read an embedded fragment with local offsets, inherited indentation
/// and the same physical tab stops.
pub fn Line::segment(self : Line, from : Int32, to : Int32) -> Line {
  self.fragment(from, to, None)
}

///|
/// Read an embedded fragment with a virtual start relative to this source.
/// Code units beyond its visible end each have width one.
pub fn Line::segment_with_start(
  self : Line,
  from : Int32,
  to : Int32,
  start : Int32,
) -> Line {
  self.fragment(from, to, Some(start))
}

///|
fn Line::fragment(
  self : Line,
  from : Int32,
  to : Int32,
  start : Int32?,
) -> Line {
  let view = self.text.clamped_view(start=from, end=to)
  let from = view.start_offset()
  let end = self.offset + from + view.length()
  let (origin, indent_end) = match start {
    None => {
      let limit = end - self.offset
      let origin = if self.start > limit {
        self.columns.at(end) + (self.start - limit)
      } else {
        self.origin_column
      }
      (origin, self.indentation_end.min(end))
    }
    Some(start) => {
      let limit = end - self.offset
      let origin = if start <= limit {
        self.columns.at(self.offset + start)
      } else {
        self.columns.at(end) + (start - limit)
      }
      (origin, self.indentation_end.min(end))
    }
  }
  {
    text: if from == 0 && view.length() == self.text.length() {
      self.text
    } else {
      view.to_owned()
    },
    start: start.unwrap_or(self.start).max(@int.MIN_VALUE + from) - from,
    offset: self.offset + from,
    origin_column: origin,
    indentation_end: indent_end,
    columns: self.columns,
  }
}

///|
/// Offset of the physical line's first non-whitespace code unit, relative to
/// this segment. A negative value places it before the embedded fragment.
pub fn Line::whitespace_end(self : Line) -> Int32 {
  self.indentation_end - self.offset
}

///|
/// A view of this fragment backed by the physical line. Its start offset
/// and backing text support lookbehind without allocating a prefix.
pub fn Line::physical_view(self : Line) -> StringView {
  self.columns.text.unsafe_view(
    start=self.offset,
    end=self.offset + self.text.length(),
  )
}

///|
/// Find a nonempty literal at or after a UTF-16 offset, within this fragment.
/// Embedded readers of one physical line share forward delimiter searches.
/// Set shared=false for a progressive reader restricted to its current segment.
pub fn Line::find_literal(
  self : Line,
  needle : String,
  from : Int32,
  shared~ : Bool = true,
) -> Int32? {
  if shared {
    return self.cached_find(needle, from, false)
  }
  guard !needle.is_empty() && from >= 0 && from <= self.text.length() else {
    return None
  }
  self.text
  .unsafe_view(start=from, end=self.text.length())
  .find(needle[:])
  .map(i => from + i)
}

///|
// An entry covers candidate starts [first, end). Its last candidate can be
// a hit; all earlier candidates in the interval are known misses.
priv struct CheckedStarts {
  first : Int32
  last_matches : Bool
}

///|
type DelimiterHits = @sorted_map.SortedMap[Int32, CheckedStarts]

///|
fn Line::cached_find(
  self : Line,
  needle : String,
  from : Int32,
  unescaped : Bool,
) -> Int32? {
  let width = needle.length()
  guard width > 0 && from >= 0 && from <= self.text.length() - width else {
    return None
  }
  let physical = self.columns
  let searches = match physical.searches {
    Some(cached) => cached
    None => {
      let table = Map([])
      physical.searches = Some(table)
      table
    }
  }
  let start = self.offset + from
  let limit = self.offset + (self.text.length() - width + 1)
  let ranges = searches.get_or_init((needle, unescaped), () => {
    @sorted_map.SortedMap([])
  })
  // Adjacent fragments can each test just one new start. Extend the previous
  // miss immediately so these sequential calls retain a single interval.
  let mut first = match ranges.get(start) {
    Some(previous) if !previous.last_matches => {
      ranges.remove(start)
      previous.first
    }
    _ => start
  }
  for pos = start {
    let next = ranges.first_gt(pos)
    let stop = next.map(entry => entry.1.first).unwrap_or(limit).min(limit)
    if pos < stop {
      // Include the tail of a needle starting at stop - 1. Its last unit is
      // inside this fragment, even when a different view established 'next'.
      let hit = next_occurrence(
        physical.text,
        needle,
        pos,
        stop + (width - 1),
        i => unescaped && escaped_at(physical.text, start, i),
      )
      if hit is Some(i) {
        ranges[i + 1] = { first, last_matches: true, }
        return Some(i - self.offset)
      }
    }
    match next {
      Some((end, checked)) if checked.first <= limit => {
        first = first.min(checked.first)
        if checked.last_matches || end >= limit {
          if first < checked.first {
            ranges[end] = { ..checked, first, }
          }
          return if checked.last_matches && end <= limit {
            Some(end - 1 - self.offset)
          } else {
            None
          }
        }
        // Join this known miss to the new interval as we continue forward.
        ranges.remove(end)
        continue end
      }
      _ => {
        ranges[limit] = { first, last_matches: false, }
        return None
      }
    }
  }
}

///|
// Find the contiguous backslashes touching a cursor within [lo, hi). A
// forward query needs only the part after its origin, and a trailing-parity
// query needs only the part before the visible end. Join observed intervals
// when a later lookup reaches them from either direction.
fn Columns::backslash_run(
  self : Columns,
  lo : Int32,
  pos : Int32,
  hi : Int32,
) -> (Int32, Int32) {
  guard (pos > lo && self.text[pos - 1] == '\\') ||
    (pos < hi && self.text[pos] == '\\') else {
    return (pos, pos)
  }
  let runs = match self.backslashes {
    Some(known) => known
    None => {
      let runs = @sorted_map.SortedMap([])
      self.backslashes = Some(runs)
      runs
    }
  }
  let known = match runs.first_ge(pos) {
    Some((end, start)) if start <= pos => (start, end)
    _ => (pos, pos)
  }
  let mut start = known.0
  let mut end = known.1
  if start <= lo && end >= hi {
    return (lo, hi)
  }
  while start > lo {
    let prev = runs.last_le(start)
    let bound = prev.map(r => r.0).unwrap_or(lo).max(lo)
    while start > bound && self.text[start - 1] == '\\' {
      start -= 1
    }
    guard prev is Some((right, left)) && start == right else { break }
    runs.remove(right)
    start = left
  }
  while end < hi {
    let next = runs.first_gt(end)
    let bound = next.map(r => r.1).unwrap_or(hi).min(hi)
    while end < bound && self.text[end] == '\\' {
      end += 1
    }
    guard next is Some((right, left)) && end == left else { break }
    runs.remove(right)
    end = right
  }
  if end != known.1 {
    runs.remove(known.1)
  }
  runs[end] = start
  (start.max(lo), end.min(hi))
}

///|
fn escaped_at(line : String, from : Int32, pos : Int32) -> Bool {
  let mut i = pos
  while i > from && line[i - 1] == '\\' {
    i -= 1
  }
  (pos - i) % 2 == 1
}

///|
fn next_occurrence(
  line : String,
  needle : String,
  pos : Int32,
  limit : Int32,
  escaped : (Int32) -> Bool,
) -> Int32? {
  for i = pos; i < limit; {
    guard line.unsafe_view(start=i, end=limit).find(needle[:]) is Some(delta) else {
      return None
    }
    let hit = i + delta
    if !escaped(hit) {
      return Some(hit)
    }
    continue hit + 1
  }
  None
}

///|
/// Find the first literal closer that follows an even number of backslashes.
/// When there is no closer, the boolean reports an unmatched final backslash.
pub fn closing_delimiter(
  line : String,
  needle : String,
  from : Int32,
) -> (Int32?, Bool) {
  guard !needle.is_empty() && from >= 0 && from <= line.length() else {
    return (None, false)
  }
  let hit = next_occurrence(line, needle, from, line.length(), i => {
    escaped_at(line, from, i)
  })
  (hit, hit is None && escaped_at(line, from, line.length()))
}

///|
/// Share closing-delimiter searches across embedded readers on an immutable
/// line. Escape parity starts at the caller's offset, including inside a run.
pub fn Line::closing_delimiter(
  self : Line,
  needle : String,
  from : Int32,
  shared~ : Bool = true,
) -> (Int32?, Bool) {
  let text = self.text
  guard !needle.is_empty() && from >= 0 && from <= text.length() else {
    return (None, false)
  }
  if !shared || needle[0] == '\\' {
    return closing_delimiter(text, needle, from)
  }
  let start = self.offset + from
  let end = self.offset + text.length()
  if from <= text.length() - needle.length() {
    // Only the first non-backslash can have different local and physical
    // escape parity. Inspect it from this query’s origin, then share the rest.
    let (_, after) = self.columns.backslash_run(start, start, end)
    if after == end {
      return (None, (end - start) % 2 == 1)
    }
    let at = after - self.offset
    if (after - start) % 2 == 0 &&
      at <= text.length() - needle.length() &&
      text.unsafe_range_equal(
        start=at,
        needle,
        other_start=0,
        len=needle.length(),
      ) {
      return (Some(at), false)
    }
    if self.cached_find(needle, at + 1, true) is Some(hit) {
      return (Some(hit), false)
    }
  }
  let (run_start, _) = self.columns.backslash_run(start, end, end)
  (None, (end - run_start) % 2 == 1)
}

///|
/// Start of the physical whitespace run immediately before this offset, relative
/// to the visible fragment. A negative result lies in the enclosing prefix.
pub fn Line::whitespace_start(self : Line, at : Int32) -> Int32 {
  let physical = self.columns
  let end = self.physical_offset(at)
  let (lo, hi) = physical.space_run
  if lo <= end && end <= hi {
    return lo - self.offset
  }
  let mut i = end
  while i > 0 && is_space(physical.text[i - 1]) {
    if i == hi {
      i = lo
      break
    }
    i -= 1
  }
  physical.space_run = (i, end)
  i - self.offset
}

///|
/// The caller-supplied tab size, including zero, passed to embedded readers.
pub fn Line::tab_size(self : Line) -> Int32 {
  self.columns.tab_size
}