forked from slint-ui/slint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
323 lines (297 loc) · 10.7 KB
/
main.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
// Copyright © SixtyFPS GmbH <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-commercial
//!
//! Tool to change the syntax or reformat a .slint file
//!
//! As of know, it just rewrite the exact same as the input, but it can be changed
//!
//! This is how it can be used:
//!
//! ````shell
//! cargo run --bin syntax_updater -- --from 0.0.5 -i **/*.60
//! cargo run --bin syntax_updater -- --from 0.0.5 -i **/*.slint
//! cargo run --bin syntax_updater -- --from 0.0.5 -i **/*.rs
//! cargo run --bin syntax_updater -- --from 0.0.5 -i **/*.md
//! ````
use clap::Parser;
use experiments::lookup_changes::LookupChangeState;
use i_slint_compiler::diagnostics::BuildDiagnostics;
use i_slint_compiler::object_tree::{self, Component, Document, ElementRc};
use i_slint_compiler::parser::{syntax_nodes, NodeOrToken, SyntaxKind, SyntaxNode};
use i_slint_compiler::typeloader::TypeLoader;
use std::cell::RefCell;
use std::io::Write;
use std::path::Path;
use std::rc::Rc;
mod experiments {
pub(super) mod input_output_properties;
pub(super) mod lookup_changes;
pub(super) mod new_component_declaration;
}
#[derive(clap::Parser)]
#[command(author, version, about, long_about = None)]
pub struct Cli {
#[arg(name = "path to .slint file(s)", action)]
paths: Vec<std::path::PathBuf>,
/// modify the file inline instead of printing to stdout
#[arg(short, long, action)]
inline: bool,
/// Move all properties declaration to root
#[arg(long, action)]
move_declaration: bool,
}
fn main() -> std::io::Result<()> {
let args = Cli::parse();
for path in &args.paths {
let source = std::fs::read_to_string(path)?;
if args.inline {
let file = std::fs::File::create(path)?;
process_file(source, path, file, &args)?
} else {
process_file(source, path, std::io::stdout(), &args)?
}
}
Ok(())
}
fn process_rust_file(source: String, mut file: impl Write, args: &Cli) -> std::io::Result<()> {
let mut source_slice = &source[..];
let slint_macro = format!("{}!", "slint"); // in a variable so it does not appear as is
'l: while let Some(idx) = source_slice.find(&slint_macro) {
// Note: this code ignore string literal and unbalanced comment, but that should be good enough
let idx2 =
if let Some(idx2) = source_slice[idx..].find(|c| c == '{' || c == '(' || c == '[') {
idx2
} else {
break 'l;
};
let open = source_slice.as_bytes()[idx + idx2].into();
let close = match open {
'{' => '}',
'(' => ')',
'[' => ']',
_ => panic!(),
};
file.write_all(source_slice[..=idx + idx2].as_bytes())?;
source_slice = &source_slice[idx + idx2 + 1..];
let mut idx = 0;
let mut count = 1;
while count > 0 {
if let Some(idx2) = source_slice[idx..].find(|c| {
if c == open {
count += 1;
true
} else if c == close {
count -= 1;
true
} else {
false
}
}) {
idx += idx2 + 1;
} else {
break 'l;
}
}
let code = &source_slice[..idx - 1];
source_slice = &source_slice[idx - 1..];
let mut diag = BuildDiagnostics::default();
let syntax_node = i_slint_compiler::parser::parse(code.to_owned(), None, &mut diag);
let len = syntax_node.text_range().end().into();
visit_node(syntax_node, &mut file, &mut State::default(), args)?;
if diag.has_error() {
file.write_all(&code.as_bytes()[len..])?;
diag.print();
}
}
return file.write_all(source_slice.as_bytes());
}
fn process_markdown_file(source: String, mut file: impl Write, args: &Cli) -> std::io::Result<()> {
let mut source_slice = &source[..];
const CODE_FENCE_START: &str = "```slint\n";
const CODE_FENCE_END: &str = "```\n";
'l: while let Some(code_start) =
source_slice.find(CODE_FENCE_START).map(|idx| idx + CODE_FENCE_START.len())
{
let code_end = if let Some(code_end) = source_slice[code_start..].find(CODE_FENCE_END) {
code_end
} else {
break 'l;
};
file.write_all(source_slice[..=code_start - 1].as_bytes())?;
source_slice = &source_slice[code_start..];
let code = &source_slice[..code_end];
source_slice = &source_slice[code_end..];
let mut diag = BuildDiagnostics::default();
let syntax_node = i_slint_compiler::parser::parse(code.to_owned(), None, &mut diag);
let len = syntax_node.text_range().end().into();
visit_node(syntax_node, &mut file, &mut State::default(), args)?;
if diag.has_error() {
file.write_all(&code.as_bytes()[len..])?;
diag.print();
}
}
return file.write_all(source_slice.as_bytes());
}
fn process_file(
source: String,
path: &Path,
mut file: impl Write,
args: &Cli,
) -> std::io::Result<()> {
match path.extension() {
Some(ext) if ext == "rs" => return process_rust_file(source, file, args),
Some(ext) if ext == "md" => return process_markdown_file(source, file, args),
_ => {}
}
let mut diag = BuildDiagnostics::default();
let syntax_node = i_slint_compiler::parser::parse(source.clone(), Some(path), &mut diag);
let len = syntax_node.node.text_range().end().into();
let mut state = State::default();
let doc = syntax_node.clone().into();
let mut type_loader = TypeLoader::new(
i_slint_compiler::typeregister::TypeRegister::builtin(),
i_slint_compiler::CompilerConfiguration::new(
i_slint_compiler::generator::OutputFormat::Llr,
),
&mut BuildDiagnostics::default(),
);
let dependency_registry = Rc::new(RefCell::new(
i_slint_compiler::typeregister::TypeRegister::new(&type_loader.global_type_registry),
));
let foreign_imports = spin_on::spin_on(type_loader.load_dependencies_recursively(
&doc,
&mut diag,
&dependency_registry,
));
let current_doc = crate::object_tree::Document::from_node(
doc,
foreign_imports,
&mut diag,
&dependency_registry,
);
state.current_doc = Rc::new(current_doc).into();
visit_node(syntax_node, &mut file, &mut state, args)?;
if diag.has_error() {
file.write_all(&source.as_bytes()[len..])?;
diag.print();
}
Ok(())
}
#[derive(Default, Clone)]
struct State {
/// When visiting a binding, this is the name of the current property
property_name: Option<String>,
/// The Document being visited
current_doc: Option<Rc<Document>>,
/// The component in scope,
current_component: Option<Rc<Component>>,
/// The element in scope
current_elem: Option<ElementRc>,
lookup_change: LookupChangeState,
}
fn visit_node(
node: SyntaxNode,
file: &mut impl Write,
state: &mut State,
args: &Cli,
) -> std::io::Result<()> {
let mut state = state.clone();
match node.kind() {
SyntaxKind::PropertyDeclaration => {
state.property_name = node.child_text(SyntaxKind::DeclaredIdentifier)
}
SyntaxKind::Binding => state.property_name = node.child_text(SyntaxKind::Identifier),
SyntaxKind::CallbackDeclaration => {
state.property_name = node.child_text(SyntaxKind::Identifier)
}
SyntaxKind::Component => {
if let Some(doc) = &state.current_doc {
let component_name =
syntax_nodes::Component::from(node.clone()).DeclaredIdentifier().to_string();
state.current_component =
doc.inner_components.iter().find(|c| c.id == component_name).cloned();
if args.move_declaration {
experiments::lookup_changes::collect_movable_properties(&mut state);
}
}
}
SyntaxKind::RepeatedElement | SyntaxKind::ConditionalElement => {
if args.move_declaration {
experiments::lookup_changes::collect_movable_properties(&mut state);
}
}
SyntaxKind::Element => {
if let Some(parent_el) = state.current_elem.take() {
state.current_elem = parent_el
.borrow()
.children
.iter()
.find(|c| c.borrow().node.as_ref().map_or(false, |n| n.node == node.node))
.cloned()
} else if let Some(parent_co) = &state.current_component {
if node.parent().map_or(false, |n| n.kind() == SyntaxKind::Component) {
state.current_elem = Some(parent_co.root_element.clone())
}
}
experiments::lookup_changes::enter_element(&mut state);
}
_ => (),
}
if fold_node(&node, file, &mut state, args)? {
return Ok(());
}
for n in node.children_with_tokens() {
visit_node_or_token(n, file, &mut state, args)?;
}
Ok(())
}
pub(crate) fn visit_node_or_token(
n: NodeOrToken,
file: &mut impl Write,
state: &mut State,
args: &Cli,
) -> std::io::Result<()> {
match n {
NodeOrToken::Node(n) => visit_node(n, file, state, args)?,
NodeOrToken::Token(t) => fold_token(t, file, state)?,
};
Ok(())
}
/// return false if one need to continue folding the children
fn fold_node(
node: &SyntaxNode,
file: &mut impl Write,
state: &mut State,
args: &Cli,
) -> std::io::Result<bool> {
if experiments::input_output_properties::fold_node(node, file, state, args)? {
return Ok(true);
}
if experiments::new_component_declaration::fold_node(node, file, state, args)? {
return Ok(true);
}
if experiments::lookup_changes::fold_node(node, file, state, args)? {
return Ok(true);
}
Ok(false)
}
fn fold_token(
node: i_slint_compiler::parser::SyntaxToken,
file: &mut impl Write,
#[allow(unused)] state: &mut State,
) -> std::io::Result<()> {
/* Example: this adds the "ms" prefix to the number within a "duration" binding
if state.property_name == Some("duration".into()) && node.kind() == SyntaxKind::NumberLiteral {
if !node.text().ends_with("s") {
return write!(file, "{}ms", node.text());
}
}*/
/* Example: replace _ by - in identifiers
if node.kind() == SyntaxKind::Identifier
&& node.text().contains('_')
&& !node.text().starts_with("_")
{
return file.write_all(node.text().replace('_', "-").as_bytes())
}*/
file.write_all(node.text().as_bytes())
}