strs_tools_meta 0.18.0

Procedural macros for strs_tools compile-time optimizations. Its meta module. Don't use directly.
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
//! Procedural macros for compile-time string processing optimizations.
//!
//! This crate provides macros that analyze string patterns at compile time
//! and generate optimized code for common string operations.
//!
//! This is a meta module for `strs_tools`. Don't use directly.

#![ doc( html_logo_url = "https://raw.githubusercontent.com/Wandalen/wTools/master/asset/img/logo_v3_trans_square.png" ) ]
#![ doc( html_favicon_url = "https://raw.githubusercontent.com/Wandalen/wTools/alpha/asset/img/logo_v3_trans_square_icon_small_v2.ico" ) ]

#[ cfg( any( feature = "optimize_split", feature = "optimize_match" ) ) ]
use macro_tools::
{
  quote::quote,
  syn::{ self, Expr, LitStr, Result },
};
#[ cfg( any( feature = "optimize_split", feature = "optimize_match" ) ) ]
use proc_macro::TokenStream;

/// Analyze string patterns at compile time and generate optimized split code.
/// 
/// This macro examines delimiter patterns and input characteristics to select
/// the most efficient splitting strategy at compile time.
/// 
/// # Examples
///
/// Basic usage with different delimiter patterns. See `tests/optimize_split_tests.rs`
/// for comprehensive executable examples.
///
/// Single character delimiter:
/// ```rust
/// // Simple comma splitting - generates optimized code
/// let result = strs_tools_meta::optimize_split!("field1,field2,field3", ",");
/// assert_eq!( result, vec![ "field1", "field2", "field3" ] );
/// ```
///
/// Multiple delimiters:
/// ```rust
/// // Multiple delimiters - generates multi-delimiter optimization
/// let input_str = "a,b;c:d";
/// let result = strs_tools_meta::optimize_split!(input_str, [",", ";", ":"]);
/// assert_eq!( result, vec![ "a", "b", "c", "d" ] );
/// ```
///
/// Complex patterns with options:
/// ```rust
/// // Complex patterns - generates pattern-specific optimization
/// let data = "a,b->c::d";
/// let result = strs_tools_meta::optimize_split!(data, [",", "->", "::"], preserve_delimiters = true);
/// assert_eq!( result, vec![ "a", ",", "b", "->", "c", "::", "d" ] );
/// ```
/// 
/// # Debug Mode
///
/// The `debug` parameter enables diagnostic output during macro expansion.
/// See `tests/optimize_split_tests.rs::tc8_debug_mode` for usage example.
#[ cfg( feature = "optimize_split" ) ]
#[ proc_macro ]
pub fn optimize_split( input: TokenStream ) -> TokenStream
{
  let result = optimize_split_impl( input );
  match result 
  {
    Ok( tokens ) => tokens.into(),
    Err( e ) => e.to_compile_error().into(),
  }
}

/// Generate compile-time optimized string matching code.
///
/// This macro creates efficient pattern matching code based on compile-time
/// analysis of the patterns and their usage context.
///
/// # Examples
///
/// Basic usage with different pattern matching strategies. See `tests/optimize_match_tests.rs`
/// for comprehensive executable examples.
///
/// Single pattern matching:
/// ```rust
/// // Single pattern matching
/// let input = "prefix_value";
/// let matched = strs_tools_meta::optimize_match!(input, "prefix_");
/// assert_eq!( matched, Some( 0 ) );
/// ```
///
/// Multiple pattern matching:
/// ```rust
/// // Multiple pattern matching with priorities
/// let text = "https://example.com";
/// let result = strs_tools_meta::optimize_match!(text, ["http://", "https://", "ftp://"], strategy = "first_match");
/// assert_eq!( result, Some( 0 ) );
/// ```
///
/// # Debug Mode
///
/// The `debug` parameter enables diagnostic output during macro expansion.
/// See `tests/optimize_match_tests.rs::tc6_debug_mode` for usage example.
#[ cfg( feature = "optimize_match" ) ]
#[ proc_macro ]
pub fn optimize_match( input: TokenStream ) -> TokenStream
{
  let result = optimize_match_impl( input );
  match result 
  {
    Ok( tokens ) => tokens.into(),
    Err( e ) => e.to_compile_error().into(),
  }
}

#[ cfg( feature = "optimize_split" ) ]
fn optimize_split_impl( input: TokenStream ) -> Result< macro_tools::proc_macro2::TokenStream >
{
  let parsed_input = syn::parse( input )?;
  Ok( generate_optimized_split( &parsed_input ) )
}

#[ cfg( feature = "optimize_match" ) ]
fn optimize_match_impl( input: TokenStream ) -> Result< macro_tools::proc_macro2::TokenStream >
{
  let parsed_input = syn::parse( input )?;
  Ok( generate_optimized_match( &parsed_input ) )
}

/// Input structure for `optimize_split` macro
#[ cfg( feature = "optimize_split" ) ]
#[ derive( Debug ) ]
#[ allow( clippy::struct_excessive_bools ) ]
struct OptimizeSplitInput
{
  source: Expr,
  delimiters: Vec< String >,
  preserve_delimiters: bool,
  preserve_empty: bool,
  debug: bool,
}

#[ cfg( feature = "optimize_split" ) ]
impl syn::parse::Parse for OptimizeSplitInput
{
  fn parse( input: syn::parse::ParseStream<'_> ) -> Result< Self >
  {
    let source: Expr = input.parse()?;
    input.parse::< syn::Token![,] >()?;
    
    let mut delimiters = Vec::new();
    let mut preserve_delimiters = false;
    let mut preserve_empty = false;
    let mut debug = false;
    
    // Parse delimiter(s)
    if input.peek( syn::token::Bracket )
    {
      // Multiple delimiters: ["a", "b", "c"]
      let content;
      syn::bracketed!( content in input );
      while !content.is_empty()
      {
        let lit: LitStr = content.parse()?;
        delimiters.push( lit.value() );
        if !content.is_empty()
        {
          content.parse::< syn::Token![,] >()?;
        }
      }
    }
    else
    {
      // Single delimiter: "a"
      let lit: LitStr = input.parse()?;
      delimiters.push( lit.value() );
    }
    
    // Parse optional parameters
    while !input.is_empty()
    {
      input.parse::< syn::Token![,] >()?;
      
      let ident: syn::Ident = input.parse()?;
      
      if ident.to_string().as_str() == "debug" {
        debug = true;
      } else {
        input.parse::< syn::Token![=] >()?;
        
        match ident.to_string().as_str()
        {
          "preserve_delimiters" =>
          {
            let lit: syn::LitBool = input.parse()?;
            preserve_delimiters = lit.value;
          },
          "preserve_empty" =>
          {
            let lit: syn::LitBool = input.parse()?;
            preserve_empty = lit.value;
          },
          _ =>
          {
            return Err( syn::Error::new( ident.span(), "Unknown parameter" ) );
          }
        }
      }
    }
    
    Ok( OptimizeSplitInput
    {
      source,
      delimiters,
      preserve_delimiters,
      preserve_empty,
      debug,
    } )
  }
}

/// Input structure for `optimize_match` macro
#[ cfg( feature = "optimize_match" ) ]
#[ derive( Debug ) ]
struct OptimizeMatchInput
{
  source: Expr,
  patterns: Vec< String >,
  strategy: String, // "first_match", "longest_match", "all_matches"
  debug: bool,
}

#[ cfg( feature = "optimize_match" ) ]
impl syn::parse::Parse for OptimizeMatchInput
{
  fn parse( input: syn::parse::ParseStream<'_> ) -> Result< Self >
  {
    let source: Expr = input.parse()?;
    input.parse::< syn::Token![,] >()?;
    
    let mut patterns = Vec::new();
    let mut strategy = "first_match".to_string();
    let mut debug = false;
    
    // Parse pattern(s)
    if input.peek( syn::token::Bracket )
    {
      // Multiple patterns: ["a", "b", "c"]
      let content;
      syn::bracketed!( content in input );
      while !content.is_empty()
      {
        let lit: LitStr = content.parse()?;
        patterns.push( lit.value() );
        if !content.is_empty()
        {
          content.parse::< syn::Token![,] >()?;
        }
      }
    }
    else
    {
      // Single pattern: "a"
      let lit: LitStr = input.parse()?;
      patterns.push( lit.value() );
    }
    
    // Parse optional parameters
    while !input.is_empty()
    {
      input.parse::< syn::Token![,] >()?;
      
      let ident: syn::Ident = input.parse()?;
      
      match ident.to_string().as_str()
      {
        "debug" =>
        {
          debug = true;
        },
        "strategy" =>
        {
          input.parse::< syn::Token![=] >()?;
          let lit: LitStr = input.parse()?;
          strategy = lit.value();
        },
        _ =>
        {
          return Err( syn::Error::new( ident.span(), "Unknown parameter" ) );
        }
      }
    }
    
    Ok( OptimizeMatchInput
    {
      source,
      patterns,
      strategy,
      debug,
    } )
  }
}

/// Generate optimized split code based on compile-time analysis
#[ cfg( feature = "optimize_split" ) ]
fn generate_optimized_split( input: &OptimizeSplitInput ) -> macro_tools::proc_macro2::TokenStream
{
  let optimization = analyze_split_pattern( &input.delimiters );
  
  if input.debug
  {
    eprintln!( "optimize_split! debug: pattern={:?}, optimization={optimization:?}", input.delimiters );
  }
  
  match optimization
  {
    SplitOptimization::SingleCharDelimiter( delim ) => generate_single_char_split( input, &delim ),
    SplitOptimization::MultipleCharDelimiters => generate_multi_delimiter_split( input ),
    SplitOptimization::ComplexPattern => generate_complex_pattern_split( input ),
  }
}

/// Generate code for single character delimiter optimization
#[ cfg( feature = "optimize_split" ) ]
fn generate_single_char_split( input: &OptimizeSplitInput, delim: &str ) -> macro_tools::proc_macro2::TokenStream
{
  let source = &input.source;
  let preserve_delimiters = input.preserve_delimiters;
  let preserve_empty = input.preserve_empty;
  let delim_char = delim.chars().next().unwrap();
  
  if preserve_delimiters || preserve_empty
  {
    quote!
    {
      {
        // Compile-time optimized single character split with options
        let src = #source;
        let delim = #delim_char;
        let mut result = Vec::new();
        let mut start = 0;
        
        for ( i, ch ) in src.char_indices()
        {
          if ch == delim
          {
            let segment = &src[ start..i ];
            if #preserve_empty || !segment.is_empty()
            {
              result.push( segment );
            }
            if #preserve_delimiters
            {
              result.push( &src[ i..i + 1 ] );
            }
            start = i + 1;
          }
        }
        
        let final_segment = &src[ start.. ];
        if #preserve_empty || !final_segment.is_empty()
        {
          result.push( final_segment );
        }
        
        result
      }
    }
  }
  else
  {
    quote!
    {
      {
        // Compile-time optimized single character split (default)
        let src = #source;
        src.split( #delim ).collect::< Vec< &str > >()
      }
    }
  }
}

/// Generate code for multiple delimiter optimization
#[ cfg( feature = "optimize_split" ) ]
fn generate_multi_delimiter_split( input: &OptimizeSplitInput ) -> macro_tools::proc_macro2::TokenStream
{
  let source = &input.source;
  let delimiters = &input.delimiters;
  let preserve_delimiters = input.preserve_delimiters;
  let preserve_empty = input.preserve_empty;
  let delim_array = delimiters.iter().collect::< Vec< _ > >();
  
  quote!
  {
    {
      // Compile-time optimized multi-delimiter split
      let src = #source;
      let delimiters = [ #( #delim_array ),* ];
      let mut result = Vec::new();
      let mut start = 0;
      let mut i = 0;
      let _src_bytes = src.as_bytes();
      
      while i < src.len()
      {
        let mut found_delimiter = None;
        let mut delim_len = 0;
        
        // Check for any delimiter at current position
        for delim in &delimiters
        {
          if src[ i.. ].starts_with( delim )
          {
            found_delimiter = Some( delim );
            delim_len = delim.len();
            break;
          }
        }
        
        if let Some( delim ) = found_delimiter
        {
          let segment = &src[ start..i ];
          if #preserve_empty || !segment.is_empty()
          {
            result.push( segment );
          }
          if #preserve_delimiters
          {
            result.push( delim );
          }
          start = i + delim_len;
          i = start;
        }
        else
        {
          i += 1;
        }
      }
      
      let final_segment = &src[ start.. ];
      if #preserve_empty || !final_segment.is_empty()
      {
        result.push( final_segment );
      }
      
      result
    }
  }
}

/// Generate code for complex pattern optimization fallback
#[ cfg( feature = "optimize_split" ) ]
fn generate_complex_pattern_split( input: &OptimizeSplitInput ) -> macro_tools::proc_macro2::TokenStream
{
  let source = &input.source;
  let delimiters = &input.delimiters;
  let preserve_delimiters = input.preserve_delimiters;
  let preserve_empty = input.preserve_empty;
  let delim_array = delimiters.iter().collect::< Vec< _ > >();
  
  quote!
  {
    {
      // Compile-time optimized complex pattern fallback using standard split
      let src = #source;
      let delimiters = [ #( #delim_array ),* ];
      let mut result = Vec::new();
      let mut remaining = src;
      
      loop
      {
        let mut min_pos = None;
        let mut best_delim = "";
        
        for delim in &delimiters
        {
          if let Some( pos ) = remaining.find( delim )
          {
            if min_pos.is_none() || pos < min_pos.unwrap()
            {
              min_pos = Some( pos );
              best_delim = delim;
            }
          }
        }
        
        if let Some( pos ) = min_pos
        {
          let segment = &remaining[ ..pos ];
          if #preserve_empty || !segment.is_empty()
          {
            result.push( segment );
          }
          if #preserve_delimiters
          {
            result.push( best_delim );
          }
          remaining = &remaining[ pos + best_delim.len().. ];
        }
        else
        {
          if #preserve_empty || !remaining.is_empty()
          {
            result.push( remaining );
          }
          break;
        }
      }
      
      result
    }
  }
}

/// Generate optimized match code based on compile-time analysis
#[ cfg( feature = "optimize_match" ) ]
fn generate_optimized_match( input: &OptimizeMatchInput ) -> macro_tools::proc_macro2::TokenStream
{
  let source = &input.source;
  let patterns = &input.patterns;
  let strategy = &input.strategy;
  
  let optimization = analyze_match_pattern( patterns, strategy );
  
  if input.debug
  {
    eprintln!( "optimize_match! debug: patterns={patterns:?}, strategy={strategy:?}, optimization={optimization:?}" );
  }
  
  match optimization
  {
    MatchOptimization::SinglePattern( pattern ) =>
    {
      // Generate optimized single pattern matching
      quote!
      {
        {
          // Compile-time optimized single pattern match
          #source.find( #pattern )
        }
      }
    },
    
    MatchOptimization::TrieBasedMatch =>
    {
      // Generate trie-based pattern matching
      let _trie_data = build_compile_time_trie( patterns );
      quote!
      {
        {
          // Compile-time generated trie matching (simplified implementation)
          let mut best_match = None;
          for pattern in [ #( #patterns ),* ]
          {
            if let Some( pos ) = #source.find( pattern )
            {
              match best_match
              {
                None => best_match = Some( pos ),
                Some( current_pos ) if pos < current_pos => best_match = Some( pos ),
                _ => {}
              }
            }
          }
          best_match
        }
      }
    },
    
    MatchOptimization::SequentialMatch =>
    {
      // Generate sequential pattern matching
      quote!
      {
        {
          // Compile-time sequential pattern matching
          let mut result = None;
          for pattern in [ #( #patterns ),* ]
          {
            if let Some( pos ) = #source.find( pattern )
            {
              result = Some( pos );
              break;
            }
          }
          result
        }
      }
    }
  }
}

/// Compile-time split pattern analysis
#[ cfg( feature = "optimize_split" ) ]
#[ derive( Debug ) ]
enum SplitOptimization
{
  SingleCharDelimiter( String ),
  MultipleCharDelimiters,
  ComplexPattern,
}

/// Compile-time match pattern analysis
#[ cfg( feature = "optimize_match" ) ]
#[ derive( Debug ) ]
enum MatchOptimization
{
  SinglePattern( String ),
  TrieBasedMatch,
  SequentialMatch,
}

/// Analyze delimiter patterns for optimization opportunities
#[ cfg( feature = "optimize_split" ) ]
fn analyze_split_pattern( delimiters: &[ String ] ) -> SplitOptimization
{
  if delimiters.len() == 1
  {
    let delim = &delimiters[0];
    if delim.len() == 1
    {
      // Single character delimiter - highest optimization potential
      SplitOptimization::SingleCharDelimiter( delim.clone() )
    }
    else
    {
      // Multi-character single delimiter
      SplitOptimization::MultipleCharDelimiters
    }
  }
  else if delimiters.len() <= 8 && delimiters.iter().all( |d| d.len() <= 4 )
  {
    // Multiple simple delimiters - good for SIMD
    SplitOptimization::MultipleCharDelimiters
  }
  else
  {
    // Complex patterns - use state machine approach
    SplitOptimization::ComplexPattern
  }
}

/// Analyze match patterns for optimization opportunities
#[ cfg( feature = "optimize_match" ) ]
fn analyze_match_pattern( patterns: &[ String ], _strategy: &str ) -> MatchOptimization
{
  if patterns.len() == 1
  {
    MatchOptimization::SinglePattern( patterns[0].clone() )
  }
  else if patterns.len() <= 16 && patterns.iter().all( |p| p.len() <= 8 )
  {
    // Small set of short patterns - use trie
    MatchOptimization::TrieBasedMatch
  }
  else
  {
    // Large pattern set - use sequential matching
    MatchOptimization::SequentialMatch
  }
}

/// Build compile-time trie data for pattern matching
#[ cfg( feature = "optimize_match" ) ]
fn build_compile_time_trie( patterns: &[ String ] ) -> Vec< macro_tools::proc_macro2::TokenStream >
{
  // Simplified trie construction for demonstration
  // In a full implementation, this would build an optimal trie structure
  patterns.iter().map( |pattern| {
    let bytes: Vec< u8 > = pattern.bytes().collect();
    quote! { &[ #( #bytes ),* ] }
  } ).collect()
}