aboutsummaryrefslogtreecommitdiff
path: root/xtask/src/codegen/gen_assists_docs.rs
blob: 6ebeb8aea4e7a53b2af7db60d78a60c428da8c8c (plain)
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
//! Generates `assists.md` documentation.

use std::{fs, path::Path};

use crate::{
    codegen::{self, extract_comment_blocks_with_empty_lines, Mode},
    project_root, rust_files, Result,
};

pub fn generate_assists_docs(mode: Mode) -> Result<()> {
    let assists = Assist::collect()?;
    generate_tests(&assists, mode)?;
    generate_docs(&assists, mode)?;
    Ok(())
}

#[derive(Debug)]
struct Assist {
    id: String,
    doc: String,
    before: String,
    after: String,
}

impl Assist {
    fn collect() -> Result<Vec<Assist>> {
        let mut res = Vec::new();
        for path in rust_files(&project_root().join(codegen::ASSISTS_DIR)) {
            collect_file(&mut res, path.as_path())?;
        }
        res.sort_by(|lhs, rhs| lhs.id.cmp(&rhs.id));
        return Ok(res);

        fn collect_file(acc: &mut Vec<Assist>, path: &Path) -> Result<()> {
            let text = fs::read_to_string(path)?;
            let comment_blocks = extract_comment_blocks_with_empty_lines("Assist", &text);

            for block in comment_blocks {
                // FIXME: doesn't support blank lines yet, need to tweak
                // `extract_comment_blocks` for that.
                let id = block.id;
                assert!(
                    id.chars().all(|it| it.is_ascii_lowercase() || it == '_'),
                    "invalid assist id: {:?}",
                    id
                );
                let mut lines = block.contents.iter();

                let doc = take_until(lines.by_ref(), "```").trim().to_string();
                assert!(
                    doc.chars().next().unwrap().is_ascii_uppercase() && doc.ends_with('.'),
                    "\n\n{}: assist docs should be proper sentences, with capitalization and a full stop at the end.\n\n{}\n\n",
                    id, doc,
                );

                let before = take_until(lines.by_ref(), "```");

                assert_eq!(lines.next().unwrap().as_str(), "->");
                assert_eq!(lines.next().unwrap().as_str(), "```");
                let after = take_until(lines.by_ref(), "```");
                acc.push(Assist { id, doc, before, after })
            }

            fn take_until<'a>(lines: impl Iterator<Item = &'a String>, marker: &str) -> String {
                let mut buf = Vec::new();
                for line in lines {
                    if line == marker {
                        break;
                    }
                    buf.push(line.clone());
                }
                buf.join("\n")
            }
            Ok(())
        }
    }
}

fn generate_tests(assists: &[Assist], mode: Mode) -> Result<()> {
    let mut buf = String::from("use super::check_doc_test;\n");

    for assist in assists.iter() {
        let test = format!(
            r######"
#[test]
fn doctest_{}() {{
    check_doc_test(
        "{}",
r#####"
{}"#####, r#####"
{}"#####)
}}
"######,
            assist.id,
            assist.id,
            reveal_hash_comments(&assist.before),
            reveal_hash_comments(&assist.after)
        );

        buf.push_str(&test)
    }
    let buf = crate::reformat(buf)?;
    codegen::update(&project_root().join(codegen::ASSISTS_TESTS), &buf, mode)
}

fn generate_docs(assists: &[Assist], mode: Mode) -> Result<()> {
    let mut buf = String::from(
        "# Assists\n\nCursor position or selection is signified by `┃` character.\n\n",
    );

    for assist in assists {
        let before = assist.before.replace("<|>", "┃"); // Unicode pseudo-graphics bar
        let after = assist.after.replace("<|>", "┃");
        let docs = format!(
            "
## `{}`

{}

```rust
// BEFORE
{}
// AFTER
{}```
",
            assist.id,
            assist.doc,
            hide_hash_comments(&before),
            hide_hash_comments(&after)
        );
        buf.push_str(&docs);
    }

    codegen::update(&project_root().join(codegen::ASSISTS_DOCS), &buf, mode)
}

fn hide_hash_comments(text: &str) -> String {
    text.split('\n') // want final newline
        .filter(|&it| !(it.starts_with("# ") || it == "#"))
        .map(|it| format!("{}\n", it))
        .collect()
}

fn reveal_hash_comments(text: &str) -> String {
    text.split('\n') // want final newline
        .map(|it| {
            if it.starts_with("# ") {
                &it[2..]
            } else if it == "#" {
                ""
            } else {
                it
            }
        })
        .map(|it| format!("{}\n", it))
        .collect()
}