include_file/
lib.rs

1// Copyright 2025 Heath Stewart.
2// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
3
4extern crate proc_macro;
5mod code;
6
7use proc_macro::TokenStream;
8
9/// Include code from within a code fence in a markdown file.
10///
11/// Two arguments are required: a file path relative to the current source file,
12/// and a name defined within the code fence as shown below.
13///
14/// All CommonMark [code fences](https://spec.commonmark.org/current/#fenced-code-blocks) are supported.
15///
16/// # Examples
17///
18/// Consider the following code fence in a crate `README.md` markdown file:
19///
20/// ````markdown
21/// ```rust example
22/// let m = example()?;
23/// println!("{m:#?}");
24/// ```
25/// ````
26///
27/// In Rust documentation comments, we can use `# line` to hide setup code.
28/// That's not possible in markdown, so we can include only the code we want to demonstrate;
29/// however, we can still compile and even run it in Rust tests:
30///
31/// ```no_run
32/// struct Model {
33///     name: String,
34/// }
35///
36/// fn example() -> Result<Model, Box<dyn std::error::Error>> {
37///     Ok(Model { name: "example".into() })
38/// }
39///
40/// #[test]
41/// fn test_example() -> Result<(), Box<dyn std::error::Error>> {
42///     include_code!("../README.md", "example");
43///     Ok(())
44/// }
45/// ```
46#[proc_macro]
47pub fn include_code(item: TokenStream) -> TokenStream {
48    code::include_code(item.into())
49        .unwrap_or_else(syn::Error::into_compile_error)
50        .into()
51}