├── .gitignore ├── tests └── suite │ ├── futures_core │ ├── test.sh │ ├── task │ │ ├── mod.rs │ │ ├── __internal │ │ │ ├── mod.rs │ │ │ └── atomic_waker.rs │ │ └── spawn.rs │ ├── output.rs │ ├── input.rs │ ├── LICENSE-MIT │ ├── future │ │ ├── mod.rs │ │ └── future_obj.rs │ ├── stream │ │ └── mod.rs │ └── LICENSE-APACHE │ └── main.rs ├── Cargo.toml ├── src ├── transforms │ ├── mod.rs │ ├── clear_blocks.rs │ ├── prune_items.rs │ └── remove_doc_attrs.rs ├── main.rs └── output.rs ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /Cargo.lock 2 | /target 3 | **/*.rs.bk 4 | -------------------------------------------------------------------------------- /tests/suite/futures_core/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | rustc --crate-type lib -o /dev/null "$1" |& exec grep -q 'trait objects without an explicit `dyn` are deprecated' 3 | -------------------------------------------------------------------------------- /tests/suite/futures_core/task/mod.rs: -------------------------------------------------------------------------------- 1 | //! Task notification. 2 | 3 | mod spawn; 4 | #[doc(hidden)] 5 | pub mod __internal; 6 | pub use self::spawn::{Spawn, LocalSpawn, SpawnError}; 7 | 8 | pub use core::task::{Context, Poll, Waker, RawWaker, RawWakerVTable}; 9 | -------------------------------------------------------------------------------- /tests/suite/futures_core/task/__internal/mod.rs: -------------------------------------------------------------------------------- 1 | #[cfg_attr( 2 | feature = "cfg-target-has-atomic", 3 | cfg(all(target_has_atomic = "cas", target_has_atomic = "ptr")) 4 | )] 5 | mod atomic_waker; 6 | #[cfg_attr( 7 | feature = "cfg-target-has-atomic", 8 | cfg(all(target_has_atomic = "cas", target_has_atomic = "ptr")) 9 | )] 10 | pub use self::atomic_waker::AtomicWaker; 11 | -------------------------------------------------------------------------------- /tests/suite/futures_core/output.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(feature = "cfg-target-has-atomic", feature(cfg_target_has_atomic))] 2 | #![cfg_attr(not(feature = "std"), no_std)] 3 | #![warn( 4 | missing_docs, 5 | missing_debug_implementations, 6 | rust_2018_idioms, 7 | unreachable_pub 8 | )] 9 | #![warn(clippy::all)] 10 | pub mod future { 11 | mod future_obj { 12 | unsafe impl<'a, T, F> UnsafeFutureObj<'a, T> for &'a mut F 13 | where 14 | F: Future + Unpin + 'a, 15 | { 16 | fn into_raw(self) -> *mut (Future + 'a) { 17 | unimplemented!() 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rust-reduce" 3 | version = "0.1.0" 4 | authors = ["Jethro Beekman "] 5 | edition = "2018" 6 | license = "AGPL-3.0" 7 | description = "`rust-reduce` will try to make the source file smaller by interpreting it as valid Rust code and intelligently removing parts of the code." 8 | repository = "https://github.com/jethrogb/rust-reduce" 9 | 10 | [dependencies] 11 | syn = { version = "1.0", features = ["full", "visit-mut", "extra-traits"] } # MIT/Apache-2.0 12 | syn-inline-mod = "0.3" # MIT 13 | quote = "1.0" # MIT/Apache-2.0 14 | tempfile = "3" # MIT/Apache-2.0 15 | clap = { version = "2.33", default-features = false } # MIT 16 | -------------------------------------------------------------------------------- /src/transforms/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Jethro G. Beekman 2 | // 3 | // This file is part of rust-reduce. 4 | // 5 | // rust-reduce is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published 7 | // by the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // rust-reduce is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with rust-reduce. If not, see . 17 | 18 | pub mod prune_items; 19 | pub mod remove_doc_attrs; 20 | pub mod clear_blocks; 21 | -------------------------------------------------------------------------------- /tests/suite/futures_core/input.rs: -------------------------------------------------------------------------------- 1 | //! Core traits and types for asynchronous operations in Rust. 2 | 3 | #![cfg_attr(feature = "cfg-target-has-atomic", feature(cfg_target_has_atomic))] 4 | 5 | #![cfg_attr(not(feature = "std"), no_std)] 6 | 7 | #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms, unreachable_pub)] 8 | #![warn(clippy::all)] 9 | 10 | #![doc(html_root_url = "https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.16/futures_core")] 11 | 12 | #[cfg(all(feature = "cfg-target-has-atomic", not(feature = "nightly")))] 13 | compile_error!("The `cfg-target-has-atomic` feature requires the `nightly` feature as an explicit opt-in to unstable features"); 14 | 15 | #[cfg(feature = "alloc")] 16 | extern crate alloc; 17 | 18 | pub mod future; 19 | #[doc(hidden)] pub use self::future::{Future, FusedFuture, TryFuture}; 20 | 21 | pub mod stream; 22 | #[doc(hidden)] pub use self::stream::{Stream, FusedStream, TryStream}; 23 | 24 | pub mod task; 25 | #[doc(hidden)] pub use self::task::Poll; 26 | -------------------------------------------------------------------------------- /tests/suite/futures_core/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Alex Crichton 2 | Copyright (c) 2017 The Tokio Authors 3 | 4 | Permission is hereby granted, free of charge, to any 5 | person obtaining a copy of this software and associated 6 | documentation files (the "Software"), to deal in the 7 | Software without restriction, including without 8 | limitation the rights to use, copy, modify, merge, 9 | publish, distribute, sublicense, and/or sell copies of 10 | the Software, and to permit persons to whom the Software 11 | is furnished to do so, subject to the following 12 | conditions: 13 | 14 | The above copyright notice and this permission notice 15 | shall be included in all copies or substantial portions 16 | of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 19 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 20 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 21 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 22 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 23 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 24 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 25 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 26 | DEALINGS IN THE SOFTWARE. 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rust-reduce 2 | 3 | `rust-reduce` will try to make the source file smaller by interpreting it as valid Rust code and intelligently removing parts of the code. After each removal, the given command will be run but passing a path to a file containing the reduced code. The command should return 0 if run on the original input, and also if the reduced code is interesting, non-0 otherwise. 4 | 5 | The original file will be overwritten with the smallest interesting reduced version, if found. This happens while `rust-reduce` is running. The original file will be backed up with the `.orig` suffix. If `rustfmt` is found, it will be used to clean up the output. 6 | 7 | A common way to use `rust-reduce` is to write a short shell script that runs `rustc` and greps the compiler output for a particular error message. NB. you will want to look for a specific error message because while `rust-reduce` will generate syntactically correct code, it's not guaranteed to compile. 8 | 9 | The original file may refer to modules in different files, these will be inlined and reduced along with the main file. 10 | 11 | ## C-reduce 12 | 13 | This project is inspired by, and should be used in conjuniction with [C-reduce](http://embed.cs.utah.edu/creduce/). 14 | 15 | Although Rust and C syntax are different, they are similar enough that running C-reduce on Rust source code can be very effective! However, C-reduce only works with single input files, whereas Rust has a module system. `rust-reduce` can be run on an entire crate and will produce a single reduced output file. `rust-reduce` only implements a few reduction passes that are designed to remove large chunks of code, after which C-reduce can take over the reduction. 16 | 17 | When using C-reduce and `rust-reduce` in the same project, please take note that `rust-reduce` will change the command line of the test command whereas C-reduce won't. 18 | 19 | ## Passes 20 | 21 | Take a look at `src/transforms` to see the kind of reductions `rust-reduce` can do. 22 | 23 | ## Examples 24 | 25 | Take a look at the test suite in `tests/suite` for example usage. 26 | -------------------------------------------------------------------------------- /tests/suite/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Jethro G. Beekman 2 | // 3 | // This file is part of rust-reduce. 4 | // 5 | // rust-reduce is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published 7 | // by the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // rust-reduce is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with rust-reduce. If not, see . 17 | 18 | use std::{env, fs, path::PathBuf, process::Command}; 19 | 20 | fn run_test(dir: &str) { 21 | let mut path = tests_dir(); 22 | path.push(dir); 23 | 24 | let out = Command::new(find_rust_reduce()) 25 | .args(&["-1", "-o", "-"]) 26 | .args(&[path.join("test.sh"), path.join("input.rs")]) 27 | .output() 28 | .unwrap(); 29 | 30 | if !out.status.success() { 31 | eprintln!("`rust-reduce` failed with {}", out.status); 32 | eprintln!("{}", String::from_utf8(out.stderr).unwrap()); 33 | panic!("Test failed"); 34 | } 35 | let expected = fs::read_to_string(path.join("output.rs")).unwrap(); 36 | assert_eq!(String::from_utf8(out.stdout).unwrap(), expected); 37 | } 38 | 39 | macro_rules! tests { 40 | ($($s:ident),* $(,)*) => { 41 | $( 42 | #[test] 43 | fn $s() { 44 | run_test(stringify!($s)); 45 | } 46 | )* 47 | } 48 | } 49 | 50 | tests!( 51 | futures_core 52 | ); 53 | 54 | fn find_rust_reduce() -> PathBuf { 55 | let mut path = env::current_exe().unwrap(); 56 | path.pop(); 57 | if path.ends_with("deps") { 58 | path.pop(); 59 | } 60 | path.push("rust-reduce"); 61 | path.set_extension(env::consts::EXE_EXTENSION); 62 | path 63 | } 64 | 65 | fn tests_dir() -> PathBuf { 66 | let mut path = PathBuf::from(file!()); 67 | path.pop(); 68 | path 69 | } 70 | -------------------------------------------------------------------------------- /src/transforms/clear_blocks.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Jethro G. Beekman 2 | // 3 | // This file is part of rust-reduce. 4 | // 5 | // rust-reduce is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published 7 | // by the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // rust-reduce is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with rust-reduce. If not, see . 17 | 18 | /// Try to replace each block with `{ unimplemented!() }`, similar to `rustc`'s 19 | /// every body loops printer. 20 | 21 | use std::mem; 22 | 23 | use syn::visit_mut::*; 24 | use quote::quote; 25 | 26 | pub fn clear_blocks bool>(file: &mut syn::File, mut try_compile: F) { 27 | let mut visitor = BlockVisitor { 28 | backup: None, 29 | cur_index: 0, 30 | target_index: 1, 31 | unimplemented: syn::parse2(quote!( { unimplemented!() } )).unwrap() 32 | }; 33 | 34 | loop { 35 | visitor.cur_index = 0; 36 | visit_file_mut(&mut visitor, file); 37 | 38 | // no more changes to be made 39 | if visitor.backup.is_none() { 40 | break 41 | } 42 | 43 | if try_compile(file) { 44 | // this change works, keep it! 45 | visitor.backup = None; 46 | } 47 | } 48 | } 49 | 50 | struct BlockVisitor { 51 | backup: Option, 52 | cur_index: usize, 53 | target_index: usize, 54 | unimplemented: syn::Block, 55 | } 56 | 57 | impl VisitMut for BlockVisitor { 58 | fn visit_block_mut(&mut self, i: &mut syn::Block) { 59 | self.cur_index += 1; 60 | 61 | if self.target_index == self.cur_index { 62 | if let Some(backup) = self.backup.take() { 63 | // the change we tried didn't work. revert and try the next 64 | // possible change 65 | mem::replace(i, backup); 66 | } else if *i != self.unimplemented { 67 | self.backup = Some(mem::replace(i, self.unimplemented.clone())); 68 | return; 69 | } 70 | 71 | self.target_index += 1; 72 | } 73 | 74 | visit_block_mut(self, i) 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/transforms/prune_items.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Jethro G. Beekman 2 | // 3 | // This file is part of rust-reduce. 4 | // 5 | // rust-reduce is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published 7 | // by the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // rust-reduce is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with rust-reduce. If not, see . 17 | 18 | /// Try to remove each item. 19 | 20 | pub fn prune_items bool>(file: &mut syn::File, mut try_compile: F) { 21 | let mut level = 0; 22 | let mut index = 0; 23 | loop { 24 | let backup = file.clone(); 25 | if !file.items.prune(level, &mut {index}) { 26 | if index == 0 { 27 | break; 28 | } 29 | level += 1; 30 | index = 0; 31 | continue; 32 | } 33 | if !try_compile(&file) { 34 | *file = backup; 35 | index += 1; 36 | } else { 37 | // try delete next, which will be at same index now that we've 38 | // deleted something 39 | } 40 | } 41 | } 42 | 43 | trait Prune { 44 | fn prune(&mut self, level: usize, index: &mut usize) -> bool; 45 | } 46 | 47 | impl Prune for Vec { 48 | fn prune(&mut self, level: usize, index: &mut usize) -> bool { 49 | if level == 0 { 50 | if *index < self.len() { 51 | self.remove(*index); 52 | true 53 | } else { 54 | *index -= self.len(); 55 | false 56 | } 57 | } else { 58 | for item in self { 59 | if match item { 60 | syn::Item::Mod(syn::ItemMod { content: Some((_, items)), .. }) 61 | => items.prune(level - 1, index), 62 | syn::Item::Impl(syn::ItemImpl { items, .. }) 63 | => items.prune(level - 1, index), 64 | _ => false 65 | } { 66 | return true 67 | } 68 | } 69 | false 70 | } 71 | } 72 | } 73 | 74 | impl Prune for Vec { 75 | fn prune(&mut self, level: usize, index: &mut usize) -> bool { 76 | if level == 0 { 77 | if *index < self.len() { 78 | self.remove(*index); 79 | true 80 | } else { 81 | *index -= self.len(); 82 | false 83 | } 84 | } else { 85 | false 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /tests/suite/futures_core/future/mod.rs: -------------------------------------------------------------------------------- 1 | //! Futures. 2 | 3 | use core::ops::DerefMut; 4 | use core::pin::Pin; 5 | use core::task::{Context, Poll}; 6 | 7 | pub use core::future::Future; 8 | 9 | mod future_obj; 10 | pub use self::future_obj::{FutureObj, LocalFutureObj, UnsafeFutureObj}; 11 | 12 | #[cfg(feature = "alloc")] 13 | /// An owned dynamically typed [`Future`] for use in cases where you can't 14 | /// statically type your result or need to add some indirection. 15 | pub type BoxFuture<'a, T> = Pin + Send + 'a>>; 16 | 17 | #[cfg(feature = "alloc")] 18 | /// `BoxFuture`, but without the `Send` requirement. 19 | pub type LocalBoxFuture<'a, T> = Pin + 'a>>; 20 | 21 | /// A `Future` or `TryFuture` which tracks whether or not the underlying future 22 | /// should no longer be polled. 23 | /// 24 | /// `is_terminated` will return `true` if a future should no longer be polled. 25 | /// Usually, this state occurs after `poll` (or `try_poll`) returned 26 | /// `Poll::Ready`. However, `is_terminated` may also return `true` if a future 27 | /// has become inactive and can no longer make progress and should be ignored 28 | /// or dropped rather than being `poll`ed again. 29 | pub trait FusedFuture { 30 | /// Returns `true` if the underlying future should no longer be polled. 31 | fn is_terminated(&self) -> bool; 32 | } 33 | 34 | impl FusedFuture for &mut F { 35 | fn is_terminated(&self) -> bool { 36 | ::is_terminated(&**self) 37 | } 38 | } 39 | 40 | impl

FusedFuture for Pin

41 | where 42 | P: DerefMut + Unpin, 43 | P::Target: FusedFuture, 44 | { 45 | fn is_terminated(&self) -> bool { 46 | ::is_terminated(&**self) 47 | } 48 | } 49 | 50 | /// A convenience for futures that return `Result` values that includes 51 | /// a variety of adapters tailored to such futures. 52 | pub trait TryFuture { 53 | /// The type of successful values yielded by this future 54 | type Ok; 55 | 56 | /// The type of failures yielded by this future 57 | type Error; 58 | 59 | /// Poll this `TryFuture` as if it were a `Future`. 60 | /// 61 | /// This method is a stopgap for a compiler limitation that prevents us from 62 | /// directly inheriting from the `Future` trait; in the future it won't be 63 | /// needed. 64 | fn try_poll( 65 | self: Pin<&mut Self>, 66 | cx: &mut Context<'_>, 67 | ) -> Poll>; 68 | } 69 | 70 | impl TryFuture for F 71 | where F: ?Sized + Future> 72 | { 73 | type Ok = T; 74 | type Error = E; 75 | 76 | #[inline] 77 | fn try_poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 78 | self.poll(cx) 79 | } 80 | } 81 | 82 | #[cfg(feature = "alloc")] 83 | mod if_alloc { 84 | use alloc::boxed::Box; 85 | use super::*; 86 | 87 | impl FusedFuture for Box { 88 | fn is_terminated(&self) -> bool { 89 | ::is_terminated(&**self) 90 | } 91 | } 92 | 93 | #[cfg(feature = "std")] 94 | impl FusedFuture for std::panic::AssertUnwindSafe { 95 | fn is_terminated(&self) -> bool { 96 | ::is_terminated(&**self) 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /tests/suite/futures_core/task/spawn.rs: -------------------------------------------------------------------------------- 1 | use crate::future::{FutureObj, LocalFutureObj}; 2 | use core::fmt; 3 | 4 | /// The `Spawn` trait allows for pushing futures onto an executor that will 5 | /// run them to completion. 6 | pub trait Spawn { 7 | /// Spawns a future that will be run to completion. 8 | /// 9 | /// # Errors 10 | /// 11 | /// The executor may be unable to spawn tasks. Spawn errors should 12 | /// represent relatively rare scenarios, such as the executor 13 | /// having been shut down so that it is no longer able to accept 14 | /// tasks. 15 | fn spawn_obj(&mut self, future: FutureObj<'static, ()>) 16 | -> Result<(), SpawnError>; 17 | 18 | /// Determines whether the executor is able to spawn new tasks. 19 | /// 20 | /// This method will return `Ok` when the executor is *likely* 21 | /// (but not guaranteed) to accept a subsequent spawn attempt. 22 | /// Likewise, an `Err` return means that `spawn` is likely, but 23 | /// not guaranteed, to yield an error. 24 | #[inline] 25 | fn status(&self) -> Result<(), SpawnError> { 26 | Ok(()) 27 | } 28 | } 29 | 30 | /// The `LocalSpawn` is similar to [`Spawn`], but allows spawning futures 31 | /// that don't implement `Send`. 32 | pub trait LocalSpawn { 33 | /// Spawns a future that will be run to completion. 34 | /// 35 | /// # Errors 36 | /// 37 | /// The executor may be unable to spawn tasks. Spawn errors should 38 | /// represent relatively rare scenarios, such as the executor 39 | /// having been shut down so that it is no longer able to accept 40 | /// tasks. 41 | fn spawn_local_obj(&mut self, future: LocalFutureObj<'static, ()>) 42 | -> Result<(), SpawnError>; 43 | 44 | /// Determines whether the executor is able to spawn new tasks. 45 | /// 46 | /// This method will return `Ok` when the executor is *likely* 47 | /// (but not guaranteed) to accept a subsequent spawn attempt. 48 | /// Likewise, an `Err` return means that `spawn` is likely, but 49 | /// not guaranteed, to yield an error. 50 | #[inline] 51 | fn status_local(&self) -> Result<(), SpawnError> { 52 | Ok(()) 53 | } 54 | } 55 | 56 | /// An error that occurred during spawning. 57 | pub struct SpawnError { 58 | _hidden: (), 59 | } 60 | 61 | impl fmt::Debug for SpawnError { 62 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 63 | f.debug_tuple("SpawnError") 64 | .field(&"shutdown") 65 | .finish() 66 | } 67 | } 68 | 69 | impl fmt::Display for SpawnError { 70 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 71 | write!(f, "Executor is shutdown") 72 | } 73 | } 74 | 75 | #[cfg(feature = "std")] 76 | impl std::error::Error for SpawnError {} 77 | 78 | impl SpawnError { 79 | /// Spawning failed because the executor has been shut down. 80 | pub fn shutdown() -> Self { 81 | Self { _hidden: () } 82 | } 83 | 84 | /// Check whether spawning failed to the executor being shut down. 85 | pub fn is_shutdown(&self) -> bool { 86 | true 87 | } 88 | } 89 | 90 | impl Spawn for &mut Sp { 91 | fn spawn_obj(&mut self, future: FutureObj<'static, ()>) 92 | -> Result<(), SpawnError> { 93 | Sp::spawn_obj(self, future) 94 | } 95 | 96 | fn status(&self) -> Result<(), SpawnError> { 97 | Sp::status(self) 98 | } 99 | } 100 | 101 | impl LocalSpawn for &mut Sp { 102 | fn spawn_local_obj(&mut self, future: LocalFutureObj<'static, ()>) 103 | -> Result<(), SpawnError> { 104 | Sp::spawn_local_obj(self, future) 105 | } 106 | 107 | fn status_local(&self) -> Result<(), SpawnError> { 108 | Sp::status_local(self) 109 | } 110 | } 111 | 112 | #[cfg(feature = "alloc")] 113 | mod if_alloc { 114 | use alloc::boxed::Box; 115 | use super::*; 116 | 117 | impl Spawn for Box { 118 | fn spawn_obj(&mut self, future: FutureObj<'static, ()>) 119 | -> Result<(), SpawnError> { 120 | (**self).spawn_obj(future) 121 | } 122 | 123 | fn status(&self) -> Result<(), SpawnError> { 124 | (**self).status() 125 | } 126 | } 127 | 128 | impl LocalSpawn for Box { 129 | fn spawn_local_obj(&mut self, future: LocalFutureObj<'static, ()>) 130 | -> Result<(), SpawnError> { 131 | (**self).spawn_local_obj(future) 132 | } 133 | 134 | fn status_local(&self) -> Result<(), SpawnError> { 135 | (**self).status_local() 136 | } 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Jethro G. Beekman 2 | // 3 | // This file is part of rust-reduce. 4 | // 5 | // rust-reduce is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published 7 | // by the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // rust-reduce is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with rust-reduce. If not, see . 17 | 18 | use std::{ffi::OsString, io::Write, process::{Command, Stdio}}; 19 | 20 | use clap::clap_app; 21 | use quote::ToTokens; 22 | use syn_inline_mod::{Error as InlineError, InlinerBuilder}; 23 | use tempfile::NamedTempFile; 24 | 25 | mod output; 26 | mod transforms; 27 | 28 | fn main() { 29 | let matches = clap_app!(("rust-reduce") => 30 | (version: clap::crate_version!()) 31 | (@arg CMD: * "Command to run.") 32 | (@arg ARGS: * ... "Arguments to the command to run. 33 | 34 | The last argument must be the path of the existing file of interest. CMD will be invoked with the last argument replaced with the path to a temporary file. 35 | 36 | You can use `--` to separate ARGS from any arguments passed to `rust-reduce`.") 37 | (@arg FILE: -o --output +takes_value "Reduced output file (default is to replace input file).") 38 | (@arg ONCE: short("1") --("no-progress") "Only save the fully reduced output, not the intermediates.") 39 | (after_help: "\ 40 | `rust-reduce` will try to make the source file smaller by interpreting it as valid Rust code and intelligently removing parts of the code. After each removal, the given command will be run but passing a path to a file containing the reduced code. The command should return 0 if run on the original input, and also if the reduced code is interesting, non-0 otherwise. 41 | 42 | The original file will be overwritten with the smallest interesting reduced version, if found. This happens while `rust-reduce` is running. The original file will be backed up with the `.orig` suffix. If `rustfmt` is found, it will be used to clean up the output. 43 | 44 | A common way to use `rust-reduce` is to write a short shell script that runs `rustc` and greps the compiler output for a particular error message. NB. you will want to look for a specific error message because while `rust-reduce` will generate syntactically correct code, it's not guaranteed to compile. 45 | 46 | The original file may refer to modules in different files, these will be inlined and reduced along with the main file.") 47 | ).get_matches(); 48 | 49 | let mut cmd = vec![matches.value_of_os("CMD").expect("validated").to_owned()]; 50 | let mut iter = matches.values_of_os("ARGS").expect("validated").map(ToOwned::to_owned); 51 | let file = iter.next_back().expect("validated"); 52 | cmd.extend(iter); 53 | 54 | if !run_with_path(&cmd, &file) { 55 | eprintln!("rust-reduce: run with initial input did not indicate success"); 56 | std::process::exit(1); 57 | } 58 | 59 | let mut inlined_file = match InlinerBuilder::new() 60 | .error_not_found(true) 61 | .parse_and_inline_modules(file.as_ref()) { 62 | Ok(f) => f, 63 | Err(InlineError::NotFound(missing)) => { 64 | eprintln!("rust-reduce: file not found"); 65 | for (modname, loc) in missing { 66 | eprintln!(" mod {} @ {}:{}", modname, loc.path.display(), loc.line); 67 | } 68 | std::process::exit(1); 69 | }, 70 | Err(_) => unimplemented!() 71 | }; 72 | let mut output = (if matches.is_present("ONCE") { 73 | output::WaitGuard::new:: 74 | } else { 75 | output::WaitGuard::new:: 76 | })( 77 | matches.value_of_os("FILE").map(ToOwned::to_owned).unwrap_or(file), 78 | !matches.is_present("FILE") 79 | ); 80 | 81 | let mut try_compile = |reduced_file: &_| { 82 | let result = run_with_path(&cmd, &write_file(reduced_file).path()); 83 | 84 | if result { 85 | output.output_formatted(reduced_file) 86 | } 87 | 88 | result 89 | }; 90 | 91 | eprintln!("Pruning items"); 92 | transforms::prune_items::prune_items(&mut inlined_file, &mut try_compile); 93 | eprintln!("Removing #[doc] attributes"); 94 | transforms::remove_doc_attrs::remove_doc_attrs(&mut inlined_file, &mut try_compile); 95 | eprintln!("Clearing block bodies"); 96 | transforms::clear_blocks::clear_blocks(&mut inlined_file, &mut try_compile); 97 | } 98 | 99 | fn run_with_path>(cmd: &[OsString], path: &P) -> bool { 100 | let (cmd, args) = cmd.split_first().expect("validated"); 101 | match Command::new(cmd) 102 | .args(args) 103 | .arg(path.as_ref()) 104 | .stdout(Stdio::null()) 105 | .stderr(Stdio::null()) 106 | .status() 107 | { 108 | Ok(ref stat) if stat.success() => true, 109 | _ => false 110 | } 111 | } 112 | 113 | fn write_file(contents: &syn::File) -> NamedTempFile { 114 | let mut file = tempfile::Builder::new().prefix("test").tempfile().unwrap(); 115 | write!(file, "{}", contents.into_token_stream()).unwrap(); 116 | file.flush().unwrap(); 117 | file 118 | } 119 | -------------------------------------------------------------------------------- /src/output.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Jethro G. Beekman 2 | // 3 | // This file is part of rust-reduce. 4 | // 5 | // rust-reduce is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published 7 | // by the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // rust-reduce is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with rust-reduce. If not, see . 17 | 18 | use std::{ffi::OsStr, fs, io::Write, path::PathBuf, process::{Command, Stdio}, sync::mpsc, thread::{self, JoinHandle}}; 19 | 20 | use quote::ToTokens; 21 | 22 | /// A type that will wait during `Drop` for all output operations to complete. 23 | pub struct WaitGuard { 24 | path: Option, 25 | constructor: fn(PathBuf, bool) -> Box, 26 | inner: Option>, 27 | need_backup: bool, 28 | } 29 | 30 | impl WaitGuard { 31 | pub fn new>(path: P, need_backup: bool) -> Self { 32 | WaitGuard { 33 | path: Some(path.into()), 34 | constructor: T::new, 35 | inner: None, 36 | need_backup, 37 | } 38 | } 39 | 40 | pub fn output_formatted(&mut self, reduced_file: &syn::File) { 41 | let path = self.path.take(); 42 | let WaitGuard { constructor, need_backup, .. } = *self; 43 | self.inner.get_or_insert_with(|| constructor(path.unwrap(), need_backup)) 44 | .output(reduced_file.into_token_stream().to_string()) 45 | } 46 | } 47 | 48 | pub trait OutputType { 49 | fn new(path: PathBuf, need_backup: bool) -> Box where Self: Sized; 50 | fn output(&mut self, reduced_file: String); 51 | } 52 | 53 | pub struct AsyncWriter { 54 | chan: mpsc::Sender, 55 | thread: Option>, 56 | } 57 | 58 | impl OutputType for AsyncWriter { 59 | fn new(file: PathBuf, need_backup: bool) -> Box { 60 | let (send, recv) = mpsc::channel(); 61 | 62 | let thread = thread::spawn(move || { 63 | TargetFileWorker { 64 | backed_up: !need_backup, 65 | file, 66 | chan: recv, 67 | }.run() 68 | }); 69 | 70 | Box::new(AsyncWriter { 71 | chan: send, 72 | thread: Some(thread), 73 | }) 74 | } 75 | 76 | fn output(&mut self, reduced_file: String) { 77 | self.chan.send(Message::Work(reduced_file)).unwrap() 78 | } 79 | } 80 | 81 | impl Drop for AsyncWriter { 82 | fn drop(&mut self) { 83 | self.chan.send(Message::Quit).unwrap(); 84 | self.thread.take().unwrap().join().unwrap() 85 | } 86 | } 87 | 88 | pub struct LastWriter { 89 | worker: TargetFileWorker, 90 | last: Option, 91 | } 92 | 93 | impl OutputType for LastWriter { 94 | fn new(file: PathBuf, need_backup: bool) -> Box { 95 | Box::new(LastWriter { 96 | worker: TargetFileWorker { 97 | backed_up: !need_backup, 98 | file, 99 | chan: mpsc::channel().1, 100 | }, 101 | last: None, 102 | }) 103 | } 104 | 105 | fn output(&mut self, reduced_file: String) { 106 | self.last = Some(reduced_file); 107 | } 108 | } 109 | 110 | impl Drop for LastWriter { 111 | fn drop(&mut self) { 112 | // unwrap ok: `new` is always immediately followed by `output` 113 | self.worker.emit_formatted_file(self.last.take().unwrap()); 114 | } 115 | } 116 | 117 | enum Message { 118 | Work(String), 119 | Quit 120 | } 121 | 122 | struct TargetFileWorker { 123 | backed_up: bool, 124 | file: PathBuf, 125 | chan: mpsc::Receiver, 126 | } 127 | 128 | impl TargetFileWorker { 129 | fn backup(&mut self) { 130 | if !self.backed_up { 131 | let mut orig = self.file.clone().into_os_string(); 132 | orig.push(".orig"); 133 | if let Err(e) = fs::copy(&self.file, orig) { 134 | eprintln!("Failed to backup input file: {}", e); 135 | std::process::exit(1); 136 | } 137 | self.backed_up = true; 138 | } 139 | } 140 | 141 | fn emit_formatted_file(&mut self, reduced_file: String) { 142 | self.backup(); 143 | 144 | eprintln!("{} bytes...", reduced_file.len()); 145 | 146 | match Command::new("rustfmt") 147 | .stdout(if self.file == OsStr::new("-") { 148 | Stdio::inherit() 149 | } else { 150 | Stdio::from(fs::File::create(&self.file).unwrap()) 151 | }) 152 | .stdin(Stdio::piped()) 153 | .spawn() { 154 | Ok(mut child) => { 155 | child.stdin.take().unwrap().write_all(reduced_file.as_bytes()).unwrap(); 156 | child.wait().unwrap(); 157 | } 158 | Err(_) => { 159 | if self.file == OsStr::new("-") { 160 | Box::new(std::io::stdout()) as Box 161 | } else { 162 | Box::new(fs::File::create(&self.file).unwrap()) 163 | }.write_all(reduced_file.as_bytes()).unwrap(); 164 | } 165 | } 166 | } 167 | 168 | fn run(&mut self) { 169 | let mut next = None; 170 | while let Message::Work(mut tokens) = next.unwrap_or_else(|| self.chan.recv().unwrap()) { 171 | next = None; 172 | 173 | // skip ahead if there's more work in the queue 174 | while let Ok(msg) = self.chan.try_recv() { 175 | match msg { 176 | Message::Work(new_toks) => tokens = new_toks, 177 | other => next = Some(other), 178 | } 179 | } 180 | 181 | self.emit_formatted_file(tokens) 182 | } 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /tests/suite/futures_core/stream/mod.rs: -------------------------------------------------------------------------------- 1 | //! Asynchronous streams. 2 | 3 | use core::ops::DerefMut; 4 | use core::pin::Pin; 5 | use core::task::{Context, Poll}; 6 | 7 | #[cfg(feature = "alloc")] 8 | /// An owned dynamically typed [`Stream`] for use in cases where you can't 9 | /// statically type your result or need to add some indirection. 10 | pub type BoxStream<'a, T> = Pin + Send + 'a>>; 11 | 12 | /// A stream of values produced asynchronously. 13 | /// 14 | /// If `Future` is an asynchronous version of `T`, then `Stream` is an asynchronous version of `Iterator`. A stream 16 | /// represents a sequence of value-producing events that occur asynchronously to 17 | /// the caller. 18 | /// 19 | /// The trait is modeled after `Future`, but allows `poll_next` to be called 20 | /// even after a value has been produced, yielding `None` once the stream has 21 | /// been fully exhausted. 22 | #[must_use = "streams do nothing unless polled"] 23 | pub trait Stream { 24 | /// Values yielded by the stream. 25 | type Item; 26 | 27 | /// Attempt to pull out the next value of this stream, registering the 28 | /// current task for wakeup if the value is not yet available, and returning 29 | /// `None` if the stream is exhausted. 30 | /// 31 | /// # Return value 32 | /// 33 | /// There are several possible return values, each indicating a distinct 34 | /// stream state: 35 | /// 36 | /// - `Poll::Pending` means that this stream's next value is not ready 37 | /// yet. Implementations will ensure that the current task will be notified 38 | /// when the next value may be ready. 39 | /// 40 | /// - `Poll::Ready(Some(val))` means that the stream has successfully 41 | /// produced a value, `val`, and may produce further values on subsequent 42 | /// `poll_next` calls. 43 | /// 44 | /// - `Poll::Ready(None)` means that the stream has terminated, and 45 | /// `poll_next` should not be invoked again. 46 | /// 47 | /// # Panics 48 | /// 49 | /// Once a stream is finished, i.e. `Ready(None)` has been returned, further 50 | /// calls to `poll_next` may result in a panic or other "bad behavior". If 51 | /// this is difficult to guard against then the `fuse` adapter can be used 52 | /// to ensure that `poll_next` always returns `Ready(None)` in subsequent 53 | /// calls. 54 | fn poll_next( 55 | self: Pin<&mut Self>, 56 | cx: &mut Context<'_>, 57 | ) -> Poll>; 58 | } 59 | 60 | impl Stream for &mut S { 61 | type Item = S::Item; 62 | 63 | fn poll_next( 64 | mut self: Pin<&mut Self>, 65 | cx: &mut Context<'_>, 66 | ) -> Poll> { 67 | S::poll_next(Pin::new(&mut **self), cx) 68 | } 69 | } 70 | 71 | impl

Stream for Pin

72 | where 73 | P: DerefMut + Unpin, 74 | P::Target: Stream, 75 | { 76 | type Item = ::Item; 77 | 78 | fn poll_next( 79 | self: Pin<&mut Self>, 80 | cx: &mut Context<'_>, 81 | ) -> Poll> { 82 | Pin::get_mut(self).as_mut().poll_next(cx) 83 | } 84 | } 85 | 86 | /// A `Stream` or `TryStream` which tracks whether or not the underlying stream 87 | /// should no longer be polled. 88 | /// 89 | /// `is_terminated` will return `true` if a future should no longer be polled. 90 | /// Usually, this state occurs after `poll_next` (or `try_poll_next`) returned 91 | /// `Poll::Ready(None)`. However, `is_terminated` may also return `true` if a 92 | /// stream has become inactive and can no longer make progress and should be 93 | /// ignored or dropped rather than being polled again. 94 | pub trait FusedStream { 95 | /// Returns `true` if the stream should no longer be polled. 96 | fn is_terminated(&self) -> bool; 97 | } 98 | 99 | impl FusedStream for &mut F { 100 | fn is_terminated(&self) -> bool { 101 | ::is_terminated(&**self) 102 | } 103 | } 104 | 105 | impl

FusedStream for Pin

106 | where 107 | P: DerefMut + Unpin, 108 | P::Target: FusedStream, 109 | { 110 | fn is_terminated(&self) -> bool { 111 | ::is_terminated(&**self) 112 | } 113 | } 114 | 115 | /// A convenience for streams that return `Result` values that includes 116 | /// a variety of adapters tailored to such futures. 117 | pub trait TryStream { 118 | /// The type of successful values yielded by this future 119 | type Ok; 120 | 121 | /// The type of failures yielded by this future 122 | type Error; 123 | 124 | /// Poll this `TryStream` as if it were a `Stream`. 125 | /// 126 | /// This method is a stopgap for a compiler limitation that prevents us from 127 | /// directly inheriting from the `Stream` trait; in the future it won't be 128 | /// needed. 129 | fn try_poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) 130 | -> Poll>>; 131 | } 132 | 133 | impl TryStream for S 134 | where S: ?Sized + Stream> 135 | { 136 | type Ok = T; 137 | type Error = E; 138 | 139 | fn try_poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) 140 | -> Poll>> 141 | { 142 | self.poll_next(cx) 143 | } 144 | } 145 | 146 | #[cfg(feature = "alloc")] 147 | mod if_alloc { 148 | use alloc::boxed::Box; 149 | use super::*; 150 | 151 | impl Stream for Box { 152 | type Item = S::Item; 153 | 154 | fn poll_next( 155 | mut self: Pin<&mut Self>, 156 | cx: &mut Context<'_>, 157 | ) -> Poll> { 158 | Pin::new(&mut **self).poll_next(cx) 159 | } 160 | } 161 | 162 | #[cfg(feature = "std")] 163 | impl Stream for ::std::panic::AssertUnwindSafe { 164 | type Item = S::Item; 165 | 166 | fn poll_next( 167 | self: Pin<&mut Self>, 168 | cx: &mut Context<'_>, 169 | ) -> Poll> { 170 | unsafe { Pin::map_unchecked_mut(self, |x| &mut x.0) }.poll_next(cx) 171 | } 172 | } 173 | 174 | impl Stream for ::alloc::collections::VecDeque { 175 | type Item = T; 176 | 177 | fn poll_next( 178 | mut self: Pin<&mut Self>, 179 | _cx: &mut Context<'_>, 180 | ) -> Poll> { 181 | Poll::Ready(self.pop_front()) 182 | } 183 | } 184 | 185 | impl FusedStream for Box { 186 | fn is_terminated(&self) -> bool { 187 | ::is_terminated(&**self) 188 | } 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /src/transforms/remove_doc_attrs.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Jethro G. Beekman 2 | // 3 | // This file is part of rust-reduce. 4 | // 5 | // rust-reduce is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published 7 | // by the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // rust-reduce is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with rust-reduce. If not, see . 17 | 18 | /// Try to remove each `#[doc]` attribute (this includes doc comments). 19 | use syn::{visit_mut::*, *}; 20 | 21 | pub fn remove_doc_attrs bool>(file: &mut File, mut try_compile: F) { 22 | let mut visitor = AttrContainerVisitor { 23 | backup: None, 24 | cur_index: 0, 25 | target_index: 1, 26 | }; 27 | 28 | loop { 29 | visitor.cur_index = 0; 30 | 31 | visitor.visit_attr_container(&mut file.attrs); 32 | visit_file_mut(&mut visitor, file); 33 | 34 | // no more changes to be made 35 | if visitor.backup.is_none() { 36 | break; 37 | } 38 | 39 | if try_compile(file) { 40 | // this change works, keep it! 41 | visitor.backup = None; 42 | } 43 | } 44 | } 45 | 46 | struct AttrContainerVisitor { 47 | backup: Option>, 48 | cur_index: usize, 49 | target_index: usize, 50 | } 51 | 52 | impl AttrContainerVisitor { 53 | fn visit_attr_container(&mut self, i: &mut Vec) { 54 | self.cur_index += 1; 55 | 56 | if self.target_index == self.cur_index { 57 | if let Some(backup) = self.backup.take() { 58 | // the change we tried didn't work. revert and try the next 59 | // possible change 60 | *i = backup; 61 | } else if i.iter().any(|attr| attr.path.is_ident("doc")) { 62 | self.backup = Some(i.clone()); 63 | i.retain(|attr| !attr.path.is_ident("doc")); 64 | return; 65 | } 66 | 67 | self.target_index += 1; 68 | } 69 | } 70 | } 71 | 72 | macro_rules! impl_VisitMut_attrs { 73 | ($(fn $i:ident(&mut self, i: &mut $t:ty))*) => { 74 | $( 75 | fn $i(&mut self, i: &mut $t) { 76 | self.visit_attr_container(&mut i.attrs); 77 | $i(self, i); 78 | } 79 | )* 80 | } 81 | } 82 | 83 | impl VisitMut for AttrContainerVisitor { 84 | impl_VisitMut_attrs! { 85 | fn visit_arm_mut(&mut self, i: &mut Arm) 86 | fn visit_const_param_mut(&mut self, i: &mut ConstParam) 87 | fn visit_derive_input_mut(&mut self, i: &mut DeriveInput) 88 | fn visit_expr_array_mut(&mut self, i: &mut ExprArray) 89 | fn visit_expr_assign_mut(&mut self, i: &mut ExprAssign) 90 | fn visit_expr_assign_op_mut(&mut self, i: &mut ExprAssignOp) 91 | fn visit_expr_async_mut(&mut self, i: &mut ExprAsync) 92 | fn visit_expr_binary_mut(&mut self, i: &mut ExprBinary) 93 | fn visit_expr_block_mut(&mut self, i: &mut ExprBlock) 94 | fn visit_expr_box_mut(&mut self, i: &mut ExprBox) 95 | fn visit_expr_break_mut(&mut self, i: &mut ExprBreak) 96 | fn visit_expr_call_mut(&mut self, i: &mut ExprCall) 97 | fn visit_expr_cast_mut(&mut self, i: &mut ExprCast) 98 | fn visit_expr_closure_mut(&mut self, i: &mut ExprClosure) 99 | fn visit_expr_continue_mut(&mut self, i: &mut ExprContinue) 100 | fn visit_expr_field_mut(&mut self, i: &mut ExprField) 101 | fn visit_expr_for_loop_mut(&mut self, i: &mut ExprForLoop) 102 | fn visit_expr_group_mut(&mut self, i: &mut ExprGroup) 103 | fn visit_expr_if_mut(&mut self, i: &mut ExprIf) 104 | fn visit_expr_index_mut(&mut self, i: &mut ExprIndex) 105 | fn visit_expr_let_mut(&mut self, i: &mut ExprLet) 106 | fn visit_expr_lit_mut(&mut self, i: &mut ExprLit) 107 | fn visit_expr_loop_mut(&mut self, i: &mut ExprLoop) 108 | fn visit_expr_macro_mut(&mut self, i: &mut ExprMacro) 109 | fn visit_expr_match_mut(&mut self, i: &mut ExprMatch) 110 | fn visit_expr_method_call_mut(&mut self, i: &mut ExprMethodCall) 111 | fn visit_expr_paren_mut(&mut self, i: &mut ExprParen) 112 | fn visit_expr_path_mut(&mut self, i: &mut ExprPath) 113 | fn visit_expr_range_mut(&mut self, i: &mut ExprRange) 114 | fn visit_expr_reference_mut(&mut self, i: &mut ExprReference) 115 | fn visit_expr_repeat_mut(&mut self, i: &mut ExprRepeat) 116 | fn visit_expr_return_mut(&mut self, i: &mut ExprReturn) 117 | fn visit_expr_struct_mut(&mut self, i: &mut ExprStruct) 118 | fn visit_expr_try_mut(&mut self, i: &mut ExprTry) 119 | fn visit_expr_try_block_mut(&mut self, i: &mut ExprTryBlock) 120 | fn visit_expr_tuple_mut(&mut self, i: &mut ExprTuple) 121 | fn visit_expr_type_mut(&mut self, i: &mut ExprType) 122 | fn visit_expr_unary_mut(&mut self, i: &mut ExprUnary) 123 | fn visit_expr_unsafe_mut(&mut self, i: &mut ExprUnsafe) 124 | fn visit_expr_while_mut(&mut self, i: &mut ExprWhile) 125 | fn visit_expr_yield_mut(&mut self, i: &mut ExprYield) 126 | fn visit_field_mut(&mut self, i: &mut Field) 127 | fn visit_field_pat_mut(&mut self, i: &mut FieldPat) 128 | fn visit_field_value_mut(&mut self, i: &mut FieldValue) 129 | fn visit_file_mut(&mut self, i: &mut File) 130 | fn visit_foreign_item_fn_mut(&mut self, i: &mut ForeignItemFn) 131 | fn visit_foreign_item_macro_mut(&mut self, i: &mut ForeignItemMacro) 132 | fn visit_foreign_item_static_mut(&mut self, i: &mut ForeignItemStatic) 133 | fn visit_foreign_item_type_mut(&mut self, i: &mut ForeignItemType) 134 | fn visit_impl_item_const_mut(&mut self, i: &mut ImplItemConst) 135 | fn visit_impl_item_macro_mut(&mut self, i: &mut ImplItemMacro) 136 | fn visit_impl_item_method_mut(&mut self, i: &mut ImplItemMethod) 137 | fn visit_impl_item_type_mut(&mut self, i: &mut ImplItemType) 138 | fn visit_item_const_mut(&mut self, i: &mut ItemConst) 139 | fn visit_item_enum_mut(&mut self, i: &mut ItemEnum) 140 | fn visit_item_extern_crate_mut(&mut self, i: &mut ItemExternCrate) 141 | fn visit_item_fn_mut(&mut self, i: &mut ItemFn) 142 | fn visit_item_foreign_mod_mut(&mut self, i: &mut ItemForeignMod) 143 | fn visit_item_impl_mut(&mut self, i: &mut ItemImpl) 144 | fn visit_item_macro_mut(&mut self, i: &mut ItemMacro) 145 | fn visit_item_macro2_mut(&mut self, i: &mut ItemMacro2) 146 | fn visit_item_mod_mut(&mut self, i: &mut ItemMod) 147 | fn visit_item_static_mut(&mut self, i: &mut ItemStatic) 148 | fn visit_item_struct_mut(&mut self, i: &mut ItemStruct) 149 | fn visit_item_trait_mut(&mut self, i: &mut ItemTrait) 150 | fn visit_item_trait_alias_mut(&mut self, i: &mut ItemTraitAlias) 151 | fn visit_item_type_mut(&mut self, i: &mut ItemType) 152 | fn visit_item_union_mut(&mut self, i: &mut ItemUnion) 153 | fn visit_item_use_mut(&mut self, i: &mut ItemUse) 154 | fn visit_lifetime_def_mut(&mut self, i: &mut LifetimeDef) 155 | fn visit_local_mut(&mut self, i: &mut Local) 156 | fn visit_trait_item_const_mut(&mut self, i: &mut TraitItemConst) 157 | fn visit_trait_item_macro_mut(&mut self, i: &mut TraitItemMacro) 158 | fn visit_trait_item_method_mut(&mut self, i: &mut TraitItemMethod) 159 | fn visit_trait_item_type_mut(&mut self, i: &mut TraitItemType) 160 | fn visit_type_param_mut(&mut self, i: &mut TypeParam) 161 | fn visit_variant_mut(&mut self, i: &mut Variant) 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /tests/suite/futures_core/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright (c) 2016 Alex Crichton 190 | Copyright (c) 2017 The Tokio Authors 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /tests/suite/futures_core/future/future_obj.rs: -------------------------------------------------------------------------------- 1 | use core::{ 2 | mem, 3 | fmt, 4 | future::Future, 5 | marker::PhantomData, 6 | pin::Pin, 7 | task::{Context, Poll}, 8 | }; 9 | 10 | /// A custom trait object for polling futures, roughly akin to 11 | /// `Box + 'a>`. 12 | /// 13 | /// This custom trait object was introduced as currently it is not possible to 14 | /// take `dyn Trait` by value and `Box` is not available in no_std 15 | /// contexts. 16 | pub struct LocalFutureObj<'a, T> { 17 | future: *mut (dyn Future + 'static), 18 | drop_fn: unsafe fn(*mut (dyn Future + 'static)), 19 | _marker: PhantomData<&'a ()>, 20 | } 21 | 22 | impl Unpin for LocalFutureObj<'_, T> {} 23 | 24 | #[allow(clippy::transmute_ptr_to_ptr)] 25 | unsafe fn remove_future_lifetime<'a, T>(ptr: *mut (dyn Future + 'a)) 26 | -> *mut (dyn Future + 'static) 27 | { 28 | mem::transmute(ptr) 29 | } 30 | 31 | unsafe fn remove_drop_lifetime<'a, T>(ptr: unsafe fn (*mut (dyn Future + 'a))) 32 | -> unsafe fn(*mut (dyn Future + 'static)) 33 | { 34 | mem::transmute(ptr) 35 | } 36 | 37 | impl<'a, T> LocalFutureObj<'a, T> { 38 | /// Create a `LocalFutureObj` from a custom trait object representation. 39 | #[inline] 40 | pub fn new + 'a>(f: F) -> LocalFutureObj<'a, T> { 41 | LocalFutureObj { 42 | future: unsafe { remove_future_lifetime(f.into_raw()) }, 43 | drop_fn: unsafe { remove_drop_lifetime(F::drop) }, 44 | _marker: PhantomData, 45 | } 46 | } 47 | 48 | /// Converts the `LocalFutureObj` into a `FutureObj` 49 | /// To make this operation safe one has to ensure that the `UnsafeFutureObj` 50 | /// instance from which this `LocalFutureObj` was created actually 51 | /// implements `Send`. 52 | #[inline] 53 | pub unsafe fn into_future_obj(self) -> FutureObj<'a, T> { 54 | FutureObj(self) 55 | } 56 | } 57 | 58 | impl fmt::Debug for LocalFutureObj<'_, T> { 59 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 60 | f.debug_struct("LocalFutureObj") 61 | .finish() 62 | } 63 | } 64 | 65 | impl<'a, T> From> for LocalFutureObj<'a, T> { 66 | #[inline] 67 | fn from(f: FutureObj<'a, T>) -> LocalFutureObj<'a, T> { 68 | f.0 69 | } 70 | } 71 | 72 | impl Future for LocalFutureObj<'_, T> { 73 | type Output = T; 74 | 75 | #[inline] 76 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 77 | unsafe { 78 | Pin::new_unchecked(&mut *self.future).poll(cx) 79 | } 80 | } 81 | } 82 | 83 | impl Drop for LocalFutureObj<'_, T> { 84 | fn drop(&mut self) { 85 | unsafe { 86 | (self.drop_fn)(self.future) 87 | } 88 | } 89 | } 90 | 91 | /// A custom trait object for polling futures, roughly akin to 92 | /// `Box + Send + 'a>`. 93 | /// 94 | /// This custom trait object was introduced as currently it is not possible to 95 | /// take `dyn Trait` by value and `Box` is not available in no_std 96 | /// contexts. 97 | /// 98 | /// You should generally not need to use this type outside of `no_std` or when 99 | /// implementing `Spawn`, consider using [`BoxFuture`](crate::future::BoxFuture) 100 | /// instead. 101 | pub struct FutureObj<'a, T>(LocalFutureObj<'a, T>); 102 | 103 | impl Unpin for FutureObj<'_, T> {} 104 | unsafe impl Send for FutureObj<'_, T> {} 105 | 106 | impl<'a, T> FutureObj<'a, T> { 107 | /// Create a `FutureObj` from a custom trait object representation. 108 | #[inline] 109 | pub fn new + Send>(f: F) -> FutureObj<'a, T> { 110 | FutureObj(LocalFutureObj::new(f)) 111 | } 112 | } 113 | 114 | impl fmt::Debug for FutureObj<'_, T> { 115 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 116 | f.debug_struct("FutureObj") 117 | .finish() 118 | } 119 | } 120 | 121 | impl Future for FutureObj<'_, T> { 122 | type Output = T; 123 | 124 | #[inline] 125 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 126 | let pinned_field: Pin<&mut LocalFutureObj<'_, T>> = unsafe { 127 | Pin::map_unchecked_mut(self, |x| &mut x.0) 128 | }; 129 | LocalFutureObj::poll(pinned_field, cx) 130 | } 131 | } 132 | 133 | /// A custom implementation of a future trait object for `FutureObj`, providing 134 | /// a vtable with drop support. 135 | /// 136 | /// This custom representation is typically used only in `no_std` contexts, 137 | /// where the default `Box`-based implementation is not available. 138 | /// 139 | /// # Safety 140 | /// 141 | /// See the safety notes on individual methods for what guarantees an 142 | /// implementor must provide. 143 | pub unsafe trait UnsafeFutureObj<'a, T>: 'a { 144 | /// Convert an owned instance into a (conceptually owned) fat pointer. 145 | /// 146 | /// # Safety 147 | /// 148 | /// ## Implementor 149 | /// 150 | /// The trait implementor must guarantee that it is safe to convert the 151 | /// provided `*mut (dyn Future + 'a)` into a `Pin<&mut (dyn 152 | /// Future + 'a)>` and call methods on it, non-reentrantly, 153 | /// until `UnsafeFutureObj::drop` is called with it. 154 | fn into_raw(self) -> *mut (dyn Future + 'a); 155 | 156 | /// Drops the future represented by the given fat pointer. 157 | /// 158 | /// # Safety 159 | /// 160 | /// ## Implementor 161 | /// 162 | /// The trait implementor must guarantee that it is safe to call this 163 | /// function once per `into_raw` invocation. 164 | /// 165 | /// ## Caller 166 | /// 167 | /// The caller must ensure: 168 | /// 169 | /// * the pointer passed was obtained from an `into_raw` invocation from 170 | /// this same trait object 171 | /// * the pointer is not currently in use as a `Pin<&mut (dyn Future + 'a)>` 173 | /// * the pointer must not be used again after this function is called 174 | unsafe fn drop(ptr: *mut (dyn Future + 'a)); 175 | } 176 | 177 | unsafe impl<'a, T, F> UnsafeFutureObj<'a, T> for &'a mut F 178 | where 179 | F: Future + Unpin + 'a 180 | { 181 | fn into_raw(self) -> *mut (Future + 'a) { 182 | self as *mut dyn Future 183 | } 184 | 185 | unsafe fn drop(_ptr: *mut (dyn Future + 'a)) {} 186 | } 187 | 188 | unsafe impl<'a, T> UnsafeFutureObj<'a, T> for &'a mut (dyn Future + Unpin + 'a) 189 | { 190 | fn into_raw(self) -> *mut (dyn Future + 'a) { 191 | self as *mut dyn Future 192 | } 193 | 194 | unsafe fn drop(_ptr: *mut (dyn Future + 'a)) {} 195 | } 196 | 197 | unsafe impl<'a, T, F> UnsafeFutureObj<'a, T> for Pin<&'a mut F> 198 | where 199 | F: Future + 'a 200 | { 201 | fn into_raw(self) -> *mut (dyn Future + 'a) { 202 | unsafe { self.get_unchecked_mut() as *mut dyn Future } 203 | } 204 | 205 | unsafe fn drop(_ptr: *mut (dyn Future + 'a)) {} 206 | } 207 | 208 | unsafe impl<'a, T> UnsafeFutureObj<'a, T> for Pin<&'a mut (dyn Future + 'a)> 209 | { 210 | fn into_raw(self) -> *mut (dyn Future + 'a) { 211 | unsafe { self.get_unchecked_mut() as *mut dyn Future } 212 | } 213 | 214 | unsafe fn drop(_ptr: *mut (dyn Future + 'a)) {} 215 | } 216 | 217 | #[cfg(feature = "alloc")] 218 | mod if_alloc { 219 | use super::*; 220 | use alloc::boxed::Box; 221 | 222 | unsafe impl<'a, T, F> UnsafeFutureObj<'a, T> for Box 223 | where F: Future + 'a 224 | { 225 | fn into_raw(self) -> *mut (dyn Future + 'a) { 226 | Box::into_raw(self) 227 | } 228 | 229 | unsafe fn drop(ptr: *mut (dyn Future + 'a)) { 230 | drop(Box::from_raw(ptr as *mut F)) 231 | } 232 | } 233 | 234 | unsafe impl<'a, T: 'a> UnsafeFutureObj<'a, T> for Box + 'a> { 235 | fn into_raw(self) -> *mut (dyn Future + 'a) { 236 | Box::into_raw(self) 237 | } 238 | 239 | unsafe fn drop(ptr: *mut (dyn Future + 'a)) { 240 | drop(Box::from_raw(ptr)) 241 | } 242 | } 243 | 244 | unsafe impl<'a, T: 'a> UnsafeFutureObj<'a, T> for Box + Send + 'a> { 245 | fn into_raw(self) -> *mut (dyn Future + 'a) { 246 | Box::into_raw(self) 247 | } 248 | 249 | unsafe fn drop(ptr: *mut (dyn Future + 'a)) { 250 | drop(Box::from_raw(ptr)) 251 | } 252 | } 253 | 254 | unsafe impl<'a, T, F> UnsafeFutureObj<'a, T> for Pin> 255 | where 256 | F: Future + 'a 257 | { 258 | fn into_raw(mut self) -> *mut (dyn Future + 'a) { 259 | let ptr = unsafe { self.as_mut().get_unchecked_mut() as *mut _ }; 260 | mem::forget(self); 261 | ptr 262 | } 263 | 264 | unsafe fn drop(ptr: *mut (dyn Future + 'a)) { 265 | drop(Pin::from(Box::from_raw(ptr))) 266 | } 267 | } 268 | 269 | unsafe impl<'a, T: 'a> UnsafeFutureObj<'a, T> for Pin + 'a>> { 270 | fn into_raw(mut self) -> *mut (dyn Future + 'a) { 271 | let ptr = unsafe { self.as_mut().get_unchecked_mut() as *mut _ }; 272 | mem::forget(self); 273 | ptr 274 | } 275 | 276 | unsafe fn drop(ptr: *mut (dyn Future + 'a)) { 277 | drop(Pin::from(Box::from_raw(ptr))) 278 | } 279 | } 280 | 281 | unsafe impl<'a, T: 'a> UnsafeFutureObj<'a, T> for Pin + Send + 'a>> { 282 | fn into_raw(mut self) -> *mut (dyn Future + 'a) { 283 | let ptr = unsafe { self.as_mut().get_unchecked_mut() as *mut _ }; 284 | mem::forget(self); 285 | ptr 286 | } 287 | 288 | unsafe fn drop(ptr: *mut (dyn Future + 'a)) { 289 | drop(Pin::from(Box::from_raw(ptr))) 290 | } 291 | } 292 | 293 | impl<'a, F: Future + Send + 'a> From> for FutureObj<'a, ()> { 294 | fn from(boxed: Box) -> Self { 295 | FutureObj::new(boxed) 296 | } 297 | } 298 | 299 | impl<'a> From + Send + 'a>> for FutureObj<'a, ()> { 300 | fn from(boxed: Box + Send + 'a>) -> Self { 301 | FutureObj::new(boxed) 302 | } 303 | } 304 | 305 | impl<'a, F: Future + Send + 'a> From>> for FutureObj<'a, ()> { 306 | fn from(boxed: Pin>) -> Self { 307 | FutureObj::new(boxed) 308 | } 309 | } 310 | 311 | impl<'a> From + Send + 'a>>> for FutureObj<'a, ()> { 312 | fn from(boxed: Pin + Send + 'a>>) -> Self { 313 | FutureObj::new(boxed) 314 | } 315 | } 316 | 317 | impl<'a, F: Future + 'a> From> for LocalFutureObj<'a, ()> { 318 | fn from(boxed: Box) -> Self { 319 | LocalFutureObj::new(boxed) 320 | } 321 | } 322 | 323 | impl<'a> From + 'a>> for LocalFutureObj<'a, ()> { 324 | fn from(boxed: Box + 'a>) -> Self { 325 | LocalFutureObj::new(boxed) 326 | } 327 | } 328 | 329 | impl<'a, F: Future + 'a> From>> for LocalFutureObj<'a, ()> { 330 | fn from(boxed: Pin>) -> Self { 331 | LocalFutureObj::new(boxed) 332 | } 333 | } 334 | 335 | impl<'a> From + 'a>>> for LocalFutureObj<'a, ()> { 336 | fn from(boxed: Pin + 'a>>) -> Self { 337 | LocalFutureObj::new(boxed) 338 | } 339 | } 340 | } 341 | -------------------------------------------------------------------------------- /tests/suite/futures_core/task/__internal/atomic_waker.rs: -------------------------------------------------------------------------------- 1 | use core::fmt; 2 | use core::cell::UnsafeCell; 3 | use core::sync::atomic::AtomicUsize; 4 | use core::sync::atomic::Ordering::{Acquire, Release, AcqRel}; 5 | use crate::task::Waker; 6 | 7 | /// A synchronization primitive for task wakeup. 8 | /// 9 | /// Sometimes the task interested in a given event will change over time. 10 | /// An `AtomicWaker` can coordinate concurrent notifications with the consumer 11 | /// potentially "updating" the underlying task to wake up. This is useful in 12 | /// scenarios where a computation completes in another thread and wants to 13 | /// notify the consumer, but the consumer is in the process of being migrated to 14 | /// a new logical task. 15 | /// 16 | /// Consumers should call `register` before checking the result of a computation 17 | /// and producers should call `wake` after producing the computation (this 18 | /// differs from the usual `thread::park` pattern). It is also permitted for 19 | /// `wake` to be called **before** `register`. This results in a no-op. 20 | /// 21 | /// A single `AtomicWaker` may be reused for any number of calls to `register` or 22 | /// `wake`. 23 | /// 24 | /// `AtomicWaker` does not provide any memory ordering guarantees, as such the 25 | /// user should use caution and use other synchronization primitives to guard 26 | /// the result of the underlying computation. 27 | pub struct AtomicWaker { 28 | state: AtomicUsize, 29 | waker: UnsafeCell>, 30 | } 31 | 32 | // `AtomicWaker` is a multi-consumer, single-producer transfer cell. The cell 33 | // stores a `Waker` value produced by calls to `register` and many threads can 34 | // race to take the waker (to wake it) by calling `wake`. 35 | // 36 | // If a new `Waker` instance is produced by calling `register` before an 37 | // existing one is consumed, then the existing one is overwritten. 38 | // 39 | // While `AtomicWaker` is single-producer, the implementation ensures memory 40 | // safety. In the event of concurrent calls to `register`, there will be a 41 | // single winner whose waker will get stored in the cell. The losers will not 42 | // have their tasks woken. As such, callers should ensure to add synchronization 43 | // to calls to `register`. 44 | // 45 | // The implementation uses a single `AtomicUsize` value to coordinate access to 46 | // the `Waker` cell. There are two bits that are operated on independently. 47 | // These are represented by `REGISTERING` and `WAKING`. 48 | // 49 | // The `REGISTERING` bit is set when a producer enters the critical section. The 50 | // `WAKING` bit is set when a consumer enters the critical section. Neither bit 51 | // being set is represented by `WAITING`. 52 | // 53 | // A thread obtains an exclusive lock on the waker cell by transitioning the 54 | // state from `WAITING` to `REGISTERING` or `WAKING`, depending on the operation 55 | // the thread wishes to perform. When this transition is made, it is guaranteed 56 | // that no other thread will access the waker cell. 57 | // 58 | // # Registering 59 | // 60 | // On a call to `register`, an attempt to transition the state from WAITING to 61 | // REGISTERING is made. On success, the caller obtains a lock on the waker cell. 62 | // 63 | // If the lock is obtained, then the thread sets the waker cell to the waker 64 | // provided as an argument. Then it attempts to transition the state back from 65 | // `REGISTERING` -> `WAITING`. 66 | // 67 | // If this transition is successful, then the registering process is complete 68 | // and the next call to `wake` will observe the waker. 69 | // 70 | // If the transition fails, then there was a concurrent call to `wake` that was 71 | // unable to access the waker cell (due to the registering thread holding the 72 | // lock). To handle this, the registering thread removes the waker it just set 73 | // from the cell and calls `wake` on it. This call to wake represents the 74 | // attempt to wake by the other thread (that set the `WAKING` bit). The state is 75 | // then transitioned from `REGISTERING | WAKING` back to `WAITING`. This 76 | // transition must succeed because, at this point, the state cannot be 77 | // transitioned by another thread. 78 | // 79 | // # Waking 80 | // 81 | // On a call to `wake`, an attempt to transition the state from `WAITING` to 82 | // `WAKING` is made. On success, the caller obtains a lock on the waker cell. 83 | // 84 | // If the lock is obtained, then the thread takes ownership of the current value 85 | // in the waker cell, and calls `wake` on it. The state is then transitioned 86 | // back to `WAITING`. This transition must succeed as, at this point, the state 87 | // cannot be transitioned by another thread. 88 | // 89 | // If the thread is unable to obtain the lock, the `WAKING` bit is still. This 90 | // is because it has either been set by the current thread but the previous 91 | // value included the `REGISTERING` bit **or** a concurrent thread is in the 92 | // `WAKING` critical section. Either way, no action must be taken. 93 | // 94 | // If the current thread is the only concurrent call to `wake` and another 95 | // thread is in the `register` critical section, when the other thread **exits** 96 | // the `register` critical section, it will observe the `WAKING` bit and handle 97 | // the wake itself. 98 | // 99 | // If another thread is in the `wake` critical section, then it will handle 100 | // waking the task. 101 | // 102 | // # A potential race (is safely handled). 103 | // 104 | // Imagine the following situation: 105 | // 106 | // * Thread A obtains the `wake` lock and wakes a task. 107 | // 108 | // * Before thread A releases the `wake` lock, the woken task is scheduled. 109 | // 110 | // * Thread B attempts to wake the task. In theory this should result in the 111 | // task being woken, but it cannot because thread A still holds the wake lock. 112 | // 113 | // This case is handled by requiring users of `AtomicWaker` to call `register` 114 | // **before** attempting to observe the application state change that resulted 115 | // in the task being awoken. The wakers also change the application state before 116 | // calling wake. 117 | // 118 | // Because of this, the waker will do one of two things. 119 | // 120 | // 1) Observe the application state change that Thread B is woken for. In this 121 | // case, it is OK for Thread B's wake to be lost. 122 | // 123 | // 2) Call register before attempting to observe the application state. Since 124 | // Thread A still holds the `wake` lock, the call to `register` will result 125 | // in the task waking itself and get scheduled again. 126 | 127 | /// Idle state 128 | const WAITING: usize = 0; 129 | 130 | /// A new waker value is being registered with the `AtomicWaker` cell. 131 | const REGISTERING: usize = 0b01; 132 | 133 | /// The waker currently registered with the `AtomicWaker` cell is being woken. 134 | const WAKING: usize = 0b10; 135 | 136 | impl AtomicWaker { 137 | /// Create an `AtomicWaker`. 138 | pub fn new() -> AtomicWaker { 139 | // Make sure that task is Sync 140 | trait AssertSync: Sync {} 141 | impl AssertSync for Waker {} 142 | 143 | AtomicWaker { 144 | state: AtomicUsize::new(WAITING), 145 | waker: UnsafeCell::new(None), 146 | } 147 | } 148 | 149 | /// Registers the waker to be notified on calls to `wake`. 150 | /// 151 | /// The new task will take place of any previous tasks that were registered 152 | /// by previous calls to `register`. Any calls to `wake` that happen after 153 | /// a call to `register` (as defined by the memory ordering rules), will 154 | /// notify the `register` caller's task and deregister the waker from future 155 | /// notifications. Because of this, callers should ensure `register` gets 156 | /// invoked with a new `Waker` **each** time they require a wakeup. 157 | /// 158 | /// It is safe to call `register` with multiple other threads concurrently 159 | /// calling `wake`. This will result in the `register` caller's current 160 | /// task being notified once. 161 | /// 162 | /// This function is safe to call concurrently, but this is generally a bad 163 | /// idea. Concurrent calls to `register` will attempt to register different 164 | /// tasks to be notified. One of the callers will win and have its task set, 165 | /// but there is no guarantee as to which caller will succeed. 166 | /// 167 | /// # Examples 168 | /// 169 | /// Here is how `register` is used when implementing a flag. 170 | /// 171 | /// ``` 172 | /// use futures::future::Future; 173 | /// use futures::task::{Context, Poll, AtomicWaker}; 174 | /// use std::sync::atomic::AtomicBool; 175 | /// use std::sync::atomic::Ordering::SeqCst; 176 | /// use std::pin::Pin; 177 | /// 178 | /// struct Flag { 179 | /// waker: AtomicWaker, 180 | /// set: AtomicBool, 181 | /// } 182 | /// 183 | /// impl Future for Flag { 184 | /// type Output = (); 185 | /// 186 | /// fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { 187 | /// // Register **before** checking `set` to avoid a race condition 188 | /// // that would result in lost notifications. 189 | /// self.waker.register(cx.waker()); 190 | /// 191 | /// if self.set.load(SeqCst) { 192 | /// Poll::Ready(()) 193 | /// } else { 194 | /// Poll::Pending 195 | /// } 196 | /// } 197 | /// } 198 | /// ``` 199 | pub fn register(&self, waker: &Waker) { 200 | match self.state.compare_and_swap(WAITING, REGISTERING, Acquire) { 201 | WAITING => { 202 | unsafe { 203 | // Locked acquired, update the waker cell 204 | *self.waker.get() = Some(waker.clone()); 205 | 206 | // Release the lock. If the state transitioned to include 207 | // the `WAKING` bit, this means that a wake has been 208 | // called concurrently, so we have to remove the waker and 209 | // wake it.` 210 | // 211 | // Start by assuming that the state is `REGISTERING` as this 212 | // is what we jut set it to. 213 | let res = self.state.compare_exchange( 214 | REGISTERING, WAITING, AcqRel, Acquire); 215 | 216 | match res { 217 | Ok(_) => {} 218 | Err(actual) => { 219 | // This branch can only be reached if a 220 | // concurrent thread called `wake`. In this 221 | // case, `actual` **must** be `REGISTERING | 222 | // `WAKING`. 223 | debug_assert_eq!(actual, REGISTERING | WAKING); 224 | 225 | // Take the waker to wake once the atomic operation has 226 | // completed. 227 | let waker = (*self.waker.get()).take().unwrap(); 228 | 229 | // Just swap, because no one could change state while state == `REGISTERING` | `WAKING`. 230 | self.state.swap(WAITING, AcqRel); 231 | 232 | // The atomic swap was complete, now 233 | // wake the task and return. 234 | waker.wake(); 235 | } 236 | } 237 | } 238 | } 239 | WAKING => { 240 | // Currently in the process of waking the task, i.e., 241 | // `wake` is currently being called on the old task handle. 242 | // So, we call wake on the new waker 243 | waker.wake_by_ref(); 244 | } 245 | state => { 246 | // In this case, a concurrent thread is holding the 247 | // "registering" lock. This probably indicates a bug in the 248 | // caller's code as racing to call `register` doesn't make much 249 | // sense. 250 | // 251 | // We just want to maintain memory safety. It is ok to drop the 252 | // call to `register`. 253 | debug_assert!( 254 | state == REGISTERING || 255 | state == REGISTERING | WAKING); 256 | } 257 | } 258 | } 259 | 260 | /// Calls `wake` on the last `Waker` passed to `register`. 261 | /// 262 | /// If `register` has not been called yet, then this does nothing. 263 | pub fn wake(&self) { 264 | if let Some(waker) = self.take() { 265 | waker.wake(); 266 | } 267 | } 268 | 269 | /// Returns the last `Waker` passed to `register`, so that the user can wake it. 270 | /// 271 | /// 272 | /// Sometimes, just waking the AtomicWaker is not fine grained enough. This allows the user 273 | /// to take the waker and then wake it separately, rather than performing both steps in one 274 | /// atomic action. 275 | /// 276 | /// If a waker has not been registered, this returns `None`. 277 | pub fn take(&self) -> Option { 278 | // AcqRel ordering is used in order to acquire the value of the `task` 279 | // cell as well as to establish a `release` ordering with whatever 280 | // memory the `AtomicWaker` is associated with. 281 | match self.state.fetch_or(WAKING, AcqRel) { 282 | WAITING => { 283 | // The waking lock has been acquired. 284 | let waker = unsafe { (*self.waker.get()).take() }; 285 | 286 | // Release the lock 287 | self.state.fetch_and(!WAKING, Release); 288 | 289 | waker 290 | } 291 | state => { 292 | // There is a concurrent thread currently updating the 293 | // associated task. 294 | // 295 | // Nothing more to do as the `WAKING` bit has been set. It 296 | // doesn't matter if there are concurrent registering threads or 297 | // not. 298 | // 299 | debug_assert!( 300 | state == REGISTERING || 301 | state == REGISTERING | WAKING || 302 | state == WAKING); 303 | None 304 | } 305 | } 306 | } 307 | } 308 | 309 | impl Default for AtomicWaker { 310 | fn default() -> Self { 311 | AtomicWaker::new() 312 | } 313 | } 314 | 315 | impl fmt::Debug for AtomicWaker { 316 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { 317 | write!(fmt, "AtomicWaker") 318 | } 319 | } 320 | 321 | unsafe impl Send for AtomicWaker {} 322 | unsafe impl Sync for AtomicWaker {} 323 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------