macro-attr-0.2.0/.gitignore00006440000000000000000000000035127450526710013747 0ustar0000000000000000/.local target Cargo.lock macro-attr-0.2.0/.gitmodules00006440000000000000000000000143130122607040014116 0ustar0000000000000000[submodule "scripts"] path = scripts url = https://github.com/DanielKeep/rust-script-toolbox.git macro-attr-0.2.0/.travis.yml00006440000000000000000000002551130106112670014061 0ustar0000000000000000language: rust script: > cargo build $CARGO_FLAGS --features "$CARGO_FEATURES" && cargo build $CARGO_FLAGS --features "$CARGO_FEATURES" --manifest-path enum_derive/Cargo.toml && cargo build $CARGO_FLAGS --features "$CARGO_FEATURES $CARGO_NEWTYPE_FEATURES" --manifest-path newtype_derive/Cargo.toml && cargo test $CARGO_FLAGS --features "$CARGO_FEATURES" && cargo test $CARGO_FLAGS --features "$CARGO_FEATURES" --manifest-path enum_derive/Cargo.toml && cargo test $CARGO_FLAGS --features "$CARGO_FEATURES $CARGO_NEWTYPE_FEATURES" --manifest-path newtype_derive/Cargo.toml && cargo run $CARGO_FLAGS --features "$CARGO_FEATURES $CARGO_DERIVE_NAME_TEST_FEATURES" --manifest-path tests/derive-name-test/Cargo.toml rust: - 1.2.0 - 1.3.0 - 1.4.0 - 1.5.0 - 1.6.0 - 1.7.0 - 1.8.0 - 1.9.0 - 1.10.0 - 1.11.0 - stable - beta - nightly env: - > CARGO_FLAGS="--verbose --no-default-features" CARGO_FEATURES=std CARGO_NEWTYPE_FEATURES= CARGO_DERIVE_NAME_TEST_FEATURES= matrix: allow_failures: - rust: nightly include: - rust: stable env: CARGO_FEATURES= - rust: beta env: CARGO_FEATURES= - rust: nightly env: CARGO_FEATURES= - rust: nightly env: CARGO_FEATURES=std CARGO_NEWTYPE_FEATURES=std-unstable CARGO_DERIVE_NAME_TEST_FEATURES=unstable-macros-1-1 macro-attr-0.2.0/Cargo.toml00006440000000000000000000002225130144711130013674 0ustar0000000000000000# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "macro-attr" version = "0.2.0" authors = ["Daniel Keep "] exclude = [".cargo/*", "local/*", "doc-pkg/*", "update-docs.py"] description = "This crate provides the `macro_attr!` macro that enables the use of custom, macro-based attributes and derivations. Supercedes the `custom_derive` crate." documentation = "https://docs.rs/crate/macro-attr/" keywords = ["custom", "derive", "attribute", "macro"] license = "MIT/Apache-2.0" repository = "https://github.com/DanielKeep/rust-custom-derive" [dev-dependencies.rustc-serialize] version = "0.3.15" [features] default = ["std"] std = [] unstable-macros-1-1 = [] macro-attr-0.2.0/Cargo.toml.orig00006440000000000000000000001530130144711130014631 0ustar0000000000000000[package] name = "macro-attr" version = "0.2.0" authors = ["Daniel Keep "] description = "This crate provides the `macro_attr!` macro that enables the use of custom, macro-based attributes and derivations. Supercedes the `custom_derive` crate." repository = "https://github.com/DanielKeep/rust-custom-derive" documentation = "https://docs.rs/crate/macro-attr/" license = "MIT/Apache-2.0" keywords = ["custom", "derive", "attribute", "macro"] exclude = [ ".cargo/*", "local/*", "doc-pkg/*", "update-docs.py", ] [workspace] members = [ "enum_derive", "newtype_derive", "tests/derive-name-macro", "tests/derive-name-proc", "tests/derive-name-test", ] [features] default = ["std"] std = [] unstable-macros-1-1 = [] [dev-dependencies] rustc-serialize = "0.3.15" macro-attr-0.2.0/LICENSE00006440000000000000000000030314130144707320012757 0ustar0000000000000000Copyright ⓒ 2015, 2016 macro-attr contributors. Licensed under either of: * MIT license, or * Apache License, Version 2.0 at your option. Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions. # MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # Apache License, Version 2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. macro-attr-0.2.0/README.md00006440000000000000000000005040130144711110013217 0ustar0000000000000000# `macro-attr` This crate provides the `macro_attr!` macro that enables the use of custom, macro-based attributes and derivations. Supercedes the `custom_derive` crate. **Links** * [Latest Release](https://crates.io/crates/macro-attr/) * [Latest Docs](https://docs.rs/crate/macro-attr/) * [Repository](https://github.com/DanielKeep/rust-custom-derive) ## Compatibility `macro-attr` is compatible with Rust 1.2 and higher. ## Example ```rust #[macro_use] extern crate macro_attr; // Define some traits to be derived. trait TypeName { fn type_name() -> &'static str; } trait ReprType { type Repr; } // Define macros which derive implementations of these macros. macro_rules! TypeName { // We can support any kind of item we want. (() $(pub)* enum $name:ident $($tail:tt)*) => { TypeName! { @impl $name } }; (() $(pub)* struct $name:ident $($tail:tt)*) => { TypeName! { @impl $name } }; // Inner rule to cut down on repetition. (@impl $name:ident) => { impl TypeName for $name { fn type_name() -> &'static str { stringify!($name) } } }; } macro_rules! ReprType { // Note that we use a "derivation argument" here for the `$repr` type. (($repr:ty) $(pub)* enum $name:ident $($tail:tt)*) => { impl ReprType for $name { type Repr = $repr; } }; } // Here is a macro that *modifies* the item. macro_rules! rename_to { ( ($new_name:ident), then $cb:tt, $(#[$($attrs:tt)*])* enum $_old_name:ident $($tail:tt)* ) => { macro_attr_callback! { $cb, $(#[$($attrs)*])* enum $new_name $($tail)* } }; } macro_attr! { #[allow(dead_code)] #[derive(Clone, Copy, Debug, ReprType!(u8), TypeName!)] #[rename_to!(Bar)] #[repr(u8)] enum Foo { A, B } } fn main() { let bar = Bar::B; let v = bar as ::Repr; let msg = format!("{}: {:?} ({:?})", Bar::type_name(), bar, v); assert_eq!(msg, "Bar: B (1)"); } ``` ## License Licensed under either of * MIT license (see [LICENSE](LICENSE) or ) * Apache License, Version 2.0 (see [LICENSE](LICENSE) or ) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions. macro-attr-0.2.0/scripts/.gitignore00006440000000000000000000000013130122607040015414 0ustar0000000000000000__pycache__macro-attr-0.2.0/scripts/common/__init__.py00006440000000000000000000006741130122607040017043 0ustar0000000000000000# Copyright ⓒ 2016 Daniel Keep. # # Licensed under the MIT license (see LICENSE or ) or the Apache License, Version 2.0 (see LICENSE of # ), at your option. All # files in the project carrying such notice may not be copied, modified, # or distributed except according to those terms. __all__ = [ "RUSTUP", "USE_ANSI", "load_globals_from_metadata", "load_metadata_from_manifest", "msg", "msg_trace", "set_toolbox_trace", "sh", "sh_eval", "which", ] import os import os.path import subprocess import sys import toml from itertools import chain TRACE = os.environ.get('TRACE_TOOLBOX', '') != '' USE_ANSI = True if sys.platform != 'win32' else os.environ.get('FORCE_ANSI', '') != '' or os.environ.get('ConEmuANSI', 'OFF') == 'ON' def which(programname, all=False): path_exts = os.environ.get('PATHEXT', '').split(os.path.pathsep) path_exts = [e for e in path_exts if e.lstrip() != ''] def matches(): for path in os.environ['PATH'].split(os.path.pathsep): base_path = os.path.join(path, programname) for ext in chain(('',), path_exts): ext_path = base_path+ext if os.path.exists(os.path.normcase(ext_path)): yield ext_path if all: return matches() else: return next(matches(), None) RUSTUP = "rustup" if which("rustup") is not None else "multirust" def load_metadata_from_manifest(section): with open('Cargo.toml', 'rt') as manifest_file: manifest = toml.loads(manifest_file.read()) return (manifest .get('package', {}) .get('metadata', {}) .get(section, {}) ) def load_globals_from_metadata(section, globals, names): metadata = load_metadata_from_manifest(section) for (k, v) in metadata.items(): k_ss = k.upper().replace('-', '_') if k_ss not in names: continue globals[k_ss] = v def msg(*args): if USE_ANSI: sys.stdout.write('\x1b[1;34m') sys.stdout.write('> ') if USE_ANSI: sys.stdout.write('\x1b[1;32m') for arg in args: sys.stdout.write(str(arg)) if USE_ANSI: sys.stdout.write('\x1b[0m') sys.stdout.write('\n') sys.stdout.flush() def msg_trace(*args): if TRACE: if USE_ANSI: sys.stderr.write('\x1b[1;31m') sys.stderr.write('$ ') if USE_ANSI: sys.stderr.write('\x1b[0m') for arg in args: sys.stderr.write(str(arg)) sys.stderr.write('\n') sys.stderr.flush() def set_toolbox_trace(env_var): global TRACE TRACE = TRACE or os.environ.get(env_var, '') != '' def sh(cmd, env=None, stdout=None, stderr=None, checked=True): msg_trace('sh(%r, env=%r)' % (cmd, env)) try: subprocess.check_call(cmd, env=env, stdout=stdout, stderr=stderr, shell=True) except Exception as e: msg_trace('FAILED: %s' % e) if checked: raise else: return False if not checked: return True def sh_eval(cmd, codec='utf-8', dont_strip=False): msg_trace('sh_eval(%r)' % cmd) result = None try: result = subprocess.check_output(cmd, shell=True).decode(codec) if not dont_strip: result = result.strip() except: msg_trace('FAILED!') raise return result macro-attr-0.2.0/scripts/LICENSE00006440000000000000000000030272130122607040014443 0ustar0000000000000000Copyright ⓒ 2016 Daniel Keep. Licensed under either of: * MIT license, or * Apache License, Version 2.0 at your option. Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions. # MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # Apache License, Version 2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. macro-attr-0.2.0/scripts/README.md00006440000000000000000000001103130122607040014704 0ustar0000000000000000# Rust Script Toolbox This repository contains some scripts which I got sick of copy & pasting all over the place. ## License Licensed under either of * MIT license (see [LICENSE](LICENSE) or ) * Apache License, Version 2.0 (see [LICENSE](LICENSE) or ) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions. macro-attr-0.2.0/scripts/redirect-to-docs.rs00006440000000000000000000022205130122607040017150 0ustar0000000000000000#!/usr/bin/env run-cargo-script /*! Rewrites all HTML files in rustdoc-generated documentation to point to `https://docs.rs/` instead. Run this script with `cargo script`. ```cargo [package] authors = ["Daniel Keep "] version = "0.2.0" [features] trace-logging = ["env_logger", "log"] [dependencies] clap = "2.13.0" env_logger = { version = "0.3.5", optional = true } log = { version = "0.3.6", optional = true } ``` */ /* Copyright ⓒ 2016 Daniel Keep. Licensed under the MIT license (see LICENSE or ) or the Apache License, Version 2.0 (see LICENSE of ), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ #[macro_use] extern crate clap; #[cfg(feature="trace-logging")] #[macro_use] extern crate log; #[cfg(feature="trace-logging")] extern crate env_logger; use std::error::Error as StdError; use std::fs; use std::io; use std::path::{Path, PathBuf}; use std::result::Result as StdResult; /// Base documentation URI. Use `*` for the latest version. const DOC_URI: &'static str = "https://docs.rs/$CRATE/*/$CRATESAFE/$TAIL"; /** Source file URI. The reason we aren't more accurate is that docs.rs changes the *structure* of the URIs, and trying to get that exactly right would just be a PITA. So I don't bother. */ const SRC_URI: &'static str = "https://docs.rs/crate/$CRATE/"; #[cfg(feature="trace-logging")] macro_rules! trace_ { ($($args:tt)*) => { trace!($($args)*) } } #[cfg(not(feature="trace-logging"))] macro_rules! trace_ { ($($args:tt)*) => {} } type Result = StdResult; type Error = Box; #[derive(Debug)] struct Args { crate_name: String, delete_others: bool, doc_root: PathBuf, dry_run: bool, } fn main() { use std::io::Write; { #[cfg(feature="trace-logging")] macro_rules! env_logger_init { () => { if let Err(err) = env_logger::init() { let _ = writeln!(std::io::stderr(), "warning: failed to initialise logging: {}", err); } } } #[cfg(not(feature="trace-logging"))] macro_rules! env_logger_init { () => {} } env_logger_init!(); } match try_main() { Ok(()) => (), Err(err) => { let _ = writeln!(std::io::stderr(), "error: {}", err); std::process::exit(1); } } } fn try_main() -> Result<()> { let args = try!(get_args()); let crate_safe_name = args.crate_name.replace("-", "_"); { let dir = args.doc_root.join(&crate_safe_name); let base_uri = DOC_URI .replace("$CRATESAFE", &crate_safe_name) .replace("$CRATE", &args.crate_name) ; println!("Rewriting {}...", dir.display()); try!(rewrite_dir(&args, &dir, &base_uri)); } { let dir = args.doc_root.join("src").join(&crate_safe_name); let base_uri = SRC_URI .replace("$CRATESAFE", &crate_safe_name) .replace("$CRATE", &args.crate_name) ; println!("Rewriting {}...", dir.display()); try!(rewrite_dir(&args, &dir, &base_uri)); } if args.delete_others { let dir = args.doc_root.join("implementors").join(&crate_safe_name); if dir.is_dir() { println!("Removing {}...", dir.display()); if !args.dry_run { try!(fs::remove_dir_all(&dir)); } } } println!("Done."); if args.delete_others { println!("You may also wish to remove files in {}.", args.doc_root.display()); } if args.dry_run { println!("Dry run complete; see `--help` for details.") } Ok(()) } fn rewrite_dir(args: &Args, dir: &Path, base_uri: &str) -> Result<()> { trace_!("rewrite_dir(_, {:?}, {:?}) {{", dir, base_uri); for de in try!(fs::read_dir(dir)) { let de = try!(de); let fpath = de.path(); let ftype = try!(de.file_type()); let fname = try!(fpath.file_name() .and_then(|s| s.to_str()) .ok_or_else(|| format!("couldn't get file name from {:?}", fpath)) ); if ftype.is_dir() { let new_uri = base_uri.replace("$TAIL", &format!("{}/$TAIL", fname)); try!(rewrite_dir(args, &fpath, &new_uri)); } else if ftype.is_file() { if fname.ends_with(".html") { let new_uri = base_uri.replace("$TAIL", fname); try!(rewrite_html(args, &fpath, &new_uri)); } else { if args.delete_others { print!("- rm {}", fpath.display()); try!(flush()); if !args.dry_run { try!(fs::remove_file(&fpath)); } println!(""); } } } } trace_!("rewrite_dir(_, {:?}, {:?}) }}", dir, base_uri); Ok(()) } fn rewrite_html(args: &Args, path: &Path, uri: &str) -> Result<()> { trace_!("rewrite_html(_, {:?}, {:?})", path, uri); use std::io::{Read, Write}; // Check to see if this file is *already* doing a redirection. let cur_body = { let f = try!(fs::File::open(path)); // We won't bother looking past the first 512 bytes. let mut buf = String::with_capacity(512); try!(f.take(buf.capacity() as u64).read_to_string(&mut buf)); buf }; if { cur_body.find("") .map(|off| cur_body[..off] .contains(r#" {}", uri); Ok(()) } fn get_args() -> Result { use clap::Arg; let matches = clap::App::new("redirect-to-docs.rs") .version(crate_version!()) .author(crate_authors!()) .about("Rewrites all HTML files in rustdoc-generated documentation \ to point to `https://docs.rs/` instead.") .after_help("By default, performs a dry run, listing everything it \ intends to do. You should review this output and then re-run \ with the --commit flag.\n\ \n\ Also note that files which contain legacy redirections generated \ by `rustdoc` itself will be skipped.") .arg(Arg::with_name("commit") .long("commit") .help("Actually take the requested actions, instead of performing a dry run.") ) .arg(Arg::with_name("crate_name") .long("crate-name") .value_name("NAME") .takes_value(true) .required(true) .help("Manually specify the name of the crate being documented.") ) .arg(Arg::with_name("delete_others") .long("delete-others") .help("Delete other, non-HTML files.") ) .arg(Arg::with_name("doc_root") .long("doc-root") .value_name("PATH") .takes_value(true) .required(true) .help("Manually specify the root directory for the crate documentation.") ) .get_matches(); let commit = matches.is_present("commit"); let crate_name = matches.value_of("crate_name").map(String::from).unwrap(); let delete_others = matches.is_present("delete_others"); let doc_root = matches.value_of("doc_root").map(PathBuf::from).unwrap(); Ok(Args { crate_name: crate_name, delete_others: delete_others, doc_root: doc_root, dry_run: !commit, }) } fn flush() -> io::Result<()> { use std::io::Write; std::io::stdout().flush() } const REDIR_TEMPLATE: &'static str = r##" $CRATE

Content Moved

This documentation is now being hosted on docs.rs. Follow the redirection if it does not work automatically.

"##; macro-attr-0.2.0/scripts/requirements.txt00006440000000000000000000000013130122607040016710 0ustar0000000000000000toml==0.9.2macro-attr-0.2.0/scripts/test-matrix.py00006440000000000000000000010271130122607040016266 0ustar0000000000000000#!/usr/bin/env python3 # coding: utf-8 # Copyright ⓒ 2016 Daniel Keep. # # Licensed under the MIT license (see LICENSE or ) or the Apache License, Version 2.0 (see LICENSE of # ), at your option. All # files in the project carrying such notice may not be copied, modified, # or distributed except according to those terms. import os.path import re import sys import yaml from common import * from itertools import chain LOG_DIR = os.path.join('local', 'tests') set_toolbox_trace(env_var='TRACE_TEST_MATRIX') def main(): load_globals_from_metadata('test-matrix', globals(), { 'LOG_DIR', }) travis = yaml.load(open('.travis.yml')) script = translate_script(travis.get('script', None)) default_rust_vers = travis['rust'] matrix_includes = travis.get('matrix', {}).get('include', []) vers = set(default_rust_vers) include_vers = [] exclude_vers = set() if not os.path.exists(LOG_DIR): os.makedirs(LOG_DIR) for arg in sys.argv[1:]: if arg in vers and arg not in include_vers: include_vers.append(arg) elif arg.startswith('-') and arg[1:] in vers: exclude_vers.add(arg[1:]) else: msg("Don't know how to deal with argument `%s`." % arg) sys.exit(1) if include_vers == []: include_vers = default_rust_vers[:] rust_vers = [v for v in include_vers if v not in exclude_vers] msg('Tests will be run for: %s' % ', '.join(rust_vers)) results = [] for rust_ver in rust_vers: seq_id = 0 for env_var_str in travis.get('env', [""]): env_vars = parse_env_vars(env_var_str) for row in chain([{}], matrix_includes): if row.get('rust', None) not in (None, rust_ver): continue row_env_vars = parse_env_vars(row.get('env', "")) cmd_env = {} cmd_env.update(env_vars) cmd_env.update(row_env_vars) success = run_script(script, rust_ver, seq_id, cmd_env) results.append((rust_ver, seq_id, success)) seq_id += 1 print("") msg('Results:') for rust_ver, seq_id, success in results: msg('%s #%d: %s' % (rust_ver, seq_id, 'OK' if success else 'Failed!')) def parse_env_vars(s): env_vars = {} for m in re.finditer(r"""([A-Za-z0-9_]+)=(?:"([^"]+)"|(\S*))""", s.strip()): k = m.group(1) v = m.group(2) or m.group(3) env_vars[k] = v return env_vars def run_script(script, rust_ver, seq_id, env): target_dir = os.path.join('target', '%s-%d' % (rust_ver, seq_id)) log_path = os.path.join(LOG_DIR, '%s-%d.log' % (rust_ver, seq_id)) log_file = open(log_path, 'wt') msg('Running tests for %s #%d...' % (rust_ver, seq_id)) success = True def sub_env(m): name = m.group(1) or m.group(2) return cmd_env[name] log_file.write('# %s #%d\n' % (rust_ver, seq_id)) for k, v in env.items(): log_file.write('# %s=%r\n' % (k, v)) cmd_env = os.environ.copy() cmd_env['CARGO_TARGET_DIR'] = target_dir cmd_env.update(env) for cmd in script: cmd = re.sub(r"\$(?:([A-Za-z0-9_]+)|{([A-Za-z0-9_]+)})\b", sub_env, cmd) cmd_str = '> %s run %s %s' % (RUSTUP, rust_ver, cmd) log_file.write(cmd_str) log_file.write("\n") log_file.flush() success = sh( '%s run %s %s' % (RUSTUP, rust_ver, cmd), checked=False, stdout=log_file, stderr=log_file, env=cmd_env, ) if not success: log_file.write('Command failed.\n') log_file.flush() break msg('... ', 'OK' if success else 'Failed!') log_file.close() return success def translate_script(script): script = script or "rustc -vV && cargo -vV && cargo build --verbose && cargo test --verbose" parts = script.split("&&") return [p.strip() for p in parts] if __name__ == '__main__': main() macro-attr-0.2.0/scripts/update-docs.py00006440000000000000000000015412130122607040016217 0ustar0000000000000000#!/usr/bin/env python3 # coding: utf-8 # Copyright ⓒ 2016 Daniel Keep. # # Licensed under the MIT license (see LICENSE or ) or the Apache License, Version 2.0 (see LICENSE of # ), at your option. All # files in the project carrying such notice may not be copied, modified, # or distributed except according to those terms. import distutils.dir_util import os import shutil import sys import tempfile import time from common import * DOC_ARGS = '--no-deps' DOC_FEATURES = "" DOC_TARGET_BRANCH = 'gh-pages' DOC_PKG_DIR = None DOC_TOOLCHAIN = None TEMP_CHECKOUT_PREFIX = 'gh-pages-checkout-' TEMP_OUTPUT_PREFIX = 'gh-pages-generated-' TRACE_UPDATE_DOCS = os.environ.get('TRACE_UPDATE_DOCS', '') != '' def copytree(src, dst): msg_trace('copytree(%r, %r)' % (src, dst)) distutils.dir_util.copy_tree(src=src, dst=dst) def really_rmtree(path): msg_trace('really_rmtree(%r)' % path) WAIT_TIME_SECS = 1.0 MAX_TRIES = 10 def on_error(func, path, exc_info): """ Error handler for ``shutil.rmtree``. If the error is due to an access error (read only file) it attempts to add write permission and then retries. If the error is for another reason it re-raises the error. Usage: ``shutil.rmtree(path, onerror=on_error)`` From _. """ import stat if not os.access(path, os.W_OK): # Is the error an access error ? os.chmod(path, stat.S_IWUSR) func(path) else: raise for _ in range(MAX_TRIES): failed = True try: msg_trace('shutil.rmtree(%r)' % path) shutil.rmtree(path, onerror=on_error) failed = False except WindowsError: time.sleep(WAIT_TIME_SECS) if not failed: return msg('Warning: failed to remove directory %r' % path) def init_doc_branch(): msg("Initialising %s branch" % DOC_TARGET_BRANCH) dir = os.getcwd() msg_trace('dir = %r' % dir) tmp = tempfile.mkdtemp(prefix=TEMP_CHECKOUT_PREFIX) msg_trace('tmp = %r' % tmp) try: msg("Cloning into a temporary directory...") sh('git init -q "%s"' % tmp) msg_trace('os.chdir(%r)' % tmp) os.chdir(tmp) sh('git checkout -q --orphan "%s"' % DOC_TARGET_BRANCH) sh('git commit -qm "Initial commit." --allow-empty') sh('git remote add origin "%s"' % dir) sh('git push -q origin gh-pages') finally: msg('Cleaning up...') msg_trace('os.chdir(%r)' % dir) os.chdir(dir) msg_trace('shutil.rmtree(%r)' % tmp) really_rmtree(tmp) msg('%s is ready. Continuing.' % DOC_TARGET_BRANCH) def gen_doc_bare(tmp1, tmp2): msg("Generating documentation...") args = '%s --features="%s"' % (DOC_ARGS, DOC_FEATURES) if DOC_TOOLCHAIN is not None: toolchain = "%s run %s " % (RUSTUP, DOC_TOOLCHAIN) else: toolchain = "" sh('%scargo doc %s' % (toolchain, args)) tmp1_target_doc = '%s/target/doc' % tmp1 msg_trace('shutil.move(%r, %r)' % (tmp1_target_doc, tmp2)) shutil.move(tmp1_target_doc, tmp2) def gen_doc_pkg(tmp1, tmp2, doc_pkg): if DOC_FEATURES != "": msg("Error: doc packages don't support features.") sys.exit(1) import json old_dir = os.getcwd() msg("Generating documentation from doc package...") msg_trace('doc_pkg = %r' % doc_pkg) msg_trace('os.chdir(%r)' % doc_pkg) try: os.chdir(doc_pkg) manifest_str = sh_eval('cargo read-manifest --manifest-path "%s"' % os.path.join(doc_pkg, 'Cargo.toml')) manifest = json.loads(manifest_str) if DOC_TOOLCHAIN is not None: toolchain = "%s run %s " % (RUSTUP, DOC_TOOLCHAIN) else: toolchain = "" packages = " ".join("--package %s" % d['name'] for d in manifest['dependencies']) sh('%scargo doc %s' % (toolchain, packages)) target_doc = os.path.join(doc_pkg, 'target/doc') msg_trace('shutil.move(%r, %r)' % (target_doc, tmp2)) shutil.move(target_doc, tmp2) finally: msg_trace('os.chdir(%r)' % old_dir) os.chdir(old_dir) def main(): load_globals_from_metadata('update-docs', globals(), { 'DOC_ARGS', 'DOC_FEATURES', 'DOC_TARGET_BRANCH', 'DOC_PKG_DIR', 'DOC_TOOLCHAIN', 'TEMP_CHECKOUT_PREFIX', 'TEMP_OUTPUT_PREFIX', }) if sh_eval('git symbolic-ref --short HEAD') != u'master': msg('Not on master; doing nothing.') return 0 # Sanity check: does the doc branch exist at all? branches = {b[2:].strip() for b in sh_eval('git branch', dont_strip=True).splitlines()} msg_trace('branches = %r' % branches) if DOC_TARGET_BRANCH not in branches: init_doc_branch() last_rev = sh_eval('git rev-parse HEAD') last_msg = sh_eval('git log -1 --pretty=%B') msg_trace('last_rev = %r' % last_rev) msg_trace('last_msg = %r' % last_msg) dir = os.getcwd() msg_trace('dir = %r' % dir) tmp1 = tempfile.mkdtemp(prefix=TEMP_CHECKOUT_PREFIX) tmp2 = tempfile.mkdtemp(prefix=TEMP_OUTPUT_PREFIX) msg_trace('tmp1 = %r' % tmp1) msg_trace('tmp2 = %r' % tmp2) try: msg("Cloning into a temporary directory...") sh('git clone -qb "%s" "%s" "%s"' % (DOC_TARGET_BRANCH, dir, tmp1)) msg_trace('os.chdir(%r)' % tmp1) os.chdir(tmp1) sh('git checkout -q master') if DOC_PKG_DIR is not None: gen_doc_pkg(tmp1, tmp2, os.path.abspath(DOC_PKG_DIR)) else: gen_doc_bare(tmp1, tmp2) msg('Updating %s...' % DOC_TARGET_BRANCH) sh('git checkout -q "%s"' % DOC_TARGET_BRANCH) sh('git clean -dfq') tmp2_doc = '%s/doc' % tmp2 msg_trace('copytree(%r, %r)' % (tmp2_doc, './doc')) copytree(tmp2_doc, './doc') msg('Committing changes...') sh('git add .') sh('git commit --amend -m "Update docs for %s" -m "%s"' % (last_rev[:7], last_msg)) sh('git push -fqu origin "%s"' % DOC_TARGET_BRANCH) finally: msg('Cleaning up...') msg_trace('os.chdir(%r)' % dir) os.chdir(dir) msg_trace('shutil.rmtree(%r)' % tmp2) really_rmtree(tmp2) msg_trace('shutil.rmtree(%r)' % tmp1) really_rmtree(tmp1) msg('Publishing...') sh('git push -f origin "%s"' % DOC_TARGET_BRANCH) msg('Done.') if __name__ == '__main__': sys.exit(main()) macro-attr-0.2.0/src/lib.rs00006440000000000000000000062547130144715130013670 0ustar0000000000000000/* Copyright ⓒ 2016 macro-attr contributors. Licensed under the MIT license (see LICENSE or ) or the Apache License, Version 2.0 (see LICENSE of ), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ /*! This crate provides the `macro_attr!` macro that enables the use of custom, macro-based attributes and derivations. Supercedes the `custom_derive` crate. ## Compatibility `macro-attr` is compatible with Rust 1.2 and higher. ## Quick Example To use it, make sure you link to the crate like so: ```rust #[macro_use] extern crate macro_attr; # macro_rules! Dummy { (() struct $name:ident;) => {}; } # macro_attr! { #[derive(Clone, Dummy!)] struct Foo; } # fn main() { let _ = Foo; } ``` The `macro_attr!` macro should be used to wrap an entire *single* item (`enum`, `struct`, *etc.*) declaration, including its attributes (both `derive` and others). All attributes and derivations which whose names end with `!` will be assumed to be implemented by macros, and treated accordingly. For example: ```rust #[macro_use] extern crate macro_attr; // Define some traits to be derived. trait TypeName { fn type_name() -> &'static str; } trait ReprType { type Repr; } // Define macros which derive implementations of these macros. macro_rules! TypeName { // We can support any kind of item we want. (() $(pub)* enum $name:ident $($tail:tt)*) => { TypeName! { @impl $name } }; (() $(pub)* struct $name:ident $($tail:tt)*) => { TypeName! { @impl $name } }; // Inner rule to cut down on repetition. (@impl $name:ident) => { impl TypeName for $name { fn type_name() -> &'static str { stringify!($name) } } }; } macro_rules! ReprType { // Note that we use a "derivation argument" here for the `$repr` type. (($repr:ty) $(pub)* enum $name:ident $($tail:tt)*) => { impl ReprType for $name { type Repr = $repr; } }; } // Here is a macro that *modifies* the item. macro_rules! rename_to { ( ($new_name:ident), then $cb:tt, $(#[$($attrs:tt)*])* enum $_old_name:ident $($tail:tt)* ) => { macro_attr_callback! { $cb, $(#[$($attrs)*])* enum $new_name $($tail)* } }; } macro_attr! { #[allow(dead_code)] #[derive(Clone, Copy, Debug, ReprType!(u8), TypeName!)] #[rename_to!(Bar)] #[repr(u8)] enum Foo { A, B } } fn main() { let bar = Bar::B; let v = bar as ::Repr; let msg = format!("{}: {:?} ({:?})", Bar::type_name(), bar, v); assert_eq!(msg, "Bar: B (1)"); } ``` */ #![cfg_attr(not(feature = "std"), no_std)] /** When given an item definition, including its attributes, this macro parses said attributes and dispatches any attributes or derivations suffixed with `!` to user-defined macros. This allows multiple macros to process the same item. This is similar to, but distinct from, the function of "procedural" macros and compiler plugins. # Supported Forms In particular, this macro looks for two kinds of syntax: - Derivations such as the `Name` in `#[derive(Name!)]` or `#[derive(Name!(...))]`. - Top-level attributes written as `#[name!]` or `#![name!(...)]`. Unlike "real" attributes, optional parenthesised arguments after the `!` are allowed to be entirely arbitrary token trees, meaning they can effectively contain any token sequence. These are supported to allow custom attribute macros to easily take arguments. Derivations parse the item and emit whatever additional definitions needed. They *cannot* change the item itself, and do not receive any other attributes attached to the item. Attributes receive *everything* lexically *after* themselves, and must re-emit the item. This allows attributes to make changes to the item, drop or alter other attributes, *etc.*. This power makes writing attribute macros more difficult, however. # Macro Derivations Given the following input: ```ignore #[derive(Copy, Name!(args...), Clone, Another!, Debug)] struct Foo; ``` `macro_attr!` will expand to the equivalent of: ```ignore #[derive(Copy, Clone, Debug)] struct Foo; Name!((args...) struct Foo;); Another!(() struct Foo;); ``` Note that macro derives may be mixed with regular derives, or put in their own `#[derive(...)]` attribute. Also note that macro derive invocations are *not* passed the other attributes on the item; input will consist of the arguments provided to the derivation (*i.e.* `(args...)` in this example), the item's visibility (if any), and the item definition itself. A macro derivation invoked *without* arguments will be treated as though it was invoked with empty parentheses. *i.e.* `#[derive(Name!)]` is equivalent to `#[derive(Name!())]`. A derivation macro may expand to any number of new items derived from the provided input. There is no way for a derivation macro to alter the item itself (for that, use a macro attribute). # Macro Attributes When `macro_attr!` encounters an attribute suffixed with a `!` (*e.g.* `#[name!(args...)]`), it invokes the macro `name!` with everything lexically *after* that attribute. A macro attribute is free to add to, remove from, or alter the provided input as it sees fit, before instructing `macro_attr!` to resume parsing. For example, given the following input: ```ignore #[make_unitary!] #[repr(C)] #[rename_to!(Quux)] #[doc="Test."] struct Bar { field: i32 } ``` `macro_attr!` will expand to: ```ignore make_unitary! { (), then $resume, #[repr(C)] #[rename_to!(Quux)] #[doc="Test."] struct Bar { field: i32 }; } ``` Note that `$resume` is **not** literal. When implementing an attribute macro, you should accept this part as `$resume:tt`, and not attempt to inspect or deconstruct the contents. Assuming `make_unitary!` removes the body of the `struct` it is attached to, `macro_attr!` *requires* that it expand to: ```ignore macro_attr_callback! { $resume, #[repr(C)] #[rename_to!(Quxx)] #[doc="Test."] struct Bar; } ``` `macro_attr!` will then resume parsing, and expand to: ```ignore rename_to! { (Quxx), then $resume, #[doc="Test."] struct Bar; } ``` Assuming `rename_to!` does the obvious thing and changes the name of the item it is attached to, it should expand to: ```ignore macro_attr_callback! { $resume, #[doc="Test."] struct Quxx; } ``` Once more, `macro_attr!` will resume, and produce the final expansion of: ```ignore #[repr(C)] #[doc="Test."] struct Quxx; ``` Note that normal attributes are automatically carried through and re-attached to the item. Macro attributes should be used as sparingly as possible: due to the way Rust macros work, they must expand recursively in sequence, which can quickly consume the available macro recursion limit. This limit can be raised, but it makes for a less-than-ideal user experience if you are authoring macros to be used by others. */ #[macro_export] macro_rules! macro_attr { ($($item:tt)*) => { macro_attr_impl! { $($item)* } }; } /** This macro exists as an implementation detail. This is because if it *wasn't*, then the public-facing `macro_attr!` macro's documentation would be hideously unwieldy. */ #[doc(hidden)] #[macro_export] macro_rules! macro_attr_impl { /* > **Convention**: a capture named `$fixed` is used for any part of a recursive rule that is needed in the terminal case, but is not actually being *used* for the recursive part. This avoids having to constantly repeat the full capture pattern (and makes changing it easier). # Primary Invocation Forms These need to catch any valid form of item. */ ( $(#[$($attrs:tt)*])* const $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), (), (), (const $($it)*) } }; ( $(#[$($attrs:tt)*])* enum $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), (), (), (enum $($it)*) } }; ( $(#[$($attrs:tt)*])* extern $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), (), (), (extern $($it)*) } }; ( $(#[$($attrs:tt)*])* fn $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), (), (), (fn $($it)*) } }; ( $(#[$($attrs:tt)*])* impl $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), (), (), (impl $($it)*) } }; ( $(#[$($attrs:tt)*])* mod $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), (), (), (mod $($it)*) } }; ( $(#[$($attrs:tt)*])* pub $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), (), (), (pub $($it)*) } }; ( $(#[$($attrs:tt)*])* static $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), (), (), (static $($it)*) } }; ( $(#[$($attrs:tt)*])* struct $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), (), (), (struct $($it)*) } }; ( $(#[$($attrs:tt)*])* trait $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), (), (), (trait $($it)*) } }; ( $(#[$($attrs:tt)*])* type $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), (), (), (type $($it)*) } }; ( $(#[$($attrs:tt)*])* use $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), (), (), (use $($it)*) } }; /* # `@split_attrs` This is responsible for dividing all attributes on an item into two groups: - `#[derive(...)]` - Everything else. As part of this, it also explodes `#[derive(A, B(..), C, ...)]` into `A, B(..), C, ...`. This is to simplify the next stage. */ ( @split_attrs (), $non_derives:tt, $derives:tt, $it:tt ) => { macro_attr_impl! { @split_derive_attrs { $non_derives, $it }, $derives, (), () } }; ( @split_attrs (#[derive($($new_drvs:tt)*)], $(#[$($attrs:tt)*],)*), $non_derives:tt, ($($derives:tt)*), $it:tt ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), $non_derives, ($($derives)* $($new_drvs)*,), $it } }; ( @split_attrs (#[$mac_attr:ident!], $(#[$($attrs:tt)*],)*), $non_derives:tt, $derives:tt, ($($it:tt)*) ) => { $mac_attr! { (), then (macro_attr_impl! { @split_attrs_resume $non_derives, $derives, }), $(#[$($attrs)*])* $($it)* } }; ( @split_attrs (#[$mac_attr:ident!($($attr_args:tt)*)], $(#[$($attrs:tt)*],)*), $non_derives:tt, $derives:tt, ($($it:tt)*) ) => { $mac_attr! { ($($attr_args)*), then (macro_attr_impl! { @split_attrs_resume $non_derives, $derives, }), $(#[$($attrs)*])* $($it)* } }; ( @split_attrs (#[$mac_attr:ident~!], $(#[$($attrs:tt)*],)*), ($($non_derives:tt)*), $derives:tt, ($($it:tt)*) ) => { macro_attr_if_proc_macros! { proc_macros: { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), ($($non_derives)* #[$mac_attr],), $derives, $($it)* } } fallback: { $mac_attr! { (), then (macro_attr_impl! { @split_attrs_resume ($($non_derives)*), $derives, }), $(#[$($attrs)*])* $($it)* } } } }; ( @split_attrs (#[$mac_attr:ident~!($($attr_args:tt)*)], $(#[$($attrs:tt)*],)*), ($($non_derives:tt)*), $derives:tt, ($($it:tt)*) ) => { macro_attr_if_proc_macros! { proc_macros: { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), ($($non_derives)* #[$mac_attr($($attr_args)*)],), $derives, $($it)* } } fallback: { $mac_attr! { ($($attr_args)*), then (macro_attr_impl! { @split_attrs_resume ($($non_derives)*), $derives, }), $(#[$($attrs)*])* $($it)* } } } }; ( @split_attrs (#[$new_attr:meta], $(#[$($attrs:tt)*],)*), ($($non_derives:tt)*), $derives:tt, $it:tt ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), ($($non_derives)* #[$new_attr],), $derives, $it } }; /* # `@split_attrs_resume` Callback used to re-enter this macro after running a macro attribute. */ ( @split_attrs_resume $non_derives:tt, $derives:tt, $(#[$($attrs:tt)*])* const $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), $non_derives, $derives, (const $($it)*) } }; ( @split_attrs_resume $non_derives:tt, $derives:tt, $(#[$($attrs:tt)*])* enum $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), $non_derives, $derives, (enum $($it)*) } }; ( @split_attrs_resume $non_derives:tt, $derives:tt, $(#[$($attrs:tt)*])* extern $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), $non_derives, $derives, (extern $($it)*) } }; ( @split_attrs_resume $non_derives:tt, $derives:tt, $(#[$($attrs:tt)*])* fn $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), $non_derives, $derives, (fn $($it)*) } }; ( @split_attrs_resume $non_derives:tt, $derives:tt, $(#[$($attrs:tt)*])* impl $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), $non_derives, $derives, (impl $($it)*) } }; ( @split_attrs_resume $non_derives:tt, $derives:tt, $(#[$($attrs:tt)*])* mod $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), $non_derives, $derives, (mod $($it)*) } }; ( @split_attrs_resume $non_derives:tt, $derives:tt, $(#[$($attrs:tt)*])* pub $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), $non_derives, $derives, (pub $($it)*) } }; ( @split_attrs_resume $non_derives:tt, $derives:tt, $(#[$($attrs:tt)*])* static $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), $non_derives, $derives, (static $($it)*) } }; ( @split_attrs_resume $non_derives:tt, $derives:tt, $(#[$($attrs:tt)*])* struct $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), $non_derives, $derives, (struct $($it)*) } }; ( @split_attrs_resume $non_derives:tt, $derives:tt, $(#[$($attrs:tt)*])* trait $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), $non_derives, $derives, (trait $($it)*) } }; ( @split_attrs_resume $non_derives:tt, $derives:tt, $(#[$($attrs:tt)*])* type $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), $non_derives, $derives, (type $($it)*) } }; ( @split_attrs_resume $non_derives:tt, $derives:tt, $(#[$($attrs:tt)*])* use $($it:tt)* ) => { macro_attr_impl! { @split_attrs ($(#[$($attrs)*],)*), $non_derives, $derives, (use $($it)*) } }; /* # `@split_derive_attrs` This is responsible for taking the list of derivation attributes and splitting them into "built-in" and "custom" groups. A custom attribute is any which has a `!` after the name, like a macro. */ (@split_derive_attrs { ($(#[$($non_derives:tt)*],)*), ($($it:tt)*) }, ($(,)*), (), ($($user_drvs:tt)*) ) => { macro_attr_impl! { @as_item $(#[$($non_derives)*])* $($it)* } macro_attr_impl! { @expand_user_drvs ($($user_drvs)*), ($($it)*) } }; (@split_derive_attrs { ($(#[$($non_derives:tt)*],)*), ($($it:tt)*) }, ($(,)*), ($($bi_drvs:ident,)+), ($($user_drvs:tt)*) ) => { macro_attr_impl! { @as_item #[derive($($bi_drvs,)+)] $(#[$($non_derives)*])* $($it)* } macro_attr_impl! { @expand_user_drvs ($($user_drvs)*), ($($it)*) } }; (@split_derive_attrs $fixed:tt, (,, $($tail:tt)*), $bi_drvs:tt, $user_drvs:tt ) => { macro_attr_impl! { @split_derive_attrs $fixed, ($($tail)*), $bi_drvs, $user_drvs } }; (@split_derive_attrs $fixed:tt, (, $($tail:tt)*), $bi_drvs:tt, $user_drvs:tt ) => { macro_attr_impl! { @split_derive_attrs $fixed, ($($tail)*), $bi_drvs, $user_drvs } }; /* ## Custom Derivations Now we can handle the custom derivations. There are two forms we care about: those *with* an argument, and those *without*. The *reason* we care is that, in order to simplify the derivation macros, we want to detect the argument-less case and generate an empty pair of parens. */ (@split_derive_attrs $fixed:tt, ($new_user:ident ! ($($new_user_args:tt)*), $($tail:tt)*), $bi_drvs:tt, ($($user_drvs:tt)*) ) => { macro_attr_impl! { @split_derive_attrs $fixed, ($($tail)*), $bi_drvs, ($($user_drvs)* $new_user($($new_user_args)*),) } }; (@split_derive_attrs $fixed:tt, ($new_user:ident !, $($tail:tt)*), $bi_drvs:tt, ($($user_drvs:tt)*) ) => { macro_attr_impl! { @split_derive_attrs $fixed, ($($tail)*), $bi_drvs, ($($user_drvs)* $new_user(),) } }; /* ## Hybrid Derivations These are derivations that use regular macros *or* procedural macros, depending on the version of Rust in use. */ (@split_derive_attrs $fixed:tt, ($new_drv:ident ~!, $($tail:tt)*), ($($bi_drvs:ident,)*), ($($user_drvs:tt)*) ) => { macro_attr_if_proc_macros! { proc_macros: { macro_attr_impl! { @split_derive_attrs $fixed, ($($tail)*), ($($bi_drvs,)* $new_drv,), ($($user_drvs)*) } } fallback: { macro_attr_impl! { @split_derive_attrs $fixed, ($($tail)*), ($($bi_drvs,)*), ($($user_drvs)* $new_drv(),) } } } }; /* ## Non-Macro Derivations All the rest. */ (@split_derive_attrs $fixed:tt, ($drv:ident, $($tail:tt)*), ($($bi_drvs:ident,)*), $user_drvs:tt ) => { macro_attr_impl! { @split_derive_attrs $fixed, ($($tail)*), ($($bi_drvs,)* $drv,), $user_drvs } }; /* # `@expand_user_drvs` Finally, we have a recursive rule for expanding user derivations. This is basically just using the derivation name as a macro identifier. This *has* to be recursive because we need to expand two independent repetition sequences simultaneously, and this causes `macro_rules!` to throw a wobbly. Don't want that. So, recursive it is. */ (@expand_user_drvs (), ($($it:tt)*) ) => {}; (@expand_user_drvs ($user_drv:ident $arg:tt, $($tail:tt)*), ($($it:tt)*) ) => { $user_drv! { $arg $($it)* } macro_attr_impl! { @expand_user_drvs ($($tail)*), ($($it)*) } }; /* # Miscellaneous Rules */ (@as_item $($i:item)*) => {$($i)*}; } /** This macro invokes a "callback" macro, merging arguments together. It takes an arbitrary macro call `(name!(args...))`, plus some sequence of `new_args...`, and expands `name!(args... new_args...)`. Importantly, it works irrespective of the kind of grouping syntax used for the macro arguments, simplifying macros which need to *capture* callbacks. */ #[macro_export] macro_rules! macro_attr_callback { ( ($cb:ident ! { $($cb_fixed:tt)* }), $($args:tt)* ) => { $cb! { $($cb_fixed)* $($args)* } }; ( ($cb:ident ! [ $($cb_fixed:tt)* ]), $($args:tt)* ) => { $cb! [ $($cb_fixed)* $($args)* ] }; ( ($cb:ident ! ( $($cb_fixed:tt)* )), $($args:tt)* ) => { $cb! ( $($cb_fixed)* $($args)* ) }; } /** This macro provides a simple way to select between two branches of code, depending on whether or not support for procedural macros is enabled or not. */ #[doc(hidden)] #[macro_export] #[cfg(feature="unstable-macros-1-1")] macro_rules! macro_attr_if_proc_macros { ( proc_macros: { $($items:item)* } fallback: $_ignore:tt ) => { $($items)* }; } /** This macro provides a simple way to select between two branches of code, depending on whether or not support for procedural macros is enabled or not. */ #[doc(hidden)] #[macro_export] #[cfg(not(feature="unstable-macros-1-1"))] macro_rules! macro_attr_if_proc_macros { ( proc_macros: $_ignore:tt fallback: { $($items:item)* } ) => { $($items)* }; } macro-attr-0.2.0/tests/empty_bi_derives.rs00006440000000000000000000001137130122434150017006 0ustar0000000000000000/* Copyright ⓒ 2015 macro-attr contributors. Licensed under the MIT license (see LICENSE or ) or the Apache License, Version 2.0 (see LICENSE of ), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ #[macro_use] extern crate macro_attr; macro_rules! Dummy { ($($tts:tt)*) => {}; } macro_attr! { #[derive(Dummy!)] enum Foo { Bar } } #[test] fn test_empty_bi_derives() { let _ = Foo::Bar; } macro-attr-0.2.0/tests/enum_iterator.rs00006440000000000000000000004211130122434150016326 0ustar0000000000000000/* Copyright ⓒ 2015 macro-attr contributors. Licensed under the MIT license (see LICENSE or ) or the Apache License, Version 2.0 (see LICENSE of ), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ #[macro_use] extern crate macro_attr; macro_rules! EnumIterator { (() $(pub)* enum $name:ident { $($body:tt)* }) => { EnumIterator! { @collect_variants ($name), ($($body)*,) -> () } }; ( @collect_variants ($name:ident), ($(,)*) -> ($($var_names:ident,)*) ) => { type NameIter = ::std::vec::IntoIter<&'static str>; type VariantIter = ::std::vec::IntoIter<$name>; impl $name { #[allow(dead_code)] pub fn iter_variants() -> VariantIter { vec![$($name::$var_names),*].into_iter() } #[allow(dead_code)] pub fn iter_variant_names() -> NameIter { vec![$(stringify!($var_names)),*].into_iter() } } }; ( @collect_variants $fixed:tt, ($var:ident $(= $_val:expr)*, $($tail:tt)*) -> ($($var_names:tt)*) ) => { EnumIterator! { @collect_variants $fixed, ($($tail)*) -> ($($var_names)* $var,) } }; ( @collect_variants ($name:ident), ($var:ident $_struct:tt, $($tail:tt)*) -> ($($var_names:tt)*) ) => { const _error: () = concat!( "cannot derive EnumIterator for ", stringify!($name), ", due to non-unitary variant ", stringify!($var), "." ); }; } macro_attr! { #[derive(Debug, PartialEq, EnumIterator!)] enum Get { Up, Down, AllAround } } #[test] fn test_enum_iterator() { let vs: Vec<_> = Get::iter_variant_names().zip(Get::iter_variants()).collect(); assert_eq!(&*vs, &[("Up", Get::Up), ("Down", Get::Down), ("AllAround", Get::AllAround)]); } macro-attr-0.2.0/tests/enum_try_from.rs00006440000000000000000000004227130122434150016345 0ustar0000000000000000/* Copyright ⓒ 2015 macro-attr contributors. Licensed under the MIT license (see LICENSE or ) or the Apache License, Version 2.0 (see LICENSE of ), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ #[macro_use] extern crate macro_attr; trait TryFrom: Sized { type Err; fn try_from(src: Src) -> Result; } macro_rules! TryFrom { (($prim:ty) $(pub)* enum $name:ident { $($body:tt)* }) => { TryFrom! { @collect_variants ($name, $prim), ($($body)*,) -> () } }; ( @collect_variants ($name:ident, $prim:ty), ($(,)*) -> ($($var_names:ident,)*) ) => { impl TryFrom<$prim> for $name { type Err = $prim; fn try_from(src: $prim) -> Result<$name, $prim> { $( if src == $name::$var_names as $prim { return Ok($name::$var_names); } )* Err(src) } } }; ( @collect_variants $fixed:tt, ($var:ident $(= $_val:expr)*, $($tail:tt)*) -> ($($var_names:tt)*) ) => { TryFrom! { @collect_variants $fixed, ($($tail)*) -> ($($var_names)* $var,) } }; ( @collect_variants ($name:ident), ($var:ident $_struct:tt, $($tail:tt)*) -> ($($var_names:tt)*) ) => { const _error: () = concat!( "cannot derive TryFrom for ", stringify!($name), ", due to non-unitary variant ", stringify!($var), "." ); }; } macro_attr! { #[derive(Debug, PartialEq, TryFrom!(u8))] enum Get { Up, Down, AllAround } } #[test] fn test_try_from() { assert_eq!(Get::try_from(0u8), Ok(Get::Up)); assert_eq!(Get::try_from(1u8), Ok(Get::Down)); assert_eq!(Get::try_from(2u8), Ok(Get::AllAround)); assert_eq!(Get::try_from(3u8), Err(3u8)); } macro-attr-0.2.0/tests/items.rs00006440000000000000000000002716130122434140014601 0ustar0000000000000000/* Copyright ⓒ 2016 macro-attr contributors. Licensed under the MIT license (see LICENSE or ) or the Apache License, Version 2.0 (see LICENSE of ), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ #[macro_use] extern crate macro_attr; macro_attr! { const DUMMY_CONST: () = (); } macro_attr! { enum DummyEnum { V } } macro_attr! { fn dummy_fn() {} } macro_attr! { impl DummyStruct { fn f(self) {} } } macro_attr! { mod dummy_mod { pub fn f() {} } } macro_attr! { static DUMMY_STATIC: () = (); } macro_attr! { struct DummyStruct; } macro_attr! { trait DummyTrait {} } macro_attr! { type DummyType = (); } macro_attr! { use self::dummy_fn as dummy_use; } #[cfg(never)] mod super_dummy { macro_attr! { extern crate dummy_crate; } macro_attr! { extern "C" dummy_extern(); } } #[test] fn test_items() { let _: () = DUMMY_CONST; let _: DummyEnum = DummyEnum::V; let _: () = dummy_fn(); let _: () = DummyStruct.f(); let _: () = dummy_mod::f(); let _: DummyStruct = DummyStruct; let _: Option<&DummyTrait> = None; let _: DummyType = (); let _: () = DUMMY_STATIC; let _: () = dummy_use(); } macro-attr-0.2.0/tests/mac_attrs.rs00006440000000000000000000003052130122530460015431 0ustar0000000000000000/* Copyright ⓒ 2016 macro-attr contributors. Licensed under the MIT license (see LICENSE or ) or the Apache License, Version 2.0 (see LICENSE of ), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ #[macro_use] extern crate macro_attr; macro_rules! Name { ( () struct $name:ident $($_tail:tt)* ) => { impl $name { pub fn name() -> &'static str { stringify!($name) } } }; } macro_rules! remove_body { ( (), then $cb:tt, $(#[$($attrs:tt)*])* struct $name:ident $($_tail:tt)* ) => { macro_attr_callback! { $cb, $(#[$($attrs)*])* struct $name; } }; } macro_rules! use_secret_alias { ( ($name:ident), then $cb:tt, $(#[$($attrs:tt)*])* struct $_old_name:ident $($tail:tt)* ) => { macro_attr_callback! { $cb, $(#[$($attrs)*])* struct $name $($tail)* } }; } macro_attr! { #[derive(Debug, Name!)] #[remove_body!] #[use_secret_alias!(Alucard)] struct Dracula { pub vulnerabilities: Vec, } } #[test] fn test_mac_attrs() { assert_eq!(format!("{:?}", Alucard), "Alucard"); assert_eq!(Alucard::name(), "Alucard"); } macro-attr-0.2.0/tests/passthru_derive.rs00006440000000000000000000001220130122434130016653 0ustar0000000000000000/* Copyright ⓒ 2015 macro-attr contributors. Licensed under the MIT license (see LICENSE or ) or the Apache License, Version 2.0 (see LICENSE of ), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ #[macro_use] extern crate macro_attr; extern crate rustc_serialize; macro_attr! { #[derive(Clone, Hash, RustcEncodable, RustcDecodable, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Copy)] pub struct Dummy(u32); } #[test] fn test_passthru_derive() {} macro-attr-0.2.0/tests/stable_encodable.rs00006440000000000000000000026431130122434120016724 0ustar0000000000000000/* Copyright ⓒ 2015 macro-attr contributors. Licensed under the MIT license (see LICENSE or ) or the Apache License, Version 2.0 (see LICENSE of ), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ #[macro_use] extern crate macro_attr; extern crate rustc_serialize; macro_rules! StableEncodable { ( () $(pub)* enum $name:ident < $($tail:tt)* ) => { StableEncodable! { @extract_gen_args (enum $name), ($($tail)*) -> bounds(), ty_clss(where) } }; ( () $(pub)* enum $name:ident { $($body:tt)* } ) => { StableEncodable! { @impl enum $name, bounds(), ty_clss(), { $($body)* } } }; ( () $(pub)* struct $name:ident { $($body:tt)* } ) => { StableEncodable! { @impl struct $name, bounds(), ty_clss(), { $($body)* } } }; ( () $(pub)* struct $name:ident < $($tail:tt)* ) => { StableEncodable! { @extract_gen_args (struct $name), ($($tail)*) -> bounds(), ty_clss(where) } }; ( @impl enum $name:ident, bounds($($bounds:tt)*), ty_clss($($ty_clss:tt)*), { $($body:tt)* } ) => { StableEncodable! { @parse_variants (enum $name, bounds($($bounds)*), ty_clss($($ty_clss)*)), 0usize, ($($body)*,) -> () } }; ( @impl struct $name:ident, bounds($($bounds:tt)*), ty_clss($($ty_clss:tt)*), { $($fnames:ident: $_ftys:ty),* $(,)* } ) => { StableEncodable! { @as_item impl<$($bounds)*> rustc_serialize::Encodable for $name<$($bounds)*> $($ty_clss)* { fn encode( &self, s: &mut StableEncodableEncoder ) -> Result<(), StableEncodableEncoder::Error> where StableEncodableEncoder: rustc_serialize::Encoder { const NUM_FIELDS: usize = StableEncodable!(@count_tts $($fnames)*); try!(s.emit_struct(stringify!($name), NUM_FIELDS, |s| { // Poor man's enumerate!($($fnames)): let mut idx = 0; $( try!(s.emit_struct_field(stringify!($fnames), idx, |s| { self.$fnames.encode(s) })); idx += 1; )* let _ = idx; Ok(()) })); Ok(()) } } } }; (@as_item $i:item) => {$i}; ( @extract_gen_args ($kind:ident $name:ident), (> { $($tail:tt)* }) -> bounds($($bounds:tt)*), ty_clss($($ty_clss:tt)*) ) => { StableEncodable! { @impl $kind $name, bounds($($bounds)*), ty_clss($($ty_clss)*), { $($tail)* } } }; ( @extract_gen_args $fixed:tt, ($ty_name:ident: $($tail)*) -> bounds($($bounds:tt)*), ty_clss($($ty_clss:tt)*) ) => { StableEncodable! { @skip_inline_bound $fixed, ($($tail)*) -> bounds($($bounds)* $ty_name:), ty_clss($($ty_clss)* $ty_name: ::rustc_serialize::Encodable,) } }; ( @extract_gen_args $fixed:tt, ($ty_name:ident $($tail:tt)*) -> bounds($($bounds:tt)*), ty_clss($($ty_clss:tt)*) ) => { StableEncodable! { @extract_gen_args $fixed, ($($tail)*) -> bounds($($bounds)* $ty_name), ty_clss($($ty_clss)* $ty_name: ::rustc_serialize::Encodable,) } }; ( @extract_gen_args $fixed:tt, (, $($tail:tt)*) -> bounds($($bounds:tt)*), ty_clss($($ty_clss:tt)*) ) => { StableEncodable! { @extract_gen_args $fixed, ($($tail)*) -> bounds($($bounds)* ,), ty_clss($($ty_clss)*) } }; ( @extract_gen_args $fixed:tt, ($lt:tt $($tail:tt)*) -> bounds($($bounds:tt)*), ty_clss($($ty_clss:tt)*) ) => { StableEncodable! { @extract_gen_args $fixed, ($($tail)*) -> bounds($($bounds)* $lt), ty_clss($($ty_clss)*) } }; ( @skip_inline_bound $fixed:tt, (, $($tail:tt)*) -> bounds($($bounds:tt)*), ty_clss($($ty_clss:tt)*) ) => { StableEncodable! { @extract_gen_args $fixed, ($($tail)*) -> bounds($($bounds)* ,), ty_clss($($ty_clss)*) } }; ( @skip_inline_bound $fixed:tt, (> { $($tail:tt)* }) -> bounds($($bounds:tt)*), ty_clss($($ty_clss:tt)*) ) => { StableEncodable! { @impl $fixed, bounds($($bounds)*), ty_clss($($ty_clss)*), { $($tail)* } } }; ( @parse_variants (enum $name:ident, bounds($($bounds:tt)*), ty_clss($($ty_clss:tt)*)), $_id:expr, ($(,)*) -> ($($variants:tt)*) ) => { StableEncodable! { @as_item impl<$($bounds)*> rustc_serialize::Encodable for $name<$($bounds)*> $($ty_clss)* { fn encode( &self, s: &mut StableEncodableEncoder) -> Result<(), StableEncodableEncoder::Error> where StableEncodableEncoder: rustc_serialize::Encoder { s.emit_enum(stringify!($name), |s| { $( StableEncodable!(@encode_variant $name, $variants, self, s); )* unreachable!(); }) } } } }; ( @parse_variants $fixed:tt, $id:expr, ($var_name:ident, $($tail:tt)*) -> ($($variants:tt)*) ) => { StableEncodable! { @parse_variants $fixed, ($id + 1usize), ($($tail)*) -> ($($variants)* ($var_name, $id)) } }; ( @parse_variants $fixed:tt, $id:expr, ($var_name:ident($(,)*), $($tail:tt)*) -> ($($variants:tt)*) ) => { StableEncodable! { @parse_variants $fixed, ($id + 1usize), ($($tail)*) -> ($($variants)* ($var_name, $id)) } }; ( @parse_variants $fixed:tt, $id:expr, ($var_name:ident($_vta:ty), $($tail:tt)*) -> ($($variants:tt)*) ) => { StableEncodable! { @parse_variants $fixed, ($id + 1usize), ($($tail)*) -> ($($variants)* ($var_name, $id, (a))) } }; ( @parse_variants $fixed:tt, $id:expr, ($var_name:ident($_vta:ty, $_vtb:ty), $($tail:tt)*) -> ($($variants:tt)*) ) => { StableEncodable! { @parse_variants $fixed, ($id + 1usize), ($($tail)*) -> ($($variants)* ($var_name, $id, (a, b))) } }; ( @parse_variants $fixed:tt, $id:expr, ($var_name:ident($_vta:ty, $_vtb:ty, $_vtc:ty), $($tail:tt)*) -> ($($variants:tt)*) ) => { StableEncodable! { @parse_variants $fixed, ($id + 1usize), ($($tail)*) -> ($($variants)* ($var_name, $id, (a, b, c))) } }; ( @parse_variants $fixed:tt, $id:expr, ($var_name:ident { $($vfn:ident: $_vft:ty),* $(,)* }, $($tail:tt)*) -> ($($variants:tt)*) ) => { StableEncodable! { @parse_variants $fixed, ($id + 1usize), ($($tail)*) -> ($($variants)* ($var_name, $id, {$($vfn),*})) } }; ( @encode_variant $name:ident, ($var_name:ident, $var_id:expr), $self_:expr, $s:ident ) => { { if let $name::$var_name = *$self_ { return $s.emit_enum_variant(stringify!($var_name), $var_id, 0, |_| Ok(())); } } }; ( @encode_variant $name:ident, ($var_name:ident, $var_id:expr, ($($tup_elems:ident),*)), $self_:expr, $s:ident ) => { { if let $name::$var_name($(ref $tup_elems),*) = *$self_ { return $s.emit_enum_variant( stringify!($var_name), $var_id, StableEncodable!(@count_tts $($tup_elems)*), |s| { let mut idx = 0; $( try!(s.emit_enum_variant_arg(idx, |s| $tup_elems.encode(s))); idx += 1; )* let _ = idx; Ok(()) } ); } } }; ( @encode_variant $name:ident, ($var_name:ident, $var_id:expr, {$($str_fields:ident),*}), $self_:expr, $s:ident ) => { { if let $name::$var_name { $(ref $str_fields),* } = *$self_ { return $s.emit_enum_struct_variant( stringify!($var_name), $var_id, StableEncodable!(@count_tts $($str_fields)*), |s| { let mut idx = 0; $( try!(s.emit_enum_struct_variant_field( stringify!($str_fields), idx, |s| $str_fields.encode(s) )); idx += 1; )* let _ = idx; Ok(()) } ); } } }; (@count_tts) => {0usize}; (@count_tts $_tt:tt $($tail:tt)*) => {1usize + StableEncodable!(@count_tts $($tail)*)}; } macro_attr! { #[derive(Debug, StableEncodable!)] struct LazyEg { a: A, b: i32, c: (u8, u8, u8) } } macro_attr! { #[derive(Clone, StableEncodable!)] enum Wonky { Flim, Flam, Flom(i32), Bees { say: S } } } #[test] fn test_stable_encodable() { macro_rules! json { ($e:expr) => (rustc_serialize::json::encode(&$e).unwrap()); } let lazy_eg = LazyEg { a: String::from("Oh hai!"), b: 42, c: (1, 3, 0), }; assert_eq!(&*json!(lazy_eg), r#"{"a":"Oh hai!","b":42,"c":[1,3,0]}"#); assert_eq!(&*json!(Wonky::Flim::<()>), r#""Flim""#); assert_eq!(&*json!(Wonky::Flam::<()>), r#""Flam""#); assert_eq!(&*json!(Wonky::Flom::<()>(42)), r#"{"variant":"Flom","fields":[42]}"#); assert_eq!(&*json!(Wonky::Bees{say:"aaaaah!"}), r#"{"variant":"Bees","fields":["aaaaah!"]}"#); } macro-attr-0.2.0/tests/trailing_comma.rs00006440000000000000000000001136130122434100016434 0ustar0000000000000000/* Copyright ⓒ 2015 macro-attr contributors. Licensed under the MIT license (see LICENSE or ) or the Apache License, Version 2.0 (see LICENSE of ), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ #[macro_use] extern crate macro_attr; macro_rules! Dummy { ($($tts:tt)*) => {}; } macro_attr! { #[derive(Dummy!,)] enum Foo { Bar } } #[test] fn test_trailing_comma() { let _ = Foo::Bar; }