include_tt 1.1.0

Macros for ultra-flexible injection of compiler trees, literals, or binary data into Rust syntax trees from external sources.
Documentation
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//Copyright 2023-2025 #UlinProject Denis Kotlyarov (Денис Котляров)

//-----------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at

//	   http://www.apache.org/licenses/LICENSE-2.0

//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
// limitations under the License.
//-----------------------------------------------------------------------------

// or

//-----------------------------------------------------------------------------
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:

//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.

/*! Macros for ultra-flexible injection of compiler trees, literals, or binary data into Rust syntax trees from external sources.

```rust
use include_tt::inject;
use std::fmt::Write;
let mut buf = String::new();

inject! {
	write!(
		&mut buf,
		"Welcome, {}. Your score is {}!",
		#tt("examples/name.tt"),			// `"Ferris"`
		#tt("examples/" "score" ".tt")	// `100500`
	).unwrap();
}

assert_eq!(buf, "Welcome, Ferris. Your score is 100500!");
```
*/

// #![no_std] TODO, impossible without: [std::io::Error, std::{io::Read, fs::File}, std::fs::read_to_string]
#![allow(clippy::tabs_in_doc_comments)]

extern crate alloc;
extern crate proc_macro;

use crate::trees::null::make_null_group;
use crate::trees::throw_sg_err;
use crate::{
	include::{InjectArr, InjectCTT, InjectStr, InjectTT, macro_rule_include},
	trees::{
		replace::{replace_tree_in_group, replace_tree_in_stream},
		result::TreeResult,
		search::SearchGroup,
		tq,
	},
};
use core::slice::IterMut;
use proc_macro::TokenStream;
use proc_macro2::{Delimiter, Group, Span, TokenStream as TokenStream2, TokenTree as TokenTree2};
use quote::{format_ident, quote};
use std::path::Path;

/// Components, templates, code for the search
/// and final construction of trees.
pub(crate) mod trees {
	pub mod group;
	pub mod null;
	pub mod replace;
	pub mod search;

	#[macro_use]
	pub mod result;
	#[allow(clippy::single_component_path_imports)]
	pub(crate) use tq;

	#[macro_use]
	pub mod sq_err;
	#[allow(clippy::single_component_path_imports)]
	pub(crate) use throw_sg_err;
	pub mod loader;
}

/// Separate syntactic expressions of trees.
pub(crate) mod exprs {
	pub mod literal;
}

/// Code component of macros.
pub(crate) mod include;

pub(crate) struct PointTrack<'tk> {
	prefix_token: &'tk mut TokenTree2,
	name_token: &'tk mut TokenTree2,
	data_token: &'tk mut TokenTree2,
	appends_files: usize,
	globalposnum: usize,
}

impl<'tk> PointTrack<'tk> {
	#[inline]
	pub const fn new(
		globalposnum: usize,
		prefix_token: &'tk mut TokenTree2,
		name_token: &'tk mut TokenTree2,
		data_token: &'tk mut TokenTree2,
	) -> Self {
		Self {
			prefix_token,
			name_token,
			data_token,
			appends_files: 0,
			globalposnum,
		}
	}

	#[inline]
	pub fn prefix_span(&self) -> Span {
		self.prefix_token.span()
	}

	#[inline]
	pub fn name_span(&self) -> Span {
		self.name_token.span()
	}

	#[inline]
	pub fn data_span(&self) -> Span {
		self.data_token.span()
	}

	#[inline]
	pub const fn is_rewritten(&self) -> bool {
		self.appends_files > 0
	}

	pub fn into_token_tree2(self) -> Option<(usize, TokenTree2)> {
		match self.appends_files {
			0 => None,
			appends_files => {
				let data_span = self.data_span();

				Some((
					appends_files,
					std::mem::replace(self.data_token, make_null_group(data_span)),
				))
			}
		}
	}

	pub fn append_track_file(&mut self, path: &Path) {
		let name_const = format_ident!(
			"_TRACKER_FILE_NUM_{}",
			self.globalposnum + self.appends_files
		);

		let path = format!("../{}", path.display());
		let ts2 = TokenStream2::from_iter(quote! {
			/// This is a file tracker point, automatically generated by `#POINT_TRACKER_FILES;`
			const #name_const: &'static [u8] = include_bytes!(#path) as &[_];
		});

		self.append_track_files_ts(ts2)
	}

	pub fn append_track_files_ts(&mut self, ts2: TokenStream2) {
		let data_span = self.data_span();
		let is_initappendfiles = self.appends_files == 0;
		self.appends_files += 1;

		let mut ngroup = Group::new(Delimiter::None, ts2);
		ngroup.set_span(data_span);

		if is_initappendfiles {
			*self.data_token = ngroup.into();
		} else {
			match &mut self.data_token {
				TokenTree2::Group(group) => {
					let mut new_group: Vec<TokenTree2> = group.stream().into_iter().collect();
					new_group.push(ngroup.into());

					let mut ngroup =
						Group::new(Delimiter::None, TokenStream2::from_iter(new_group));
					ngroup.set_span(data_span);

					*self.data_token = ngroup.into();
				}
				_ => panic!(
					"Undefined behavior reported in `PointTrack`, someone redefined `TokenTree2`, expected `TokenTree2::Group`"
				),
			}
		}
	}
}

impl<'tk> Drop for PointTrack<'tk> {
	fn drop(&mut self) {
		if !self.is_rewritten() {
			let data_span = self.data_span();
			*self.data_token = make_null_group(data_span);
		}
		*self.prefix_token = make_null_group(self.prefix_token.span());
		*self.name_token = make_null_group(self.prefix_token.span());
	}
}

/// The task of the function is to find a group with the desired macro
/// and perform useful work specific to the selected macro.
///
/// The design of this feature has been adapted to search for attachments.
fn autoinject_tt_in_group<'tk, 'gpsn>(
	globalposnum: &'gpsn mut usize,
	mut iter: IterMut<'tk, TokenTree2>,
	point_track_file: &'_ mut Option<PointTrack<'tk>>,
) -> SearchGroup {
	'sbegin: while let Some(m_punct) = iter.next() {
		match m_punct {
			#[cfg(feature = "escape_symbol")]
			TokenTree2::Punct(punct) if punct.as_char() == '-' => {
				/*
					Just a way to escape `#` to prevent the macro from parsing `#` and executing it.

					(Making `\`, `_` didn't work at this point)
				*/
				let mut is_allow_skip_atree = false;
				if let Some(TokenTree2::Punct(punct)) = iter.next() {
					if punct.as_char() == '#' {
						is_allow_skip_atree = true
					}
				}
				if is_allow_skip_atree {
					*m_punct = make_null_group(m_punct.span());
				}
				continue 'sbegin;
			}
			TokenTree2::Punct(punct) if punct.as_char() == '#' => {
				if let Some(m_ident) = iter.next() {
					if let TokenTree2::Ident(ident) = m_ident {
						#[allow(clippy::type_complexity)]
						let macro_fn = match &*ident {
							ident if ident == "AS_IS" => {
								/*
									Stop indexing after the given keyword. This saves resources.
								*/
								if let Some(m_punct2) = iter.next() {
									if let TokenTree2::Punct(punct2) = m_punct2 {
										if punct2.as_char() == ':' {
											*m_ident = make_null_group(m_ident.span());
											*m_punct = make_null_group(m_punct.span());
											*m_punct2 = make_null_group(m_punct2.span());

											return SearchGroup::Break;
										}
									}
								}

								throw_sg_err! {
									return [ident.span()]: "`:` was expected."
								}
							}
							ident if ident == "POINT_TRACKER_FILES" => {
								if let Some(m_punct2) = iter.next() {
									if let TokenTree2::Punct(punct2) = m_punct2 {
										if punct2.as_char() == ':' {
											*point_track_file = Some(PointTrack::new(
												*globalposnum,
												m_punct,
												m_ident,
												m_punct2,
											));

											continue 'sbegin;
										}
									}
								}

								throw_sg_err! {
									return [ident.span()]: "`:` was expected."
								}
							}
							ident if ident == "tt" => {
								macro_rule_include::<InjectTT>
									as fn(
										&Group,
										Option<&mut PointTrack<'tk>>,
									) -> TreeResult<TokenTree2>
							}
							ident if ident == "ctt" => macro_rule_include::<InjectCTT> as _,
							ident if ident == "str" => macro_rule_include::<InjectStr> as _,
							ident if ident == "arr" || ident == "array" => {
								macro_rule_include::<InjectArr> as _
							}
							ident if ident == "break" => {
								/*
									Stop indexing after the given keyword. This saves resources.
								*/
								if let Some(m_punct2) = iter.next() {
									if let TokenTree2::Punct(punct2) = m_punct2 {
										if punct2.as_char() == ';' {
											*m_ident = make_null_group(m_ident.span());
											*m_punct = make_null_group(m_punct.span());
											*m_punct2 = make_null_group(m_punct2.span());

											return SearchGroup::Break;
										}
									}
								}

								throw_sg_err! {
									return [ident.span()]: "`;` was expected."
								}
							}

							_ => throw_sg_err! {
								return [ident.span()]: "Undefined action to include data in macro or change its behavior, expected macro data type: `tt`, `ctt`, `arr`, `str`, or marker: `#AS_IS:`, `#POINT_TRACKER_FILES:`, or stop parsing macro via `#break;`."
							},
						};

						if let Some(m_group) = iter.next() {
							if let TokenTree2::Group(group) = m_group {
								let result = tq!(macro_fn(group, point_track_file.as_mut()));

								*m_ident = make_null_group(m_ident.span());
								*m_punct = make_null_group(m_punct.span());
								*m_group = result;

								continue 'sbegin;
							}
						}
						throw_sg_err! {
							return [ident.span()]: "After this input, the group `()`, `[]`, `{}` is expected."
						}
					}
				}
			}
			// If this is a group, then you need to go down inside the
			// group and look for the necessary macros there.
			TokenTree2::Group(group) => match replace_tree_in_group(group, |iter| {
				let mut prefixgroup;
				let mut namegroup;
				let mut datagroup;
				#[allow(clippy::manual_map)] // see ngroup
				let mut ptf = match point_track_file {
					Some(point_track_file) => Some({
						prefixgroup = make_null_group(point_track_file.prefix_span());
						namegroup = make_null_group(point_track_file.name_span());
						datagroup = make_null_group(point_track_file.data_span());

						PointTrack::new(
							*globalposnum,
							&mut prefixgroup,
							&mut namegroup,
							&mut datagroup,
						)
					}),
					None => None,
				};

				let result = autoinject_tt_in_group(globalposnum, iter, &mut ptf);
				if let Some(ptf) = ptf {
					if ptf.is_rewritten() {
						if let Some(point_track_file) = point_track_file {
							match ptf.into_token_tree2() {
								Some((appends_files, TokenTree2::Group(group))) => {
									*globalposnum += appends_files;

									point_track_file.append_track_files_ts(group.stream());
								}
								_ => panic!(
									"Undefined behavior reported in `PointTrack`, someone redefined `TokenTree2`, expected `TokenTree2::Group`"
								),
							}
						}
					}
				}
				result
			}) {
				SearchGroup::Break => continue 'sbegin,
				result @ SearchGroup::Error(..) => return result,
			},
			_ => {}
		}
	}

	SearchGroup::Break
}

/// Macro for injecting trees, strings, arrays from files.
/// 
/// ## template_macro
/// ```rust
/// use include_tt::inject;
/// use std::fmt::Write;
/// let mut buf = String::new();
/// 
/// inject! {
/// 	write!(
/// 		&mut buf,
/// 		"Welcome, {}. Your score is {}!",
/// 		#tt("examples/name.tt"),			// `"Ferris"`
/// 		#tt("examples/" "score" ".tt")	// `100500`
/// 	).unwrap();
/// }
///
/// assert_eq!(buf, "Welcome, Ferris. Your score is 100500!");
/// ```
/// 
/// ## basic_codegen
/// 
/// ```rust
/// macro_rules! new_module {
/// 	[ @($const_t: ident) : [ $($path:tt)* ]; ] => {
/// 		include_tt::inject! {
/// 			#[allow(dead_code)]
/// 			#[allow(non_upper_case_globals)]
/// 			pub mod my_module {
/// 				pub const a: usize = 0;
/// 				pub const b: usize = 10;
/// 				
/// 				// The `#POINT_TRACKER_FILES:` marker allows the macro to add additional 
/// 				// instructions that tell the compiler which files to track so that it can 
/// 				// recompile the macro if they change. This is completely optional, but without 
/// 				// it tracking will not work.
/// 				#POINT_TRACKER_FILES: 
/// 				
/// 				pub const $const_t: (usize, usize) = (#tt($($path)*));
/// 			}
/// 		}
/// 	};
/// }
/// 
/// // we created a module "my_module" and a constant "T" containing (a, b).
/// //
/// // if you need to change, for example, to (b,a) or substitute constant values,
/// // we will only change the contents of the file "for_examples/full.tt"!
/// new_module! {
///	@(T): [examples / "full" . t 't']; // this file contains "a, b", see "for_examples/full.tt"
/// }
/// assert_eq!(my_module::T, (0, 10));
/// ```
#[proc_macro]
pub fn inject(input: TokenStream) -> TokenStream {
	let mut tt: TokenStream2 = input.into();

	match replace_tree_in_stream(&mut tt, |iter| {
		autoinject_tt_in_group(&mut 0, iter, &mut None)
	}) {
		SearchGroup::Error(e) => e.into(),
		SearchGroup::Break => tt.into(),
	}
}