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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::default::Default;
use std::path::{Path, PathBuf};
#[derive(Debug, Serialize, Deserialize)]
pub struct Document {
pub nodes: Vec<Node>,
pub newline: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum Node {
Text(TextBlock),
Code(CodeBlock),
Transclusion(Transclusion),
}
impl Document {
pub fn new(nodes: Vec<Node>, newline: String) -> Self {
Document { nodes, newline }
}
pub fn newline(&self) -> &str {
&self.newline
}
pub fn code_blocks(&self) -> impl Iterator<Item = &CodeBlock> {
self.nodes.iter().filter_map(|node| match node {
Node::Code(block) => Some(block),
_ => None,
})
}
pub fn code_blocks_by_name(&self) -> HashMap<Option<&str>, Vec<&CodeBlock>> {
let mut code_blocks = HashMap::<_, Vec<&CodeBlock>>::new();
for block in self.code_blocks() {
code_blocks
.entry(block.name.as_deref())
.or_default()
.push(block);
}
code_blocks
}
pub fn transclusions(&self) -> impl Iterator<Item = &Transclusion> {
self.nodes.iter().filter_map(|node| match node {
Node::Transclusion(trans) => Some(trans),
_ => None,
})
}
pub fn entry_points(&self) -> HashMap<Option<&str>, (&Path, Option<PathBuf>)> {
let mut entries = HashMap::new();
for block in self.code_blocks() {
if let Some(name) = block.name.as_deref() {
if block.is_file {
entries.insert(
Some(name),
(
Path::new(name),
block.source_file.as_ref().map(|file| file.into()),
),
);
}
}
}
entries
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct TextBlock {
pub text: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Transclusion {
pub file: PathBuf,
pub original: String,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct CodeBlock {
pub line_number: usize,
pub indent: String,
pub name: Option<String>,
pub is_unnamed: bool,
pub language: Option<String>,
pub is_hidden: bool,
pub is_file: bool,
pub is_alternative: bool,
pub source: Vec<Line>,
pub source_file: Option<String>,
}
impl CodeBlock {
pub fn new(
line_number: usize,
indent: String,
language: Option<String>,
alternative: bool,
) -> Self {
CodeBlock {
line_number,
indent,
language,
is_alternative: alternative,
..Default::default()
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub enum Line {
Macro {
indent: String,
name: String,
},
Source {
indent: String,
source: String,
},
}