lib.rs 6.2 KB

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