|
| 1 | +//! Structural editing for ast using `SyntaxEditor` |
| 2 | +
|
| 3 | +use crate::{ |
| 4 | + ast::make, ast::AstNode, ast::Fn, ast::GenericParam, ast::HasGenericParams, ast::HasName, |
| 5 | + syntax_editor::Position, syntax_editor::SyntaxEditor, SyntaxKind, |
| 6 | +}; |
| 7 | + |
| 8 | +impl SyntaxEditor { |
| 9 | + /// Adds a new generic param to the function using `SyntaxEditor` |
| 10 | + pub fn syntax_editor_add_generic_param(&mut self, function: Fn, new_param: GenericParam) { |
| 11 | + match function.generic_param_list() { |
| 12 | + Some(generic_param_list) => match generic_param_list.generic_params().last() { |
| 13 | + Some(last_param) => { |
| 14 | + // There exists a generic param list and it's not empty |
| 15 | + let position = generic_param_list.r_angle_token().map_or_else( |
| 16 | + || Position::last_child_of(function.syntax()), |
| 17 | + Position::before, |
| 18 | + ); |
| 19 | + |
| 20 | + if last_param |
| 21 | + .syntax() |
| 22 | + .next_sibling_or_token() |
| 23 | + .map_or(false, |it| it.kind() == SyntaxKind::COMMA) |
| 24 | + { |
| 25 | + self.insert( |
| 26 | + Position::after(last_param.syntax()), |
| 27 | + new_param.syntax().clone(), |
| 28 | + ); |
| 29 | + self.insert( |
| 30 | + Position::after(last_param.syntax()), |
| 31 | + make::token(SyntaxKind::WHITESPACE), |
| 32 | + ); |
| 33 | + self.insert( |
| 34 | + Position::after(last_param.syntax()), |
| 35 | + make::token(SyntaxKind::COMMA), |
| 36 | + ); |
| 37 | + } else { |
| 38 | + let elements = vec![ |
| 39 | + make::token(SyntaxKind::COMMA).into(), |
| 40 | + make::token(SyntaxKind::WHITESPACE).into(), |
| 41 | + new_param.syntax().clone().into(), |
| 42 | + ]; |
| 43 | + self.insert_all(position, elements); |
| 44 | + } |
| 45 | + } |
| 46 | + None => { |
| 47 | + // There exists a generic param list but it's empty |
| 48 | + let position = Position::after(generic_param_list.l_angle_token().unwrap()); |
| 49 | + self.insert(position, new_param.syntax()); |
| 50 | + } |
| 51 | + }, |
| 52 | + None => { |
| 53 | + // There was no generic param list |
| 54 | + let position = if let Some(name) = function.name() { |
| 55 | + Position::after(name.syntax) |
| 56 | + } else if let Some(fn_token) = function.fn_token() { |
| 57 | + Position::after(fn_token) |
| 58 | + } else if let Some(param_list) = function.param_list() { |
| 59 | + Position::before(param_list.syntax) |
| 60 | + } else { |
| 61 | + Position::last_child_of(function.syntax()) |
| 62 | + }; |
| 63 | + let elements = vec![ |
| 64 | + make::token(SyntaxKind::L_ANGLE).into(), |
| 65 | + new_param.syntax().clone().into(), |
| 66 | + make::token(SyntaxKind::R_ANGLE).into(), |
| 67 | + ]; |
| 68 | + self.insert_all(position, elements); |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments