├── .github ├── FUNDING.yml └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── src ├── expand.rs └── lib.rs └── tests ├── compiletest.rs ├── readme.rs └── ui ├── enum.rs ├── enum.stderr ├── readme.rs ├── readme.stderr ├── readonly-meta.rs ├── readonly-meta.stderr ├── unit-struct.rs └── unit-struct.stderr /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: dtolnay 2 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | pull_request: 6 | workflow_dispatch: 7 | schedule: [cron: "40 1 * * *"] 8 | 9 | permissions: 10 | contents: read 11 | 12 | env: 13 | RUSTFLAGS: -Dwarnings 14 | 15 | jobs: 16 | pre_ci: 17 | uses: dtolnay/.github/.github/workflows/pre_ci.yml@master 18 | 19 | test: 20 | name: Rust ${{matrix.rust}} 21 | needs: pre_ci 22 | if: needs.pre_ci.outputs.continue 23 | runs-on: ubuntu-latest 24 | strategy: 25 | fail-fast: false 26 | matrix: 27 | rust: [nightly, beta, stable, 1.56.0] 28 | timeout-minutes: 45 29 | steps: 30 | - uses: actions/checkout@v4 31 | - uses: dtolnay/rust-toolchain@master 32 | with: 33 | toolchain: ${{matrix.rust}} 34 | - name: Enable type layout randomization 35 | run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV 36 | if: matrix.rust == 'nightly' 37 | - run: cargo test 38 | - uses: actions/upload-artifact@v4 39 | if: matrix.rust == 'nightly' && always() 40 | with: 41 | name: Cargo.lock 42 | path: Cargo.lock 43 | continue-on-error: true 44 | 45 | minimal: 46 | name: Minimal versions 47 | needs: pre_ci 48 | if: needs.pre_ci.outputs.continue 49 | runs-on: ubuntu-latest 50 | timeout-minutes: 45 51 | steps: 52 | - uses: actions/checkout@v4 53 | - uses: dtolnay/rust-toolchain@nightly 54 | - run: cargo generate-lockfile -Z minimal-versions 55 | - run: cargo check --locked 56 | 57 | doc: 58 | name: Documentation 59 | needs: pre_ci 60 | if: needs.pre_ci.outputs.continue 61 | runs-on: ubuntu-latest 62 | timeout-minutes: 45 63 | env: 64 | RUSTDOCFLAGS: -Dwarnings 65 | steps: 66 | - uses: actions/checkout@v4 67 | - uses: dtolnay/rust-toolchain@nightly 68 | - uses: dtolnay/install@cargo-docs-rs 69 | - run: cargo docs-rs 70 | 71 | miri: 72 | name: Miri 73 | needs: pre_ci 74 | if: needs.pre_ci.outputs.continue 75 | runs-on: ubuntu-latest 76 | timeout-minutes: 45 77 | steps: 78 | - uses: actions/checkout@v4 79 | - uses: dtolnay/rust-toolchain@miri 80 | with: 81 | toolchain: nightly-2025-05-16 # https://github.com/rust-lang/miri/issues/4323 82 | - run: cargo miri setup 83 | - run: cargo miri test 84 | env: 85 | MIRIFLAGS: -Zmiri-strict-provenance 86 | 87 | clippy: 88 | name: Clippy 89 | runs-on: ubuntu-latest 90 | if: github.event_name != 'pull_request' 91 | timeout-minutes: 45 92 | steps: 93 | - uses: actions/checkout@v4 94 | - uses: dtolnay/rust-toolchain@clippy 95 | - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic 96 | 97 | outdated: 98 | name: Outdated 99 | runs-on: ubuntu-latest 100 | if: github.event_name != 'pull_request' 101 | timeout-minutes: 45 102 | steps: 103 | - uses: actions/checkout@v4 104 | - uses: dtolnay/rust-toolchain@stable 105 | - uses: dtolnay/install@cargo-outdated 106 | - run: cargo outdated --workspace --exit-code 1 107 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "readonly" 3 | version = "0.2.13" 4 | authors = ["David Tolnay "] 5 | categories = ["rust-patterns", "no-std", "no-std::no-alloc"] 6 | description = "Struct fields that are made read-only accessible to other modules" 7 | documentation = "https://docs.rs/readonly" 8 | edition = "2021" 9 | license = "MIT OR Apache-2.0" 10 | repository = "https://github.com/dtolnay/readonly" 11 | rust-version = "1.56" 12 | 13 | [lib] 14 | proc-macro = true 15 | 16 | [dependencies] 17 | proc-macro2 = "1.0.74" 18 | quote = "1.0.35" 19 | syn = { version = "2.0.46", features = ["visit-mut"] } 20 | 21 | [dev-dependencies] 22 | rustversion = "1.0.13" 23 | trybuild = { version = "1.0.81", features = ["diff"] } 24 | 25 | [package.metadata.docs.rs] 26 | targets = ["x86_64-unknown-linux-gnu"] 27 | rustdoc-args = [ 28 | "--generate-link-to-definition", 29 | "--extern-html-root-url=core=https://doc.rust-lang.org", 30 | "--extern-html-root-url=alloc=https://doc.rust-lang.org", 31 | "--extern-html-root-url=std=https://doc.rust-lang.org", 32 | "--extern-html-root-url=proc_macro=https://doc.rust-lang.org", 33 | ] 34 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Readonly 2 | ======== 3 | 4 | [github](https://github.com/dtolnay/readonly) 5 | [crates.io](https://crates.io/crates/readonly) 6 | [docs.rs](https://docs.rs/readonly) 7 | [build status](https://github.com/dtolnay/readonly/actions?query=branch%3Amaster) 8 | 9 | This crate provides an attribute macro to expose struct fields that are readable 10 | and writable from within the same module but readable only outside the module. 11 | 12 | ```toml 13 | [dependencies] 14 | readonly = "0.2" 15 | ``` 16 | 17 | ## Syntax 18 | 19 | Place `#[readonly::make]` on a braced struct or tuple struct. This will make all 20 | fields of the struct publicly readable according to their individual visibility 21 | specifiers, but not writable from other modules. 22 | 23 | ```rust 24 | mod m { 25 | #[readonly::make] 26 | pub struct S { 27 | pub n: i32, 28 | } 29 | 30 | impl S { 31 | pub fn demo(&mut self) { 32 | // Can read and write from inside the same module. 33 | println!("{}", self.n); 34 | self.n += 1; 35 | } 36 | } 37 | } 38 | 39 | fn demo(s: &mut m::S) { 40 | // From outside the module, can only read. 41 | println!("{}", s.n); 42 | 43 | // Does not compile: 44 | //s.n += 1; 45 | } 46 | ``` 47 | 48 | The error appears as follows. 49 | 50 | ```console 51 | error[E0594]: cannot assign to data in a dereference of `m::S` 52 | --> readme.rs:21:5 53 | | 54 | 21 | s.n += 1; 55 | | ^^^^^^^^ cannot assign 56 | ``` 57 | 58 | Optionally, place `#[readonly]` on individual struct fields to make just those 59 | fields publicly readable, without affecting other fields of the struct. 60 | 61 | ```rust 62 | #[readonly::make] 63 | pub struct S { 64 | // This field can be read (but not written) by super. 65 | #[readonly] 66 | pub(super) readable: i32, 67 | 68 | // This field can be neither read nor written by other modules. 69 | private: i32, 70 | } 71 | ``` 72 | 73 |
74 | 75 | #### License 76 | 77 | 78 | Licensed under either of Apache License, Version 79 | 2.0 or MIT license at your option. 80 | 81 | 82 |
83 | 84 | 85 | Unless you explicitly state otherwise, any contribution intentionally submitted 86 | for inclusion in this crate by you, as defined in the Apache-2.0 license, shall 87 | be dual licensed as above, without any additional terms or conditions. 88 | 89 | -------------------------------------------------------------------------------- /src/expand.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::{Span, TokenStream, TokenTree}; 2 | use quote::quote; 3 | use syn::visit_mut::{self, VisitMut}; 4 | use syn::{ 5 | parse_quote, token, Data, DeriveInput, Error, Expr, Field, Fields, Ident, Path, Result, Token, 6 | Visibility, 7 | }; 8 | 9 | type Punctuated = syn::punctuated::Punctuated; 10 | 11 | pub fn readonly(input: DeriveInput) -> Result { 12 | let call_site = Span::call_site(); 13 | 14 | match &input.data { 15 | Data::Struct(data) => { 16 | if data.fields.iter().count() == 0 { 17 | return Err(Error::new(call_site, "input must be a struct with fields")); 18 | } 19 | } 20 | Data::Enum(_) | Data::Union(_) => { 21 | return Err(Error::new(call_site, "input must be a struct")); 22 | } 23 | } 24 | 25 | let mut input = input; 26 | 27 | let mut attr_errors = Vec::new(); 28 | let indices = find_and_strip_readonly_attrs(&mut input, &mut attr_errors); 29 | 30 | let original_input = quote! { 31 | #[cfg(doc)] 32 | #input 33 | }; 34 | 35 | if !has_defined_repr(&input) { 36 | input.attrs.push(parse_quote!(#[repr(C)])); 37 | } 38 | 39 | let mut readonly = input.clone(); 40 | readonly.attrs.insert(0, parse_quote!(#[doc(hidden)])); 41 | 42 | let input_vis = input.vis.clone(); 43 | let input_fields = fields_of_input(&mut input); 44 | let readonly_fields = fields_of_input(&mut readonly); 45 | 46 | if indices.is_empty() { 47 | for field in input_fields { 48 | field.vis = Visibility::Inherited; 49 | } 50 | } else { 51 | for i in indices { 52 | input_fields[i].vis = Visibility::Inherited; 53 | if let Visibility::Inherited = readonly_fields[i].vis { 54 | readonly_fields[i].vis = input_vis.clone(); 55 | } 56 | } 57 | } 58 | 59 | let ident = &input.ident; 60 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 61 | 62 | let self_path: Path = parse_quote!(#ident #ty_generics); 63 | for field in readonly_fields { 64 | ReplaceSelf::new(&self_path).visit_type_mut(&mut field.ty); 65 | } 66 | 67 | readonly.ident = Ident::new(&format!("ReadOnly{}", input.ident), call_site); 68 | let readonly_ident = &readonly.ident; 69 | 70 | input.attrs.insert(0, parse_quote!(#[cfg(not(doc))])); 71 | 72 | let attr_errors = attr_errors.iter().map(Error::to_compile_error); 73 | 74 | Ok(quote! { 75 | #original_input 76 | 77 | #input 78 | 79 | const _: () = { 80 | #readonly 81 | 82 | #[doc(hidden)] 83 | impl #impl_generics core::ops::Deref for #ident #ty_generics #where_clause { 84 | type Target = #readonly_ident #ty_generics; 85 | 86 | fn deref(&self) -> &Self::Target { 87 | // Two repr(C) structs with the same fields are guaranteed to 88 | // have the same layout. 89 | unsafe { &*(self as *const Self as *const Self::Target) } 90 | } 91 | } 92 | }; 93 | 94 | #(#attr_errors)* 95 | }) 96 | } 97 | 98 | fn has_defined_repr(input: &DeriveInput) -> bool { 99 | let mut has_defined_repr = false; 100 | for attr in &input.attrs { 101 | if !attr.path().is_ident("repr") { 102 | continue; 103 | } 104 | let _ = attr.parse_nested_meta(|meta| { 105 | let path = &meta.path; 106 | if path.is_ident("C") || path.is_ident("transparent") || path.is_ident("packed") { 107 | has_defined_repr = true; 108 | } 109 | if meta.input.peek(Token![=]) { 110 | let _value: Expr = meta.value()?.parse()?; 111 | } else if meta.input.peek(token::Paren) { 112 | let _group: TokenTree = meta.input.parse()?; 113 | } 114 | Ok(()) 115 | }); 116 | } 117 | has_defined_repr 118 | } 119 | 120 | fn fields_of_input(input: &mut DeriveInput) -> &mut Punctuated { 121 | match &mut input.data { 122 | Data::Struct(data) => match &mut data.fields { 123 | Fields::Named(fields) => &mut fields.named, 124 | Fields::Unnamed(fields) => &mut fields.unnamed, 125 | Fields::Unit => unreachable!(), 126 | }, 127 | Data::Enum(_) | Data::Union(_) => unreachable!(), 128 | } 129 | } 130 | 131 | fn find_and_strip_readonly_attrs(input: &mut DeriveInput, errors: &mut Vec) -> Vec { 132 | let mut indices = Vec::new(); 133 | 134 | for (i, field) in fields_of_input(input).iter_mut().enumerate() { 135 | let mut readonly_attr_index = None; 136 | 137 | for (j, attr) in field.attrs.iter().enumerate() { 138 | if attr.path().is_ident("readonly") { 139 | if let Err(err) = attr.meta.require_path_only() { 140 | errors.push(err); 141 | } 142 | readonly_attr_index = Some(j); 143 | break; 144 | } 145 | } 146 | 147 | if let Some(readonly_attr_index) = readonly_attr_index { 148 | field.attrs.remove(readonly_attr_index); 149 | indices.push(i); 150 | } 151 | } 152 | 153 | indices 154 | } 155 | 156 | struct ReplaceSelf<'a> { 157 | with: &'a Path, 158 | } 159 | 160 | impl<'a> ReplaceSelf<'a> { 161 | fn new(with: &'a Path) -> Self { 162 | ReplaceSelf { with } 163 | } 164 | } 165 | 166 | impl<'a> VisitMut for ReplaceSelf<'a> { 167 | fn visit_path_mut(&mut self, path: &mut Path) { 168 | if path.is_ident("Self") { 169 | let span = path.segments[0].ident.span(); 170 | *path = self.with.clone(); 171 | path.segments[0].ident.set_span(span); 172 | } else { 173 | visit_mut::visit_path_mut(self, path); 174 | } 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! [![github]](https://github.com/dtolnay/readonly) [![crates-io]](https://crates.io/crates/readonly) [![docs-rs]](https://docs.rs/readonly) 2 | //! 3 | //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github 4 | //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust 5 | //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs 6 | //! 7 | //!
8 | //! 9 | //! Struct fields that can be read and written from within the same module, but 10 | //! from outside the module can only be read. 11 | //! 12 | //! # Syntax 13 | //! 14 | //! Place `#[readonly::make]` on a braced struct or tuple struct. This will make 15 | //! all fields of the struct publicly readable according to their individual 16 | //! visibility specifiers, but not writable from other modules. 17 | //! 18 | //! ``` 19 | //! mod m { 20 | //! #[readonly::make] 21 | //! pub struct S { 22 | //! pub n: i32, 23 | //! } 24 | //! 25 | //! impl S { 26 | //! pub fn demo(&mut self) { 27 | //! // Can read and write from inside the same module. 28 | //! println!("{}", self.n); 29 | //! self.n += 1; 30 | //! } 31 | //! } 32 | //! } 33 | //! 34 | //! fn demo(s: &mut m::S) { 35 | //! // From outside the module, can only read. 36 | //! println!("{}", s.n); 37 | //! 38 | //! // Does not compile: 39 | //! //s.n += 1; 40 | //! } 41 | //! ``` 42 | //! 43 | //! The error appears as follows. 44 | //! 45 | //! ```console 46 | //! error[E0594]: cannot assign to data in a dereference of `m::S` 47 | //! --> readme.rs:21:5 48 | //! | 49 | //! 21 | s.n += 1; 50 | //! | ^^^^^^^^ cannot assign 51 | //! ``` 52 | //! 53 | //! Optionally, place `#[readonly]` on individual struct fields to make just 54 | //! those fields publicly readable, without affecting other fields of the 55 | //! struct. 56 | //! 57 | //! ``` 58 | //! # mod m { 59 | //! #[readonly::make] 60 | //! pub struct S { 61 | //! // This field can be read (but not written) by super. 62 | //! #[readonly] 63 | //! pub(super) readable: i32, 64 | //! 65 | //! // This field can be neither read nor written by other modules. 66 | //! private: i32, 67 | //! } 68 | //! # } 69 | //! ``` 70 | 71 | #![doc(html_root_url = "https://docs.rs/readonly/0.2.13")] 72 | #![allow(clippy::elidable_lifetime_names, clippy::needless_lifetimes)] 73 | 74 | extern crate proc_macro; 75 | 76 | mod expand; 77 | 78 | use proc_macro::TokenStream; 79 | use quote::quote; 80 | use syn::parse::Nothing; 81 | use syn::{parse_macro_input, DeriveInput}; 82 | 83 | #[proc_macro_attribute] 84 | pub fn make(args: TokenStream, tokens: TokenStream) -> TokenStream { 85 | let original = tokens.clone(); 86 | parse_macro_input!(args as Nothing); 87 | let input = parse_macro_input!(tokens as DeriveInput); 88 | 89 | expand::readonly(input) 90 | .unwrap_or_else(|e| { 91 | let original = proc_macro2::TokenStream::from(original); 92 | let compile_error = e.to_compile_error(); 93 | quote! { 94 | #original 95 | #compile_error 96 | } 97 | }) 98 | .into() 99 | } 100 | -------------------------------------------------------------------------------- /tests/compiletest.rs: -------------------------------------------------------------------------------- 1 | #[rustversion::attr(not(nightly), ignore = "requires nightly")] 2 | #[cfg_attr(miri, ignore = "incompatible with miri")] 3 | #[test] 4 | fn ui() { 5 | let t = trybuild::TestCases::new(); 6 | t.compile_fail("tests/ui/*.rs"); 7 | } 8 | -------------------------------------------------------------------------------- /tests/readme.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::needless_pass_by_ref_mut)] 2 | 3 | mod m { 4 | #[readonly::make] 5 | pub struct S { 6 | pub n: i32, 7 | } 8 | 9 | impl S { 10 | pub fn new(n: i32) -> Self { 11 | S { n } 12 | } 13 | 14 | pub fn demo(&mut self) { 15 | // Can read and write from inside the same module. 16 | println!("{}", self.n); 17 | self.n += 1; 18 | } 19 | } 20 | } 21 | 22 | fn demo(s: &mut m::S) { 23 | // From outside the module, can only read. 24 | println!("{}", s.n); 25 | 26 | // Does not compile: 27 | //s.n += 1; 28 | } 29 | 30 | #[test] 31 | fn test() { 32 | let mut s = m::S::new(0); 33 | 34 | s.demo(); 35 | 36 | demo(&mut s); 37 | } 38 | -------------------------------------------------------------------------------- /tests/ui/enum.rs: -------------------------------------------------------------------------------- 1 | #[readonly::make] 2 | enum E { 3 | V(u8), 4 | } 5 | 6 | fn main() {} 7 | -------------------------------------------------------------------------------- /tests/ui/enum.stderr: -------------------------------------------------------------------------------- 1 | error: input must be a struct 2 | --> tests/ui/enum.rs:1:1 3 | | 4 | 1 | #[readonly::make] 5 | | ^^^^^^^^^^^^^^^^^ 6 | | 7 | = note: this error originates in the attribute macro `readonly::make` (in Nightly builds, run with -Z macro-backtrace for more info) 8 | -------------------------------------------------------------------------------- /tests/ui/readme.rs: -------------------------------------------------------------------------------- 1 | mod m { 2 | #[readonly::make] 3 | pub struct S { 4 | pub n: i32, 5 | } 6 | 7 | impl S { 8 | pub fn demo(&mut self) { 9 | // Can read and write from inside the same module. 10 | println!("{}", self.n); 11 | self.n += 1; 12 | } 13 | } 14 | } 15 | 16 | fn demo(s: &mut m::S) { 17 | // From outside the module, can only read. 18 | println!("{}", s.n); 19 | 20 | // Does not compile: 21 | s.n += 1; 22 | } 23 | 24 | fn main() {} 25 | -------------------------------------------------------------------------------- /tests/ui/readme.stderr: -------------------------------------------------------------------------------- 1 | error[E0594]: cannot assign to data in dereference of `S` 2 | --> tests/ui/readme.rs:21:5 3 | | 4 | 21 | s.n += 1; 5 | | ^^^^^^^^ cannot assign 6 | | 7 | = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `S` 8 | -------------------------------------------------------------------------------- /tests/ui/readonly-meta.rs: -------------------------------------------------------------------------------- 1 | #[readonly::make] 2 | pub struct S { 3 | #[readonly = "..."] 4 | namevalue: i32, 5 | 6 | #[readonly(...)] 7 | list: i32, 8 | } 9 | 10 | fn main() {} 11 | -------------------------------------------------------------------------------- /tests/ui/readonly-meta.stderr: -------------------------------------------------------------------------------- 1 | error: unexpected token in attribute 2 | --> tests/ui/readonly-meta.rs:3:16 3 | | 4 | 3 | #[readonly = "..."] 5 | | ^ 6 | 7 | error: unexpected token in attribute 8 | --> tests/ui/readonly-meta.rs:6:15 9 | | 10 | 6 | #[readonly(...)] 11 | | ^ 12 | -------------------------------------------------------------------------------- /tests/ui/unit-struct.rs: -------------------------------------------------------------------------------- 1 | #[readonly::make] 2 | struct Unit; 3 | 4 | fn main() {} 5 | -------------------------------------------------------------------------------- /tests/ui/unit-struct.stderr: -------------------------------------------------------------------------------- 1 | error: input must be a struct with fields 2 | --> tests/ui/unit-struct.rs:1:1 3 | | 4 | 1 | #[readonly::make] 5 | | ^^^^^^^^^^^^^^^^^ 6 | | 7 | = note: this error originates in the attribute macro `readonly::make` (in Nightly builds, run with -Z macro-backtrace for more info) 8 | --------------------------------------------------------------------------------