Skip to main content

dprint_core/formatting/
print_items.rs

1use std::cell::UnsafeCell;
2use std::mem;
3
4use super::Arena;
5use super::condition_resolvers;
6use super::printer::Printer;
7use super::thread_state;
8
9/// A list of print items allocated in an [`Arena`].
10pub struct PrintItems<'a> {
11  arena: &'a Arena,
12  pub(super) first_node: Option<PrintItemPath<'a>>,
13  last_node: Option<PrintItemPath<'a>>,
14}
15
16impl<'a> PrintItems<'a> {
17  pub fn new(arena: &'a Arena) -> Self {
18    Self {
19      arena,
20      first_node: None,
21      last_node: None,
22    }
23  }
24
25  /// Gets the arena the print items are allocated in.
26  #[inline]
27  pub fn arena(&self) -> &'a Arena {
28    self.arena
29  }
30
31  pub fn into_rc_path(self) -> Option<PrintItemPath<'a>> {
32    self.first_node
33  }
34
35  pub fn push_item(&mut self, item: PrintItem<'a>) {
36    self.push_item_internal(item);
37  }
38
39  #[inline]
40  fn push_item_internal(&mut self, item: PrintItem<'a>) {
41    let node = self.arena.alloc_print_node_cell(PrintNodeCell::new(item));
42    if let Some(first_node) = &self.first_node {
43      let new_last_node = node.get_last_next().unwrap_or(node);
44      self.last_node.as_ref().unwrap_or(first_node).set_next(Some(node));
45      self.last_node = Some(new_last_node);
46    } else {
47      self.last_node = node.get_last_next();
48      self.first_node = Some(node);
49    }
50  }
51
52  pub fn extend(&mut self, items: PrintItems<'a>) {
53    if let Some(first_node) = items.first_node {
54      if let Some(current_first_node) = &self.first_node {
55        self.last_node.as_ref().unwrap_or(current_first_node).set_next(Some(first_node));
56
57        if items.last_node.is_some() {
58          self.last_node = items.last_node;
59        } else if items.first_node.is_some() {
60          self.last_node = items.first_node;
61        }
62      } else {
63        self.first_node = items.first_node;
64        self.last_node = items.last_node;
65      }
66    }
67  }
68
69  /// Pushes a string that will have its width computed at runtime.
70  ///
71  /// The string isn't copied, so this can be used for text that lives at least
72  /// as long as the arena, such as the text of the file being formatted.
73  ///
74  /// Instead of using this, prefer to use `push_sc` where possible
75  /// with the `sc!` macro from the dprint-core-macros crate.
76  pub fn push_str_runtime_width_computed(&mut self, item: &'a str) {
77    let string_container = self.arena.alloc_string_container(item);
78    self.push_item_internal(PrintItem::String(string_container));
79  }
80
81  pub fn push_force_current_line_indentation(&mut self) {
82    const STR_EMPTY: StringContainer = StringContainer { text: "", char_count: 0 };
83    self.push_item_internal(PrintItem::String(&STR_EMPTY))
84  }
85
86  pub fn push_space(&mut self) {
87    const STR_SPACE: StringContainer = StringContainer { text: " ", char_count: 1 };
88    self.push_item_internal(PrintItem::String(&STR_SPACE))
89  }
90
91  /// Pushes a string that's had its width computed at compile time.
92  pub fn push_sc(&mut self, item: &'a StringContainer<'a>) {
93    self.push_item_internal(PrintItem::String(item))
94  }
95
96  /// Pushes a string, copying it into the arena.
97  pub fn push_string(&mut self, item: String) {
98    self.push_str(&item);
99  }
100
101  /// Pushes a borrowed string, copying it into the arena, and computes its width at
102  /// runtime.
103  ///
104  /// Prefer `push_sc` with the `sc!` macro for text known at compile time, and
105  /// `push_str_runtime_width_computed` for text that lives as long as the arena, since
106  /// neither copies. Use this for other text the caller doesn't own: it avoids building
107  /// a `String` only for it to be copied and thrown away.
108  pub fn push_str(&mut self, item: &str) {
109    let string_container = self.arena.alloc_str(item);
110    self.push_item_internal(PrintItem::String(string_container));
111  }
112
113  pub fn push_condition(&mut self, condition: Condition<'a>) {
114    let condition = self.arena.alloc_condition(condition);
115    self.push_item_internal(PrintItem::Condition(condition));
116  }
117
118  pub fn push_info(&mut self, info: impl Into<Info>) {
119    self.push_item_internal(PrintItem::Info(info.into()));
120  }
121
122  pub fn push_line_and_column(&mut self, line_and_col: LineAndColumn) {
123    self.push_info(line_and_col.line);
124    self.push_info(line_and_col.column);
125  }
126
127  pub fn push_anchor(&mut self, anchor: impl Into<Anchor>) {
128    self.push_item_internal(PrintItem::Anchor(anchor.into()));
129  }
130
131  pub fn push_reevaluation(&mut self, condition_reevaluation: ConditionReevaluation) {
132    self.push_item_internal(PrintItem::ConditionReevaluation(condition_reevaluation));
133  }
134
135  pub fn push_signal(&mut self, signal: Signal) {
136    self.push_item_internal(PrintItem::Signal(signal));
137  }
138
139  pub fn push_path(&mut self, path: PrintItemPath<'a>) {
140    self.push_item_internal(PrintItem::RcPath(path))
141  }
142
143  pub fn push_optional_path(&mut self, path: Option<PrintItemPath<'a>>) {
144    if let Some(path) = path {
145      self.push_path(path);
146    }
147  }
148
149  pub fn is_empty(&self) -> bool {
150    self.first_node.is_none()
151  }
152
153  // todo: clean this up
154  #[cfg(debug_assertions)]
155  pub fn get_as_text(&self) -> String {
156    return if let Some(first_node) = &self.first_node {
157      get_items_as_text(first_node, String::from(""))
158    } else {
159      String::new()
160    };
161
162    fn get_items_as_text(items: PrintItemPath, indent_text: String) -> String {
163      let mut text = String::new();
164      for item in PrintItemsIterator::new(items) {
165        match item {
166          PrintItem::Signal(signal) => text.push_str(&get_line(format!("Signal::{:?}", signal), &indent_text)),
167          PrintItem::Condition(condition) => {
168            text.push_str(&get_line(format!("Condition: {}", condition.name), &indent_text));
169            if let Some(true_path) = &condition.true_path {
170              text.push_str(&get_line(String::from("  true:"), &indent_text));
171              text.push_str(&get_items_as_text(true_path, format!("{}    ", indent_text)));
172            }
173            if let Some(false_path) = &condition.false_path {
174              text.push_str(&get_line(String::from("  false:"), &indent_text));
175              text.push_str(&get_items_as_text(false_path, format!("{}    ", indent_text)));
176            }
177          }
178          PrintItem::String(str_text) => text.push_str(&get_line(format!("`{}`", str_text.text), &indent_text)),
179          PrintItem::RcPath(path) => text.push_str(&get_items_as_text(path, indent_text.clone())),
180          PrintItem::Anchor(Anchor::LineNumber(line_number_anchor)) => {
181            text.push_str(&get_line(format!("Line number anchor: {}", line_number_anchor.name()), &indent_text))
182          }
183          PrintItem::Info(info) => {
184            let (desc, name) = match info {
185              Info::LineNumber(info) => ("Line number", info.name()),
186              Info::ColumnNumber(info) => ("Column number", info.name()),
187              Info::IsStartOfLine(info) => ("Is start of line", info.name()),
188              Info::IndentLevel(info) => ("Indent level", info.name()),
189              Info::LineStartColumnNumber(info) => ("Line start column number", info.name()),
190              Info::LineStartIndentLevel(info) => ("Line start indent level", info.name()),
191            };
192            text.push_str(&get_line(format!("{}: {}", desc, name), &indent_text))
193          }
194          PrintItem::ConditionReevaluation(reevaluation) => text.push_str(&get_line(format!("Condition reevaluation: {}", reevaluation.name()), &indent_text)),
195        }
196      }
197
198      return text;
199
200      fn get_line(text: String, indent_text: &str) -> String {
201        format!("{}{}\n", indent_text, text)
202      }
203    }
204  }
205
206  pub fn iter(&self) -> PrintItemsIterator<'a> {
207    PrintItemsIterator { node: self.first_node }
208  }
209}
210
211pub struct PrintItemsIterator<'a> {
212  node: Option<PrintItemPath<'a>>,
213}
214
215impl<'a> PrintItemsIterator<'a> {
216  pub fn new(path: PrintItemPath<'a>) -> Self {
217    Self { node: Some(path) }
218  }
219}
220
221impl<'a> Iterator for PrintItemsIterator<'a> {
222  type Item = PrintItem<'a>;
223
224  fn next(&mut self) -> Option<PrintItem<'a>> {
225    let node = self.node.take();
226
227    match node {
228      Some(node) => {
229        self.node = node.get_next();
230        Some(node.get_item())
231      }
232      None => None,
233    }
234  }
235}
236
237/// Converts a value into print items allocated in an arena.
238pub trait IntoPrintItems<'a> {
239  fn into_print_items(self, arena: &'a Arena) -> PrintItems<'a>;
240}
241
242impl<'a> IntoPrintItems<'a> for PrintItems<'a> {
243  fn into_print_items(self, _arena: &'a Arena) -> PrintItems<'a> {
244    self
245  }
246}
247
248impl<'a> IntoPrintItems<'a> for &'a str {
249  fn into_print_items(self, arena: &'a Arena) -> PrintItems<'a> {
250    let mut items = PrintItems::new(arena);
251    items.push_str_runtime_width_computed(self);
252    items
253  }
254}
255
256impl<'a> IntoPrintItems<'a> for &'a StringContainer<'a> {
257  fn into_print_items(self, arena: &'a Arena) -> PrintItems<'a> {
258    let mut items = PrintItems::new(arena);
259    items.push_sc(self);
260    items
261  }
262}
263
264impl<'a> IntoPrintItems<'a> for String {
265  fn into_print_items(self, arena: &'a Arena) -> PrintItems<'a> {
266    let mut items = PrintItems::new(arena);
267    items.push_string(self);
268    items
269  }
270}
271
272impl<'a> IntoPrintItems<'a> for Condition<'a> {
273  fn into_print_items(self, arena: &'a Arena) -> PrintItems<'a> {
274    let mut items = PrintItems::new(arena);
275    items.push_condition(self);
276    items
277  }
278}
279
280impl<'a> IntoPrintItems<'a> for Signal {
281  fn into_print_items(self, arena: &'a Arena) -> PrintItems<'a> {
282    let mut items = PrintItems::new(arena);
283    items.push_signal(self);
284    items
285  }
286}
287
288impl<'a> IntoPrintItems<'a> for PrintItemPath<'a> {
289  fn into_print_items(self, arena: &'a Arena) -> PrintItems<'a> {
290    let mut items = PrintItems::new(arena);
291    items.push_path(self);
292    items
293  }
294}
295
296impl<'a, T: IntoPrintItems<'a>> IntoPrintItems<'a> for Option<T> {
297  fn into_print_items(self, arena: &'a Arena) -> PrintItems<'a> {
298    match self {
299      Some(value) => value.into_print_items(arena),
300      None => PrintItems::new(arena),
301    }
302  }
303}
304
305/** Tracing */
306
307#[cfg(feature = "tracing")]
308#[derive(serde::Serialize)]
309#[serde(rename_all = "camelCase")]
310pub struct Trace {
311  /// The relative time of the trace from the start of printing in nanoseconds.
312  pub nanos: u128,
313  pub print_node_id: u32,
314  #[serde(skip_serializing_if = "Option::is_none")]
315  pub writer_node_id: Option<u32>,
316  /// Why printing the node made the printer go back to an earlier point, if it did.
317  ///
318  /// The printer continues from the print node of the next trace.
319  #[serde(skip_serializing_if = "Option::is_none")]
320  pub jump: Option<TraceJump>,
321}
322
323/// Why the printer went back to an earlier point.
324#[cfg(feature = "tracing")]
325#[derive(serde::Serialize)]
326#[serde(tag = "kind", content = "content", rename_all = "camelCase")]
327pub enum TraceJump {
328  /// The line was too long, so the printer went back to the last
329  /// possible newline to write a newline there.
330  NewLine,
331  /// An info was printed after a condition used it before it was resolved.
332  Info(TraceInfoJump),
333  /// A condition was printed after another condition used its value
334  /// before it was resolved.
335  Condition(TraceConditionJump),
336  /// A condition was re-evaluated and its value changed.
337  ConditionReevaluation(TraceConditionJump),
338}
339
340#[cfg(feature = "tracing")]
341#[derive(serde::Serialize)]
342#[serde(rename_all = "camelCase")]
343pub struct TraceInfoJump {
344  pub info: TraceInfo,
345  /// The value the info resolved to.
346  pub value: TraceInfoValue,
347}
348
349#[cfg(feature = "tracing")]
350#[derive(serde::Serialize)]
351#[serde(untagged)]
352pub enum TraceInfoValue {
353  Number(u32),
354  Bool(bool),
355}
356
357#[cfg(feature = "tracing")]
358#[derive(serde::Serialize)]
359#[serde(rename_all = "camelCase")]
360pub struct TraceConditionJump {
361  pub condition_id: u32,
362  pub name: String,
363  /// The value the condition resolved to.
364  pub value: Option<bool>,
365}
366
367#[cfg(feature = "tracing")]
368#[derive(serde::Serialize)]
369#[serde(rename_all = "camelCase")]
370pub struct TraceWriterNode {
371  pub writer_node_id: u32,
372  #[serde(skip_serializing_if = "Option::is_none")]
373  pub previous_node_id: Option<u32>,
374  pub text: String,
375}
376
377#[cfg(feature = "tracing")]
378#[derive(serde::Serialize)]
379#[serde(rename_all = "camelCase")]
380pub struct TracePrintNode {
381  pub print_node_id: u32,
382  #[serde(skip_serializing_if = "Option::is_none")]
383  pub next_print_node_id: Option<u32>,
384  pub print_item: TracePrintItem,
385}
386
387#[cfg(feature = "tracing")]
388#[derive(serde::Serialize)]
389#[serde(tag = "kind", content = "content", rename_all = "camelCase")]
390pub enum TracePrintItem {
391  String(String),
392  Condition(TraceCondition),
393  Info(TraceInfo),
394  Signal(Signal),
395  /// Identifier to the print node.
396  RcPath(u32),
397  Anchor(TraceLineNumberAnchor),
398  ConditionReevaluation(TraceConditionReevaluation),
399}
400
401#[cfg(feature = "tracing")]
402#[derive(serde::Serialize)]
403#[serde(tag = "kind", content = "content", rename_all = "camelCase")]
404pub enum TraceInfo {
405  LineNumber(TraceInfoInner),
406  ColumnNumber(TraceInfoInner),
407  IsStartOfLine(TraceInfoInner),
408  IndentLevel(TraceInfoInner),
409  LineStartColumnNumber(TraceInfoInner),
410  LineStartIndentLevel(TraceInfoInner),
411}
412
413#[cfg(feature = "tracing")]
414#[derive(serde::Serialize)]
415#[serde(rename_all = "camelCase")]
416pub struct TraceInfoInner {
417  pub info_id: u32,
418  pub name: String,
419}
420
421#[cfg(feature = "tracing")]
422impl TraceInfoInner {
423  pub fn new(info_id: u32, name: &str) -> Self {
424    Self {
425      info_id,
426      name: name.to_string(),
427    }
428  }
429}
430
431#[cfg(feature = "tracing")]
432#[derive(serde::Serialize)]
433#[serde(rename_all = "camelCase")]
434pub struct TraceLineNumberAnchor {
435  pub anchor_id: u32,
436  pub name: String,
437}
438
439#[cfg(feature = "tracing")]
440#[derive(serde::Serialize)]
441#[serde(rename_all = "camelCase")]
442pub struct TraceConditionReevaluation {
443  pub condition_id: u32,
444  pub name: String,
445}
446
447#[cfg(feature = "tracing")]
448#[derive(serde::Serialize)]
449#[serde(rename_all = "camelCase")]
450pub struct TraceCondition {
451  pub condition_id: u32,
452  pub name: String,
453  pub is_stored: bool,
454  pub store_save_point: bool,
455  #[serde(skip_serializing_if = "Option::is_none")]
456  /// Identifier to the true path print node.
457  pub true_path: Option<u32>,
458  #[serde(skip_serializing_if = "Option::is_none")]
459  /// Identifier to the false path print node.
460  pub false_path: Option<u32>,
461}
462
463pub struct PrintNode<'a> {
464  pub(super) next: Option<PrintItemPath<'a>>,
465  pub(super) item: PrintItem<'a>,
466  #[cfg(feature = "tracing")]
467  pub print_node_id: u32,
468}
469
470impl<'a> PrintNode<'a> {
471  fn new(item: PrintItem<'a>) -> PrintNode<'a> {
472    PrintNode {
473      item,
474      next: None,
475      #[cfg(feature = "tracing")]
476      print_node_id: thread_state::next_print_node_id(),
477    }
478  }
479
480  fn set_next(&mut self, new_next: Option<PrintItemPath<'a>>) {
481    let past_next = mem::replace(&mut self.next, new_next);
482
483    if let Some(past_next) = past_next
484      && let Some(new_next) = new_next
485    {
486      new_next.get_last_next().unwrap_or(new_next).set_next(Some(past_next));
487    }
488  }
489}
490
491/// A fast implementation of RefCell<PrintNode> that avoids runtime checks on borrows.
492pub struct PrintNodeCell<'a> {
493  value: UnsafeCell<PrintNode<'a>>,
494}
495
496impl<'a> PrintNodeCell<'a> {
497  pub(super) fn new(item: PrintItem<'a>) -> PrintNodeCell<'a> {
498    PrintNodeCell {
499      value: UnsafeCell::new(PrintNode::new(item)),
500    }
501  }
502
503  #[inline]
504  pub(super) fn get_item(&self) -> PrintItem<'a> {
505    unsafe { (*self.value.get()).item.clone() }
506  }
507
508  #[inline]
509  pub(super) fn get_next(&self) -> Option<PrintItemPath<'a>> {
510    unsafe { (*self.value.get()).next }
511  }
512
513  #[inline]
514  pub(super) fn set_next(&self, new_next: Option<PrintItemPath<'a>>) {
515    unsafe {
516      (*self.value.get()).set_next(new_next);
517    }
518  }
519
520  #[inline]
521  pub(super) fn get_last_next(&self) -> Option<PrintItemPath<'a>> {
522    let mut current = self.get_next();
523    loop {
524      if let Some(last) = &current
525        && let Some(next) = last.get_next()
526      {
527        current.replace(next);
528        continue;
529      }
530      break;
531    }
532
533    current
534  }
535
536  #[cfg(feature = "tracing")]
537  pub(super) fn get_node_id(&self) -> u32 {
538    unsafe { (*self.get_node()).print_node_id }
539  }
540
541  /// Gets the node unsafely. Be careful when using this and ensure no mutation is
542  /// happening during the borrow.
543  #[inline]
544  pub(super) unsafe fn get_node(&self) -> *mut PrintNode<'a> {
545    self.value.get()
546  }
547
548  #[inline]
549  pub fn take_next(self) -> Option<PrintItemPath<'a>> {
550    self.value.into_inner().next.take()
551  }
552}
553
554pub type PrintItemPath<'a> = &'a PrintNodeCell<'a>;
555
556/* Print item and kinds */
557
558/// The different items the printer could encounter.
559#[derive(Clone)]
560pub enum PrintItem<'a> {
561  String(&'a StringContainer<'a>),
562  Condition(&'a Condition<'a>),
563  Signal(Signal),
564  RcPath(PrintItemPath<'a>),
565  Anchor(Anchor),
566  Info(Info),
567  ConditionReevaluation(ConditionReevaluation),
568}
569
570#[derive(Clone, PartialEq, Eq, Copy, Debug, serde::Serialize)]
571pub enum Signal {
572  /// Signal that a new line should occur based on the printer settings.
573  NewLine,
574  /// Signal that a tab should occur based on the printer settings.
575  Tab,
576  /// Signal that the current location could be a newline when
577  /// exceeding the line width.
578  PossibleNewLine,
579  /// Signal that the current location should be a space, but
580  /// could be a newline if exceeding the line width.
581  SpaceOrNewLine,
582  /// Expect the next character to be a newline. If it's not, force a newline.
583  ExpectNewLine,
584  /// Queue a start indent to be set after the next written item.
585  QueueStartIndent,
586  /// Signal the start of a section that should be indented.
587  StartIndent,
588  /// Signal the end of a section that should be indented.
589  FinishIndent,
590  /// Signal the start of a group of print items that have a lower precedence
591  /// for being broken up with a newline for exceeding the line width.
592  StartNewLineGroup,
593  /// Signal the end of a newline group.
594  FinishNewLineGroup,
595  /// Signal that a single indent should occur based on the printer settings.
596  SingleIndent,
597  /// Signal to the printer that it should stop using indentation.
598  StartIgnoringIndent,
599  /// Signal to the printer that it should start using indentation again.
600  FinishIgnoringIndent,
601  /// Signal the start of a section whose indentation starts from no indentation
602  /// instead of the current indentation, which can then be indented with `StartIndent`
603  /// (ex. to indent relative to text written as is while ignoring the indentation).
604  ///
605  /// The indent levels in the section (ex. of an `IndentLevel` info) count from the
606  /// start of the section, so they shouldn't be compared with the indent levels from
607  /// outside of it. The column numbers are the actual columns. A `QueueStartIndent`
608  /// from before the section is applied after it.
609  StartResettingIndent,
610  /// Signal the end of a section that reset the indentation, which restores the
611  /// indentation from before. The indents and aligns started in the section must be
612  /// finished first.
613  FinishResettingIndent,
614  /// Signal the start of a section that's aligned by the number of columns of spaces
615  /// after the indentation (ex. to line up with text that isn't at an indent level).
616  /// The alignment always goes after the indentation, so with tabs it's tabs then spaces.
617  ///
618  /// The alignment isn't part of the indent levels (ex. of an `IndentLevel` info),
619  /// but it's included in the column numbers.
620  StartAlign(u8),
621  /// Signal the end of the most recent section that aligns.
622  FinishAlign,
623  /// Signal to the printer that it shouldn't print any new lines.
624  StartForceNoNewLines,
625  /// Signal to the printer that it should finish not printing any new lines.
626  FinishForceNoNewLines,
627  /// Signal that a space should occur if not trailing.
628  SpaceIfNotTrailing,
629}
630
631#[derive(Clone)]
632pub enum Anchor {
633  LineNumber(LineNumberAnchor),
634}
635
636impl From<LineNumberAnchor> for Anchor {
637  fn from(anchor: LineNumberAnchor) -> Self {
638    Anchor::LineNumber(anchor)
639  }
640}
641
642/// Handles updating the position of a future resolved line
643/// number if the anchor changes.
644#[derive(Clone)]
645pub struct LineNumberAnchor {
646  id: u32,
647  line_number: LineNumber,
648}
649
650impl LineNumberAnchor {
651  pub fn new(line_number: LineNumber) -> Self {
652    Self {
653      id: thread_state::next_line_number_anchor_id(),
654      line_number,
655    }
656  }
657
658  #[inline]
659  pub fn unique_id(&self) -> u32 {
660    self.id
661  }
662
663  #[inline]
664  pub fn line_number_id(&self) -> u32 {
665    self.line_number.id
666  }
667
668  #[inline]
669  pub fn name(&self) -> &'static str {
670    self.line_number.name()
671  }
672}
673
674#[derive(Clone, PartialEq, Eq, Copy, Debug)]
675pub enum Info {
676  LineNumber(LineNumber),
677  ColumnNumber(ColumnNumber),
678  IsStartOfLine(IsStartOfLine),
679  IndentLevel(IndentLevel),
680  LineStartColumnNumber(LineStartColumnNumber),
681  LineStartIndentLevel(LineStartIndentLevel),
682}
683
684impl From<LineNumber> for Info {
685  fn from(info: LineNumber) -> Self {
686    Info::LineNumber(info)
687  }
688}
689
690impl From<ColumnNumber> for Info {
691  fn from(info: ColumnNumber) -> Self {
692    Info::ColumnNumber(info)
693  }
694}
695
696impl From<IsStartOfLine> for Info {
697  fn from(info: IsStartOfLine) -> Self {
698    Info::IsStartOfLine(info)
699  }
700}
701
702impl From<IndentLevel> for Info {
703  fn from(info: IndentLevel) -> Self {
704    Info::IndentLevel(info)
705  }
706}
707
708impl From<LineStartColumnNumber> for Info {
709  fn from(info: LineStartColumnNumber) -> Self {
710    Info::LineStartColumnNumber(info)
711  }
712}
713
714impl From<LineStartIndentLevel> for Info {
715  fn from(info: LineStartIndentLevel) -> Self {
716    Info::LineStartIndentLevel(info)
717  }
718}
719
720/// Helper IR that holds line and column number IR.
721#[derive(Clone, PartialEq, Eq, Copy, Debug)]
722pub struct LineAndColumn {
723  pub line: LineNumber,
724  pub column: ColumnNumber,
725}
726
727impl LineAndColumn {
728  pub fn new(name: &'static str) -> Self {
729    Self {
730      line: LineNumber::new(name),
731      column: ColumnNumber::new(name),
732    }
733  }
734}
735
736#[derive(Clone, PartialEq, Eq, Copy, Debug)]
737pub struct LineNumber {
738  id: u32,
739  /// Name for debugging purposes.
740  #[cfg(debug_assertions)]
741  name: &'static str,
742}
743
744impl LineNumber {
745  pub fn new(_name: &'static str) -> Self {
746    Self {
747      id: thread_state::next_line_number_id(),
748      #[cfg(debug_assertions)]
749      name: _name,
750    }
751  }
752
753  #[inline]
754  pub fn unique_id(&self) -> u32 {
755    self.id
756  }
757
758  #[inline]
759  pub fn name(&self) -> &'static str {
760    #[cfg(debug_assertions)]
761    return self.name;
762    #[cfg(not(debug_assertions))]
763    return "line_number";
764  }
765}
766
767#[derive(Clone, PartialEq, Eq, Copy, Debug)]
768pub struct ColumnNumber {
769  id: u32,
770  /// Name for debugging purposes.
771  #[cfg(debug_assertions)]
772  name: &'static str,
773}
774
775impl ColumnNumber {
776  pub fn new(_name: &'static str) -> Self {
777    Self {
778      id: thread_state::next_column_number_id(),
779      #[cfg(debug_assertions)]
780      name: _name,
781    }
782  }
783
784  #[inline]
785  pub fn unique_id(&self) -> u32 {
786    self.id
787  }
788
789  #[inline]
790  pub fn name(&self) -> &'static str {
791    #[cfg(debug_assertions)]
792    return self.name;
793    #[cfg(not(debug_assertions))]
794    return "column_number";
795  }
796}
797
798#[derive(Clone, PartialEq, Eq, Copy, Debug)]
799pub struct IsStartOfLine {
800  id: u32,
801  /// Name for debugging purposes.
802  #[cfg(debug_assertions)]
803  name: &'static str,
804}
805
806impl IsStartOfLine {
807  pub fn new(_name: &'static str) -> Self {
808    Self {
809      id: thread_state::next_is_start_of_line_id(),
810      #[cfg(debug_assertions)]
811      name: _name,
812    }
813  }
814
815  #[inline]
816  pub fn unique_id(&self) -> u32 {
817    self.id
818  }
819
820  #[inline]
821  pub fn name(&self) -> &'static str {
822    #[cfg(debug_assertions)]
823    return self.name;
824    #[cfg(not(debug_assertions))]
825    return "is_start_of_line";
826  }
827}
828
829#[derive(Clone, PartialEq, Eq, Copy, Debug)]
830pub struct LineStartColumnNumber {
831  id: u32,
832  /// Name for debugging purposes.
833  #[cfg(debug_assertions)]
834  name: &'static str,
835}
836
837impl LineStartColumnNumber {
838  pub fn new(_name: &'static str) -> Self {
839    Self {
840      id: thread_state::next_line_start_column_number_id(),
841      #[cfg(debug_assertions)]
842      name: _name,
843    }
844  }
845
846  #[inline]
847  pub fn unique_id(&self) -> u32 {
848    self.id
849  }
850
851  #[inline]
852  pub fn name(&self) -> &'static str {
853    #[cfg(debug_assertions)]
854    return self.name;
855    #[cfg(not(debug_assertions))]
856    return "line_start_column_number";
857  }
858}
859
860#[derive(Clone, PartialEq, Eq, Copy, Debug)]
861pub struct IndentLevel {
862  id: u32,
863  /// Name for debugging purposes.
864  #[cfg(debug_assertions)]
865  name: &'static str,
866}
867
868impl IndentLevel {
869  pub fn new(_name: &'static str) -> Self {
870    Self {
871      id: thread_state::next_indent_level_id(),
872      #[cfg(debug_assertions)]
873      name: _name,
874    }
875  }
876
877  #[inline]
878  pub fn unique_id(&self) -> u32 {
879    self.id
880  }
881
882  #[inline]
883  pub fn name(&self) -> &'static str {
884    #[cfg(debug_assertions)]
885    return self.name;
886    #[cfg(not(debug_assertions))]
887    return "indent_level";
888  }
889}
890
891#[derive(Clone, PartialEq, Eq, Copy, Debug)]
892pub struct LineStartIndentLevel {
893  id: u32,
894  /// Name for debugging purposes.
895  #[cfg(debug_assertions)]
896  name: &'static str,
897}
898
899impl LineStartIndentLevel {
900  pub fn new(_name: &'static str) -> Self {
901    Self {
902      id: thread_state::next_line_start_indent_level_id(),
903      #[cfg(debug_assertions)]
904      name: _name,
905    }
906  }
907
908  #[inline]
909  pub fn unique_id(&self) -> u32 {
910    self.id
911  }
912
913  #[inline]
914  pub fn name(&self) -> &'static str {
915    #[cfg(debug_assertions)]
916    return self.name;
917    #[cfg(not(debug_assertions))]
918    return "line_start_indent_level";
919  }
920}
921
922/// Used to re-evaluate a condition.
923#[derive(Clone, Copy, PartialEq, Eq, Debug)]
924pub struct ConditionReevaluation {
925  pub(crate) condition_reevaluation_id: u32,
926  pub(crate) condition_id: u32,
927  /// Name for debugging purposes.
928  #[cfg(debug_assertions)]
929  name: &'static str,
930}
931
932impl ConditionReevaluation {
933  pub(crate) fn new(_name: &'static str, condition_id: u32) -> Self {
934    ConditionReevaluation {
935      condition_reevaluation_id: thread_state::next_condition_reevaluation_id(),
936      condition_id,
937      #[cfg(debug_assertions)]
938      name: _name,
939    }
940  }
941
942  pub fn name(&self) -> &'static str {
943    #[cfg(debug_assertions)]
944    return self.name;
945    #[cfg(not(debug_assertions))]
946    return "condition_reevaluation";
947  }
948}
949
950/// Conditionally print items based on a condition.
951///
952/// These conditions are extremely flexible and can even be resolved based on
953/// information found later on in the file.
954#[derive(Clone)]
955pub struct Condition<'a> {
956  /// Unique identifier.
957  id: u32,
958  /// Name for debugging purposes.
959  #[cfg(debug_assertions)]
960  name: &'static str,
961  /// If a reference has been created for the condition via `create_reference()`. If so, the printer
962  /// will store the condition and it will be retrievable via a condition resolver.
963  pub(super) is_stored: bool,
964  pub(super) store_save_point: bool,
965  /// If what's printed when the condition isn't resolved yet is the same as when it's false.
966  pub(super) is_unknown_same_as_false: bool,
967  /// The condition to resolve.
968  pub(super) condition: ConditionResolver<'a>,
969  /// The items to print when the condition is true.
970  pub(super) true_path: Option<PrintItemPath<'a>>,
971  /// The items to print when the condition is false or undefined (not yet resolved).
972  pub(super) false_path: Option<PrintItemPath<'a>>,
973}
974
975impl<'a> Condition<'a> {
976  pub fn new(name: &'static str, properties: ConditionProperties<'a>) -> Self {
977    Self::new_internal(name, properties)
978  }
979
980  pub fn new_true() -> Self {
981    Self::new_internal(
982      "trueCondition",
983      ConditionProperties {
984        condition: condition_resolvers::true_resolver(),
985        true_path: None,
986        false_path: None,
987      },
988    )
989  }
990
991  pub fn new_false() -> Self {
992    Self::new_internal(
993      "falseCondition",
994      ConditionProperties {
995        condition: condition_resolvers::false_resolver(),
996        true_path: None,
997        false_path: None,
998      },
999    )
1000  }
1001
1002  fn new_internal(_name: &'static str, properties: ConditionProperties<'a>) -> Self {
1003    Self {
1004      id: thread_state::next_condition_id(),
1005      is_stored: false,
1006      store_save_point: false,
1007      is_unknown_same_as_false: false,
1008      #[cfg(debug_assertions)]
1009      name: _name,
1010      condition: properties.condition,
1011      true_path: properties.true_path.and_then(|x| x.first_node),
1012      false_path: properties.false_path.and_then(|x| x.first_node),
1013    }
1014  }
1015
1016  #[inline]
1017  pub fn unique_id(&self) -> u32 {
1018    self.id
1019  }
1020
1021  #[inline]
1022  pub fn name(&self) -> &'static str {
1023    #[cfg(debug_assertions)]
1024    return self.name;
1025    #[cfg(not(debug_assertions))]
1026    return "condition";
1027  }
1028
1029  #[inline]
1030  pub fn true_path(&self) -> &Option<PrintItemPath<'a>> {
1031    &self.true_path
1032  }
1033
1034  #[inline]
1035  pub fn false_path(&self) -> &Option<PrintItemPath<'a>> {
1036    &self.false_path
1037  }
1038
1039  #[inline]
1040  pub(super) fn resolve(&self, context: &mut ConditionResolverContext) -> Option<bool> {
1041    (self.condition)(context)
1042  }
1043
1044  pub fn create_reference(&mut self) -> ConditionReference {
1045    self.is_stored = true;
1046    ConditionReference::new(self.name(), self.id)
1047  }
1048
1049  pub fn create_reevaluation(&mut self) -> ConditionReevaluation {
1050    self.store_save_point = true;
1051    self.is_stored = true;
1052    ConditionReevaluation::new(self.name(), self.id)
1053  }
1054
1055  /// Says that what's printed when the condition isn't resolved yet is the same as when it's
1056  /// false, including by the conditions using its value. When it looked ahead and turns out to be
1057  /// false, the printer then doesn't go back to print the same thing again.
1058  ///
1059  /// This is only needed when the condition has a reference, since the printer already doesn't
1060  /// go back to a condition without one when it takes the same path as before.
1061  pub fn set_unknown_same_as_false(&mut self) {
1062    self.is_unknown_same_as_false = true;
1063  }
1064}
1065
1066#[derive(Clone, PartialEq, Eq, Copy, Debug)]
1067pub struct ConditionReference {
1068  #[cfg(debug_assertions)]
1069  pub(super) name: &'static str,
1070  pub(super) id: u32,
1071}
1072
1073impl ConditionReference {
1074  pub(super) fn new(_name: &'static str, id: u32) -> ConditionReference {
1075    ConditionReference {
1076      #[cfg(debug_assertions)]
1077      name: _name,
1078      id,
1079    }
1080  }
1081
1082  #[inline]
1083  pub(super) fn name(&self) -> &'static str {
1084    #[cfg(debug_assertions)]
1085    return self.name;
1086    #[cfg(not(debug_assertions))]
1087    return "conditionRef";
1088  }
1089
1090  /// Creates a condition resolver that checks the value of the condition this references.
1091  pub fn create_resolver<'a>(&self, arena: &'a Arena) -> ConditionResolver<'a> {
1092    let captured_self = *self;
1093    arena.alloc_resolver(move |condition_context| condition_context.resolved_condition(&captured_self))
1094  }
1095}
1096
1097/// Properties for the condition.
1098pub struct ConditionProperties<'a> {
1099  /// The condition to resolve.
1100  pub condition: ConditionResolver<'a>,
1101  /// The items to print when the condition is true.
1102  pub true_path: Option<PrintItems<'a>>,
1103  /// The items to print when the condition is false or undefined (not yet resolved).
1104  pub false_path: Option<PrintItems<'a>>,
1105}
1106
1107/// Function used to resolve a condition, which is allocated in an arena with
1108/// [`Arena::alloc_resolver`] (or is static, like the ones in `condition_resolvers`).
1109pub type ConditionResolver<'a> = &'a dyn Fn(&mut ConditionResolverContext) -> Option<bool>;
1110
1111/// Context used when resolving a condition.
1112pub struct ConditionResolverContext<'a, 'b> {
1113  printer: &'a mut Printer<'b>,
1114  /// Gets the writer info at the condition's location.
1115  pub writer_info: WriterInfo,
1116}
1117
1118impl<'a, 'b> ConditionResolverContext<'a, 'b> {
1119  pub(super) fn new(printer: &'a mut Printer<'b>, writer_info: WriterInfo) -> Self {
1120    ConditionResolverContext { printer, writer_info }
1121  }
1122
1123  /// Gets if a condition was true, false, or returns None when not yet resolved.
1124  /// A condition reference can be retrieved by calling the `create_reference()` on a condition.
1125  pub fn resolved_condition(&mut self, condition_reference: &ConditionReference) -> Option<bool> {
1126    self.printer.resolved_condition(condition_reference)
1127  }
1128
1129  /// Gets a resolved line and column.
1130  pub fn resolved_line_and_column(&mut self, line_and_column: LineAndColumn) -> Option<(u32, u32)> {
1131    let line = self.printer.resolved_line_number(line_and_column.line)?;
1132    let column = self.printer.resolved_column_number(line_and_column.column)?;
1133    Some((line, column))
1134  }
1135
1136  /// Gets the line number or returns None when not yet resolved.
1137  pub fn resolved_line_number(&mut self, line_number: LineNumber) -> Option<u32> {
1138    self.printer.resolved_line_number(line_number)
1139  }
1140
1141  /// Gets the column number or returns None when not yet resolved.
1142  pub fn resolved_column_number(&mut self, column_number: ColumnNumber) -> Option<u32> {
1143    self.printer.resolved_column_number(column_number)
1144  }
1145
1146  /// Gets if the info is at the start of the line or returns None when not yet resolved.
1147  pub fn resolved_is_start_of_line(&mut self, is_start_of_line: IsStartOfLine) -> Option<bool> {
1148    self.printer.resolved_is_start_of_line(is_start_of_line)
1149  }
1150
1151  /// Gets if the indent level at this info or returns None when not yet resolved.
1152  pub fn resolved_indent_level(&mut self, indent_level: IndentLevel) -> Option<u8> {
1153    self.printer.resolved_indent_level(indent_level)
1154  }
1155
1156  /// Gets the column number at the start of the line this info appears or returns None when not yet resolved.
1157  pub fn resolved_line_start_column_number(&mut self, line_start_column_number: LineStartColumnNumber) -> Option<u32> {
1158    self.printer.resolved_line_start_column_number(line_start_column_number)
1159  }
1160
1161  /// Gets the indent level at the start of the line this info appears or returns None when not yet resolved.
1162  pub fn resolved_line_start_indent_level(&mut self, line_start_indent_level: LineStartIndentLevel) -> Option<u8> {
1163    self.printer.resolved_line_start_indent_level(line_start_indent_level)
1164  }
1165
1166  /// Clears the line and column from being stored.
1167  pub fn clear_line_and_column(&mut self, lc: LineAndColumn) {
1168    self.clear_info(lc.line);
1169    self.clear_info(lc.column);
1170  }
1171
1172  /// Clears the info from being stored.
1173  pub fn clear_info(&mut self, info: impl Into<Info>) {
1174    self.printer.clear_info(info.into())
1175  }
1176
1177  /// Moves an already resolved line number by `delta` lines.
1178  ///
1179  /// Use this instead of clearing when the text the line number refers to has only moved up or down
1180  /// the page, so that it stays correct relative to everything around it.
1181  pub fn shift_line_number(&mut self, info: LineNumber, delta: isize) {
1182    self.printer.shift_line_number(info, delta)
1183  }
1184
1185  /// Gets the maximum width of a line.
1186  pub fn max_width(&self) -> u32 {
1187    self.printer.max_width()
1188  }
1189
1190  /// Runs `f` without the printer going back to this condition once the infos and conditions
1191  /// it gets that aren't resolved yet are resolved.
1192  ///
1193  /// This is for a condition that's re-evaluated after them (see `Condition::create_reevaluation`),
1194  /// which only goes back when its value changes, so it can assume a value until then.
1195  pub fn without_looking_ahead<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1196    let was_not_looking_ahead = self.printer.replace_is_not_looking_ahead(true);
1197    let result = f(self);
1198    self.printer.replace_is_not_looking_ahead(was_not_looking_ahead);
1199    result
1200  }
1201
1202  /// Gets the line number when it's resolved, without looking ahead to it when it isn't.
1203  pub fn peek_line_number(&self, line_number: LineNumber) -> Option<u32> {
1204    self.printer.peek_line_number(line_number)
1205  }
1206
1207  /// Sets the line number to a value that was worked out before (ex. when the text it
1208  /// refers to is printed at the same position again).
1209  pub fn set_line_number(&mut self, line_number: LineNumber, value: u32) {
1210    self.printer.set_line_number(line_number, value)
1211  }
1212
1213  /// Gets if the printer is currently forcing no newlines.
1214  pub fn is_forcing_no_newlines(&self) -> bool {
1215    self.printer.is_forcing_no_newlines()
1216  }
1217}
1218
1219/// A container that holds the string's value and character count.
1220#[derive(Clone)]
1221pub struct StringContainer<'a> {
1222  /// The string value.
1223  pub text: &'a str,
1224  /// The cached character count.
1225  /// It is much faster to cache this than to recompute it all the time.
1226  pub(super) char_count: u32,
1227}
1228
1229impl<'a> StringContainer<'a> {
1230  /// Creates a new string container.
1231  pub fn new(text: &'a str) -> Self {
1232    let char_count = unicode_width::UnicodeWidthStr::width(text) as u32;
1233    Self { text, char_count }
1234  }
1235
1236  /// This is used by the sc! proc macro and should not be used otherwise
1237  /// because the character count is pre-computed.
1238  pub const fn proc_macro_new_with_char_count(text: &'a str, char_count: u32) -> Self {
1239    Self { text, char_count }
1240  }
1241}
1242
1243/// Information about a certain location being printed.
1244#[derive(Clone, Debug)]
1245pub struct WriterInfo {
1246  pub line_number: u32,
1247  pub column_number: u32,
1248  pub indent_level: u8,
1249  pub line_start_indent_level: u8,
1250  /// The columns of spaces after the indentation that the line started with.
1251  pub line_start_align_columns: u32,
1252  pub indent_width: u8,
1253  pub expect_newline_next: bool,
1254}
1255
1256impl WriterInfo {
1257  /// Gets if the current column number equals the line start column number
1258  /// or if a newline is expected next.
1259  pub fn is_start_of_line(&self) -> bool {
1260    self.expect_newline_next || self.is_column_number_at_line_start()
1261  }
1262
1263  /// Gets if the start of the line is indented.
1264  pub fn is_start_of_line_indented(&self) -> bool {
1265    self.line_start_indent_level > self.indent_level
1266  }
1267
1268  /// Gets if the current column number is at the line start column number.
1269  pub fn is_column_number_at_line_start(&self) -> bool {
1270    self.column_number == self.line_start_column_number()
1271  }
1272
1273  pub fn line_start_column_number(&self) -> u32 {
1274    (self.line_start_indent_level as u32) * (self.indent_width as u32) + self.line_start_align_columns
1275  }
1276
1277  /// Gets the line and column number.
1278  pub fn line_and_column(&self) -> (u32, u32) {
1279    (self.line_number, self.column_number)
1280  }
1281}