Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
use syntax::{
    ast::{self, edit::AstNodeEdit},
    AstNode, T,
};

use crate::{AssistContext, AssistId, AssistKind, Assists};

// Assist: unwrap_tuple
//
// Unwrap the tuple to different variables.
//
// ```
// # //- minicore: result
// fn main() {
//     $0let (foo, bar) = ("Foo", "Bar");
// }
// ```
// ->
// ```
// fn main() {
//     let foo = "Foo";
//     let bar = "Bar";
// }
// ```
pub(crate) fn unwrap_tuple(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
    let let_kw = ctx.find_token_syntax_at_offset(T![let])?;
    let let_stmt = let_kw.parent().and_then(ast::LetStmt::cast)?;
    let indent_level = let_stmt.indent_level().0 as usize;
    let pat = let_stmt.pat()?;
    let ty = let_stmt.ty();
    let init = let_stmt.initializer()?;

    // This only applies for tuple patterns, types, and initializers.
    let tuple_pat = match pat {
        ast::Pat::TuplePat(pat) => pat,
        _ => return None,
    };
    let tuple_ty = ty.and_then(|it| match it {
        ast::Type::TupleType(ty) => Some(ty),
        _ => None,
    });
    let tuple_init = match init {
        ast::Expr::TupleExpr(expr) => expr,
        _ => return None,
    };

    if tuple_pat.fields().count() != tuple_init.fields().count() {
        return None;
    }
    if let Some(tys) = &tuple_ty {
        if tuple_pat.fields().count() != tys.fields().count() {
            return None;
        }
    }

    let parent = let_kw.parent()?;

    acc.add(
        AssistId("unwrap_tuple", AssistKind::RefactorRewrite),
        "Unwrap tuple",
        let_kw.text_range(),
        |edit| {
            let indents = "    ".repeat(indent_level);

            // If there is an ascribed type, insert that type for each declaration,
            // otherwise, omit that type.
            if let Some(tys) = tuple_ty {
                let mut zipped_decls = String::new();
                for (pat, ty, expr) in
                    itertools::izip!(tuple_pat.fields(), tys.fields(), tuple_init.fields())
                {
                    zipped_decls.push_str(&format!("{indents}let {pat}: {ty} = {expr};\n"))
                }
                edit.replace(parent.text_range(), zipped_decls.trim());
            } else {
                let mut zipped_decls = String::new();
                for (pat, expr) in itertools::izip!(tuple_pat.fields(), tuple_init.fields()) {
                    zipped_decls.push_str(&format!("{indents}let {pat} = {expr};\n"));
                }
                edit.replace(parent.text_range(), zipped_decls.trim());
            }
        },
    )
}

#[cfg(test)]
mod tests {
    use crate::tests::check_assist;

    use super::*;

    #[test]
    fn unwrap_tuples() {
        check_assist(
            unwrap_tuple,
            r#"
fn main() {
    $0let (foo, bar) = ("Foo", "Bar");
}
"#,
            r#"
fn main() {
    let foo = "Foo";
    let bar = "Bar";
}
"#,
        );

        check_assist(
            unwrap_tuple,
            r#"
fn main() {
    $0let (foo, bar, baz) = ("Foo", "Bar", "Baz");
}
"#,
            r#"
fn main() {
    let foo = "Foo";
    let bar = "Bar";
    let baz = "Baz";
}
"#,
        );
    }

    #[test]
    fn unwrap_tuple_with_types() {
        check_assist(
            unwrap_tuple,
            r#"
fn main() {
    $0let (foo, bar): (u8, i32) = (5, 10);
}
"#,
            r#"
fn main() {
    let foo: u8 = 5;
    let bar: i32 = 10;
}
"#,
        );

        check_assist(
            unwrap_tuple,
            r#"
fn main() {
    $0let (foo, bar, baz): (u8, i32, f64) = (5, 10, 17.5);
}
"#,
            r#"
fn main() {
    let foo: u8 = 5;
    let bar: i32 = 10;
    let baz: f64 = 17.5;
}
"#,
        );
    }
}
ne(line); } else { on_stderr_line(line); } } if eof { on_eof(); } } })?; Ok((stdout, stderr)) } pub fn spawn_with_streaming_output( mut cmd: Command, on_stdout_line: &mut dyn FnMut(&str), on_stderr_line: &mut dyn FnMut(&str), ) -> io::Result<Output> { let cmd = cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::null()); let mut child = JodChild(cmd.spawn()?); let (stdout, stderr) = streaming_output( child.stdout.take().unwrap(), child.stderr.take().unwrap(), on_stdout_line, on_stderr_line, &mut || (), )?; let status = child.wait()?; Ok(Output { status, stdout, stderr }) } #[cfg(unix)] mod imp { use std::{ io::{self, prelude::*}, mem, os::unix::prelude::*, process::{ChildStderr, ChildStdout}, }; pub(crate) fn read2( mut out_pipe: ChildStdout, mut err_pipe: ChildStderr, data: &mut dyn FnMut(bool, &mut Vec<u8>, bool), ) -> io::Result<()> { unsafe { libc::fcntl(out_pipe.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK); libc::fcntl(err_pipe.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK); } let mut out_done = false; let mut err_done = false; let mut out = Vec::new(); let mut err = Vec::new(); let mut fds: [libc::pollfd; 2] = unsafe { mem::zeroed() }; fds[0].fd = out_pipe.as_raw_fd(); fds[0].events = libc::POLLIN; fds[1].fd = err_pipe.as_raw_fd(); fds[1].events = libc::POLLIN; let mut nfds = 2; let mut errfd = 1; while nfds > 0 { // wait for either pipe to become readable using `select` let r = unsafe { libc::poll(fds.as_mut_ptr(), nfds, -1) }; if r == -1 { let err = io::Error::last_os_error(); if err.kind() == io::ErrorKind::Interrupted { continue; } return Err(err); } // Read as much as we can from each pipe, ignoring EWOULDBLOCK or // EAGAIN. If we hit EOF, then this will happen because the underlying // reader will return Ok(0), in which case we'll see `Ok` ourselves. In // this case we flip the other fd back into blocking mode and read // whatever's leftover on that file descriptor. let handle = |res: io::Result<_>| match res { Ok(_) => Ok(true), Err(e) => { if e.kind() == io::ErrorKind::WouldBlock { Ok(false) } else { Err(e) } } }; if !err_done && fds[errfd].revents != 0 && handle(err_pipe.read_to_end(&mut err))? { err_done = true; nfds -= 1; } data(false, &mut err, err_done); if !out_done && fds[0].revents != 0 && handle(out_pipe.read_to_end(&mut out))? { out_done = true; fds[0].fd = err_pipe.as_raw_fd(); errfd = 0; nfds -= 1; } data(true, &mut out, out_done); } Ok(()) } } #[cfg(windows)] mod imp { use std::{ io, os::windows::prelude::*, process::{ChildStderr, ChildStdout}, slice, }; use miow::{ iocp::{CompletionPort, CompletionStatus}, pipe::NamedPipe, Overlapped, }; use windows_sys::Win32::Foundation::ERROR_BROKEN_PIPE; struct Pipe<'a> { dst: &'a mut Vec<u8>, overlapped: Overlapped, pipe: NamedPipe, done: bool, } pub(crate) fn read2( out_pipe: ChildStdout, err_pipe: ChildStderr, data: &mut dyn FnMut(bool, &mut Vec<u8>, bool), ) -> io::Result<()> { let mut out = Vec::new(); let mut err = Vec::new(); let port = CompletionPort::new(1)?; port.add_handle(0, &out_pipe)?; port.add_handle(1, &err_pipe)?; unsafe { let mut out_pipe = Pipe::new(out_pipe, &mut out); let mut err_pipe = Pipe::new(err_pipe, &mut err); out_pipe.read()?; err_pipe.read()?; let mut status = [CompletionStatus::zero(), CompletionStatus::zero()]; while !out_pipe.done || !err_pipe.done { for status in port.get_many(&mut status, None)? { if status.token() == 0 { out_pipe.complete(status); data(true, out_pipe.dst, out_pipe.done); out_pipe.read()?; } else { err_pipe.complete(status); data(false, err_pipe.dst, err_pipe.done); err_pipe.read()?; } } } Ok(()) } } impl<'a> Pipe<'a> { unsafe fn new<P: IntoRawHandle>(p: P, dst: &'a mut Vec<u8>) -> Pipe<'a> { let pipe = unsafe { NamedPipe::from_raw_handle(p.into_raw_handle()) }; Pipe { dst, pipe, overlapped: Overlapped::zero(), done: false } } unsafe fn read(&mut self) -> io::Result<()> { let dst = unsafe { slice_to_end(self.dst) }; match unsafe { self.pipe.read_overlapped(dst, self.overlapped.raw()) } { Ok(_) => Ok(()), Err(e) => { if e.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) { self.done = true; Ok(()) } else { Err(e) } } } } unsafe fn complete(&mut self, status: &CompletionStatus) { let prev = self.dst.len(); unsafe { self.dst.set_len(prev + status.bytes_transferred() as usize) }; if status.bytes_transferred() == 0 { self.done = true; } } } unsafe fn slice_to_end(v: &mut Vec<u8>) -> &mut [u8] { if v.capacity() == 0 { v.reserve(16); } if v.capacity() == v.len() { v.reserve(1); } let data = unsafe { v.as_mut_ptr().add(v.len()) }; let len = v.capacity() - v.len(); unsafe { slice::from_raw_parts_mut(data, len) } } } #[cfg(target_arch = "wasm32")] mod imp { use std::{ io, process::{ChildStderr, ChildStdout}, }; pub(crate) fn read2( _out_pipe: ChildStdout, _err_pipe: ChildStderr, _data: &mut dyn FnMut(bool, &mut Vec<u8>, bool), ) -> io::Result<()> { panic!("no processes on wasm") } }