inline_tweak 1.2.4

Tweak values directly from the source code
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
//! Tweak any literal directly from your code, changes to the source appear while running the program.
//! It works by parsing the file when a change occurs.
//!
//! The library is minimal with 0 dependencies.
//! In release mode, the tweaking code is disabled and compiled away.
//!
//! The `derive` feature exposes a proc macro to turn all literals from a function body into tweakable values.
//!
//! ## Usage
//!
//! ```rust
//! loop {
//!     // Try changing the value while the application is running
//!     println!("{}", inline_tweak::tweak!(3.14));
//! }
//! ```
//!
//! ## Extra features
//!
//! ### derive
//!
//! The `derive` feature allows to tweak any number/bool/char literal in a function.
//! It avoids cluttering the code with `inline_tweak::tweak!` calls.
//!
//! ```rust
//! #[inline_tweak::tweak_fn]
//! fn main() {
//!     loop {
//!        let v = 1.0; // Try changing this value!
//!        println!("{}", v);
//!        std::thread::sleep(std::time::Duration::from_millis(200)); // or even this value :)
//!     }
//! }
//! ```
//!
//! #### watch!
//!
//! `inline_tweak` provides a `watch!()` macro that sleeps until the file is modified, akin to a breakpoint:
//! ```rust
//! loop {
//!     println!("{}", inline_tweak::tweak!(3.14));
//!     watch!(); // The thread will sleep here until anything in the file changes
//! }
//! ```
//!
//! #### Expressions
//!
//! `inline_tweak` allows to tweak expressions by providing a value later.
//! For example:
//! ```rust
//! tweak!(rng.gen_range(0.0, 1.0))
//! ```
//!
//! can then be replaced by a constant value by modifying the file (even while the application is running) to
//! ```rust
//! tweak!(5.0; rng.gen_range(0.0, 1.0)) // will always return 5.0
//! ```
//!
//! #### release_tweak!
//!
//! The `release_tweak!` macro acts exactly like `tweak!` except that it also works in release mode.
//! It is accessible behind the feature flag `"release_tweak"` which is not enabled by default.
#![allow(clippy::needless_doctest_main)]

#[cfg(all(any(debug_assertions, feature = "release_tweak"), not(target_arch = "wasm32")))]
mod hasher;

pub trait Tweakable: Sized + Send + Clone + 'static {
    fn parse(x: &str) -> Option<Self>;
}

#[cfg(all(any(debug_assertions, feature = "release_tweak"), not(target_arch = "wasm32")))]
mod itweak {
    use super::Tweakable;
    use core::str::FromStr;
    use crate::hasher::FxHashMap;
    use std::any::Any;
    use std::fs::File;
    use std::io::{BufRead, BufReader};
    use std::sync::{LazyLock, Mutex};
    use std::time::{Instant, SystemTime};

    macro_rules! impl_tweakable_float {
        ($($t: ty) +) => {
            $(
            impl Tweakable for $t {
                fn parse(x: &str) -> Option<$t> {
                    let v = x.replace("_", "").replace(stringify!($t), "");
                    FromStr::from_str(&v).ok()
                }
            }
            )+
        };
    }

    // Follows reference https://doc.rust-lang.org/reference/expressions/literal-expr.html
    macro_rules! impl_tweakable_integer {
        ($($t: ty) +) => {
            $(
            impl Tweakable for $t {
                fn parse(x: &str) -> Option<$t> {
                    let s = x.replace("_", "").replace(stringify!($t), "");
                    let radix = if s.starts_with("0x") {
                        16
                    } else if s.starts_with("0o") {
                        8
                    } else if s.starts_with("0b") {
                        2
                    } else {
                        10
                    };

                    let s_without_radix = if radix == 10 {
                        &s
                    } else {
                        &s[2..]
                    };

                    let v = i128::from_str_radix(&s_without_radix, radix).ok()?;

                    Some(v as $t)
                }
            }
            )+
        };
    }

    impl_tweakable_integer!(u8 u16 u32 u64 u128 i8 i16 i32 i64 i128 usize isize);
    impl_tweakable_float!(f32 f64);

    impl Tweakable for bool {
        fn parse(x: &str) -> Option<Self> {
            match x {
                "true" => Some(true),
                "false" => Some(false),
                _ => None,
            }
        }
    }

    impl Tweakable for char {
        fn parse(x: &str) -> Option<Self> {
            x.trim_start_matches('\'')
                .trim_end_matches('\'')
                .chars()
                .next()
        }
    }

    impl Tweakable for &'static str {
        fn parse(x: &str) -> Option<Self> {
            let raw_remove = x.trim_start_matches(['r', '#']).trim_end_matches('#');
            let remove_starting_quote = raw_remove
                .split_once('"')
                .map(|v| v.1)
                .unwrap_or(raw_remove);

            let remove_ending_quote = remove_starting_quote
                .rsplit_once('"')
                .map(|v| v.0)
                .unwrap_or(remove_starting_quote);

            Some(Box::leak(Box::new(String::from(remove_ending_quote))))
        }
    }

    impl Tweakable for () {
        fn parse(_x: &str) -> Option<Self> {
            Some(())
        }
    }

    /// The struct holding the value of a call to tweak!.
    struct TweakValue {
        /// The value of the tweak. Downcasted to the type of the tweak when appropriate.
        value: Option<Box<dyn Any + Send>>,
        /// The last time this value was checked for modifications. Avoids too many hashmap lookups.
        last_checked: Instant,
        /// The version of the file when the value was last updated.
        file_version: u64,
    }

    /// A cache of the values of the tweaks in a file before being parsed.
    struct ParsedFile {
        /// The last time the file was checked for modifications. Avoids too many syscalls.
        last_checked_modified_time: Instant,
        file_modified: SystemTime,
        /// The list of the literal strings.
        values: Vec<String>,
        version: u64,
        /// The map of (line, column) -> position.
        /// This is only done once per file.
        /// This allows the line/columns to change without breaking the tweak.
        positions: Option<FxHashMap<(u32, u32), u32>>,
    }

    #[allow(dead_code)]
    struct FileWatcher {
        last_checked: Instant,
        file_modified: SystemTime,
    }

    #[derive(Hash, PartialEq, Eq)]
    struct TweakKey {
        filename: Filename,
        line: u32,
        column: u32,
    }

    type Filename = &'static str;

    /// Stores the values of the tweaks. The key is the file, line and column of the tweak.
    static VALUES: LazyLock<Mutex<FxHashMap<TweakKey, TweakValue>>> =
        LazyLock::new(Default::default);

    static PARSED_FILES: LazyLock<Mutex<FxHashMap<Filename, ParsedFile>>> =
        LazyLock::new(Default::default);

    static WATCHERS: LazyLock<Mutex<FxHashMap<Filename, FileWatcher>>> =
        LazyLock::new(Default::default);

    fn last_modified(file: Filename) -> Option<SystemTime> {
        File::open(file).ok()?.metadata().ok()?.modified().ok()
    }

    // Assume that the first time a tweak! is called, all tweak!s will be in original line/column.
    fn parse_tweak_positions(file: &mut ParsedFile, filename: Filename) -> Option<()> {
        let mut tweaks_seen = 0u32;

        let mut positions = FxHashMap::default();
        for (line_n, line) in BufReader::new(File::open(filename).ok()?)
            .lines()
            .map_while(Result::ok)
            .enumerate()
        {
            for (column, _) in line.match_indices("tweak!(") {
                let path_corrected_column = line[..column]
                    .rfind(|c: char| !(c.is_ascii_alphanumeric() || c == ':' || c == '_')) // https://doc.rust-lang.org/reference/paths.html follows the rust path grammar
                    .map(|x| x + 1)
                    .unwrap_or(0);

                positions.insert(
                    (line_n as u32 + 1, path_corrected_column as u32 + 1),
                    tweaks_seen,
                );
                tweaks_seen += 1;
            }
        }

        file.positions = Some(positions);

        Some(())
    }

    fn parse_tweaks(f: &mut ParsedFile, filename: Filename) -> Option<()> {
        if f.last_checked_modified_time.elapsed() < std::time::Duration::from_millis(500)
            && f.version != 0
        {
            return Some(());
        }
        f.last_checked_modified_time = Instant::now();

        let last_modified = last_modified(filename).unwrap_or_else(SystemTime::now);

        if last_modified == f.file_modified && f.version != 0 {
            return Some(());
        }
        f.file_modified = last_modified;
        f.version += 1;

        f.values.clear();

        let content = std::fs::read_to_string(filename).ok()?;
        let mut it = content.split("tweak!(");

        it.next(); // skip part before first tweak!

        for val_str in it {
            // Find end of tweak
            let mut prec = 1;
            let (end, _) = val_str.char_indices().find(|(_, c)| {
                match c {
                    ';' | ')' if prec == 1 => {
                        return true;
                    }
                    ')' => prec -= 1,
                    '(' => prec += 1,
                    _ => {}
                }
                false
            })?;

            f.values.push(val_str[..end].to_string());
        }

        Some(())
    }

    fn update_tweak<T: Tweakable>(
        tweak: &mut TweakValue,
        line: u32,
        column: u32,
        file: &ParsedFile,
    ) -> Option<()> {
        if tweak.file_version == file.version {
            return Some(());
        }

        let position = file.positions.as_ref()?.get(&(line, column))?;

        let value = &**file.values.get(*position as usize)?;

        let parsed: Option<T> = Tweakable::parse(value);

        tweak.value = parsed.map(|inner| Box::new(inner) as Box<dyn Any + Send>);
        tweak.file_version = file.version;

        Some(())
    }

    pub(crate) fn get_value<T: Tweakable>(
        initial_value: Option<T>,
        filename: Filename,
        line: u32,
        column: u32,
    ) -> Option<T> {
        let mut lock = VALUES.lock().unwrap();

        let tweak = lock
            .entry(TweakKey {
                filename,
                line,
                column,
            })
            .or_insert_with(|| TweakValue {
                value: initial_value.map(|inner| Box::new(inner) as Box<dyn Any + Send>),
                last_checked: Instant::now(),
                file_version: 0,
            });

        if tweak.last_checked.elapsed().as_secs_f32() > 0.5 {
            tweak.last_checked = Instant::now();
            let mut fileinfos = PARSED_FILES.lock().unwrap();
            let f = fileinfos.entry(filename).or_insert_with(|| ParsedFile {
                last_checked_modified_time: Instant::now(),
                file_modified: SystemTime::now(),
                values: Default::default(),
                version: 0,
                positions: Default::default(),
            });

            if f.positions.is_none() {
                parse_tweak_positions(f, filename)?;
            }

            parse_tweaks(f, filename)?;

            update_tweak::<T>(tweak, line, column, f)?;
        }

        tweak.value.as_ref()?.downcast_ref().cloned()
    }

    #[allow(dead_code)]
    pub fn watch_modified(file: Filename) -> bool {
        let mut lock = WATCHERS.lock().unwrap();
        let entry = lock.entry(file);

        let now = Instant::now();

        let watcher = entry.or_insert_with(|| FileWatcher {
            last_checked: now,
            file_modified: last_modified(file).unwrap_or_else(SystemTime::now),
        });

        watcher.last_checked = now;

        let last_modified = last_modified(file).unwrap_or_else(SystemTime::now);
        last_modified
            .duration_since(watcher.file_modified)
            .map(|time| {
                watcher.file_modified = last_modified;
                time.as_secs_f32() > 0.5
            })
            .unwrap_or(true)
    }

    #[cfg(feature = "derive")]
    pub(crate) mod derive {
        use super::*;

        use crate::Tweakable;
        use crate::hasher::FxHashMap;
        use std::any::Any;
        use std::hash::{Hash, Hasher};
        use std::sync::Mutex;
        use std::time::{Instant, SystemTime};
        use syn::spanned::Spanned;
        use syn::visit::Visit;
        use syn::{
            Attribute, ExprConst, ImplItemFn, ItemConst, ItemFn, ItemStatic, Lit, TraitItemFn, Type,
        };

        struct ParsedFile {
            /// The last time the file was checked for modifications. Avoids too many syscalls.
            last_checked_modified_time: Instant,
            file_modified: SystemTime,
            /// Map of function name to the literal strings
            values: FxHashMap<String, Vec<String>>,
            version: u64,
        }

        /// Stores the values of the tweaks. The key is the file, the function name and the nth tweak
        /// within the function it is derived from.
        static VALUES_DERIVE: LazyLock<Mutex<FxHashMap<DeriveValueKey, TweakValue>>> =
            LazyLock::new(Default::default);

        /// Caches the values of the tweaks before being parsed.
        /// This allows only parsing the updated file once instead of every tweak call.
        static PARSED_DERIVE_VALUES: LazyLock<Mutex<FxHashMap<Filename, ParsedFile>>> =
            LazyLock::new(Default::default);

        #[derive(Debug, Hash, PartialEq, Eq)]
        struct DeriveValueKey {
            filename: Filename,
            nth: u32,
            fname_hash: u64, // Store a hash of the function name to avoid borrowing constraints
        }

        /// Visiter that finds all number/bool/char literals in a function.
        struct LiteralFinder<'a> {
            file: &'a mut ParsedFile,
            inside_derive_fn: Option<String>,
            derive_fn_count: u32,
        }

        impl<'a> LiteralFinder<'a> {
            fn enter_fn(
                &mut self,
                fn_name: String,
                attrs: &[Attribute],
                f: impl FnOnce(&mut Self),
            ) {
                let was_inside_derive_fn = self.inside_derive_fn.take();
                let was_derive_fn_count = self.derive_fn_count;
                if attrs.iter().any(|attr| {
                    attr.path()
                        .segments
                        .last()
                        .map(|seg| seg.ident == "tweak_fn" || seg.ident == "release_tweak_fn")
                        .unwrap_or(false)
                }) {
                    self.inside_derive_fn = Some(fn_name);
                    self.derive_fn_count = 0;
                }
                f(self);
                self.inside_derive_fn = was_inside_derive_fn;
                self.derive_fn_count = was_derive_fn_count;
            }
        }

        impl<'a, 'ast> Visit<'ast> for LiteralFinder<'a> {
            fn visit_impl_item_fn(&mut self, i: &'ast ImplItemFn) {
                self.enter_fn(i.sig.ident.to_string(), &i.attrs, |me| {
                    syn::visit::visit_impl_item_fn(me, i);
                });
            }

            fn visit_item_fn(&mut self, i: &'ast ItemFn) {
                self.enter_fn(i.sig.ident.to_string(), &i.attrs, |me| {
                    syn::visit::visit_item_fn(me, i);
                });
            }

            fn visit_lit(&mut self, l: &'ast Lit) {
                match l {
                    Lit::Char(_) | Lit::Int(_) | Lit::Float(_) | Lit::Bool(_) | Lit::Str(_) => {}
                    _ => return,
                }

                if let Some(ref fn_name) = self.inside_derive_fn {
                    if let Some(mut t) = l.span().source_text() {
                        let newlen = t.trim_end_matches(l.suffix()).len();
                        t.truncate(newlen);
                        if let Some(v) = self.file.values.get_mut(fn_name) {
                            v.push(t);
                        } else {
                            self.file.values.insert(fn_name.clone(), vec![t]);
                        }
                    }
                    self.derive_fn_count += 1;
                }
            }

            fn visit_expr(&mut self, i: &'ast syn::Expr) {
                match i {
                    syn::Expr::Unary(syn::ExprUnary {
                        op: syn::UnOp::Neg(_),
                        expr,
                        ..
                    }) => {
                        if let syn::Expr::Lit(syn::ExprLit {
                            lit: l @ (Lit::Int(_) | Lit::Float(_)),
                            ..
                        }) = &**expr
                        {
                            if let Some(ref fn_name) = self.inside_derive_fn {
                                if let Some(mut t) = i.span().source_text() {
                                    let newlen = t.trim_end_matches(l.suffix()).len();
                                    t.truncate(newlen);
                                    if let Some(v) = self.file.values.get_mut(fn_name) {
                                        v.push(t);
                                    } else {
                                        self.file.values.insert(fn_name.clone(), vec![t]);
                                    }
                                }
                                self.derive_fn_count += 1;
                            }
                        } else {
                            syn::visit::visit_expr(self, i)
                        }
                    }
                    _ => syn::visit::visit_expr(self, i),
                }
            }

            fn visit_trait_item_fn(&mut self, i: &'ast TraitItemFn) {
                self.enter_fn(i.sig.ident.to_string(), &i.attrs, |me| {
                    syn::visit::visit_trait_item_fn(me, i);
                });
            }

            fn visit_attribute(&mut self, _: &Attribute) {}

            fn visit_expr_const(&mut self, _: &ExprConst) {}

            fn visit_item_const(&mut self, _: &ItemConst) {}

            fn visit_item_static(&mut self, _: &ItemStatic) {}

            fn visit_type(&mut self, _: &Type) {}
        }

        fn parse_tweaks_derive<'a>(f: &mut ParsedFile, filename: Filename) -> Option<()> {
            if f.last_checked_modified_time.elapsed() < std::time::Duration::from_millis(500)
                && f.version != 0
            {
                return Some(());
            }

            f.last_checked_modified_time = Instant::now();
            let last_modified = last_modified(filename).unwrap_or_else(SystemTime::now);

            if last_modified == f.file_modified {
                return Some(());
            }
            f.file_modified = last_modified;

            let content = std::fs::read_to_string(filename).ok()?;
            let parsed = syn::parse_file(&content).ok()?;

            f.values.clear();
            LiteralFinder {
                inside_derive_fn: None,
                file: f,
                derive_fn_count: 0,
            }
            .visit_file(&parsed);

            f.version += 1;

            Some(())
        }

        pub(crate) fn get_value_derive<T: Tweakable>(
            filename: Filename,
            function_name: &'static str,
            nth: u32,
        ) -> Option<T> {
            let mut lock = VALUES_DERIVE.lock().unwrap();

            let tweak = lock
                .entry(DeriveValueKey {
                    filename: filename,
                    nth,
                    fname_hash: {
                        let mut hasher = crate::hasher::FxHasher::default();
                        function_name.hash(&mut hasher);
                        hasher.finish()
                    },
                })
                .or_insert_with(|| TweakValue {
                    value: None,
                    last_checked: Instant::now(),
                    file_version: 0,
                });

            if tweak.last_checked.elapsed().as_secs_f32() > 0.5 {
                tweak.last_checked = Instant::now();
                let mut fileinfos = PARSED_DERIVE_VALUES.lock().unwrap();
                let f = fileinfos.entry(filename).or_insert_with(|| ParsedFile {
                    last_checked_modified_time: Instant::now(),
                    file_modified: SystemTime::now(),
                    values: Default::default(),
                    version: 0,
                });

                parse_tweaks_derive(f, filename)?;

                update_tweak_derive::<T>(tweak, function_name, nth, f)?;
            }

            tweak.value.as_ref()?.downcast_ref().cloned()
        }

        fn update_tweak_derive<T: Tweakable>(
            tweak: &mut TweakValue,
            function_name: &'static str,
            nth: u32,
            file: &ParsedFile,
        ) -> Option<()> {
            if tweak.file_version == file.version {
                return Some(());
            }

            let value = &**file.values.get(function_name)?.get(nth as usize)?;

            let parsed: Option<T> = Tweakable::parse(value);

            tweak.value = parsed.map(|inner| Box::new(inner) as Box<dyn Any + Send>);
            tweak.file_version = file.version;

            Some(())
        }
    }
}

#[cfg(all(any(debug_assertions, feature = "release_tweak"), not(target_arch = "wasm32")))]
pub fn inline_tweak<T: Tweakable>(
    initial_value: Option<T>,
    filename: &'static str,
    line: u32,
    column: u32,
) -> Option<T> {
    itweak::get_value(initial_value, filename, line, column)
}

#[cfg(all(feature = "derive", all(any(debug_assertions, feature = "release_tweak"), not(target_arch = "wasm32"))))]
pub fn inline_tweak_derive<T: Tweakable>(
    file: &'static str,
    function_name: &'static str,
    nth: u32,
) -> Option<T> {
    itweak::derive::get_value_derive(file, function_name, nth)
}

#[cfg(all(feature = "release_tweak", not(target_arch = "wasm32")))]
mod macros_release {
    #[macro_export]
    macro_rules! release_tweak {
        ($default:expr) => {
            inline_tweak::inline_tweak(None, std::file!(), std::line!(), std::column!())
                .unwrap_or_else(|| $default)
        };
        ($value:literal; $default:expr) => {
            inline_tweak::inline_tweak(Some($value), std::file!(), std::line!(), std::column!())
                .unwrap_or_else(|| $default)
        };
    }

    #[macro_export]
    macro_rules! derive_release_tweak {
        ($default:expr, $fn_name:expr, $position:expr) => {
            inline_tweak::inline_tweak_derive(std::file!(), $fn_name, $position).unwrap_or($default)
        };
    }
}

#[cfg(all(feature = "release_tweak", target_arch = "wasm32"))]
mod macros_release {
    #[macro_export]
    macro_rules! release_tweak {
        ($default:expr) => {
            $default
        };
        ($value:literal; $default:expr) => {
            $default
        };
    }

    #[macro_export]
    macro_rules! derive_release_tweak {
        ($default:expr, $fn_name:expr, $position:expr) => {
            inline_tweak::inline_tweak_derive(std::file!(), $fn_name, $position)
                .unwrap_or_else(|| $default)
        };
    }
}

#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
mod macros_tweak {
    use crate::itweak;
    #[macro_export]
    macro_rules! tweak {
        ($default:expr) => {
            inline_tweak::inline_tweak(None, std::file!(), std::line!(), std::column!())
                .unwrap_or_else(|| $default)
        };
        ($value:literal; $default:expr) => {
            inline_tweak::inline_tweak(Some($value), std::file!(), std::line!(), std::column!())
                .unwrap_or_else(|| $default)
        };
    }

    #[cfg(feature = "derive")]
    #[doc(hidden)]
    #[macro_export]
    macro_rules! derive_tweak {
        ($default:expr, $fn_name:expr, $position:expr) => {
            inline_tweak::inline_tweak_derive(std::file!(), $fn_name, $position).unwrap_or($default)
        };
    }

    #[cfg(not(feature = "derive"))]
    #[doc(hidden)]
    #[macro_export]
    macro_rules! derive_tweak {
        ($default:expr, $fn_name:expr, $position:expr) => {
            $default
        };
    }

    #[doc(hidden)]
    pub fn watch_file(filename: &'static str) {
        while !itweak::watch_modified(filename) {
            std::thread::sleep(std::time::Duration::from_millis(500));
        }
    }

    #[macro_export]
    macro_rules! watch {
        () => {
            inline_tweak::watch_file(std::file!());
        };
    }
}

#[cfg(any(not(debug_assertions), target_arch = "wasm32"))]
mod macros_tweak {
    #[macro_export]
    macro_rules! tweak {
        ($default:expr) => {
            $default
        };
        ($value:literal; $default:expr) => {
            $default
        };
    }

    #[macro_export]
    #[doc(hidden)]
    macro_rules! derive_tweak {
        ($default:expr, $fn_name:expr, $position:expr) => {
            $default
        };
    }

    #[doc(hidden)]
    pub fn watch_file(_filename: &'static str) {}

    #[macro_export]
    macro_rules! watch {
        () => {};
    }
}

pub use macros_tweak::*;

#[cfg(feature = "derive")]
pub use inline_tweak_derive::*;