Skip to main content

rustidy_ast_util/
line.rs

1//! Line remainder
2
3// Imports
4use {
5	rustidy_format::{Format, Formattable},
6	rustidy_parse::Parse,
7	rustidy_print::Print,
8	rustidy_util::AstStr,
9};
10
11/// Characters remaining until the end of the line (including the newline if it exists)
12#[derive(PartialEq, Eq, Clone, Debug)]
13#[derive(serde::Serialize, serde::Deserialize)]
14#[derive(Parse, Formattable, Format, Print)]
15#[parse(name = "remaining characters in line")]
16#[format(no_prefix_ws)]
17pub struct RemainingLine(#[parse(update_with = Self::parse)] #[format(str)] pub AstStr);
18
19impl RemainingLine {
20	fn parse(s: &mut &str) {
21		*s = match s.find('\n') {
22			Some(idx) => &s[idx + 1..],
23			None => &s[s.len()..],
24		};
25	}
26}
27
28/// Characters remaining until the end of block comment
29// TODO: This should not be in this file, or maybe this file should
30//       just be merged with `attr.rs`.
31#[derive(PartialEq, Eq, Clone, Debug)]
32#[derive(serde::Serialize, serde::Deserialize)]
33#[derive(Parse, Formattable, Format, Print)]
34#[parse(name = "remaining characters in block comment")]
35#[parse(error(name = MissingCommentEnd, fmt = "Expected `*/` after `/*`", fatal))]
36pub struct RemainingBlockComment(#[parse(try_update_with = Self::parse)] #[format(str)] pub AstStr);
37
38impl RemainingBlockComment {
39	// TODO: Deduplicate this with `whitespace::BlockComment::parse`
40	fn parse(s: &mut &str) -> Result<(), RemainingBlockCommentError> {
41		let mut depth = 1;
42		while depth != 0 {
43			let close_idx = s
44				.find("*/")
45				.ok_or(RemainingBlockCommentError::MissingCommentEnd)?;
46
47			match s[..close_idx].find("/*") {
48				Some(open_idx) => {
49					*s = &s[open_idx + 2..];
50					depth += 1;
51				},
52				None => {
53					*s = &s[close_idx + 2..];
54					depth -= 1;
55				},
56			}
57		}
58
59		Ok(())
60	}
61}