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
/*!
Format XML Templating
=====================

Minimal compile time templating for XML in Rust!

The `format_xml!` macro by example accepts an XML-like syntax and transforms it into a `format_args!` invocation.
We say _XML-like_ because due to limitations of the macro system some concessions had to be made, see the examples below.

Examples
--------

### Basic usage

```rust
# use format_xml::format_xml;
let point = (20, 30);
let name = "World";

# let result =
format_xml! {
	<svg width="200" height="200">
		<line x1="0" y1="0" x2={point.0} y2={point.1} stroke="black" stroke-width="2" />
		<text x={point.1} y={point.0}>"Hello '" {name} "'!"</text>
	</svg>
}.to_string()
# ; assert_eq!(result, r#"<svg width="200" height="200"><line x1="0" y1="0" x2="20" y2="30" stroke="black" stroke-width="2" /><text x="30" y="20">Hello 'World'!</text></svg>"#);
```

The resulting string is `<svg width="200" height="200"><line x1="0" y1="0" x2="20" y2="30" stroke="black" stroke-width="2" /><text x="30" y="20">Hello 'World!'</text></svg>`.

Note how the expression values to be formatted are inlined in the formatting braces.

### Formatting specifiers

```rust
# use format_xml::format_xml;
let value = 42;

# let result =
format_xml! {
	<span data-value={value}>{value;#x?}</span>
}.to_string()
# ; assert_eq!(result, r#"<span data-value="42">0x2a</span>"#);
```

The resulting string is `<span data-value="42">0x2a</span>`.

Due to limitations of macros by example, a semicolon is used to separate the value from the formatting specifiers. The rules for the specifiers are exactly the same as the standard library of Rust.

### Supported tags

```rust
# use format_xml::format_xml;
# let result =
format_xml! {
	<!doctype html>
	<?xml version="1.0" encoding="UTF-8"?>
	<tag-name></tag-name>
	<ns:self-closing-tag />
	<!-- "comment" -->
	<![CDATA["cdata"]]>
}.to_string()
# ; assert_eq!(result, r#"<!doctype html><?xml version="1.0" encoding="UTF-8"?><tag-name></tag-name><ns:self-closing-tag /><!-- comment --><![CDATA[cdata]]>"#);
```

The resulting string is `<!doctype html><?xml version="1.0" encoding="UTF-8"?><open-tag></open-tag><ns:self-closing-tag />`.

### Control flow

```rust
# use format_xml::format_xml;
let switch = true;
let opt = Some("World");
let result: Result<f32, i32> = Err(13);

# let result =
format_xml! {
	if let Some(name) = (opt) {
		<h1>"Hello " {name}</h1>
	}
	else {
		<!-- "no header" -->
	}
	if (switch) {
		match (result) {
			Ok(f) => { <i>{f}</i> }
			Err(i) => { <b>{i}</b> }
		}
		<ul>
		for i in (1..=5) {
			let times_five = i * 5;
			<li>{i}"*5="{times_five}</li>
		}
		</ul>
	}
	else {
		<p>"No contents"</p>
	}
}.to_string()
# ; assert_eq!(result, r#"<h1>Hello World</h1><b>13</b><ul><li>1*5=5</li><li>2*5=10</li><li>3*5=15</li><li>4*5=20</li><li>5*5=25</li></ul>"#);
```

The resulting string is `<h1>Hello World</h1><ul><li>1*5=5</li><li>2*5=10</li><li>3*5=15</li><li>4*5=20</li><li>5*5=25</li></ul>`.

Control flow are currently only supported outside tags. They are not supported in attributes. The expressions for `if` and `for` must be surrounded with parentheses due to macro by example limitations.

### Specialised attribute syntax

```rust
# use format_xml::format_xml;
let has_a = true;
let has_b = false;
let make_red = true;

# let result =
format_xml! {
	<div class=["class-a": has_a, "class-b": has_b]><span style=["color: red;": make_red]></span></div>
}.to_string()
# ; assert_eq!(result, r#"<div class="class-a "><span style="color: red; "></span></div>"#);
```

The resulting string is `<div class="class-a "><span style="color: red; "></span></div>`.

Dedicated syntax for fixed set of space delimited attribute values where each element can be conditionally included. This is specifically designed to work with the style and class attributes of html.

Limitations
-----------

This crate is implemented with standard macros by example (`macro_rules!`). Because of this there are various limitations:

* It is not possible to check whether tags are closed by the appropriate closing tag. This crate will happily accept `<open></close>`. It does enforce more simple lexical rules such as rejecting `</tag/>`.

* Escaping of `&<>"'` is not automatic. You can trivially break the structure by including these characters in either the formatting string or formatted values. Avoid untrusted input!

* The formatting specifiers are separated from its value by a semicolon instead of a colon.

* The compiler may complain about macro expansion recursion limit being reached, simply apply the suggested fix and increase the limit. This crate implements a 'tt muncher' which are known to hit these limits.

* Text nodes must be valid Rust literals. Bare words are not supported.

 */

use std::fmt;

mod util;
pub use self::util::*;

/// Implements `std::fmt::Display` for the Fn closure matching fmt's signature.
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct FnFmt<F: Fn(&mut fmt::Formatter) -> fmt::Result>(pub F);
impl<F: Fn(&mut fmt::Formatter) -> fmt::Result> fmt::Display for FnFmt<F> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		(self.0)(f)
	}
}
impl<F: Fn(&mut fmt::Formatter) -> fmt::Result> fmt::Debug for FnFmt<F> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.write_str("FnFmt([closure])")
	}
}

/// Format XML tokens with `format_args!`
///
/// See the [module-level documentation](index.html) for more information.
#[macro_export]
macro_rules! format_xml {
	($($tt:tt)*) => {
		$crate::_format_tag1_!(; "",; $($tt)*)
	};
}

//----------------------------------------------------------------
// Parse xml tags, text nodes and control flow

#[doc(hidden)]
#[macro_export]
macro_rules! _format_tag1_ {
	// tags
	(; $fmt:expr, $($args:expr,)*; </ $($tail:tt)*) => {
		$crate::_format_ident1_!(_format_tag3_!; concat!($fmt, "</"), $($args,)*; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; <? $($tail:tt)*) => {
		$crate::_format_ident1_!(_format_attrs1_! _format_tag4_!; concat!($fmt, "<?"), $($args,)*; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; <!-- $($tail:tt)*) => {
		$crate::_format_text1_!(; concat!($fmt, "<!-- "), $($args,)*; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; <![CDATA[ $($text:literal)* ]]> $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, "<![CDATA[", $($text,)* "]]>"), $($args,)*; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; <! $($tail:tt)*) => {
		$crate::_format_ident1_!(_format_attrs1_! _format_tag2_!; concat!($fmt, "<!"), $($args,)*; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; < $($tail:tt)*) => {
		$crate::_format_ident1_!(_format_attrs1_! _format_tag2_!; concat!($fmt, "<"), $($args,)*; $($tail)*)
	};
	// text
	(; $fmt:expr, $($args:expr,)*; $text:literal $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, $text), $($args,)*; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; {$e:expr} $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, "{}"), $($args,)* $e,; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; {$e:expr;$($s:tt)*} $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, "{:", $(stringify!($s),)* "}"), $($args,)* $e,; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; escape!($($body:tt)*) $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, "{}"), $($args,)* $crate::escape!($($body)*),; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; |$f:ident| { $($body:tt)* } $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, "{}"), $($args,)* $crate::FnFmt(|$f| { $($body)* }),; $($tail)*)
	};
	// control
	(; $fmt:expr, $($args:expr,)*; let $p:pat = $e:expr; $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, "{}"), $($args,)* $crate::FnFmt(|f| match $e { $p => f.write_fmt($crate::format_xml!{$($tail)*}) }),;)
	};
	(; $fmt:expr, $($args:expr,)*; if ($e:expr) { $($if_body:tt)* } else { $($else_body:tt)* } $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, "{}"), $($args,)* $crate::FnFmt(|f| if $e { f.write_fmt($crate::format_xml!{$($if_body)*}) } else { f.write_fmt($crate::format_xml!{$($else_body)*}) }),; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; if ($e:expr) { $($body:tt)* } $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, "{}"), $($args,)* $crate::FnFmt(|f| if $e { f.write_fmt($crate::format_xml!{$($body)*}) } else { Ok(()) }),; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; if let $p:pat = ($e:expr) { $($if_body:tt)* } else { $($else_body:tt)* } $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, "{}"), $($args,)* $crate::FnFmt(|f| if let $p = $e { f.write_fmt($crate::format_xml!{$($if_body)*}) } else { f.write_fmt($crate::format_xml!{$($else_body)*}) }),; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; if let $p:pat = ($e:expr) { $($body:tt)* } $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, "{}"), $($args,)* $crate::FnFmt(|f| if let $p = $e { f.write_fmt($crate::format_xml!{$($body)*}) } else { Ok(()) }),; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; match ($e:expr) { $($p:pat => { $($body:tt)* })* } $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, "{}"), $($args,)* $crate::FnFmt(|f| match $e { $($p => f.write_fmt($crate::format_xml!{$($body)*}),)* }),; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; for $p:pat in ($e:expr) { $($body:tt)* } $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, "{}"), $($args,)* $crate::FnFmt(|f| { for $p in $e { f.write_fmt($crate::format_xml!{$($body)*})?; } Ok(()) }),; $($tail)*)
	};
	// term
	(; $fmt:expr, $($args:expr,)*;) => {
		format_args!($fmt $(,$args)*)
	};
}
#[doc(hidden)]
#[macro_export]
macro_rules! _format_tag2_ {
	(; $fmt:expr, $($args:expr,)*; > $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, ">"), $($args,)*; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; /> $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, " />"), $($args,)*; $($tail)*)
	};
}
#[doc(hidden)]
#[macro_export]
macro_rules! _format_tag3_ {
	(; $fmt:expr, $($args:expr,)*; > $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, ">"), $($args,)*; $($tail)*)
	};
}
#[doc(hidden)]
#[macro_export]
macro_rules! _format_tag4_ {
	(; $fmt:expr, $($args:expr,)*; ?> $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, "?>"), $($args,)*; $($tail)*)
	};
}

//----------------------------------------------------------------
// Parse comments and CDATA

#[doc(hidden)]
#[macro_export]
macro_rules! _format_text1_ {
	(; $fmt:expr, $($args:expr,)*; --> $($tail:tt)*) => {
		$crate::_format_tag1_!(; concat!($fmt, " -->"), $($args,)*; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; $text:literal $($tail:tt)*) => {
		$crate::_format_text1_!(; concat!($fmt, $text), $($args,)*; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; {$e:expr} $($tail:tt)*) => {
		$crate::_format_text1_!(; concat!($fmt, "{}"), $($args,)* $e,; $($tail)*)
	};
	(; $fmt:expr, $($args:expr,)*; {$e:expr;$($s:tt)*} $($tail:tt)*) => {
		$crate::_format_text1_!(; concat!($fmt, "{:", $(stringify!($s),)* "}"), $($args,)* $e,; $($tail)*)
	};
}

//----------------------------------------------------------------
// Parse xml names

#[doc(hidden)]
#[macro_export]
macro_rules! _format_ident1_ {
	($($q:ident!)+; $fmt:expr, $($args:expr,)*; $name:ident : $($tail:tt)*) => {
		$crate::_format_ident2_!($($q!)+; concat!($fmt, stringify!($name), ":"), $($args,)*; $($tail)*)
	};
	($($q:ident!)+; $fmt:expr, $($args:expr,)*; $name:ident - $($tail:tt)*) => {
		$crate::_format_ident2_!($($q!)+; concat!($fmt, stringify!($name), "-"), $($args,)*; $($tail)*)
	};
	($next:ident! $($q:ident!)*; $fmt:expr, $($args:expr,)*; $name:ident $($tail:tt)*) => {
		$crate::$next!($($q!)*; concat!($fmt, stringify!($name)), $($args,)*; $($tail)*)
	};
}
#[doc(hidden)]
#[macro_export]
macro_rules! _format_ident2_ {
	($($q:ident!)+; $fmt:expr, $($args:expr,)*; $name:ident - $($tail:tt)*) => {
		$crate::_format_ident2_!($($q!)+; concat!($fmt, stringify!($name), "-"), $($args,)*; $($tail)*)
	};
	($next:ident! $($q:ident!)*; $fmt:expr, $($args:expr,)*; $name:ident $($tail:tt)*) => {
		$crate::$next!($($q!)*; concat!($fmt, stringify!($name)), $($args,)*; $($tail)*)
	};
}

//----------------------------------------------------------------
// Parse xml attributes

#[doc(hidden)]
#[macro_export]
macro_rules! _format_attrs1_ {
	($($q:ident!)+; $fmt:expr, $($args:expr,)*; $tail_id:ident $($tail:tt)*) => {
		$crate::_format_ident1_!(_format_attrs2_! $($q!)+; concat!($fmt, " "), $($args,)*; $tail_id $($tail)*)
	};
	($next:ident! $($q:ident!)*; $fmt:expr, $($args:expr,)*; $($tail:tt)*) => {
		$crate::$next!($($q!)*; $fmt, $($args,)*; $($tail)*)
	};
}
#[doc(hidden)]
#[macro_export]
macro_rules! _format_attrs2_ {
	($($q:ident!)+; $fmt:expr, $($args:expr,)*; = $text:literal $($tail:tt)*) => {
		$crate::_format_attrs1_!($($q!)*; concat!($fmt, "=\"", $text, '"'), $($args,)*; $($tail)*)
	};
	($($q:ident!)+; $fmt:expr, $($args:expr,)*; = {$e:expr} $($tail:tt)*) => {
		$crate::_format_attrs1_!($($q!)*; concat!($fmt, "=\"{}\""), $($args,)* $e,; $($tail)*)
	};
	($($q:ident!)+; $fmt:expr, $($args:expr,)*; = {$e:expr; $($s:tt)*} $($tail:tt)*) => {
		$crate::_format_attrs1_!($($q!)*; concat!($fmt, "=\"{:", $(stringify!($s),)* "}\""), $($args,)* $e,; $($tail)*)
	};
	($($q:ident!)+; $fmt:expr, $($args:expr,)*; = [$($text:literal : $cond:expr),*$(,)?] $($tail:tt)*) => {
		$crate::_format_attrs1_!($($q!)*; concat!($fmt, "=\"{}\""), $($args,)* $crate::FnFmt(|f| { $(if $cond { f.write_str(concat!($text, " "))? })* Ok(()) }),; $($tail)*)
	};
	($($q:ident!)+; $fmt:expr, $($args:expr,)*; = escape!($($body:tt)*) $($tail:tt)*) => {
		$crate::_format_attrs1_!($($q!)*; concat!($fmt, "=\"{}\""), $($args,)* $crate::escape!($($body)*),; $($tail)*)
	};
	($($q:ident!)+; $fmt:expr, $($args:expr,)*; = |$f:ident| { $($body:tt)* } $($tail:tt)*) => {
		$crate::_format_attrs1_!($($q!)*; concat!($fmt, "=\"{}\""), $($args,)* $crate::FnFmt(|$f| { $($body)* }),; $($tail)*)
	};
	($($q:ident!)+; $fmt:expr, $($args:expr,)*; $($tail:tt)*) => {
		$crate::_format_attrs1_!($($q!)*; $fmt, $($args,)*; $($tail)*)
	};
}