lib.rs 6.9 KB

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