log_args 0.2.0

A simple procedural macro to log function arguments using the tracing crate.
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
//! # log_args
//!
//! A powerful procedural macro crate providing the `#[params]` attribute for automatic parameter logging
//! and context propagation in Rust applications. Built on top of the `tracing` ecosystem, it enables
//! truly automatic context inheritance across all boundaries including async/await, spawned tasks,
//! closures, and WebSocket upgrades.
//!
//! ## ✨ Key Features
//!
//! ### 🎯 Automatic Context Inheritance
//! - **Zero Configuration**: Child functions inherit parent context with just `#[params]`
//! - **Cross-Boundary**: Works across closures, async spawns, WebSocket upgrades, and thread boundaries
//! - **Transparent**: No manual context passing or management required
//!
//! ### 🚀 Performance & Safety
//! - **Zero Runtime Overhead**: All processing happens at compile-time via macro expansion
//! - **Memory Efficient**: Only specified fields are cloned and logged
//! - **Async Safe**: Proper handling of ownership in async contexts
//! - **Thread Safe**: Context propagation uses thread-local and task-local storage
//!
//! ### 🔧 Flexible Configuration
//! - **Selective Logging**: Choose exactly which parameters to log with `fields(...)`
//! - **Custom Fields**: Add computed metadata and expressions with `custom(...)`
//! - **Span Propagation**: Automatic context inheritance with `span(...)`
//! - **Nested Access**: Support for deep field access like `user.profile.settings.theme`
//! - **Method Calls**: Log results of method calls and expressions
//!
//! ### 🔒 Security & Privacy
//! - **Secure by Default**: Sensitive parameters excluded unless explicitly specified
//! - **Fine-grained Control**: Log only what's needed for debugging
//! - **Compliance Ready**: Selective logging helps meet privacy requirements
//! - **Production Safe**: Configurable logging levels and field selection
//!
//! ## 🚀 Quick Start
//!
//! Add to your `Cargo.toml`:
//! ```toml
//! [dependencies]
//! log_args = "0.1.4"
//! log-args-runtime = { version = "0.1.2", features = ["with_context"] }
//! tracing = "0.1"
//! tracing-subscriber = { version = "0.3", features = ["json"] }
//! ```
//!
//! ### Basic Usage Examples
//!
//! ```rust, ignore
//! use log_args::params;
//! use tracing::info;
//!
//! // Default behavior: Only span propagation and function name logging
//! #[params]
//! fn process_request(user_id: String, data: String) {
//!     info!("Processing request");
//!     // Output: {"message": "Processing request", "target": "my_app::process_request"}
//! }
//!
//! // Selective parameter logging (excludes sensitive data)
//! #[params(fields(user_id, action))]
//! fn user_action(user_id: String, action: String, password: String) {
//!     info!("User performed action");
//!     // Output: {"message": "User performed action", "user_id": "123", "action": "login"}
//!     // Note: password is excluded for security
//! }
//!
//! // Span context propagation - the killer feature!
//! #[params(span(request_id, user_id))]
//! fn handle_api_request(request_id: String, user_id: String, payload: String) {
//!     info!("API request received");
//!     validate_request(payload); // Child function inherits context
//!     process_business_logic();   // This too!
//! }
//!
//! // Child functions automatically inherit request_id and user_id
//! #[params]
//! fn validate_request(payload: String) {
//!     info!("Validating request");
//!     // Output: {"request_id": "req-123", "user_id": "user-456", "message": "Validating request"}
//! }
//!
//! #[params]
//! fn process_business_logic() {
//!     info!("Processing business logic");
//!     // Output: {"request_id": "req-123", "user_id": "user-456", "message": "Processing business logic"}
//! }
//! ```
//!
//! ## 🔧 Advanced Usage
//!
//! ### Custom Fields with Expressions
//! ```rust, ignore
//! #[params(
//!     fields(user.id, user.name),
//!     custom(
//!         email_count = user.emails.len(),
//!         is_premium = user.subscription.tier == "premium",
//!         timestamp = std::time::SystemTime::now()
//!     )
//! )]
//! fn analyze_user(user: User, api_key: String) {
//!     info!("Analyzing user account");
//!     // Output: {
//!     //   "message": "Analyzing user account",
//!     //   "user_id": 42,
//!     //   "user_name": "Alice",
//!     //   "email_count": 3,
//!     //   "is_premium": true,
//!     //   "timestamp": "2024-01-01T12:00:00Z"
//!     // }
//! }
//! ```
//!
//! ### Async Task Processing
//! ```rust, ignore
//! #[params(span(job_id, user_id))]
//! async fn process_background_job(job_id: String, user_id: String, job_data: JobData) {
//!     info!("Background job started");
//!     
//!     // Spawn async tasks - they inherit context automatically
//!     let handle1 = tokio::spawn(async {
//!         validate_job_data().await;
//!     });
//!     
//!     let handle2 = tokio::spawn(async {
//!         send_notifications().await;
//!     });
//!     
//!     tokio::try_join!(handle1, handle2).unwrap();
//!     info!("Background job completed");
//! }
//!
//! #[params]
//! async fn validate_job_data() {
//!     info!("Validating job data");
//!     // Automatically includes job_id and user_id from parent context
//! }
//! ```
//!
//! ## 🔧 Setup & Configuration
//!
//! ### Tracing Subscriber Setup
//! For structured JSON logging with context fields at the top level:
//!
//! ```rust, ignore
//! fn init_logging() {
//!     tracing_subscriber::fmt()
//!         .json()
//!         .flatten_event(true)  // Required for field flattening
//!         .init();
//! }
//! ```
//!
//! ### Production Configuration
//! ```rust, ignore
//! fn init_prod_logging() {
//!     tracing_subscriber::fmt()
//!         .json()
//!         .flatten_event(true)
//!         .with_env_filter("info,my_app=debug")
//!         .with_target(false)
//!         .init();
//! }
//! ```
//!
//! ## 🔒 Security Best Practices
//!
//! **Always use selective logging in production:**
//! ```rust, ignore
//! // ✅ Good - Only logs safe fields
//! #[params(fields(user_id, operation_type))]
//! fn secure_operation(user_id: String, password: String, operation_type: String) {
//!     info!("Operation started");
//!     // password is excluded for security
//! }
//!
//! // ❌ Bad - Logs everything including sensitive data
//! #[params(all)]
//! fn insecure_operation(user_id: String, password: String) {
//!     info!("Operation started"); // This would log the password!
//! }
//! ```
//!
//! ## 📚 Attribute Reference
//!
//! - `#[params]` - Default: span propagation and function name logging only
//! - `#[params(all)]` - Log all parameters (use carefully in production)
//! - `#[params(fields(param1, param2))]` - Log only specified parameters
//! - `#[params(span(param1, param2))]` - Propagate parameters as context to child functions
//! - `#[params(custom(key = expression))]` - Add computed custom fields
//!
//! ## 🚫 Limitations
//!
//! - Array indexing like `users[0].name` is not supported (use `users.first().map(|u| &u.name)` instead)
//! - The macro redefines logging macros within function scope only
//! - Complex expressions may not parse correctly (simplify or use custom fields)
//!
//! ## 📚 Examples
//!
//! See the [workspace examples](https://github.com/MKJSM/rs-log-args/tree/main/examples) for comprehensive demonstrations.

use proc_macro::TokenStream;
use quote::quote;
use syn::parse::{Parse, Parser};
use syn::punctuated::Punctuated;
#[allow(unused_imports)]
use syn::{
    parenthesized, parse_quote,
    visit_mut::{self, VisitMut},
    Expr, FnArg, Ident, MetaNameValue, Pat, Token,
};

const WITH_CONTEXT_ENABLED: bool = cfg!(feature = "with_context");

struct BlockRewriter;

impl VisitMut for BlockRewriter {
    fn visit_macro_mut(&mut self, mac: &mut syn::Macro) {
        let path = &mac.path;
        if let Some(last_segment) = path.segments.last() {
            if last_segment.ident == "info"
                || last_segment.ident == "warn"
                || last_segment.ident == "error"
                || last_segment.ident == "debug"
                || last_segment.ident == "trace"
            {
                if let Some(first_segment) = path.segments.first() {
                    if first_segment.ident == "tracing" {
                        // It's a `tracing::info!` style macro call. We need to strip `tracing::`
                        // so it becomes `info!`, which will then be resolved to our redefined macro.
                        let mut new_path = path.clone();
                        new_path.segments = new_path.segments.into_iter().skip(1).collect();
                        mac.path = new_path;
                    }
                }
            }
        }

        // Continue traversing the rest of the macro contents
        visit_mut::visit_macro_mut(self, mac);
    }
}

struct SpawnInstrumentRewriter;

impl VisitMut for SpawnInstrumentRewriter {
    fn visit_expr_mut(&mut self, expr: &mut syn::Expr) {
        if let syn::Expr::Call(expr_call) = expr {
            if let syn::Expr::Path(expr_path) = &*expr_call.func {
                if expr_path.path.segments.iter().any(|s| s.ident == "spawn") {
                    if let Some(fut_arg) = expr_call.args.first_mut() {
                        let original_fut = fut_arg.clone();
                        *fut_arg = parse_quote! {
                            ::log_args_runtime::instrument_spawn(#original_fut)
                        };
                    }
                }
            }
        }

        // Continue traversing to find nested spawns
        visit_mut::visit_expr_mut(self, expr);
    }
}

// Convert snake_case to camelCase (first letter lowercase)
#[cfg(feature = "function-names-camel")]
#[allow(dead_code)]
fn to_camel_case(snake_case: &str) -> String {
    let mut camel_case = String::new();
    let mut capitalize = false;
    for c in snake_case.chars() {
        if c == '_' {
            capitalize = true;
        } else if capitalize {
            camel_case.push(c.to_ascii_uppercase());
            capitalize = false;
        } else {
            camel_case.push(c);
        }
    }
    camel_case
}

// Convert snake_case to SCREAMING_SNAKE_CASE
#[cfg(feature = "function-names-screaming")]
#[allow(dead_code)]
fn to_screaming_snake_case(snake_case: &str) -> String {
    snake_case.to_ascii_uppercase()
}

// Convert snake_case to kebab-case
#[cfg(feature = "function-names-kebab")]
#[allow(dead_code)]
fn to_kebab_case(snake_case: &str) -> String {
    snake_case.replace('_', "-")
}

// Convert snake_case to PascalCase (first letter uppercase)
#[cfg(any(feature = "function-names-pascal", feature = "function-names"))]
fn to_pascal_case(snake_case: &str) -> String {
    let mut pascal_case = String::new();
    let mut capitalize = true; // Start with capital
    for c in snake_case.chars() {
        if c == '_' {
            capitalize = true;
        } else if capitalize {
            pascal_case.push(c.to_ascii_uppercase());
            capitalize = false;
        } else {
            pascal_case.push(c);
        }
    }
    pascal_case
}

// Get the formatted function name based on enabled features
#[allow(dead_code)]
fn get_formatted_function_name(function_name: &str) -> String {
    #[cfg(feature = "function-names-camel")]
    {
        return to_camel_case(function_name);
    }

    #[cfg(any(feature = "function-names-pascal", feature = "function-names"))]
    {
        return to_pascal_case(function_name);
    }

    #[cfg(feature = "function-names-screaming")]
    {
        return to_screaming_snake_case(function_name);
    }

    #[cfg(feature = "function-names-kebab")]
    {
        return to_kebab_case(function_name);
    }

    #[cfg(feature = "function-names-snake")]
    {
        return function_name.to_string();
    }

    // Default: return original snake_case function name
    #[allow(unreachable_code)]
    function_name.to_string()
}

/// A powerful procedural macro for automatic function argument logging with structured tracing.
///
/// **The `#[params]` macro enables truly automatic context inheritance across all boundaries**
/// including async/await, spawned tasks, closures, and WebSocket upgrades. By default, it provides
/// span-based context propagation and function name logging with zero configuration.
///
/// ## ✨ Key Features
///
/// - **🎯 Automatic Context Inheritance**: Child functions inherit parent context seamlessly
/// - **🚀 Zero Runtime Overhead**: All processing happens at compile-time
/// - **🔧 Selective Logging**: Choose exactly which parameters to log
/// - **🔒 Security-First**: Sensitive data excluded by default
/// - **🌐 Cross-Boundary**: Works across async/await, spawned tasks, closures
///
/// ## 🚀 Basic Usage (Default Behavior)
///
/// By default, `#[params]` only enables span propagation and function name logging:
///
/// ```rust, ignore
/// use log_args::params;
/// use tracing::info;
///
/// #[params]
/// fn process_request(user_id: String, data: String) {
///     info!("Processing request");
///     // Child functions inherit context automatically - no manual passing needed!
///     validate_request(data);
///     send_response();
/// }
///
/// #[params]
/// fn validate_request(payload: String) {
///     info!("Validating request"); // Inherits parent context automatically
/// }
///
/// #[params]
/// fn send_response() {
///     info!("Sending response"); // Also inherits parent context
/// }
/// ```
///
/// **JSON Output:**
/// ```json
/// {
///   "timestamp": "2024-01-01T12:00:00Z",
///   "level": "INFO",
///   "fields": {
///     "message": "Processing request",
///     "target": "my_app::process_request"
///   }
/// }
/// ```
///
/// ## 🔧 Selective Field Logging (Production Recommended)
///
/// For security and performance, specify exactly which fields to log:
///
/// ```rust, ignore
/// #[params(fields(user_id, action))]
/// fn user_action(user_id: String, action: String, password: String, api_key: String) {
///     info!("User performed action");
///     // Output: {"user_id": "123", "action": "login", "message": "User performed action"}
///     // Note: password and api_key are excluded for security
/// }
/// ```
///
/// ## 🔗 Span Context Propagation (The Killer Feature!)
///
/// Automatically propagate context to all child functions:
///
/// ```rust, ignore
/// // Parent function sets up context
/// #[params(span(request_id, user_id))]
/// fn handle_api_request(request_id: String, user_id: String, payload: String) {
///     info!("API request received");
///     validate_request(payload);   // Inherits request_id and user_id
///     process_business_logic();    // Also inherits context
///     audit_log();                 // This too!
/// }
///
/// // Child functions automatically inherit request_id and user_id
/// #[params]
/// fn validate_request(payload: String) {
///     info!("Validating request");
///     // Output: {"request_id": "req-123", "user_id": "user-456", "message": "Validating request"}
/// }
///
/// #[params]
/// fn process_business_logic() {
///     info!("Processing business logic");
///     // Output: {"request_id": "req-123", "user_id": "user-456", "message": "Processing business logic"}
/// }
/// ```
///
/// ## 🏷️ Custom Fields with Expressions
///
/// Add computed metadata and service information:
///
/// ```rust, ignore
/// #[params(
///     fields(user_id),
///     custom(
///         service = "user-management",
///         version = "2.1.0",
///         environment = "production"
///     )
/// )]
/// fn service_operation(user_id: u64, sensitive_data: String) {
///     info!("Service operation");
/// }
/// ```
///
/// ## All Parameters Logging
///
/// Use the `all` attribute to explicitly log all function parameters:
///
/// ```rust, ignore
/// #[params(all)]
/// fn debug_function(user_id: u64, data: String, config: Config) {
///     info!("Debug information");
/// }
/// ```
///
/// This is useful for debugging or when you want to ensure all parameters are logged
/// regardless of other attributes.
///
/// ## Span Context Propagation (Enabled by Default)
///
/// **Note: Span propagation is now enabled by default with `#[params]`.**
/// Context automatically propagates to child functions:
///
/// ```rust, ignore
/// use log_args_runtime::{info as ctx_info};
///
/// #[params(fields(user.id, transaction.amount))]
/// fn process_payment(user: User, transaction: Transaction, card_data: CardData) {
///     info!("Starting payment processing");
///     
///     validate_payment();  // Inherits context automatically
///     charge_card();       // Inherits context automatically
/// }
///
/// #[params]
/// fn validate_payment() {
///     info!("Validating payment");  // Includes parent context
/// }
/// ```
///
/// ## Function Name Logging
///
/// Enable function name logging with Cargo features:
///
/// ```toml
/// [dependencies]
/// log_args = { version = "0.1", features = ["function-names-pascal"] }
/// ```
///
/// Available casing styles:
/// - `function-names-snake` → `process_payment`
/// - `function-names-camel` → `processPayment`
/// - `function-names-pascal` → `ProcessPayment` (recommended)
/// - `function-names-screaming` → `PROCESS_PAYMENT`
/// - `function-names-kebab` → `process-payment`
///
/// ## Async Support
///
/// Works seamlessly with async functions:
///
/// ```rust, ignore
/// #[params(span, fields(user_id, operation_type))]
/// async fn async_operation(user_id: u64, operation_type: String, secret: String) {
///     info!("Starting async operation");
///     
///     tokio::time::sleep(Duration::from_millis(100)).await;
///     
///     info!("Async operation completed");
/// }
/// ```
///
/// ## Method Support
///
/// Works with methods in impl blocks:
///
/// ```rust, ignore
/// impl UserService {
///     #[params(span, fields(user.id, self.config.timeout))]
///     fn process_user(&self, user: User, sensitive_token: String) {
///         info!("Processing user in service");
///     }
/// }
/// ```
///
/// ## Security Considerations
///
/// **⚠️ Important:** Always use selective logging in production to avoid logging sensitive data:
///
/// - Passwords, tokens, API keys
/// - Personal Identifiable Information (PII)
/// - Credit card numbers, financial data
/// - Internal system keys and secrets
///
/// ## Error Handling
///
/// The macro works with Result types and error handling patterns:
///
/// ```rust, ignore
/// #[params(fields(operation_id, retry_count))]
/// fn fallible_operation(
///     operation_id: String,
///     retry_count: u32,
///     secret_key: String,  // Not logged
/// ) -> Result<String, ProcessingError> {
///     info!("Starting fallible operation");
///     
///     // Operation logic that might fail
///     Ok("success".to_string())
/// }
/// ```
///
/// ## Performance Notes
///
/// - Selective logging (`fields(...)`) is more efficient than logging all parameters
/// - Complex field expressions are evaluated at runtime - use judiciously in hot paths
/// - Span creation has overhead - use for important operations that benefit from context
///
/// For comprehensive documentation and examples, see:
/// - [USAGE.md](https://github.com/MKJSM/rs-log-args/blob/main/USAGE.md)
/// - [Examples](https://github.com/MKJSM/rs-log-args/tree/main/examples)
/// - [Integration Tests](https://github.com/MKJSM/rs-log-args/tree/main/tests)
///
/// fn child_function() {
///     info!("Child task");
/// }
///
#[proc_macro_attribute]
pub fn params(args: TokenStream, input: TokenStream) -> TokenStream {
    let mut item = if let Ok(item_fn) = syn::parse::<syn::ItemFn>(input.clone()) {
        FnItem::Item(item_fn)
    } else if let Ok(impl_item_fn) = syn::parse::<syn::ImplItemFn>(input.clone()) {
        FnItem::ImplItem(impl_item_fn)
    } else {
        return syn::Error::new_spanned(
            proc_macro2::TokenStream::from(input),
            "The #[params] attribute can only be applied to functions or methods.",
        )
        .to_compile_error()
        .into();
    };

    let allow_unused_macros_attr: syn::Attribute = syn::parse_quote! { #[allow(unused_macros)] };
    item.attrs_mut().push(allow_unused_macros_attr);

    let attrs = match Punctuated::<Attribute, Token![,]>::parse_terminated.parse(args) {
        Ok(attrs) => attrs,
        Err(e) => return e.to_compile_error().into(),
    };

    let config = AttrConfig::from_attributes(attrs);
    let (context_fields, clone_stmts) = get_context_fields_quote(&item, &config);

    let is_async = item.sig().asyncness.is_some();
    let new_block_tokens = generate_new_block(&item, &config, &context_fields, is_async, clone_stmts);
    *item.block_mut() = match syn::parse2(new_block_tokens) {
        Ok(block) => block,
        Err(e) => return e.to_compile_error().into(),
    };

    TokenStream::from(quote! { #item })
}

fn generate_new_block(
    item: &FnItem,
    config: &AttrConfig,
    context_fields: &[proc_macro2::TokenStream],
    is_async: bool,
    clone_stmts: Vec<proc_macro2::TokenStream>,
) -> proc_macro2::TokenStream {
    let log_redefines = get_log_redefines_with_fields(context_fields, is_async);
    let original_block = item.block().clone();
    let mut transformed_block = original_block.clone();
    BlockRewriter.visit_block_mut(&mut transformed_block);
    SpawnInstrumentRewriter.visit_block_mut(&mut transformed_block);

    if config.span {
        let context_map = get_context_map_for_span(item, config);
        let auto_capture_stmt = if config.auto_capture {
            quote! { let _auto_capture_guard = ::log_args_runtime::capture_context(); }
        } else {
            quote! {}
        };

        if is_async {
            quote! {
                {
                    #(#clone_stmts)*
                    ::log_args_runtime::with_async_context(#context_map, async move {
                        #auto_capture_stmt
                        #log_redefines
                        #transformed_block
                    }).await
                }
            }
        } else {
            quote! {
                {
                    #(#clone_stmts)*
                    let _context_guard = ::log_args_runtime::push_context(#context_map);
                    #auto_capture_stmt
                    #log_redefines
                    #transformed_block
                }
            }
        }
    } else {
        quote! {
            {
                #(#clone_stmts)*
                #log_redefines
                #transformed_block
            }
        }
    }
}

/// Represents the different attribute configurations available for the `#[params]` macro.
///
/// Each attribute controls how function parameters are logged and how context is propagated
/// to child functions. These attributes can be combined to create flexible logging strategies.
///
/// # Available Attributes
///
/// - `fields(...)` - Selectively log specific function parameters as individual fields
/// - `custom(...)` - Add computed fields with custom expressions and metadata
/// - `current(...)` - Log current context values (legacy/internal use)
/// - `clone_upfront` - Clone parameters before async operations to prevent move issues
/// - `span(...)` - Set up context propagation for child functions to inherit
/// - `all` - Log all function parameters (use with caution in production)
/// - `auto_capture` - Automatically capture context in closures and spawned tasks
///
/// # Security Note
///
/// By default, `#[params]` without arguments is secure and doesn't log parameters.
/// Always be explicit about what you log in production environments.
#[derive(Clone)]
enum FieldKey {
    Ident(Ident),
    LitStr(syn::LitStr),
}

impl quote::ToTokens for FieldKey {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        match self {
            FieldKey::Ident(ident) => ident.to_tokens(tokens),
            FieldKey::LitStr(lit) => lit.to_tokens(tokens),
        }
    }
}

impl FieldKey {
    fn to_string(&self) -> String {
        match self {
            FieldKey::Ident(ident) => ident.to_string(),
            FieldKey::LitStr(lit) => lit.value(),
        }
    }
}

#[allow(dead_code)]
#[derive(Clone)]
struct NameValueField {
    key: FieldKey,
    eq_token: Token![=],
    value: Expr,
}

impl Parse for NameValueField {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let key = if input.peek(syn::LitStr) {
            FieldKey::LitStr(input.parse()?)
        } else {
            FieldKey::Ident(input.parse()?)
        };
        let eq_token: Token![=] = input.parse()?;
        let value: Expr = input.parse()?;
        Ok(NameValueField {
            key,
            eq_token,
            value,
        })
    }
}

#[derive(Clone)]
enum Field {
    NameValue(NameValueField),
    Expr(Expr),
}

impl Parse for Field {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        if (input.peek(Ident) || input.peek(syn::LitStr)) && input.peek2(Token![=]) {
            Ok(Field::NameValue(input.parse()?))
        } else {
            Ok(Field::Expr(input.parse()?))
        }
    }
}

enum Attribute {
    /// **Selective Parameter Logging** - `fields(param1, param2, ...)`
    ///
    /// Logs only the specified function parameters as individual fields in the log output.
    /// This is the recommended approach for production logging as it gives you precise
    /// control over what data is logged.
    ///
    /// # Example
    /// ```rust,ignore
    /// #[params(fields(user_id, action))]
    /// fn user_action(user_id: String, action: String, password: String) {
    ///     info!("User performed action"); // Only user_id and action are logged
    /// }
    /// ```
    ///
    /// # Security
    /// - ✅ Secure: Only specified parameters are logged
    /// - ✅ Production-safe: Excludes sensitive data by default
    /// - ✅ Performance: Only processes specified fields
    Fields(Punctuated<Field, Token![,]>),

    /// **Custom Computed Fields** - `custom(field_name = expression, ...)`
    ///
    /// Adds computed fields to log output using custom expressions. Useful for adding
    /// metadata, timestamps, or derived values that aren't direct function parameters.
    ///
    /// # Example
    /// ```rust,ignore
    /// #[params(
    ///     custom(
    ///         timestamp = std::time::SystemTime::now(),
    ///         data_size = data.len(),
    ///         is_admin = user.role == "admin"
    ///     )
    /// )]
    /// fn process_data(data: Vec<u8>, user: User) {
    ///     info!("Processing data"); // Includes computed fields
    /// }
    /// ```
    ///
    /// # Performance Note
    /// Keep expressions lightweight as they're evaluated on every log call.
    Custom(Punctuated<NameValueField, Token![,]>),

    /// **Current Context Values** - `current(...)`
    ///
    /// Internal attribute for logging current context values. Primarily used internally
    /// by the macro system for context management.
    ///
    /// # Usage
    /// This is typically not used directly by end users.
    Current(Punctuated<Expr, Token![,]>),

    /// **Clone Upfront** - `clone_upfront`
    ///
    /// Clones function parameters before async operations to prevent ownership issues.
    /// Useful when parameters need to be moved into async blocks or spawned tasks.
    ///
    /// # Example
    /// ```rust,ignore
    /// #[params(fields(user_id), clone_upfront)]
    /// async fn async_operation(user_id: String, data: Vec<u8>) {
    ///     tokio::spawn(async move {
    ///         // user_id was cloned upfront, so this works
    ///         process_data(data).await;
    ///     });
    /// }
    /// ```
    ///
    /// # Performance Impact
    /// Only use when necessary as it adds cloning overhead.
    CloneUpfront,

    /// **Context Propagation** - `span(param1, param2, ...)` or `span`
    ///
    /// Sets up automatic context inheritance for child functions. This is the key feature
    /// that enables truly automatic context propagation across function boundaries.
    ///
    /// # Example
    /// ```rust,ignore
    /// #[params(span(request_id, user_id))]
    /// fn handle_request(request_id: String, user_id: String, data: String) {
    ///     info!("Request received");
    ///     process_data(data); // Child function inherits request_id and user_id
    /// }
    ///
    /// #[params] // Inherits context from parent
    /// fn process_data(data: String) {
    ///     info!("Processing"); // Automatically includes request_id and user_id
    /// }
    /// ```
    ///
    /// # Cross-Boundary Support
    /// - ✅ Async/await boundaries
    /// - ✅ Spawned tasks (tokio::spawn)
    /// - ✅ Closures and iterators
    /// - ✅ Thread boundaries
    Span(Punctuated<Expr, Token![,]>),

    /// **Log All Parameters** - `all`
    ///
    /// Logs all function parameters as individual fields.
    ///
    /// # ⚠️ Security Warning
    /// Use with extreme caution in production as this logs ALL parameters,
    /// including potentially sensitive data like passwords, tokens, and personal information.
    ///
    /// # Example
    /// ```rust,ignore
    /// #[params(all)] // ⚠️ Only use in development/debugging
    /// fn debug_function(user_id: String, email: String, data: Vec<u8>) {
    ///     info!("Debug info"); // Logs ALL parameters
    /// }
    /// ```
    ///
    /// # Recommended Usage
    /// - ✅ Development and debugging
    /// - ✅ Non-production environments
    /// - ❌ Production environments
    /// - ❌ Functions with sensitive parameters
    All,

    /// **Automatic Context Capture** - `auto_capture`
    ///
    /// Automatically captures and propagates context in closures and spawned tasks.
    /// This ensures context is preserved even in complex async scenarios.
    ///
    /// # Example
    /// ```rust,ignore
    /// #[params(span(batch_id), auto_capture)]
    /// fn process_batch(batch_id: String, items: Vec<Item>) {
    ///     items.iter().for_each(|item| {
    ///         // Context automatically captured in closure
    ///         process_item(item.clone());
    ///     });
    /// }
    /// ```
    ///
    /// # Use Cases
    /// - Complex async workflows
    /// - Iterator chains with closures
    /// - Nested task spawning
    AutoCapture,
    WithContext,
}

impl Parse for Attribute {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let ident: Ident = input.parse()?;
        if ident == "fields" {
            let content;
            parenthesized!(content in input);
            let fields = Punctuated::<Field, Token![,]>::parse_terminated(&content)?;
            Ok(Attribute::Fields(fields))
        } else if ident == "custom" {
            let content;
            parenthesized!(content in input);
            let custom = Punctuated::<NameValueField, Token![,]>::parse_terminated(&content)?;
            Ok(Attribute::Custom(custom))
        } else if ident == "current" {
            let content;
            parenthesized!(content in input);
            let current = Punctuated::<Expr, Token![,]>::parse_terminated(&content)?;
            Ok(Attribute::Current(current))
        } else if ident == "clone_upfront" {
            Ok(Attribute::CloneUpfront)
        } else if ident == "span" {
            // Accept both `span` and `span(...)`
            if input.peek(syn::token::Paren) {
                let content;
                parenthesized!(content in input);
                let span_fields = Punctuated::<Expr, Token![,]>::parse_terminated(&content)?;
                Ok(Attribute::Span(span_fields))
            } else {
                Ok(Attribute::Span(Punctuated::new()))
            }
        } else if ident == "all" {
            Ok(Attribute::All)
        } else if ident == "auto_capture" {
            Ok(Attribute::AutoCapture)
        } else if ident == "with_context" {
            Ok(Attribute::WithContext)
        } else {
            Err(syn::Error::new_spanned(ident, "unknown attribute"))
        }
    }
}

struct AttrConfig {
    fields: Vec<Field>,
    custom: Vec<NameValueField>,
    current: Vec<syn::Expr>,
    clone_upfront: bool,
    span: bool,
    span_fields: Vec<syn::Expr>,
    all_params: bool,
    auto_capture: bool,
    with_context: bool,
}

impl Default for AttrConfig {
    fn default() -> Self {
        Self {
            fields: Vec::new(),
            custom: Vec::new(),
            current: Vec::new(),
            clone_upfront: true, // Default to true for safety
            span: true,          // Enable span propagation by default
            span_fields: Vec::new(),
            all_params: false,
            auto_capture: false, // Default to false for auto_capture
            with_context: false,
        }
    }
}

impl AttrConfig {
    fn from_attributes(attrs: Punctuated<Attribute, Token![,]>) -> Self {
        let mut config = AttrConfig::default();
        for attr in attrs {
            match attr {
                Attribute::Fields(fields) => config.fields.extend(fields),
                Attribute::Custom(custom) => config.custom.extend(custom),
                Attribute::Current(current) => config.current.extend(current),
                Attribute::CloneUpfront => config.clone_upfront = true,
                Attribute::Span(span_fields) => {
                    config.span = true;
                    config.clone_upfront = true; // Span implies clone_upfront for safety
                    config.span_fields.extend(span_fields);
                }
                Attribute::All => {
                    config.all_params = true;
                }
                Attribute::AutoCapture => {
                    config.auto_capture = true;
                    config.span = true;
                }
                Attribute::WithContext => {
                    config.with_context = true;
                    config.span = true;
                }
            }
        }
        config
    }
}

fn get_context_fields_quote(
    item: &FnItem,
    config: &AttrConfig,
) -> (Vec<proc_macro2::TokenStream>, Vec<proc_macro2::TokenStream>) {
    let mut field_assignments = vec![];
    let mut clone_statements = vec![];
    let mut cloned_fields = std::collections::HashSet::new();

    // Helper to handle self.field clones
    let mut process_expr = |expr: &syn::Expr| -> syn::Expr {
        let expr_str = quote!(#expr).to_string();
        if config.clone_upfront && expr_str.contains("self.") {
            let mut modified_expr_str = expr_str.clone();
            let mut start = 0;
            while let Some(pos) = modified_expr_str[start..].find("self.") {
                let field_start = start + pos + 5; // Skip "self."
                let remaining = &modified_expr_str[field_start..];

                // Find the end of the field name
                let field_end = remaining
                    .find(|c: char| !c.is_alphanumeric() && c != '_')
                    .unwrap_or(remaining.len());

                let field_name_part = &remaining[..field_end];
                let replacement = format!("__{field_name_part}_for_macro");

                if cloned_fields.insert(field_name_part.to_string()) {
                    let field_ident = Ident::new(field_name_part, proc_macro2::Span::call_site());
                    let replacement_ident = Ident::new(&replacement, proc_macro2::Span::call_site());
                    clone_statements.push(quote! {
                        let #replacement_ident = self.#field_ident.clone();
                    });
                }

                // Replace self.field_name with __field_name_for_macro
                let old_expr = format!("self.{field_name_part}");
                modified_expr_str = modified_expr_str.replace(&old_expr, &replacement);

                start = field_start + field_end;
            }
            syn::parse_str(&modified_expr_str).unwrap_or_else(|_| expr.clone())
        } else {
            expr.clone()
        }
    };

    // For span propagation, automatically inherit parent context fields
    if config.span
        && config.fields.is_empty()
        && config.custom.is_empty()
        && config.current.is_empty()
        && !config.all_params
    {
        if WITH_CONTEXT_ENABLED {
            field_assignments.push(quote! {
                context = ::log_args_runtime::get_inherited_context_string()
            });
        }
    }

    if config.all_params {
        let all_args = get_all_args(item);
        for ident in all_args {
            let ident_str = ident.to_string();
            if config.span {
                field_assignments.push(quote! {
                    #ident = ::log_args_runtime::get_context_value_merged(&#ident_str).unwrap_or_else(|| "".to_string())
                });
            } else {
                field_assignments.push(quote! {#ident = ?#ident });
            }
        }
    }

    if !config.fields.is_empty() {
        for field in &config.fields {
            match field {
                Field::Expr(expr) => {
                    let field_name = quote! { #expr }.to_string().replace(' ', "");
                    if config.span {
                        field_assignments.push(quote! {
                            #field_name = ::log_args_runtime::get_context_value_merged(&#field_name).unwrap_or_else(|| "".to_string())
                        });
                    } else {
                        let processed = process_expr(expr);
                        field_assignments.push(quote! { #field_name = ?#processed });
                    }
                }
                Field::NameValue(nv) => {
                    let key = &nv.key;
                    let value = &nv.value;
                    let key_str = key.to_string();
                    if config.span {
                        field_assignments.push(quote! {
                            #key_str = ::log_args_runtime::get_context_value_merged(&#key_str).unwrap_or_else(|| "".to_string())
                        });
                    } else {
                        let processed = process_expr(value);
                        field_assignments.push(quote! { #key = ?#processed });
                    }
                }
            }
        }
    }

    if !config.span_fields.is_empty() {
        for field_expr in &config.span_fields {
            let field_name = quote! { #field_expr }.to_string().replace(' ', "");
            field_assignments.push(quote! {
                #field_name = ::log_args_runtime::get_context_value_merged(&#field_name).unwrap_or_else(|| "".to_string())
            });
        }
    }

    for nv in &config.custom {
        let key = &nv.key;
        let value = &nv.value;
        let processed = process_expr(value);
        field_assignments.push(quote! {
            #key = ?#processed
        });
    }

    for current_field in &config.current {
        let field_name = quote! { #current_field }.to_string().replace(' ', "");
        if config.span {
            field_assignments.push(quote! {
                #field_name = ::log_args_runtime::get_context_value_merged(&#field_name).unwrap_or_else(|| "".to_string())
            });
        } else {
            let processed = process_expr(current_field);
            field_assignments.push(quote! { #field_name = ?#processed });
        }
    }

    add_function_name_field(&mut field_assignments, item);

    (field_assignments, clone_statements)
}

/// Add function name field to log output when any function-names feature is enabled.
/// The function name will be formatted according to the enabled feature.
#[allow(dead_code, unused_variables)]
fn add_function_name_field(field_assignments: &mut Vec<proc_macro2::TokenStream>, item: &FnItem) {
    // Check if any function-names feature is enabled
    #[cfg(any(
        feature = "function-names-snake",
        feature = "function-names-camel",
        feature = "function-names-pascal",
        feature = "function-names-screaming",
        feature = "function-names-kebab",
        feature = "function-names"
    ))]
    {
        let function_name = item.sig().ident.to_string();
        let formatted_name = get_formatted_function_name(&function_name);

        field_assignments.push(quote! {
            function_name = #formatted_name
        });
    }
}

fn get_context_map_for_span(item: &FnItem, config: &AttrConfig) -> proc_macro2::TokenStream {
    let mut fields_to_log = vec![];
    let all_args = get_all_args(item);
    let arg_idents: std::collections::HashSet<String> =
        all_args.iter().map(|i| i.to_string()).collect();

    // 1. Add all parameters if requested
    if config.all_params {
        for ident in all_args {
            let ident_str = ident.to_string();
            fields_to_log.push(quote! {
                new_context.insert(#ident_str.to_string(), format!("{:?}", #ident));
            });
        }
    }

    // 2. Add explicitly specified fields if they are local parameters or self fields
    if !config.fields.is_empty() {
        for field in &config.fields {
            match field {
                Field::Expr(expr) => {
                    let key_str = quote!(#expr).to_string().replace(' ', "");
                    if arg_idents.contains(&key_str) || key_str.starts_with("self.") {
                        fields_to_log.push(quote! {
                            new_context.insert(#key_str.to_string(), format!("{:?}", &#expr));
                        });
                    }
                }
                Field::NameValue(nv) => {
                    let key_str = nv.key.to_string();
                    let value = &nv.value;
                    let val_str = quote!(#value).to_string().replace(' ', "");
                    if arg_idents.contains(&val_str) || val_str.starts_with("self.") {
                        fields_to_log.push(quote! {
                            new_context.insert(#key_str.to_string(), format!("{:?}", &#value));
                        });
                    }
                }
            }
        }
    }

    // 3. Add custom fields (always included as they are evaluated locally)
    for nv in &config.custom {
        let key_str = nv.key.to_string();
        let value = &nv.value;
        fields_to_log.push(quote! {
            new_context.insert(#key_str.to_string(), format!("{:?}", #value));
        });
    }

    quote! {
        {
            let mut new_context = ::std::collections::HashMap::new();
            #(#fields_to_log)*
            new_context
        }
    }
}

fn get_all_args(item: &FnItem) -> Vec<Ident> {
    item.sig()
        .inputs
        .iter()
        .filter_map(|arg| {
            if let FnArg::Typed(pt) = arg {
                if let Pat::Ident(pi) = &*pt.pat {
                    if pi.ident != "self" {
                        return Some(pi.ident.clone());
                    }
                }
            }
            None
        })
        .collect()
}

enum FnItem {
    Item(syn::ItemFn),
    ImplItem(syn::ImplItemFn),
}

impl quote::ToTokens for FnItem {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        match self {
            FnItem::Item(i) => i.to_tokens(tokens),
            FnItem::ImplItem(i) => i.to_tokens(tokens),
        }
    }
}

impl FnItem {
    fn attrs_mut(&mut self) -> &mut Vec<syn::Attribute> {
        match self {
            FnItem::Item(item_fn) => &mut item_fn.attrs,
            FnItem::ImplItem(impl_item_fn) => &mut impl_item_fn.attrs,
        }
    }

    fn sig(&self) -> &syn::Signature {
        match self {
            FnItem::Item(i) => &i.sig,
            FnItem::ImplItem(i) => &i.sig,
        }
    }

    fn block(&self) -> &syn::Block {
        match self {
            FnItem::Item(i) => &i.block,
            FnItem::ImplItem(i) => &i.block,
        }
    }

    fn block_mut(&mut self) -> &mut syn::Block {
        match self {
            FnItem::Item(i) => &mut i.block,
            FnItem::ImplItem(i) => &mut i.block,
        }
    }
}

fn get_log_redefines_with_fields(
    context_fields: &[proc_macro2::TokenStream],
    _is_async: bool,
) -> proc_macro2::TokenStream {
    // Always redefine macros to include both local fields and inherited context
    // The context inheritance will be handled by including context fields from the runtime
    quote! {
        macro_rules! info {
            ($($t:tt)*) => {
                ::log_args_runtime::log_with_context!(::tracing::info, ::log_args_runtime::get_context_merged(), #(#context_fields,)* $($t)*)
            };
        }
        macro_rules! warn {
            ($($t:tt)*) => {
                ::log_args_runtime::log_with_context!(::tracing::warn, ::log_args_runtime::get_context_merged(), #(#context_fields,)* $($t)*)
            };
        }
        macro_rules! error {
            ($($t:tt)*) => {
                ::log_args_runtime::log_with_context!(::tracing::error, ::log_args_runtime::get_context_merged(), #(#context_fields,)* $($t)*)
            };
        }
        macro_rules! debug {
            ($($t:tt)*) => {
                ::log_args_runtime::log_with_context!(::tracing::debug, ::log_args_runtime::get_context_merged(), #(#context_fields,)* $($t)*)
            };
        }
        macro_rules! trace {
            ($($t:tt)*) => {
                ::log_args_runtime::log_with_context!(::tracing::trace, ::log_args_runtime::get_context_merged(), #(#context_fields,)* $($t)*)
            };
        }
    }
}