├── .gitignore ├── .travis.yml ├── Cargo.toml ├── EXAMPLE.md ├── LICENSE.md ├── README.md └── src ├── lib.rs └── sorty.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: nightly 3 | sudo: false 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sorty" 3 | description = "A plugin to check whether the 'extern crate', 'mod' and 'use' declarations are in their sorted format" 4 | 5 | repository = "https://github.com/Wafflespeanut/rust-sorty" 6 | readme = "README.md" 7 | license = "MPL-2.0" 8 | 9 | version = "0.1.2" 10 | authors = ["Ravi Shankar "] 11 | keywords = ["sort", "lint", "plugin", "declaration"] 12 | 13 | [lib] 14 | name = "sorty" 15 | plugin = true 16 | -------------------------------------------------------------------------------- /EXAMPLE.md: -------------------------------------------------------------------------------- 1 | ## Detailed Example: 2 | 3 | Let's try sorting the declarations in an [older checkout of `gfx/lib.rs` module](https://github.com/servo/servo/blob/8f1469eb08a437bcc6cfb510334be2b6430b4a8f/components/gfx/lib.rs) in Servo (I chose this file specifically, because it covers all the use cases). Once we add the plugin to the dependencies, we get some pretty warnings. 4 | 5 | Let's see them one by one... 6 | 7 | ### `extern crate` 8 | 9 | So, we have this first set of mess in `gfx/lib.rs`... 10 | 11 | ``` rust 12 | #[macro_use] 13 | extern crate log; 14 | extern crate serde; 15 | 16 | extern crate azure; 17 | #[macro_use] extern crate bitflags; 18 | extern crate fnv; 19 | extern crate euclid; 20 | extern crate ipc_channel; 21 | #[macro_use] 22 | extern crate lazy_static; 23 | extern crate layers; 24 | extern crate libc; 25 | #[macro_use] 26 | extern crate profile_traits; 27 | extern crate script_traits; 28 | extern crate rustc_serialize; 29 | extern crate net_traits; 30 | #[macro_use] 31 | extern crate util; 32 | extern crate msg; 33 | extern crate rand; 34 | 35 | #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] 36 | extern crate simd; 37 | 38 | extern crate smallvec; 39 | extern crate string_cache; 40 | extern crate style; 41 | extern crate skia; 42 | extern crate time; 43 | extern crate url; 44 | 45 | extern crate gfx_traits; 46 | extern crate canvas_traits; 47 | 48 | // Eventually we would like the shaper to be pluggable, as many operating systems have their own 49 | // shapers. For now, however, this is a hard dependency. 50 | extern crate harfbuzz; 51 | 52 | // Linux and Android-specific library dependencies 53 | #[cfg(any(target_os = "linux", target_os = "android"))] 54 | extern crate fontconfig; 55 | 56 | #[cfg(any(target_os = "linux", target_os = "android"))] 57 | extern crate freetype; 58 | 59 | // Mac OS-specific library dependencies 60 | #[cfg(target_os = "macos")] extern crate core_foundation; 61 | #[cfg(target_os = "macos")] extern crate core_graphics; 62 | #[cfg(target_os = "macos")] extern crate core_text; 63 | ``` 64 | 65 | ... for which we get the following warning, 66 | 67 | gfx/lib.rs:26:1: 70:23 warning: crate declarations should be in alphabetical order!, #[warn(unsorted_declarations)] on by default 68 | gfx/lib.rs:26 extern crate log; 69 | gfx/lib.rs:27 extern crate serde; 70 | gfx/lib.rs:28 71 | gfx/lib.rs:29 extern crate azure; 72 | gfx/lib.rs:30 #[macro_use] extern crate bitflags; 73 | gfx/lib.rs:31 extern crate fnv; 74 | ... 75 | gfx/lib.rs:26:1: 70:23 help: Try this... 76 | 77 | #[macro_use] 78 | extern crate bitflags; 79 | #[macro_use] 80 | extern crate lazy_static; 81 | #[macro_use] 82 | extern crate log; 83 | #[macro_use] 84 | extern crate profile_traits; 85 | #[macro_use] 86 | extern crate util; 87 | extern crate azure; 88 | extern crate canvas_traits; 89 | extern crate euclid; 90 | extern crate fnv; 91 | #[cfg(any(target_os = "linux", target_os = "android"))] 92 | extern crate fontconfig; 93 | #[cfg(any(target_os = "linux", target_os = "android"))] 94 | extern crate freetype; 95 | extern crate gfx_traits; 96 | extern crate harfbuzz; 97 | extern crate ipc_channel; 98 | extern crate layers; 99 | extern crate libc; 100 | extern crate msg; 101 | extern crate net_traits; 102 | extern crate rand; 103 | extern crate rustc_serialize; 104 | extern crate script_traits; 105 | extern crate serde; 106 | #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] 107 | extern crate simd; 108 | extern crate skia; 109 | extern crate smallvec; 110 | extern crate string_cache; 111 | extern crate style; 112 | extern crate time; 113 | extern crate url; 114 | 115 | As you can see, **sorty is blind to spaces and comments** (for now). You should always remember that it's a plugin. All it does is play with the AST and rebuild the input back from there. So, the output is as expected - stuff with `#[macro_use]` are sorted and moved to the top, while those with other attributes are below them. 116 | 117 | It shows exactly where you should replace the code, 118 | 119 | gfx/lib.rs:26:1: 70:23 warning: ... 120 | 121 | ... which is useful when (for example) half of the code's already sorted. 122 | 123 | Also, note that the declarations with attributes like `#[cfg(target_os = "macos")]` are stripped off while building in linux (for example), and so the lint can't see the `core_foundation`, `core_graphics` and `core_text` crates in my system, because the stripping happens well before lints. So, folks should take care of that. 124 | 125 | ### `mod` 126 | 127 | Now, off to the second set of mess. In `gfx/lib.rs`, we have... 128 | 129 | ``` rust 130 | // Private painting modules 131 | mod paint_context; 132 | 133 | #[path = "display_list/mod.rs"] 134 | pub mod display_list; 135 | pub mod paint_task; 136 | 137 | // Fonts 138 | pub mod font; 139 | pub mod font_cache_task; 140 | pub mod font_context; 141 | pub mod font_template; 142 | 143 | // Misc. 144 | mod filters; 145 | 146 | // Platform-specific implementations. 147 | #[path = "platform/mod.rs"] 148 | pub mod platform; 149 | 150 | // Text 151 | #[path = "text/mod.rs"] 152 | pub mod text; 153 | ``` 154 | 155 | and, we get... 156 | 157 | gfx/lib.rs:80:1: 101:14 warning: module declarations (other than inline modules) should be in alphabetical order!, #[warn(unsorted_declarations)] on by default 158 | gfx/lib.rs:80 mod paint_context; 159 | gfx/lib.rs:81 160 | gfx/lib.rs:82 #[path = "display_list/mod.rs"] 161 | gfx/lib.rs:83 pub mod display_list; 162 | gfx/lib.rs:84 pub mod paint_task; 163 | gfx/lib.rs:85 164 | ... 165 | gfx/lib.rs:80:1: 101:14 help: Try this... 166 | 167 | mod filters; 168 | mod paint_context; 169 | #[deny(unsafe_code)] 170 | #[path = "display_list/mod.rs"] 171 | pub mod display_list; 172 | pub mod font; 173 | pub mod font_cache_task; 174 | pub mod font_context; 175 | pub mod font_template; 176 | pub mod paint_task; 177 | #[path = "platform/mod.rs"] 178 | pub mod platform; 179 | #[path = "text/mod.rs"] 180 | pub mod text; 181 | 182 | The comments and spaces are ignored, just like I'd said previously. And, the private modules are sorted and moved to the top, while the public modules are sorted and moved to the bottom. If there were any `#[macro_use]`, it would've been moved to the top irrespective of whether it's public or private. 183 | 184 | Anyways, there's more. The public module `display_list` only had a `path` attribute, but we now have a `#[deny(unsafe_code)]` along with it. That's because the `display_list` [has the attribute in its file](https://github.com/servo/servo/blob/8f1469eb08a437bcc6cfb510334be2b6430b4a8f/components/gfx/display_list/mod.rs#L17). I'm not sure whether it's a bad style, but even if it's good, there's no way we could train the lint to detect them, because in the AST level, there's no difference between both the cases i.e., it doesn't matter where you declare the attribute. 185 | 186 | So, that should be taken care of as well... 187 | 188 | ### `use` 189 | 190 | There's only one `use` statement in `gfx/lib.rs`, which sorty doesn't mind. But, since it makes use of [`check_mod`](https://manishearth.github.io/rust-internals-docs/rustc/lint/trait.EarlyLintPass.html#method.check_mod) function, `rustc` walks into the other modules and submodules (and subsubmodules and ...) of the crate, and so we have warnings for the `use` statements declared there. For our example, let's choose [`gfx/paint_task.rs`](https://github.com/servo/servo/blob/8f1469eb08a437bcc6cfb510334be2b6430b4a8f/components/gfx/paint_task.rs), which has the following contents... 191 | 192 | ``` rust 193 | use azure::AzFloat; 194 | use azure::azure_hl::{SurfaceFormat, Color, DrawTarget, BackendType}; 195 | use canvas_traits::CanvasMsg; 196 | use display_list::{self, StackingContext}; 197 | use euclid::Matrix4; 198 | use euclid::point::Point2D; 199 | use euclid::rect::Rect; 200 | use euclid::size::Size2D; 201 | use font_cache_task::FontCacheTask; 202 | use font_context::FontContext; 203 | use ipc_channel::ipc::IpcSender; 204 | use layers::layers::{BufferRequest, LayerBuffer, LayerBufferSet}; 205 | use layers::platform::surface::{NativeDisplay, NativeSurface}; 206 | use msg::compositor_msg::{Epoch, FrameTreeId, LayerId, LayerKind}; 207 | use msg::compositor_msg::{LayerProperties, PaintListener}; 208 | use msg::constellation_msg::Msg as ConstellationMsg; 209 | use msg::constellation_msg::PipelineExitType; 210 | use msg::constellation_msg::{ConstellationChan, Failure, PipelineId}; 211 | use paint_context::PaintContext; 212 | use profile_traits::mem::{self, ReportsChan}; 213 | use profile_traits::time::{self, profile}; 214 | use rand::{self, Rng}; 215 | use skia::gl_context::GLContext; 216 | use std::borrow::ToOwned; 217 | use std::collections::HashMap; 218 | use std::mem as std_mem; 219 | use std::sync::Arc; 220 | use std::sync::mpsc::{Receiver, Select, Sender, channel}; 221 | use url::Url; 222 | use util::geometry::{Au, ZERO_POINT}; 223 | use util::opts; 224 | use util::task::spawn_named; 225 | use util::task::spawn_named_with_send_on_failure; 226 | use util::task_state; 227 | ``` 228 | 229 | and, we get the following warning... 230 | 231 | gfx/paint_task.rs:8:5: 40:22 warning: use statements should be in alphabetical order!, #[warn(unsorted_declarations)] on by default 232 | gfx/paint_task.rs: 8 use azure::azure_hl::{SurfaceFormat, Color, DrawTarget, BackendType}; 233 | gfx/paint_task.rs: 9 use canvas_traits::CanvasMsg; 234 | gfx/paint_task.rs:10 use display_list::{self, StackingContext}; 235 | gfx/paint_task.rs:11 use euclid::Matrix4; 236 | gfx/paint_task.rs:12 use euclid::point::Point2D; 237 | gfx/paint_task.rs:13 use euclid::rect::Rect; 238 | ... 239 | gfx/paint_task.rs:8:5: 40:22 help: Try this... 240 | 241 | use azure::azure_hl::{BackendType, Color, DrawTarget, SurfaceFormat}; 242 | use canvas_traits::CanvasMsg; 243 | use display_list::{self, StackingContext}; 244 | use euclid::Matrix4; 245 | use euclid::point::Point2D; 246 | use euclid::rect::Rect; 247 | use euclid::size::Size2D; 248 | use font_cache_task::FontCacheTask; 249 | use font_context::FontContext; 250 | use ipc_channel::ipc::IpcSender; 251 | use layers::layers::{BufferRequest, LayerBuffer, LayerBufferSet}; 252 | use layers::platform::surface::{NativeDisplay, NativeSurface}; 253 | use msg::compositor_msg::{Epoch, FrameTreeId, LayerId, LayerKind}; 254 | use msg::compositor_msg::{LayerProperties, PaintListener}; 255 | use msg::constellation_msg::Msg as ConstellationMsg; 256 | use msg::constellation_msg::PipelineExitType; 257 | use msg::constellation_msg::{ConstellationChan, Failure, PipelineId}; 258 | use paint_context::PaintContext; 259 | use profile_traits::mem::{self, ReportsChan}; 260 | use profile_traits::time::{self, profile}; 261 | use rand::{self, Rng}; 262 | use skia::gl_context::GLContext; 263 | use std::borrow::ToOwned; 264 | use std::collections::HashMap; 265 | use std::mem as std_mem; 266 | use std::sync::Arc; 267 | use std::sync::mpsc::{Receiver, Select, Sender, channel}; 268 | use url::Url; 269 | use util::geometry::{Au, ZERO_POINT}; 270 | use util::opts; 271 | use util::task::spawn_named; 272 | use util::task::spawn_named_with_send_on_failure; 273 | use util::task_state; 274 | 275 | As you can see, the first declaration `use azure::AzFloat;` has been left out, and the span has began from line 8 instead of line 7. This means that in the eyes of sorty, the first declaration stays right where it was even after sorting, but the statements following it aren't following the rule (though the second line stays where it was, its list items aren't sorted!), and so it throws the warning for all the remaining statements. 276 | 277 | Also, note that sorty doesn't care about how many correct statements you have. Even if one declaration's in the wrong place, then it starts printing out all the following statements, because it's easier for everyone to just *copy-paste* everything instead of looking for the exact span in lengthy code. 278 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Mozilla Public License, version 2.0 2 | 3 | 1. Definitions 4 | 5 | 1.1. "Contributor" 6 | 7 | means each individual or legal entity that creates, contributes to the 8 | creation of, or owns Covered Software. 9 | 10 | 1.2. "Contributor Version" 11 | 12 | means the combination of the Contributions of others (if any) used by a 13 | Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | 17 | means Covered Software of a particular Contributor. 18 | 19 | 1.4. "Covered Software" 20 | 21 | means Source Code Form to which the initial Contributor has attached the 22 | notice in Exhibit A, the Executable Form of such Source Code Form, and 23 | Modifications of such Source Code Form, in each case including portions 24 | thereof. 25 | 26 | 1.5. "Incompatible With Secondary Licenses" 27 | means 28 | 29 | a. that the initial Contributor has attached the notice described in 30 | Exhibit B to the Covered Software; or 31 | 32 | b. that the Covered Software was made available under the terms of 33 | version 1.1 or earlier of the License, but not also under the terms of 34 | a Secondary License. 35 | 36 | 1.6. "Executable Form" 37 | 38 | means any form of the work other than Source Code Form. 39 | 40 | 1.7. "Larger Work" 41 | 42 | means a work that combines Covered Software with other material, in a 43 | separate file or files, that is not Covered Software. 44 | 45 | 1.8. "License" 46 | 47 | means this document. 48 | 49 | 1.9. "Licensable" 50 | 51 | means having the right to grant, to the maximum extent possible, whether 52 | at the time of the initial grant or subsequently, any and all of the 53 | rights conveyed by this License. 54 | 55 | 1.10. "Modifications" 56 | 57 | means any of the following: 58 | 59 | a. any file in Source Code Form that results from an addition to, 60 | deletion from, or modification of the contents of Covered Software; or 61 | 62 | b. any new file in Source Code Form that contains any Covered Software. 63 | 64 | 1.11. "Patent Claims" of a Contributor 65 | 66 | means any patent claim(s), including without limitation, method, 67 | process, and apparatus claims, in any patent Licensable by such 68 | Contributor that would be infringed, but for the grant of the License, 69 | by the making, using, selling, offering for sale, having made, import, 70 | or transfer of either its Contributions or its Contributor Version. 71 | 72 | 1.12. "Secondary License" 73 | 74 | means either the GNU General Public License, Version 2.0, the GNU Lesser 75 | General Public License, Version 2.1, the GNU Affero General Public 76 | License, Version 3.0, or any later versions of those licenses. 77 | 78 | 1.13. "Source Code Form" 79 | 80 | means the form of the work preferred for making modifications. 81 | 82 | 1.14. "You" (or "Your") 83 | 84 | means an individual or a legal entity exercising rights under this 85 | License. For legal entities, "You" includes any entity that controls, is 86 | controlled by, or is under common control with You. For purposes of this 87 | definition, "control" means (a) the power, direct or indirect, to cause 88 | the direction or management of such entity, whether by contract or 89 | otherwise, or (b) ownership of more than fifty percent (50%) of the 90 | outstanding shares or beneficial ownership of such entity. 91 | 92 | 93 | 2. License Grants and Conditions 94 | 95 | 2.1. Grants 96 | 97 | Each Contributor hereby grants You a world-wide, royalty-free, 98 | non-exclusive license: 99 | 100 | a. under intellectual property rights (other than patent or trademark) 101 | Licensable by such Contributor to use, reproduce, make available, 102 | modify, display, perform, distribute, and otherwise exploit its 103 | Contributions, either on an unmodified basis, with Modifications, or 104 | as part of a Larger Work; and 105 | 106 | b. under Patent Claims of such Contributor to make, use, sell, offer for 107 | sale, have made, import, and otherwise transfer either its 108 | Contributions or its Contributor Version. 109 | 110 | 2.2. Effective Date 111 | 112 | The licenses granted in Section 2.1 with respect to any Contribution 113 | become effective for each Contribution on the date the Contributor first 114 | distributes such Contribution. 115 | 116 | 2.3. Limitations on Grant Scope 117 | 118 | The licenses granted in this Section 2 are the only rights granted under 119 | this License. No additional rights or licenses will be implied from the 120 | distribution or licensing of Covered Software under this License. 121 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 122 | Contributor: 123 | 124 | a. for any code that a Contributor has removed from Covered Software; or 125 | 126 | b. for infringements caused by: (i) Your and any other third party's 127 | modifications of Covered Software, or (ii) the combination of its 128 | Contributions with other software (except as part of its Contributor 129 | Version); or 130 | 131 | c. under Patent Claims infringed by Covered Software in the absence of 132 | its Contributions. 133 | 134 | This License does not grant any rights in the trademarks, service marks, 135 | or logos of any Contributor (except as may be necessary to comply with 136 | the notice requirements in Section 3.4). 137 | 138 | 2.4. Subsequent Licenses 139 | 140 | No Contributor makes additional grants as a result of Your choice to 141 | distribute the Covered Software under a subsequent version of this 142 | License (see Section 10.2) or under the terms of a Secondary License (if 143 | permitted under the terms of Section 3.3). 144 | 145 | 2.5. Representation 146 | 147 | Each Contributor represents that the Contributor believes its 148 | Contributions are its original creation(s) or it has sufficient rights to 149 | grant the rights to its Contributions conveyed by this License. 150 | 151 | 2.6. Fair Use 152 | 153 | This License is not intended to limit any rights You have under 154 | applicable copyright doctrines of fair use, fair dealing, or other 155 | equivalents. 156 | 157 | 2.7. Conditions 158 | 159 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in 160 | Section 2.1. 161 | 162 | 163 | 3. Responsibilities 164 | 165 | 3.1. Distribution of Source Form 166 | 167 | All distribution of Covered Software in Source Code Form, including any 168 | Modifications that You create or to which You contribute, must be under 169 | the terms of this License. You must inform recipients that the Source 170 | Code Form of the Covered Software is governed by the terms of this 171 | License, and how they can obtain a copy of this License. You may not 172 | attempt to alter or restrict the recipients' rights in the Source Code 173 | Form. 174 | 175 | 3.2. Distribution of Executable Form 176 | 177 | If You distribute Covered Software in Executable Form then: 178 | 179 | a. such Covered Software must also be made available in Source Code Form, 180 | as described in Section 3.1, and You must inform recipients of the 181 | Executable Form how they can obtain a copy of such Source Code Form by 182 | reasonable means in a timely manner, at a charge no more than the cost 183 | of distribution to the recipient; and 184 | 185 | b. You may distribute such Executable Form under the terms of this 186 | License, or sublicense it under different terms, provided that the 187 | license for the Executable Form does not attempt to limit or alter the 188 | recipients' rights in the Source Code Form under this License. 189 | 190 | 3.3. Distribution of a Larger Work 191 | 192 | You may create and distribute a Larger Work under terms of Your choice, 193 | provided that You also comply with the requirements of this License for 194 | the Covered Software. If the Larger Work is a combination of Covered 195 | Software with a work governed by one or more Secondary Licenses, and the 196 | Covered Software is not Incompatible With Secondary Licenses, this 197 | License permits You to additionally distribute such Covered Software 198 | under the terms of such Secondary License(s), so that the recipient of 199 | the Larger Work may, at their option, further distribute the Covered 200 | Software under the terms of either this License or such Secondary 201 | License(s). 202 | 203 | 3.4. Notices 204 | 205 | You may not remove or alter the substance of any license notices 206 | (including copyright notices, patent notices, disclaimers of warranty, or 207 | limitations of liability) contained within the Source Code Form of the 208 | Covered Software, except that You may alter any license notices to the 209 | extent required to remedy known factual inaccuracies. 210 | 211 | 3.5. Application of Additional Terms 212 | 213 | You may choose to offer, and to charge a fee for, warranty, support, 214 | indemnity or liability obligations to one or more recipients of Covered 215 | Software. However, You may do so only on Your own behalf, and not on 216 | behalf of any Contributor. You must make it absolutely clear that any 217 | such warranty, support, indemnity, or liability obligation is offered by 218 | You alone, and You hereby agree to indemnify every Contributor for any 219 | liability incurred by such Contributor as a result of warranty, support, 220 | indemnity or liability terms You offer. You may include additional 221 | disclaimers of warranty and limitations of liability specific to any 222 | jurisdiction. 223 | 224 | 4. Inability to Comply Due to Statute or Regulation 225 | 226 | If it is impossible for You to comply with any of the terms of this License 227 | with respect to some or all of the Covered Software due to statute, 228 | judicial order, or regulation then You must: (a) comply with the terms of 229 | this License to the maximum extent possible; and (b) describe the 230 | limitations and the code they affect. Such description must be placed in a 231 | text file included with all distributions of the Covered Software under 232 | this License. Except to the extent prohibited by statute or regulation, 233 | such description must be sufficiently detailed for a recipient of ordinary 234 | skill to be able to understand it. 235 | 236 | 5. Termination 237 | 238 | 5.1. The rights granted under this License will terminate automatically if You 239 | fail to comply with any of its terms. However, if You become compliant, 240 | then the rights granted under this License from a particular Contributor 241 | are reinstated (a) provisionally, unless and until such Contributor 242 | explicitly and finally terminates Your grants, and (b) on an ongoing 243 | basis, if such Contributor fails to notify You of the non-compliance by 244 | some reasonable means prior to 60 days after You have come back into 245 | compliance. Moreover, Your grants from a particular Contributor are 246 | reinstated on an ongoing basis if such Contributor notifies You of the 247 | non-compliance by some reasonable means, this is the first time You have 248 | received notice of non-compliance with this License from such 249 | Contributor, and You become compliant prior to 30 days after Your receipt 250 | of the notice. 251 | 252 | 5.2. If You initiate litigation against any entity by asserting a patent 253 | infringement claim (excluding declaratory judgment actions, 254 | counter-claims, and cross-claims) alleging that a Contributor Version 255 | directly or indirectly infringes any patent, then the rights granted to 256 | You by any and all Contributors for the Covered Software under Section 257 | 2.1 of this License shall terminate. 258 | 259 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user 260 | license agreements (excluding distributors and resellers) which have been 261 | validly granted by You or Your distributors under this License prior to 262 | termination shall survive termination. 263 | 264 | 6. Disclaimer of Warranty 265 | 266 | Covered Software is provided under this License on an "as is" basis, 267 | without warranty of any kind, either expressed, implied, or statutory, 268 | including, without limitation, warranties that the Covered Software is free 269 | of defects, merchantable, fit for a particular purpose or non-infringing. 270 | The entire risk as to the quality and performance of the Covered Software 271 | is with You. Should any Covered Software prove defective in any respect, 272 | You (not any Contributor) assume the cost of any necessary servicing, 273 | repair, or correction. This disclaimer of warranty constitutes an essential 274 | part of this License. No use of any Covered Software is authorized under 275 | this License except under this disclaimer. 276 | 277 | 7. Limitation of Liability 278 | 279 | Under no circumstances and under no legal theory, whether tort (including 280 | negligence), contract, or otherwise, shall any Contributor, or anyone who 281 | distributes Covered Software as permitted above, be liable to You for any 282 | direct, indirect, special, incidental, or consequential damages of any 283 | character including, without limitation, damages for lost profits, loss of 284 | goodwill, work stoppage, computer failure or malfunction, or any and all 285 | other commercial damages or losses, even if such party shall have been 286 | informed of the possibility of such damages. This limitation of liability 287 | shall not apply to liability for death or personal injury resulting from 288 | such party's negligence to the extent applicable law prohibits such 289 | limitation. Some jurisdictions do not allow the exclusion or limitation of 290 | incidental or consequential damages, so this exclusion and limitation may 291 | not apply to You. 292 | 293 | 8. Litigation 294 | 295 | Any litigation relating to this License may be brought only in the courts 296 | of a jurisdiction where the defendant maintains its principal place of 297 | business and such litigation shall be governed by laws of that 298 | jurisdiction, without reference to its conflict-of-law provisions. Nothing 299 | in this Section shall prevent a party's ability to bring cross-claims or 300 | counter-claims. 301 | 302 | 9. Miscellaneous 303 | 304 | This License represents the complete agreement concerning the subject 305 | matter hereof. If any provision of this License is held to be 306 | unenforceable, such provision shall be reformed only to the extent 307 | necessary to make it enforceable. Any law or regulation which provides that 308 | the language of a contract shall be construed against the drafter shall not 309 | be used to construe this License against a Contributor. 310 | 311 | 312 | 10. Versions of the License 313 | 314 | 10.1. New Versions 315 | 316 | Mozilla Foundation is the license steward. Except as provided in Section 317 | 10.3, no one other than the license steward has the right to modify or 318 | publish new versions of this License. Each version will be given a 319 | distinguishing version number. 320 | 321 | 10.2. Effect of New Versions 322 | 323 | You may distribute the Covered Software under the terms of the version 324 | of the License under which You originally received the Covered Software, 325 | or under the terms of any subsequent version published by the license 326 | steward. 327 | 328 | 10.3. Modified Versions 329 | 330 | If you create software not governed by this License, and you want to 331 | create a new license for such software, you may create and use a 332 | modified version of this License if you rename the license and remove 333 | any references to the name of the license steward (except to note that 334 | such modified license differs from this License). 335 | 336 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 337 | Licenses If You choose to distribute Source Code Form that is 338 | Incompatible With Secondary Licenses under the terms of this version of 339 | the License, the notice described in Exhibit B of this License must be 340 | attached. 341 | 342 | Exhibit A - Source Code Form License Notice 343 | 344 | This Source Code Form is subject to the 345 | terms of the Mozilla Public License, v. 346 | 2.0. If a copy of the MPL was not 347 | distributed with this file, You can 348 | obtain one at 349 | http://mozilla.org/MPL/2.0/. 350 | 351 | If it is not possible or desirable to put the notice in a particular file, 352 | then You may include the notice in a location (such as a LICENSE file in a 353 | relevant directory) where a recipient would be likely to look for such a 354 | notice. 355 | 356 | You may add additional accurate notices of copyright ownership. 357 | 358 | Exhibit B - "Incompatible With Secondary Licenses" Notice 359 | 360 | This Source Code Form is "Incompatible 361 | With Secondary Licenses", as defined by 362 | the Mozilla Public License, v. 2.0. 363 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## rust-sorty 2 | 3 | [![Build Status](https://travis-ci.org/Wafflespeanut/rust-sorty.svg?branch=master)](https://travis-ci.org/Wafflespeanut/rust-sorty) 4 | [![Current Version](https://meritbadge.herokuapp.com/sorty)](https://crates.io/crates/sorty) 5 | 6 | A lint to help with sorting the `extern crate`, `mod` and `use` declarations, according to the style rules. Have a look at the [detailed example](https://github.com/Wafflespeanut/rust-sorty/tree/master/EXAMPLE.md) for a start! I guess it will be very handy for large projects written in Rust (well, at least once!). 7 | 8 | And yeah, this should actually be done by **[rustfmt](https://github.com/rust-lang-nursery/rustfmt)**, but it [doesn't have this option](https://github.com/rust-lang-nursery/rustfmt/issues/298) for now. So, this plugin would serve until `rustfmt` becomes intelligent enough to detect the unsorted declarations. 9 | 10 | ### Usage 11 | 12 | Add this to your `Cargo.toml`... 13 | 14 | ``` toml 15 | sorty = "0.1" 16 | ``` 17 | 18 | ... and then to the top of the main module you wanna check, 19 | 20 | ``` rust 21 | #![feature(plugin)] 22 | #![plugin(sorty)] 23 | ``` 24 | 25 | (It can show warnings or errors based on your choice, just like any other lint) 26 | 27 | ``` rust 28 | #![deny(unsorted_declarations)] // throw errors! (poor choice for styling lints) 29 | 30 | #![warn(unsorted_declarations)] // show warnings (default) 31 | 32 | #![allow(unsorted_declarations)] // stay quiet! 33 | ``` 34 | 35 | Remove it once you've done all the checks, when you'll no longer be needing the plugin! 36 | 37 | I was just kidding. I'll be very happy if you just keep it :) 38 | 39 | ### Note: 40 | 41 | This is a compiler lint, and it's unstable. So, make sure you're using the latest [nightly Rust](https://www.rust-lang.org/install.html). Though this lint shows an output of the lexicographically sorted declarations, it follows some rules: 42 | 43 | - stuff with `#[macro_use]` are sorted and moved to the top, since macros become visible to the surroundings [only after their declaration](https://doc.rust-lang.org/book/macros.html#scoping-and-macro-importexport), unlike others. 44 | - `pub` declarations (of uses & mods) are sorted and moved to the bottom 45 | - `self` in use lists are moved to the left (other list items are sorted as usual) 46 | 47 | Also, note that there are some stuff that aren't tracked (for now). It includes comments, spaces, etc. 48 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![feature(plugin_registrar, plugin, box_syntax, rustc_private)] 2 | 3 | #[macro_use] 4 | extern crate rustc; 5 | extern crate rustc_plugin; 6 | extern crate syntax; 7 | 8 | pub mod sorty; 9 | 10 | use rustc_plugin::registry::Registry; 11 | 12 | #[plugin_registrar] 13 | pub fn plugin_registrar(reg: &mut Registry) { 14 | reg.register_early_lint_pass(box sorty::Sorty); 15 | } 16 | -------------------------------------------------------------------------------- /src/sorty.rs: -------------------------------------------------------------------------------- 1 | use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass}; 2 | use std::cmp::Ordering; 3 | use syntax::ast::{Item, ItemKind, LitKind, MetaItemKind, Mod, NodeId}; 4 | use syntax::ast::{NestedMetaItemKind, ViewPath_, Visibility}; 5 | use syntax::codemap::Span; 6 | use syntax::print::pprust::path_to_string; 7 | use syntax::symbol::keywords; 8 | 9 | // Warn unsorted declarations by default (since denying is a poor choice for styling lints) 10 | declare_lint!(UNSORTED_DECLARATIONS, Warn, 11 | "Warn when the declarations of crates or modules are not in alphabetical order"); 12 | 13 | pub struct Sorty; 14 | 15 | impl LintPass for Sorty { 16 | fn get_lints(&self) -> LintArray { 17 | lint_array!(UNSORTED_DECLARATIONS) 18 | } 19 | } 20 | 21 | impl EarlyLintPass for Sorty { 22 | // Walking through all the modules is enough for our purpose 23 | fn check_mod(&mut self, cx: &EarlyContext, module: &Mod, _span: Span, _id: NodeId) { 24 | // TODO: lint should stop ignoring the comments near the declarations 25 | let session_codemap = cx.sess.codemap(); // required only for checking inline mods 26 | let mut extern_crates = Vec::new(); 27 | let mut uses = Vec::new(); 28 | let mut mods = Vec::new(); 29 | 30 | for item in &module.items { 31 | // I've made use of `format!` most of the time, because we have a mixture of 32 | // `String` & `InternedString` 33 | let item_name = format!("{}", item.ident.name.as_str()); 34 | let item_span = item.span; 35 | match item.node { 36 | ItemKind::ExternCrate(ref optional_name) if item_name != "std" => { 37 | // We've put the declaration here because, we have to sort crate declarations 38 | // with respect to the renamed version (instead of the old one). 39 | // Since we also don't have `pub` (indicated by the `false` below), 40 | // we could just append the declaration to the attributes. 41 | let mut item_attrs = get_item_attrs(&item, false); 42 | item_attrs = match *optional_name { // for `extern crate foo as bar` 43 | Some(ref old_name) => format!("{}extern crate {} as", item_attrs, old_name), 44 | None => format!("{}extern crate", item_attrs), 45 | }; 46 | 47 | extern_crates.push((item_name, item_attrs, item_span, false)); 48 | } 49 | 50 | ItemKind::Mod(ref module) => { 51 | let mod_invoked_file = session_codemap.span_to_filename(item.span); 52 | let mod_declared_file = session_codemap.span_to_filename(module.inner); 53 | if mod_declared_file != mod_invoked_file { // ignores inline modules 54 | let item_attrs = get_item_attrs(&item, true); 55 | mods.push((item_name, item_attrs, item_span, false)); 56 | } 57 | } 58 | 59 | ItemKind::Use(ref spanned) => { 60 | let item_attrs = get_item_attrs(&item, true); 61 | match spanned.node { 62 | ViewPath_::ViewPathSimple(ref ident, ref path) => { 63 | let path_str = path_to_string(&path); 64 | let name = ident.name.as_str(); 65 | 66 | let renamed = { // `use foo as bar` 67 | let split = path_str.split(":").collect::>(); 68 | match split[split.len() - 1] == &*name { 69 | true => path_str.clone(), 70 | false => format!("{} as {}", &path_str, &name), 71 | } 72 | }; 73 | 74 | uses.push((renamed, item_attrs, item_span, false)); 75 | } 76 | 77 | ViewPath_::ViewPathList(ref path, ref list) => { 78 | let old_list = list.iter().map(|&list_item| { 79 | if list_item.node.name.name == keywords::SelfValue.name() { 80 | "self".to_owned() // this must be `self` 81 | } else { 82 | let name = list_item.node.name.name.as_str(); 83 | match list_item.node.rename { 84 | Some(new_name) => format!("{} as {}", name, new_name), 85 | None => (&*name).to_owned(), 86 | } 87 | } 88 | }).collect::>(); 89 | 90 | let mut new_list = old_list.clone(); 91 | new_list.sort_by(|a, b| { 92 | match (&**a, &**b) { // `self` should be first in a list of use items 93 | ("self", _) => Ordering::Less, 94 | (_, "self") => Ordering::Greater, 95 | _ => a.cmp(b), 96 | } 97 | }); 98 | 99 | let mut warn = false; 100 | let use_list = format!("{}::{{{}}}", path_to_string(&path), new_list.join(", ")); 101 | for (old_stuff, new_stuff) in old_list.iter().zip(new_list.iter()) { 102 | // check whether the use list is sorted 103 | if old_stuff != new_stuff { 104 | warn = true; 105 | break 106 | } 107 | } 108 | 109 | uses.push((use_list, item_attrs, path.span, warn)); 110 | } 111 | 112 | ViewPath_::ViewPathGlob(ref path) => { 113 | let path_str = path_to_string(&path) + "::*"; 114 | // We don't have any use statements like `use std::prelude::*` 115 | // since it's done only by rustc, we can safely neglect those here 116 | if !path_str.starts_with("std::") { 117 | uses.push((path_str, item_attrs, item_span, false)); 118 | } 119 | } 120 | } 121 | } 122 | _ => (), 123 | } 124 | } 125 | 126 | // We don't include the crate declaration here, because we've already appended it with the 127 | // attributes 128 | check_sort(&extern_crates, cx, "crate declarations", ""); 129 | check_sort(&mods, cx, "module declarations (other than inline modules)", "mod"); 130 | check_sort(&uses, cx, "use statements", "use"); 131 | 132 | // for collecting, formatting & filtering the attributes (and checking the visibility) 133 | fn get_item_attrs(item: &Item, pub_check: bool) -> String { 134 | let mut attr_vec = item.attrs.iter().filter_map(|attr| { 135 | attr.meta().and_then(|meta| { 136 | let meta_string = get_meta_as_string(&meta.name.as_str(), &meta.node); 137 | match meta_string.starts_with("doc = ") { 138 | true => None, 139 | false => Some(format!("#[{}]", meta_string)), 140 | } 141 | }) 142 | }).collect::>(); 143 | 144 | attr_vec.sort_by(|a, b| { 145 | match (&**a, &**b) { // put `macro_use` first for later checking 146 | ("#[macro_use]", _) => Ordering::Less, 147 | (_, "#[macro_use]") => Ordering::Greater, 148 | _ => a.cmp(b), 149 | } 150 | }); 151 | 152 | let attr_string = attr_vec.join("\n"); 153 | match item.vis { 154 | Visibility::Public if pub_check => match attr_string.is_empty() { 155 | true => "pub ".to_owned(), 156 | false => attr_string + "\npub ", // `pub` for mods and uses 157 | }, 158 | _ => match attr_string.is_empty() { 159 | true => attr_string, 160 | false => attr_string + "\n", 161 | }, 162 | } 163 | } 164 | 165 | fn format_literal(lit: &LitKind) -> String { 166 | match lit { 167 | &LitKind::Str(ref inner_str, _) => format!("{}", inner_str), 168 | _ => panic!("unexpected literal for meta item!"), 169 | } 170 | } 171 | 172 | // Collect the information from meta items into Strings 173 | fn get_meta_as_string(name: &str, meta_item: &MetaItemKind) -> String { 174 | match *meta_item { 175 | MetaItemKind::Word => format!("{}", name), 176 | MetaItemKind::List(ref meta_items) => { 177 | let mut stuff = meta_items.iter().map(|meta_item| { 178 | match meta_item.node { 179 | NestedMetaItemKind::MetaItem(ref meta) => 180 | get_meta_as_string(&meta.name.as_str(), &meta.node), 181 | NestedMetaItemKind::Literal(ref value) => format_literal(&value.node), 182 | } 183 | }).collect::>(); 184 | 185 | stuff.sort(); 186 | format!("{}({})", name, stuff.join(", ")) 187 | }, 188 | MetaItemKind::NameValue(ref literal) => { 189 | let value = format_literal(&literal.node); 190 | format!("{} = \"{}\"", name, value) 191 | }, 192 | } 193 | } 194 | 195 | // Checks the sorting of all the declarations and raises warnings whenever necessary 196 | // takes a slice of tuples with name, related attributes, spans and whether to warn for 197 | // unordered use lists 198 | fn check_sort(old_list: &[(String, String, Span, bool)], cx: &EarlyContext, 199 | kind: &str, syntax: &str) { 200 | 201 | // prepend given characters to the names for "biased" sorting 202 | fn str_for_biased_sort(string: &str, choice: bool, prepend_char: &str) -> String { 203 | match choice { 204 | true => prepend_char.to_owned() + string, 205 | false => string.to_owned(), 206 | } 207 | } 208 | 209 | let mut new_list = old_list.iter().map(|&(ref name, ref attrs, _span, warn)| { 210 | (name.clone(), attrs.clone(), warn) 211 | }).collect::>(); 212 | 213 | new_list.sort_by(|&(ref str_a, ref attr_a, _), &(ref str_b, ref attr_b, _)| { 214 | // move the `pub` statements below 215 | // (with `~` since it's on the farther side of ASCII) 216 | let mut new_str_a = str_for_biased_sort(&str_a, attr_a.ends_with("pub "), "~"); 217 | let mut new_str_b = str_for_biased_sort(&str_b, attr_b.ends_with("pub "), "~"); 218 | // move the #[macro_use] stuff above 219 | // (with `!` since it's on the lower extreme of ASCII) 220 | new_str_a = str_for_biased_sort(&new_str_a, 221 | attr_a.starts_with("#[macro_use]"), "!"); 222 | new_str_b = str_for_biased_sort(&new_str_b, 223 | attr_b.starts_with("#[macro_use]"), "!"); 224 | new_str_a.cmp(&new_str_b) 225 | }); 226 | 227 | for (i, (&(ref old_name, _, span_start, _warn), 228 | &(ref new_name, _, warn))) in old_list.iter() 229 | .zip(new_list.iter()) 230 | .enumerate() { 231 | if (old_name != new_name) || warn { 232 | // print all the declarations proceeding the first unsorted one 233 | let suggestion_list = new_list[i..new_list.len()] 234 | .iter() 235 | .map(|&(ref name, ref attrs, _)| { 236 | format!("{}{} {};", attrs, syntax, name) 237 | }).collect::>(); 238 | 239 | // increase the span to include more lines 240 | let mut final_span = span_start; 241 | let (_, _, old_span, _) = old_list[old_list.len() - 1]; 242 | final_span.hi = old_span.hi; 243 | 244 | let message = format!("{} should be in alphabetical order!", kind); 245 | let suggestion = format!("Try this...\n\n{}\n", suggestion_list.join("\n")); 246 | cx.span_lint_help(UNSORTED_DECLARATIONS, final_span, &message, &suggestion); 247 | break 248 | } 249 | } 250 | } 251 | } 252 | } 253 | --------------------------------------------------------------------------------