documented_macros/lib.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
mod attr_impl;
mod config;
mod derive_impl;
pub(crate) mod util;
use proc_macro::TokenStream;
use syn::{parse_macro_input, Error};
use crate::{
attr_impl::docs_const_impl,
derive_impl::{documented_fields_impl, documented_impl, documented_variants_impl, DocType},
};
/// Derive proc-macro for `Documented` trait.
///
/// # Example
///
/// ```rust
/// use documented::Documented;
///
/// /// Nice.
/// /// Multiple single-line doc comments are supported.
/// ///
/// /** Multi-line doc comments are supported too.
/// Each line of the multi-line block is individually trimmed by default.
/// Note the lack of spaces in front of this line.
/// */
/// #[doc = "Attribute-style documentation is supported too."]
/// #[derive(Documented)]
/// struct BornIn69;
///
/// let doc_str = "Nice.
/// Multiple single-line doc comments are supported.
///
/// Multi-line doc comments are supported too.
/// Each line of the multi-line block is individually trimmed by default.
/// Note the lack of spaces in front of this line.
///
/// Attribute-style documentation is supported too.";
/// assert_eq!(BornIn69::DOCS, doc_str);
/// ```
///
/// # Configuration
///
/// With the `customise` feature enabled, you can customise this macro's
/// behaviour using the `#[documented(...)]` attribute.
///
/// Currently, you can:
///
/// ## 1. set a default value when doc comments are absent like so:
///
/// ```rust
/// # use documented::Documented;
/// #[derive(Documented)]
/// #[documented(default = "The answer is fries.")]
/// struct WhosTurnIsIt;
///
/// assert_eq!(WhosTurnIsIt::DOCS, "The answer is fries.");
/// ```
///
/// This option is primarily designed for [`DocumentedFields`] and
/// [`DocumentedVariants`], so it's probably not very useful here. But it could
/// conceivably come in handy in some niche meta-programming contexts.
///
/// ## 2. disable line-trimming like so:
///
/// ```rust
/// # use documented::Documented;
/// /// Terrible.
/// #[derive(Documented)]
/// #[documented(trim = false)]
/// struct Frankly;
///
/// assert_eq!(Frankly::DOCS, " Terrible.");
/// ```
///
/// If there are other configuration options you wish to have, please submit an
/// issue or a PR.
#[cfg_attr(not(feature = "customise"), proc_macro_derive(Documented))]
#[cfg_attr(
feature = "customise",
proc_macro_derive(Documented, attributes(documented))
)]
pub fn documented(input: TokenStream) -> TokenStream {
documented_impl(parse_macro_input!(input), DocType::Str)
.unwrap_or_else(Error::into_compile_error)
.into()
}
/// Derive proc-macro for `DocumentedOpt` trait.
///
/// See [`Documented`] for usage.
#[cfg_attr(not(feature = "customise"), proc_macro_derive(DocumentedOpt))]
#[cfg_attr(
feature = "customise",
proc_macro_derive(DocumentedOpt, attributes(documented))
)]
pub fn documented_opt(input: TokenStream) -> TokenStream {
documented_impl(parse_macro_input!(input), DocType::OptStr)
.unwrap_or_else(Error::into_compile_error)
.into()
}
/// Derive proc-macro for `DocumentedFields` trait.
///
/// # Example
///
/// ```rust
/// use documented::DocumentedFields;
///
/// #[derive(DocumentedFields)]
/// struct BornIn69 {
/// /// Cry like a grandmaster.
/// rawr: String,
/// /// Before what?
/// explosive: usize,
/// };
///
/// assert_eq!(
/// BornIn69::FIELD_DOCS,
/// ["Cry like a grandmaster.", "Before what?"]
/// );
/// ```
///
/// You can also use `DocumentedFields::get_field_docs` to access the fields'
/// documentation using their names.
///
/// ```rust
/// # use documented::{DocumentedFields, Error};
/// #
/// # #[derive(DocumentedFields)]
/// # struct BornIn69 {
/// # /// Cry like a grandmaster.
/// # rawr: String,
/// # /// Before what?
/// # explosive: usize,
/// # };
/// #
/// assert_eq!(
/// BornIn69::get_field_docs("rawr"),
/// Ok("Cry like a grandmaster.")
/// );
/// assert_eq!(BornIn69::get_field_docs("explosive"), Ok("Before what?"));
/// assert_eq!(
/// BornIn69::get_field_docs("gotcha"),
/// Err(Error::NoSuchField("gotcha".to_string()))
/// );
/// ```
///
/// # Configuration
///
/// With the `customise` feature enabled, you can customise this macro's
/// behaviour using the `#[documented_fields(...)]` attribute. Note that this
/// attribute works on both the container and each individual field, with the
/// per-field configurations overriding container configurations, which
/// override the default.
///
/// Currently, you can:
///
/// ## 1. set a different case convention for `get_field_docs` like so:
///
/// ```rust
/// # use documented::DocumentedFields;
/// #[derive(DocumentedFields)]
/// #[documented_fields(rename_all = "kebab-case")]
/// struct BooksYouShouldWrite {
/// /// It's my move?
/// whose_turn_is_it: String,
/// /// Isn't it checkmate?
/// #[documented_fields(rename_all = "PascalCase")]
/// how_many_legal_moves_do_you_have: String,
/// }
///
/// assert_eq!(
/// BooksYouShouldWrite::get_field_docs("whose-turn-is-it"),
/// Ok("It's my move?")
/// );
/// assert_eq!(
/// BooksYouShouldWrite::get_field_docs("HowManyLegalMovesDoYouHave"),
/// Ok("Isn't it checkmate?")
/// );
/// ```
///
/// ## 2. set a custom name for a specific field for `get_field_docs` like so:
///
/// ```rust
/// # use documented::DocumentedFields;
/// #[derive(DocumentedFields)]
/// // #[documented_field(rename = "fries")] // this is not allowed
/// struct ThisPosition {
/// /// I'm guessing, but I'm not really guessing.
/// #[documented_fields(rename = "knows")]
/// esserman_knows: bool,
/// /// And that's true if you're van Wely.
/// #[documented_fields(rename = "doesnt_know")]
/// van_wely_doesnt: bool,
/// }
///
/// assert_eq!(
/// ThisPosition::get_field_docs("knows"),
/// Ok("I'm guessing, but I'm not really guessing.")
/// );
/// assert_eq!(
/// ThisPosition::get_field_docs("doesnt_know"),
/// Ok("And that's true if you're van Wely.")
/// );
/// ```
///
/// Obviously this option is only available on each individual field.
/// It makes no sense on the container.
///
/// This option also always takes priority over `rename_all`.
///
/// ## 3. set a default value when doc comments are absent like so:
///
/// ```rust
/// # use documented::DocumentedFields;
/// #[derive(DocumentedFields)]
/// #[documented_fields(default = "Confusing the audience.")]
/// struct SettingUpForTheNextGame {
/// rh8: bool,
/// ng8: bool,
/// /// Always play:
/// bf8: bool,
/// }
///
/// assert_eq!(
/// SettingUpForTheNextGame::FIELD_DOCS,
/// [
/// "Confusing the audience.",
/// "Confusing the audience.",
/// "Always play:"
/// ]
/// );
/// ```
///
/// ## 4. (selectively) disable line-trimming like so:
///
/// ```rust
/// # use documented::DocumentedFields;
/// #[derive(DocumentedFields)]
/// #[documented_fields(trim = false)]
/// struct Frankly {
/// /// Delicious.
/// perrier: usize,
/// /// I'm vegan.
/// #[documented_fields(trim = true)]
/// fried_liver: bool,
/// }
///
/// assert_eq!(Frankly::FIELD_DOCS, [" Delicious.", "I'm vegan."]);
/// ```
///
/// If there are other configuration options you wish to have, please
/// submit an issue or a PR.
#[cfg_attr(not(feature = "customise"), proc_macro_derive(DocumentedFields))]
#[cfg_attr(
feature = "customise",
proc_macro_derive(DocumentedFields, attributes(documented_fields))
)]
pub fn documented_fields(input: TokenStream) -> TokenStream {
documented_fields_impl(parse_macro_input!(input), DocType::Str)
.unwrap_or_else(Error::into_compile_error)
.into()
}
/// Derive proc-macro for `DocumentedFieldsOpt` trait.
///
/// See [`DocumentedFields`] for usage.
#[cfg_attr(not(feature = "customise"), proc_macro_derive(DocumentedFieldsOpt))]
#[cfg_attr(
feature = "customise",
proc_macro_derive(DocumentedFieldsOpt, attributes(documented_fields))
)]
pub fn documented_fields_opt(input: TokenStream) -> TokenStream {
documented_fields_impl(parse_macro_input!(input), DocType::OptStr)
.unwrap_or_else(Error::into_compile_error)
.into()
}
/// Derive proc-macro for `DocumentedVariants` trait.
///
/// # Example
///
/// ```rust
/// use documented::{DocumentedVariants, Error};
///
/// #[derive(DocumentedVariants)]
/// enum NeverPlay {
/// /// Terrible.
/// F3,
/// /// I fell out of my chair.
/// F6,
/// }
///
/// assert_eq!(NeverPlay::F3.get_variant_docs(), "Terrible.");
/// assert_eq!(NeverPlay::F6.get_variant_docs(), "I fell out of my chair.");
/// ```
///
/// # Configuration
///
/// With the `customise` feature enabled, you can customise this macro's
/// behaviour using the `#[documented_variants(...)]` attribute. Note that this
/// attribute works on both the container and each individual variant, with the
/// per-variant configurations overriding container configurations, which
/// override the default.
///
/// Currently, you can:
///
/// ## 1. set a default value when doc comments are absent like so:
///
/// ```rust
/// # use documented::DocumentedVariants;
/// #[derive(DocumentedVariants)]
/// #[documented_variants(default = "Still theory.")]
/// enum OurHeroPlayed {
/// G4Mate,
/// OOOMate,
/// /// Frankly ridiculous.
/// Bf1g2Mate,
/// }
///
/// assert_eq!(OurHeroPlayed::G4Mate.get_variant_docs(), "Still theory.");
/// assert_eq!(OurHeroPlayed::OOOMate.get_variant_docs(), "Still theory.");
/// assert_eq!(
/// OurHeroPlayed::Bf1g2Mate.get_variant_docs(),
/// "Frankly ridiculous."
/// );
/// ```
///
/// ## 2. (selectively) disable line-trimming like so:
///
/// ```rust
/// # use documented::DocumentedVariants;
/// #[derive(DocumentedVariants)]
/// #[documented_variants(trim = false)]
/// enum Always {
/// /// Or the quality.
/// SacTheExchange,
/// /// Like a Frenchman.
/// #[documented_variants(trim = true)]
/// Retreat,
/// }
/// assert_eq!(
/// Always::SacTheExchange.get_variant_docs(),
/// " Or the quality."
/// );
/// assert_eq!(Always::Retreat.get_variant_docs(), "Like a Frenchman.");
/// ```
///
/// If there are other configuration options you wish to have, please
/// submit an issue or a PR.
#[cfg_attr(not(feature = "customise"), proc_macro_derive(DocumentedVariants))]
#[cfg_attr(
feature = "customise",
proc_macro_derive(DocumentedVariants, attributes(documented_variants))
)]
pub fn documented_variants(input: TokenStream) -> TokenStream {
documented_variants_impl(parse_macro_input!(input), DocType::Str)
.unwrap_or_else(Error::into_compile_error)
.into()
}
/// Derive proc-macro for `DocumentedVariantsOpt` trait.
///
/// See [`DocumentedVariants`] for usage.
#[cfg_attr(not(feature = "customise"), proc_macro_derive(DocumentedVariantsOpt))]
#[cfg_attr(
feature = "customise",
proc_macro_derive(DocumentedVariantsOpt, attributes(documented_variants))
)]
pub fn documented_variants_opt(input: TokenStream) -> TokenStream {
documented_variants_impl(parse_macro_input!(input), DocType::OptStr)
.unwrap_or_else(Error::into_compile_error)
.into()
}
/// Macro to extract the documentation on any item that accepts doc comments
/// and store it in a const variable.
///
/// By default, this const variable inherits visibility from its parent item.
/// This can be manually configured; see configuration section below.
///
/// # Examples
///
/// ```rust
/// use documented::docs_const;
///
/// /// This is a test function
/// #[docs_const]
/// fn test_fn() {}
///
/// assert_eq!(TEST_FN_DOCS, "This is a test function");
/// ```
///
/// # Configuration
///
/// With the `customise` feature enabled, you can customise this macro's
/// behaviour using attribute arguments.
///
/// Currently, you can:
///
/// ## 1. set a custom constant visibility like so:
///
/// ```rust
/// mod submodule {
/// # use documented::docs_const;
/// /// Boo!
/// #[docs_const(vis = pub)]
/// struct Wooooo;
/// }
///
/// // notice how the constant can be seen from outside
/// assert_eq!(submodule::WOOOOO_DOCS, "Boo!");
/// ```
///
/// ## 2. set a custom constant name like so:
///
/// ```rust
/// # use documented::docs_const;
/// /// If you have a question raise your hand
/// #[docs_const(rename = "DONT_RAISE_YOUR_HAND")]
/// mod whatever {}
///
/// assert_eq!(DONT_RAISE_YOUR_HAND, "If you have a question raise your hand");
/// ```
///
/// ## 3. set a default value when doc comments are absent like so:
///
/// ```rust
/// use documented::docs_const;
///
/// #[docs_const(default = "In this position many of you blunder.")]
/// trait StartingPosition {}
///
/// assert_eq!(
/// STARTING_POSITION_DOCS,
/// "In this position many of you blunder."
/// );
/// ```
///
/// This option is primarily designed for [`DocumentedFields`] and
/// [`DocumentedVariants`], so it's probably not very useful here. But it could
/// conceivably come in handy in some niche meta-programming contexts.
///
/// ## 4. disable line-trimming like so:
///
/// ```rust
/// # use documented::docs_const;
/// /// This is a test constant
/// #[docs_const(trim = false)]
/// const test_const: u8 = 0;
///
/// assert_eq!(TEST_CONST_DOCS, " This is a test constant");
/// ```
///
/// ---
///
/// Multiple option can be specified in a list like so:
/// `name = "FOO", trim = false`.
///
/// If there are other configuration options you wish to have, please
/// submit an issue or a PR.
#[proc_macro_attribute]
pub fn docs_const(#[allow(unused_variables)] attr: TokenStream, item: TokenStream) -> TokenStream {
#[cfg(not(feature = "customise"))]
let ts = docs_const_impl(parse_macro_input!(item));
#[cfg(feature = "customise")]
let ts = docs_const_impl(parse_macro_input!(item), parse_macro_input!(attr));
ts.unwrap_or_else(Error::into_compile_error).into()
}