use alloc::{
borrow::Cow,
boxed::Box,
collections::{BTreeMap, BTreeSet},
vec::Vec,
};
use core::{fmt, ops::Range};
use crate::{
BareKeys, Diagnostic, DiagnosticCode, Dialect, Duplicates, EditError, LineIndex, PositionError,
QuotedTail,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Quote {
None,
Single,
Double,
Backtick,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AssignmentState {
Bare,
Empty,
Value,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LineEnding {
None,
Lf,
CrLf,
Cr,
}
impl LineEnding {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::None => "",
Self::Lf => "\n",
Self::CrLf => "\r\n",
Self::Cr => "\r",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ItemKind {
Blank,
Comment,
Entry,
Invalid,
Ignored,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct EntryTokens {
pub indent: Range<usize>,
pub export: Option<Range<usize>>,
pub space_after_export: Range<usize>,
pub key: Range<usize>,
pub space_before_eq: Range<usize>,
pub eq: Option<Range<usize>>,
pub space_after_eq: Range<usize>,
pub value: Option<Range<usize>>,
pub body: Option<Range<usize>>,
pub quoted_tail: Option<Range<usize>>,
pub trailing_space: Range<usize>,
pub inline_comment: Option<Range<usize>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DecodeSegment {
pub decoded: Range<usize>,
pub raw: Range<usize>,
}
pub(crate) const NO_ENTRY: usize = usize::MAX;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct EntryData {
pub item: usize,
pub line: usize,
pub tokens: EntryTokens,
pub quote: Quote,
pub state: AssignmentState,
pub key_quoted: bool,
pub participates: bool,
pub decoded: Option<Box<str>>,
pub map: Option<Box<[DecodeSegment]>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ItemData {
pub kind: ItemKind,
pub span: Range<usize>,
pub ending: LineEnding,
pub entry: usize,
pub comment: Option<Range<usize>>,
pub invalid: Option<Box<Diagnostic>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Document<'src> {
pub(crate) source: Cow<'src, str>,
pub(crate) items: Vec<ItemData>,
pub(crate) entries: Vec<EntryData>,
pub(crate) bom_len: usize,
pub(crate) dialect: Dialect,
pub(crate) has_duplicate_keys: bool,
}
impl Document<'_> {
#[must_use]
pub fn source(&self) -> &str {
&self.source
}
#[must_use]
pub const fn dialect(&self) -> Dialect {
self.dialect
}
#[must_use]
pub fn reparse(&self, dialect: Dialect) -> (Document<'_>, Vec<Diagnostic>) {
crate::parse_with(self.source(), dialect)
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub fn items(&self) -> impl DoubleEndedIterator<Item = Item<'_>> + ExactSizeIterator {
(0..self.items.len()).map(|index| Item {
document: self,
index,
})
}
#[must_use]
pub fn item(&self, index: usize) -> Option<Item<'_>> {
(index < self.items.len()).then_some(Item {
document: self,
index,
})
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub fn entries(&self) -> impl DoubleEndedIterator<Item = Entry<'_>> + ExactSizeIterator {
(0..self.entries.len()).map(|index| Entry {
document: self,
index,
})
}
#[must_use]
pub fn entry(&self, index: usize) -> Option<Entry<'_>> {
(index < self.entries.len()).then_some(Entry {
document: self,
index,
})
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub fn get_all<'doc, 'key>(
&'doc self,
key: &'key str,
) -> impl DoubleEndedIterator<Item = Entry<'doc>> + 'key
where
'doc: 'key,
{
self.entries().filter(move |entry| entry.key() == key)
}
#[must_use]
pub fn get_entry(&self, key: &str) -> Option<Entry<'_>> {
let mut entries = self
.entries()
.filter(|entry| entry.participates_in_lookup() && entry.key() == key);
match self.dialect.duplicates {
Duplicates::First => entries.next(),
Duplicates::Last => entries.next_back(),
}
}
#[must_use]
pub fn get(&self, key: &str) -> Option<&str> {
self.get_entry(key).and_then(|entry| {
entry.value().or_else(|| {
(entry.state() == AssignmentState::Bare
&& self.dialect.bare_keys == BareKeys::Empty)
.then_some("")
})
})
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub fn effective_entries(&self) -> impl Iterator<Item = EffectiveEntry<'_>> {
let mut effective = Vec::new();
if self.has_duplicate_keys {
let mut seen = BTreeSet::new();
let indices: alloc::boxed::Box<dyn Iterator<Item = usize>> =
match self.dialect.duplicates {
Duplicates::First => alloc::boxed::Box::new(0..self.entries.len()),
Duplicates::Last => alloc::boxed::Box::new((0..self.entries.len()).rev()),
};
for index in indices {
let Some(entry) = self.entry(index) else {
continue;
};
let key = entry.key();
if !entry.participates_in_lookup() || key.is_empty() || !seen.insert(key) {
continue;
}
let value = entry.value().or_else(|| {
(entry.state() == AssignmentState::Bare
&& self.dialect.bare_keys == BareKeys::Empty)
.then_some("")
});
if let Some(value) = value {
effective.push((index, EffectiveEntry { entry, value }));
}
}
effective.sort_unstable_by_key(|(index, _)| *index);
} else {
for index in 0..self.entries.len() {
let Some(entry) = self.entry(index) else {
continue;
};
if !entry.participates_in_lookup() || entry.key().is_empty() {
continue;
}
let value = entry.value().or_else(|| {
(entry.state() == AssignmentState::Bare
&& self.dialect.bare_keys == BareKeys::Empty)
.then_some("")
});
if let Some(value) = value {
effective.push((index, EffectiveEntry { entry, value }));
}
}
}
effective.into_iter().map(|(_, entry)| entry)
}
#[must_use]
pub fn lookup_index(&self) -> LookupIndex<'_> {
let (winners, non_participating) = Winners::build(self, self.dialect.duplicates);
LookupIndex {
document: self,
winners,
non_participating,
}
}
#[cfg(test)]
pub(crate) fn lookup_index_with_probe_limit(&self, probe_limit: usize) -> LookupIndex<'_> {
let (winners, non_participating) =
Winners::build_with_limit(self, self.dialect.duplicates, probe_limit);
LookupIndex {
document: self,
winners,
non_participating,
}
}
pub fn unique(&self, key: &str) -> Result<Entry<'_>, EditError> {
let mut entries = self.entries().filter(|entry| entry.key() == key);
let first = entries.next().ok_or(EditError::Missing)?;
let remaining = entries.count();
if remaining == 0 {
Ok(first)
} else {
Err(EditError::Duplicate(remaining + 1))
}
}
#[must_use]
pub const fn has_bom(&self) -> bool {
self.bom_len > 0
}
#[must_use]
pub fn bom_span(&self) -> Option<Range<usize>> {
(self.bom_len > 0).then_some(0..self.bom_len)
}
#[must_use]
pub fn has_final_newline(&self) -> bool {
self.source.ends_with(['\n', '\r'])
}
#[must_use]
pub fn line_index(&self) -> LineIndex<'_> {
LineIndex::new(self.source())
}
#[must_use]
pub fn into_owned(self) -> Document<'static> {
Document {
source: Cow::Owned(self.source.into_owned()),
items: self.items,
entries: self.entries,
bom_len: self.bom_len,
dialect: self.dialect,
has_duplicate_keys: self.has_duplicate_keys,
}
}
pub(crate) fn preferred_ending(&self) -> &'static str {
let mut counts = [0usize; 3];
let bytes = self.source.as_bytes();
let mut at = 0;
while at < bytes.len() {
match bytes[at] {
b'\r' if bytes.get(at + 1) == Some(&b'\n') => {
counts[1] += 1;
at += 1;
}
b'\r' if self.dialect.line_breaks == crate::LineBreaks::Universal => counts[2] += 1,
b'\n' => counts[0] += 1,
_ => {}
}
at += 1;
}
if counts[1] > counts[0] && counts[1] >= counts[2] {
"\r\n"
} else if self.dialect.line_breaks == crate::LineBreaks::Universal
&& counts[2] > counts[0]
&& counts[2] > counts[1]
{
"\r"
} else {
"\n"
}
}
}
impl fmt::Display for Document<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.source())
}
}
#[derive(Debug, Clone, Copy)]
pub struct Entry<'doc> {
pub(crate) document: &'doc Document<'doc>,
pub(crate) index: usize,
}
#[derive(Debug, Clone)]
pub struct LookupIndex<'doc> {
document: &'doc Document<'doc>,
winners: Winners<'doc>,
non_participating: Option<BTreeMap<&'doc str, (usize, usize)>>,
}
#[cfg(test)]
impl LookupIndex<'_> {
pub(crate) fn hash_slots(&self) -> Option<usize> {
match &self.winners {
Winners::Hash(winners) => Some(winners.slots.len()),
Winners::Tree(_) => None,
}
}
}
type NonParticipating<'doc> = Option<BTreeMap<&'doc str, (usize, usize)>>;
#[derive(Debug, Clone)]
enum Winners<'doc> {
Hash(HashWinners<'doc>),
Tree(BTreeMap<&'doc str, (usize, usize)>),
}
impl<'doc> Winners<'doc> {
fn build(document: &'doc Document<'doc>, policy: Duplicates) -> (Self, NonParticipating<'doc>) {
let entries = document.entries().len();
let probe_limit = entries.saturating_mul(4).max(64);
Self::build_with_limit(document, policy, probe_limit)
}
fn build_with_limit(
document: &'doc Document<'doc>,
policy: Duplicates,
probe_limit: usize,
) -> (Self, NonParticipating<'doc>) {
if probe_limit == 0 {
let (tree, non_participating) = tree_winners(document, policy);
return (Self::Tree(tree), non_participating);
}
if let Some((hash, non_participating)) = HashWinners::build(document, policy, probe_limit) {
(Self::Hash(hash), non_participating)
} else {
let (tree, non_participating) = tree_winners(document, policy);
(Self::Tree(tree), non_participating)
}
}
fn get(&self, key: &str) -> Option<usize> {
self.get_with_count(key).map(|(index, _)| index)
}
fn get_with_count(&self, key: &str) -> Option<(usize, usize)> {
match self {
Self::Hash(winners) => winners.get_with_count(key),
Self::Tree(winners) => winners.get(key).copied(),
}
}
fn len(&self) -> usize {
match self {
Self::Hash(winners) => winners.len,
Self::Tree(winners) => winners.len(),
}
}
fn is_empty(&self) -> bool {
self.len() == 0
}
}
fn record_non_participating<'doc>(
non_participating: &mut NonParticipating<'doc>,
key: &'doc str,
index: usize,
) {
let map = non_participating.get_or_insert_with(BTreeMap::new);
let slot = map.entry(key).or_insert((index, 0));
slot.1 += 1;
}
#[derive(Debug, Clone, Copy)]
struct HashSlot<'doc> {
key: &'doc str,
index: usize,
count: usize,
}
#[derive(Debug, Clone)]
struct HashWinners<'doc> {
slots: Vec<Option<HashSlot<'doc>>>,
len: usize,
}
impl<'doc> HashWinners<'doc> {
fn build(
document: &'doc Document<'doc>,
policy: Duplicates,
probe_limit: usize,
) -> Option<(Self, NonParticipating<'doc>)> {
let mut slots = alloc::vec![None; 8];
let mut len: usize = 0;
let mut probes = 0;
let mut non_participating = None;
for entry in document.entries() {
let key = entry.key();
if !entry.participates_in_lookup() || key.is_empty() {
record_non_participating(&mut non_participating, key, entry.id());
continue;
}
if len.saturating_add(1) > slots.len().saturating_mul(3) / 4 {
let capacity = slots.len().checked_mul(2)?;
slots = rehash(slots, capacity);
}
let mask = slots.len() - 1;
let mut at = hash_key(key) & mask;
loop {
match slots[at] {
None => {
slots[at] = Some(HashSlot {
key,
index: entry.id(),
count: 1,
});
len += 1;
break;
}
Some(mut slot) if slot.key == key => {
slot.count += 1;
if policy == Duplicates::Last {
slot.index = entry.id();
}
slots[at] = Some(slot);
break;
}
Some(_) => {
probes += 1;
if probes > probe_limit {
return None;
}
at = (at + 1) & mask;
}
}
}
}
Some((Self { slots, len }, non_participating))
}
fn get_with_count(&self, key: &str) -> Option<(usize, usize)> {
let mask = self.slots.len() - 1;
let mut at = hash_key(key) & mask;
loop {
match self.slots[at] {
None => return None,
Some(slot) if slot.key == key => return Some((slot.index, slot.count)),
Some(_) => at = (at + 1) & mask,
}
}
}
}
fn rehash(slots: Vec<Option<HashSlot<'_>>>, capacity: usize) -> Vec<Option<HashSlot<'_>>> {
let mask = capacity - 1;
let mut grown = alloc::vec![None; capacity];
for slot in slots.into_iter().flatten() {
let mut at = hash_key(slot.key) & mask;
while grown[at].is_some() {
at = (at + 1) & mask;
}
grown[at] = Some(slot);
}
grown
}
fn tree_winners<'doc>(
document: &'doc Document<'doc>,
policy: Duplicates,
) -> (BTreeMap<&'doc str, (usize, usize)>, NonParticipating<'doc>) {
let mut winners: BTreeMap<&'doc str, (usize, usize)> = BTreeMap::new();
let mut non_participating = None;
for (index, entry) in document.entries().enumerate() {
let key = entry.key();
if !entry.participates_in_lookup() || key.is_empty() {
record_non_participating(&mut non_participating, key, index);
continue;
}
let slot = winners.entry(key).or_insert((index, 0));
if slot.1 > 0 && policy == Duplicates::Last {
slot.0 = index;
}
slot.1 += 1;
}
(winners, non_participating)
}
#[allow(clippy::cast_possible_truncation)]
fn hash_key(key: &str) -> usize {
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
for byte in key.as_bytes() {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
hash as usize
}
impl<'doc> LookupIndex<'doc> {
#[must_use]
pub fn get_entry(&self, key: &str) -> Option<Entry<'doc>> {
self.winners
.get(key)
.and_then(|index| self.document.entry(index))
}
#[must_use]
pub fn get(&self, key: &str) -> Option<&'doc str> {
self.get_entry(key).and_then(|entry| {
entry.value().or_else(|| {
(entry.state() == AssignmentState::Bare
&& self.document.dialect().bare_keys == BareKeys::Empty)
.then_some("")
})
})
}
pub fn unique(&self, key: &str) -> Result<Entry<'doc>, EditError> {
let participating = if key.is_empty() {
None
} else {
self.winners.get_with_count(key)
};
let non_participating = self
.non_participating
.as_ref()
.and_then(|map| map.get(key).copied());
match (participating, non_participating) {
(None, None) => Err(EditError::Missing),
(Some((index, 1)), None) | (None, Some((index, 1))) => {
self.document.entry(index).ok_or(EditError::Missing)
}
(Some((_, a)), Some((_, b))) => Err(EditError::Duplicate(a + b)),
(Some((_, count)), None) | (None, Some((_, count))) => Err(EditError::Duplicate(count)),
}
}
#[must_use]
pub fn len(&self) -> usize {
self.winners.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.winners.is_empty()
}
}
#[derive(Debug, Clone, Copy)]
pub struct EffectiveEntry<'doc> {
entry: Entry<'doc>,
value: &'doc str,
}
impl<'doc> EffectiveEntry<'doc> {
#[must_use]
pub const fn entry(self) -> Entry<'doc> {
self.entry
}
#[must_use]
pub fn key(self) -> &'doc str {
self.entry.key()
}
#[must_use]
pub const fn value(self) -> &'doc str {
self.value
}
#[must_use]
pub fn line(self) -> usize {
self.entry.line()
}
}
impl<'doc> Entry<'doc> {
fn data(self) -> &'doc EntryData {
&self.document.entries[self.index]
}
#[must_use]
pub const fn id(self) -> usize {
self.index
}
#[must_use]
pub fn item_id(self) -> usize {
self.data().item
}
#[must_use]
pub fn key(self) -> &'doc str {
&self.document.source[self.key_span()]
}
#[must_use]
pub fn value(self) -> Option<&'doc str> {
let data = self.data();
data.tokens.body.as_ref().map(|body| {
data.decoded
.as_deref()
.unwrap_or(&self.document.source[body.clone()])
})
}
#[must_use]
pub fn raw_value(self) -> Option<&'doc str> {
self.value_span().map(|span| &self.document.source[span])
}
#[must_use]
pub fn participates_in_lookup(self) -> bool {
self.data().participates
}
#[must_use]
pub fn quote(self) -> Quote {
self.data().quote
}
#[must_use]
pub fn exported(self) -> bool {
self.data().tokens.export.is_some()
}
#[must_use]
pub fn state(self) -> AssignmentState {
self.data().state
}
#[must_use]
pub fn line(self) -> usize {
self.data().line
}
#[must_use]
pub fn line_span(self) -> Range<usize> {
self.document.items[self.item_id()].span.clone()
}
#[must_use]
pub fn key_span(self) -> Range<usize> {
let range = self.data().tokens.key.clone();
if self.data().key_quoted {
range.start + 1..range.end - 1
} else {
range
}
}
#[must_use]
pub fn value_span(self) -> Option<Range<usize>> {
self.data().tokens.value.as_ref().map(|range| {
range.start..if self.document.dialect.quoted_tail == QuotedTail::Append {
self.data()
.tokens
.quoted_tail
.as_ref()
.map_or(range.end, |tail| tail.end)
} else {
range.end
}
})
}
#[must_use]
pub fn tokens(self) -> &'doc EntryTokens {
&self.data().tokens
}
#[must_use]
pub fn inline_comment(self) -> Option<&'doc str> {
self.data()
.tokens
.inline_comment
.as_ref()
.map(|span| &self.document.source[span.clone()])
}
pub fn decoded_offset_to_raw(self, offset: usize) -> Result<usize, PositionError> {
let value = self.value().ok_or(PositionError::OutOfBounds)?;
if offset > value.len() {
return Err(PositionError::OutOfBounds);
}
if !value.is_char_boundary(offset) {
return Err(PositionError::InvalidUtf8Boundary);
}
let data = self.data();
let body = data
.tokens
.body
.as_ref()
.ok_or(PositionError::OutOfBounds)?;
let segments = data.map.as_deref().unwrap_or(&[]);
let count = segments.partition_point(|segment| segment.decoded.start <= offset);
let Some(index) = count.checked_sub(1) else {
return Ok(body.start + offset);
};
let segment = &segments[index];
if offset == segment.decoded.start {
return Ok(segment.raw.start);
}
if offset < segment.decoded.end {
return Err(PositionError::InvalidUtf8Boundary);
}
Ok(segment.raw.end + offset - segment.decoded.end)
}
pub fn decoded_span_to_raw(self, span: Range<usize>) -> Result<Range<usize>, PositionError> {
if span.start > span.end {
return Err(PositionError::OutOfBounds);
}
Ok(self.decoded_offset_to_raw(span.start)?..self.decoded_offset_to_raw(span.end)?)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Item<'doc> {
pub(crate) document: &'doc Document<'doc>,
pub(crate) index: usize,
}
impl<'doc> Item<'doc> {
fn data(self) -> &'doc ItemData {
&self.document.items[self.index]
}
#[must_use]
pub const fn id(self) -> usize {
self.index
}
#[must_use]
pub fn kind(self) -> ItemKind {
self.data().kind
}
#[must_use]
pub fn span(self) -> Range<usize> {
self.data().span.clone()
}
#[must_use]
pub fn raw(self) -> &'doc str {
&self.document.source[self.span()]
}
#[must_use]
pub fn line_ending(self) -> LineEnding {
self.data().ending
}
#[must_use]
pub fn content_span(self) -> Range<usize> {
let span = self.span();
span.start..span.end - self.line_ending().as_str().len()
}
#[must_use]
pub fn entry(self) -> Option<Entry<'doc>> {
let index = self.data().entry;
(index != NO_ENTRY).then_some(Entry {
document: self.document,
index,
})
}
#[must_use]
pub fn comment_text(self) -> Option<&'doc str> {
self.data()
.comment
.as_ref()
.map(|span| &self.document.source[span.clone()])
}
#[must_use]
pub fn diagnostic(self) -> Option<&'doc Diagnostic> {
self.data().invalid.as_deref()
}
#[must_use]
pub fn invalid_code(self) -> Option<DiagnosticCode> {
self.diagnostic().map(Diagnostic::code)
}
}