1
0

lib.rs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. #![doc = include_str!("../README.md")]
  2. #![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
  3. #![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
  4. use std::fmt::{Display, Write};
  5. use crate::writer::*;
  6. use collect_macros::byte_offset;
  7. use dioxus_rsx::{BodyNode, CallBody, IfmtInput};
  8. use proc_macro2::LineColumn;
  9. use quote::ToTokens;
  10. use syn::{ExprMacro, MacroDelimiter};
  11. mod buffer;
  12. mod collect_macros;
  13. mod component;
  14. mod element;
  15. mod expr;
  16. mod indent;
  17. mod prettier_please;
  18. mod writer;
  19. pub use indent::{IndentOptions, IndentType};
  20. /// A modification to the original file to be applied by an IDE
  21. ///
  22. /// Right now this re-writes entire rsx! blocks at a time, instead of precise line-by-line changes.
  23. ///
  24. /// In a "perfect" world we would have tiny edits to preserve things like cursor states and selections. The API here makes
  25. /// it possible to migrate to a more precise modification approach in the future without breaking existing code.
  26. ///
  27. /// Note that this is tailored to VSCode's TextEdit API and not a general Diff API. Line numbers are not accurate if
  28. /// multiple edits are applied in a single file without tracking text shifts.
  29. #[derive(serde::Deserialize, serde::Serialize, Clone, Debug, PartialEq, Eq, Hash)]
  30. pub struct FormattedBlock {
  31. /// The new contents of the block
  32. pub formatted: String,
  33. /// The line number of the first line of the block.
  34. pub start: usize,
  35. /// The end of the block, exclusive.
  36. pub end: usize,
  37. }
  38. /// Format a file into a list of `FormattedBlock`s to be applied by an IDE for autoformatting.
  39. ///
  40. /// This function expects a complete file, not just a block of code. To format individual rsx! blocks, use fmt_block instead.
  41. ///
  42. /// The point here is to provide precise modifications of a source file so an accompanying IDE tool can map these changes
  43. /// back to the file precisely.
  44. ///
  45. /// Nested blocks of RSX will be handled automatically
  46. pub fn fmt_file(contents: &str, indent: IndentOptions) -> Vec<FormattedBlock> {
  47. let mut formatted_blocks = Vec::new();
  48. let parsed = syn::parse_file(contents).unwrap();
  49. let mut macros = vec![];
  50. collect_macros::collect_from_file(&parsed, &mut macros);
  51. // No macros, no work to do
  52. if macros.is_empty() {
  53. return formatted_blocks;
  54. }
  55. let mut writer = Writer::new(contents);
  56. writer.out.indent = indent;
  57. // Don't parse nested macros
  58. let mut end_span = LineColumn { column: 0, line: 0 };
  59. for item in macros {
  60. let macro_path = &item.path.segments[0].ident;
  61. // this macro is inside the last macro we parsed, skip it
  62. if macro_path.span().start() < end_span {
  63. continue;
  64. }
  65. let body = item.parse_body::<CallBody>().unwrap();
  66. let rsx_start = macro_path.span().start();
  67. writer.out.indent_level = writer
  68. .out
  69. .indent
  70. .count_indents(writer.src[rsx_start.line - 1]);
  71. write_body(&mut writer, &body);
  72. // writing idents leaves the final line ended at the end of the last ident
  73. if writer.out.buf.contains('\n') {
  74. writer.out.new_line().unwrap();
  75. writer.out.tab().unwrap();
  76. }
  77. let span = match item.delimiter {
  78. MacroDelimiter::Paren(b) => b.span,
  79. MacroDelimiter::Brace(b) => b.span,
  80. MacroDelimiter::Bracket(b) => b.span,
  81. }
  82. .join();
  83. let mut formatted = String::new();
  84. std::mem::swap(&mut formatted, &mut writer.out.buf);
  85. let start = byte_offset(contents, span.start()) + 1;
  86. let end = byte_offset(contents, span.end()) - 1;
  87. // Rustfmt will remove the space between the macro and the opening paren if the macro is a single expression
  88. let body_is_solo_expr = body.roots.len() == 1
  89. && matches!(body.roots[0], BodyNode::RawExpr(_) | BodyNode::Text(_));
  90. if formatted.len() <= 80 && !formatted.contains('\n') && !body_is_solo_expr {
  91. formatted = format!(" {formatted} ");
  92. }
  93. end_span = span.end();
  94. if contents[start..end] == formatted {
  95. continue;
  96. }
  97. formatted_blocks.push(FormattedBlock {
  98. formatted,
  99. start,
  100. end,
  101. });
  102. }
  103. formatted_blocks
  104. }
  105. pub fn write_block_out(body: CallBody) -> Option<String> {
  106. let mut buf = Writer::new("");
  107. write_body(&mut buf, &body);
  108. buf.consume()
  109. }
  110. fn write_body(buf: &mut Writer, body: &CallBody) {
  111. match body.roots.len() {
  112. 0 => {}
  113. 1 if matches!(body.roots[0], BodyNode::Text(_)) => {
  114. write!(buf.out, " ").unwrap();
  115. buf.write_ident(&body.roots[0]).unwrap();
  116. write!(buf.out, " ").unwrap();
  117. }
  118. _ => buf.write_body_indented(&body.roots).unwrap(),
  119. }
  120. }
  121. pub fn fmt_block_from_expr(raw: &str, expr: ExprMacro) -> Option<String> {
  122. let body = syn::parse2::<CallBody>(expr.mac.tokens).unwrap();
  123. let mut buf = Writer::new(raw);
  124. write_body(&mut buf, &body);
  125. buf.consume()
  126. }
  127. pub fn fmt_block(block: &str, indent_level: usize, indent: IndentOptions) -> Option<String> {
  128. let body = syn::parse_str::<dioxus_rsx::CallBody>(block).unwrap();
  129. let mut buf = Writer::new(block);
  130. buf.out.indent = indent;
  131. buf.out.indent_level = indent_level;
  132. write_body(&mut buf, &body);
  133. // writing idents leaves the final line ended at the end of the last ident
  134. if buf.out.buf.contains('\n') {
  135. buf.out.new_line().unwrap();
  136. }
  137. buf.consume()
  138. }
  139. pub fn apply_format(input: &str, block: FormattedBlock) -> String {
  140. let start = block.start;
  141. let end = block.end;
  142. let (left, _) = input.split_at(start);
  143. let (_, right) = input.split_at(end);
  144. format!("{}{}{}", left, block.formatted, right)
  145. }
  146. // Apply all the blocks
  147. pub fn apply_formats(input: &str, blocks: Vec<FormattedBlock>) -> String {
  148. let mut out = String::new();
  149. let mut last = 0;
  150. for FormattedBlock {
  151. formatted,
  152. start,
  153. end,
  154. } in blocks
  155. {
  156. let prefix = &input[last..start];
  157. out.push_str(prefix);
  158. out.push_str(&formatted);
  159. last = end;
  160. }
  161. let suffix = &input[last..];
  162. out.push_str(suffix);
  163. out
  164. }
  165. struct DisplayIfmt<'a>(&'a IfmtInput);
  166. impl Display for DisplayIfmt<'_> {
  167. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  168. let inner_tokens = self.0.source.as_ref().unwrap().to_token_stream();
  169. inner_tokens.fmt(f)
  170. }
  171. }
  172. pub(crate) fn ifmt_to_string(input: &IfmtInput) -> String {
  173. let mut buf = String::new();
  174. let display = DisplayIfmt(input);
  175. write!(&mut buf, "{}", display).unwrap();
  176. buf
  177. }
  178. pub(crate) fn write_ifmt(input: &IfmtInput, writable: &mut impl Write) -> std::fmt::Result {
  179. let display = DisplayIfmt(input);
  180. write!(writable, "{}", display)
  181. }