lib.rs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. use crate::writer::*;
  2. use collect_macros::byte_offset;
  3. use dioxus_rsx::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. // Oneliner optimization
  68. if writer.is_short_children(&body.roots).is_some() {
  69. writer.write_ident(&body.roots[0]).unwrap();
  70. } else {
  71. writer.write_body_indented(&body.roots).unwrap();
  72. }
  73. // writing idents leaves the final line ended at the end of the last ident
  74. if writer.out.buf.contains('\n') {
  75. writer.out.new_line().unwrap();
  76. writer.out.tab().unwrap();
  77. }
  78. let span = match item.delimiter {
  79. MacroDelimiter::Paren(_) => todo!(),
  80. MacroDelimiter::Brace(b) => b.span,
  81. MacroDelimiter::Bracket(_) => todo!(),
  82. };
  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. if formatted.len() <= 80 && !formatted.contains('\n') {
  88. formatted = format!(" {} ", formatted);
  89. }
  90. end_span = span.end();
  91. if contents[start..end] == formatted {
  92. continue;
  93. }
  94. formatted_blocks.push(FormattedBlock {
  95. formatted,
  96. start,
  97. end,
  98. });
  99. }
  100. formatted_blocks
  101. }
  102. pub fn write_block_out(body: CallBody) -> Option<String> {
  103. let mut buf = Writer {
  104. src: vec![""],
  105. ..Writer::default()
  106. };
  107. // Oneliner optimization
  108. if buf.is_short_children(&body.roots).is_some() {
  109. buf.write_ident(&body.roots[0]).unwrap();
  110. } else {
  111. buf.write_body_indented(&body.roots).unwrap();
  112. }
  113. buf.consume()
  114. }
  115. pub fn fmt_block_from_expr(raw: &str, expr: ExprMacro) -> Option<String> {
  116. let body = syn::parse2::<CallBody>(expr.mac.tokens).unwrap();
  117. let mut buf = Writer {
  118. src: raw.lines().collect(),
  119. ..Writer::default()
  120. };
  121. // Oneliner optimization
  122. if buf.is_short_children(&body.roots).is_some() {
  123. buf.write_ident(&body.roots[0]).unwrap();
  124. } else {
  125. buf.write_body_indented(&body.roots).unwrap();
  126. }
  127. buf.consume()
  128. }
  129. pub fn fmt_block(block: &str, indent_level: usize) -> Option<String> {
  130. let body = syn::parse_str::<dioxus_rsx::CallBody>(block).unwrap();
  131. let mut buf = Writer {
  132. src: block.lines().collect(),
  133. ..Writer::default()
  134. };
  135. buf.out.indent = indent_level;
  136. // Oneliner optimization
  137. if buf.is_short_children(&body.roots).is_some() {
  138. buf.write_ident(&body.roots[0]).unwrap();
  139. } else {
  140. buf.write_body_indented(&body.roots).unwrap();
  141. }
  142. // writing idents leaves the final line ended at the end of the last ident
  143. if buf.out.buf.contains('\n') {
  144. buf.out.new_line().unwrap();
  145. }
  146. buf.consume()
  147. }
  148. pub fn apply_format(input: &str, block: FormattedBlock) -> String {
  149. let start = block.start;
  150. let end = block.end;
  151. let (left, _) = input.split_at(start);
  152. let (_, right) = input.split_at(end);
  153. // dbg!(&block.formatted);
  154. format!("{}{}{}", left, block.formatted, right)
  155. }
  156. // Apply all the blocks
  157. pub fn apply_formats(input: &str, blocks: Vec<FormattedBlock>) -> String {
  158. let mut out = String::new();
  159. let mut last = 0;
  160. for FormattedBlock {
  161. formatted,
  162. start,
  163. end,
  164. } in blocks
  165. {
  166. let prefix = &input[last..start];
  167. out.push_str(prefix);
  168. out.push_str(&formatted);
  169. last = end;
  170. }
  171. let suffix = &input[last..];
  172. out.push_str(suffix);
  173. out
  174. }