1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 //! Macros for use with ylong_runtime
15 
16 #![allow(clippy::needless_doctest_main)]
17 #![doc(test(no_crate_inject,))]
18 
19 mod select;
20 
21 use proc_macro::{Delimiter, Group, Punct, Spacing, TokenStream, TokenTree};
22 
23 /// Implementation detail of the `select!` macro. This macro is **not** intended
24 /// to be used as part of the public API.
25 /// # Examples
26 ///
27 /// ```
28 /// #[derive(PartialEq, Debug)]
29 /// enum Out {
30 ///     Finish,
31 ///     Fail,
32 /// }
33 /// let tuple = ylong_runtime_macros::tuple_form!(( (((0)+1)+1) ) with Out::Fail except Out::Finish at ( ) );
34 /// assert_eq!(tuple, (Out::Finish, Out::Fail));
35 /// ```
36 #[proc_macro]
37 #[doc(hidden)]
tuple_form(input: TokenStream) -> TokenStream38 pub fn tuple_form(input: TokenStream) -> TokenStream {
39     let tuple_parser = select::tuple_parser(input);
40 
41     let mut group_inner = TokenStream::new();
42 
43     // Constructing Tuples
44     for i in 0..tuple_parser.len {
45         if i == tuple_parser.except_index {
46             // Set 'except_index' at index
47             group_inner.extend(tuple_parser.except.clone());
48         } else {
49             // Set 'default'
50             group_inner.extend(tuple_parser.default.clone());
51         }
52         // Add ',' separator
53         if i != tuple_parser.len - 1 {
54             let punct: Punct = Punct::new(',', Spacing::Alone);
55             group_inner.extend(TokenStream::from(TokenTree::from(punct)));
56         }
57     }
58     // Add parentheses on the outermost
59     let tuple = Group::new(Delimiter::Parenthesis, group_inner);
60 
61     TokenStream::from(TokenTree::from(tuple))
62 }
63