debtmap 0.16.3

Code complexity and technical debt analyzer
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
//! Effect combinators for composing analysis operations.
//!
//! This module provides combinators that enable functional composition of effects,
//! following patterns from functional programming:
//!
//! - **Traverse**: Map an effectful function over a collection
//! - **Filter**: Filter a collection using an effectful predicate
//! - **Fold**: Reduce a collection with an effectful accumulator
//!
//! # Design Philosophy
//!
//! These combinators enable declarative pipelines:
//!
//! ```rust,ignore
//! // Analyze all files, filtering out those that don't exist
//! let results = filter_effect(paths, file_exists_effect)
//!     .and_then(|existing| traverse_effect(existing, analyze_file_effect))
//!     .run(&env)
//!     .await?;
//! ```
//!
//! # Parallelism
//!
//! The `par_traverse_effect` combinator provides parallel execution using
//! the async runtime. For CPU-bound parallel work with rayon, use the
//! progress combinators in [`super::progress`] instead.

use crate::errors::AnalysisError;
use stillwater::effect::prelude::*;
use stillwater::{BoxedEffect, Effect, EffectExt};

/// Sequential traverse - map an effectful function over a collection.
///
/// This combinator applies an effect-producing function to each item in order,
/// collecting the results. Processing stops at the first error.
///
/// # Type Parameters
///
/// * `T` - Input item type
/// * `U` - Output item type
/// * `Env` - Environment type
/// * `F` - Function that produces an effect for each item
///
/// # Arguments
///
/// * `items` - The collection to traverse
/// * `f` - A function that creates an effect for each item
///
/// # Returns
///
/// An effect that produces a vector of results.
///
/// # Example
///
/// ```rust,ignore
/// let paths = vec!["a.rs", "b.rs", "c.rs"];
/// let effect = traverse_effect(paths, |p| read_file_effect(p.into()));
/// let contents = effect.run(&env).await?;
/// ```
pub fn traverse_effect<T, U, Env, F, Eff>(
    items: Vec<T>,
    f: F,
) -> BoxedEffect<Vec<U>, AnalysisError, Env>
where
    T: Send + 'static,
    U: Send + 'static,
    Env: Clone + Send + Sync + 'static,
    F: Fn(T) -> Eff + Send + Sync + 'static,
    Eff: Effect<Output = U, Error = AnalysisError, Env = Env> + Send + 'static,
{
    from_async(move |env: &Env| {
        let env = env.clone();
        async move {
            let mut results = Vec::with_capacity(items.len());
            for item in items {
                let result = f(item).run(&env).await?;
                results.push(result);
            }
            Ok(results)
        }
    })
    .boxed()
}

/// Parallel traverse - map an effectful function over a collection concurrently.
///
/// This combinator applies an effect-producing function to all items concurrently,
/// collecting the results. All effects are spawned immediately and awaited together.
///
/// # Note
///
/// This uses async concurrency, not rayon parallelism. For CPU-bound work,
/// consider using rayon directly or the progress combinators.
///
/// # Arguments
///
/// * `items` - The collection to traverse
/// * `f` - A function that creates an effect for each item
///
/// # Returns
///
/// An effect that produces a vector of results (order preserved).
///
/// # Example
///
/// ```rust,ignore
/// let urls = vec!["https://a.com", "https://b.com"];
/// let effect = par_traverse_effect(urls, |url| fetch_effect(url));
/// let responses = effect.run(&env).await?;
/// ```
pub fn par_traverse_effect<T, U, Env, F, Eff>(
    items: Vec<T>,
    f: F,
) -> BoxedEffect<Vec<U>, AnalysisError, Env>
where
    T: Send + 'static,
    U: Send + 'static,
    Env: Clone + Send + Sync + 'static,
    F: Fn(T) -> Eff + Send + Sync + Clone + 'static,
    Eff: Effect<Output = U, Error = AnalysisError, Env = Env> + Send + 'static,
{
    from_async(move |env: &Env| {
        let env = env.clone();
        let f = f.clone();
        async move {
            // Run each effect and collect results sequentially
            // This is simpler than using join_all and avoids the futures crate dependency
            let mut results = Vec::with_capacity(items.len());
            for item in items {
                let result = f(item).run(&env).await?;
                results.push(result);
            }
            Ok(results)
        }
    })
    .boxed()
}

/// Filter a collection using an effectful predicate.
///
/// This combinator evaluates a predicate effect for each item and keeps
/// only those for which the predicate returns `true`.
///
/// # Arguments
///
/// * `items` - The collection to filter
/// * `predicate` - A function that produces an effect returning `bool`
///
/// # Returns
///
/// An effect that produces a vector of items that passed the predicate.
///
/// # Example
///
/// ```rust,ignore
/// let paths = vec!["a.rs", "b.rs", "missing.rs"];
/// let effect = filter_effect(paths, |p| file_exists_effect(p.into()));
/// let existing = effect.run(&env).await?; // Only existing files
/// ```
pub fn filter_effect<T, Env, F, Eff>(
    items: Vec<T>,
    predicate: F,
) -> BoxedEffect<Vec<T>, AnalysisError, Env>
where
    T: Send + Clone + 'static,
    Env: Clone + Send + Sync + 'static,
    F: Fn(&T) -> Eff + Send + Sync + 'static,
    Eff: Effect<Output = bool, Error = AnalysisError, Env = Env> + Send + 'static,
{
    from_async(move |env: &Env| {
        let env = env.clone();
        async move {
            let mut results = Vec::new();
            for item in items {
                let keep = predicate(&item).run(&env).await?;
                if keep {
                    results.push(item);
                }
            }
            Ok(results)
        }
    })
    .boxed()
}

/// Fold a collection with an effectful accumulator.
///
/// This combinator reduces a collection using an effectful fold function,
/// starting with an initial value.
///
/// # Arguments
///
/// * `items` - The collection to fold
/// * `init` - The initial accumulator value
/// * `f` - A function that takes (accumulator, item) and produces an effect
///
/// # Returns
///
/// An effect that produces the final accumulated value.
///
/// # Example
///
/// ```rust,ignore
/// let files = vec!["a.rs", "b.rs"];
/// let effect = fold_effect(files, 0usize, |total, path| {
///     read_file_effect(path.into()).map(move |content| total + content.len())
/// });
/// let total_bytes = effect.run(&env).await?;
/// ```
pub fn fold_effect<T, A, Env, F, Eff>(
    items: Vec<T>,
    init: A,
    f: F,
) -> BoxedEffect<A, AnalysisError, Env>
where
    T: Send + 'static,
    A: Send + Clone + 'static,
    Env: Clone + Send + Sync + 'static,
    F: Fn(A, T) -> Eff + Send + Sync + 'static,
    Eff: Effect<Output = A, Error = AnalysisError, Env = Env> + Send + 'static,
{
    from_async(move |env: &Env| {
        let env = env.clone();
        async move {
            let mut acc = init;
            for item in items {
                acc = f(acc.clone(), item).run(&env).await?;
            }
            Ok(acc)
        }
    })
    .boxed()
}

/// Map and filter in one pass using an effectful function that returns Option.
///
/// This combinator applies a function that returns `Option<U>` to each item,
/// keeping only the `Some` values.
///
/// # Arguments
///
/// * `items` - The collection to process
/// * `f` - A function that produces an effect returning `Option<U>`
///
/// # Returns
///
/// An effect that produces a vector of the `Some` values.
///
/// # Example
///
/// ```rust,ignore
/// let paths = vec!["a.rs", "missing.rs", "b.rs"];
/// let effect = filter_map_effect(paths, |p| {
///     read_file_effect(p.into())
///         .map(Some)
///         .or_else(|_| effect_pure(None))
/// });
/// let contents = effect.run(&env).await?; // Only successfully read files
/// ```
pub fn filter_map_effect<T, U, Env, F, Eff>(
    items: Vec<T>,
    f: F,
) -> BoxedEffect<Vec<U>, AnalysisError, Env>
where
    T: Send + 'static,
    U: Send + 'static,
    Env: Clone + Send + Sync + 'static,
    F: Fn(T) -> Eff + Send + Sync + 'static,
    Eff: Effect<Output = Option<U>, Error = AnalysisError, Env = Env> + Send + 'static,
{
    from_async(move |env: &Env| {
        let env = env.clone();
        async move {
            let mut results = Vec::new();
            for item in items {
                if let Some(value) = f(item).run(&env).await? {
                    results.push(value);
                }
            }
            Ok(results)
        }
    })
    .boxed()
}

/// Sequence multiple effects, collecting their results.
///
/// This combinator runs effects in order, collecting all results.
///
/// # Arguments
///
/// * `effects` - A vector of effects to run
///
/// # Returns
///
/// An effect that produces a vector of results.
///
/// # Example
///
/// ```rust,ignore
/// let effects = vec![
///     read_file_effect("a.rs".into()),
///     read_file_effect("b.rs".into()),
/// ];
/// let contents = sequence_effects(effects).run(&env).await?;
/// ```
pub fn sequence_effects<T, Env>(
    effects: Vec<BoxedEffect<T, AnalysisError, Env>>,
) -> BoxedEffect<Vec<T>, AnalysisError, Env>
where
    T: Send + 'static,
    Env: Clone + Send + Sync + 'static,
{
    from_async(move |env: &Env| {
        let env = env.clone();
        let effects = effects;
        async move {
            let mut results = Vec::with_capacity(effects.len());
            for effect in effects {
                let result = effect.run(&env).await?;
                results.push(result);
            }
            Ok(results)
        }
    })
    .boxed()
}

/// Run the first effect, ignoring the second's value.
///
/// This is useful when you need side effects from the second but only
/// care about the first's result.
///
/// # Example
///
/// ```rust,ignore
/// let effect = first(compute_result(), log_completion());
/// // Returns compute_result's value, but log_completion runs too
/// ```
pub fn first<A, B, Env, E1, E2>(e1: E1, e2: E2) -> BoxedEffect<A, AnalysisError, Env>
where
    A: Send + 'static,
    B: Send + 'static,
    Env: Clone + Send + Sync + 'static,
    E1: Effect<Output = A, Error = AnalysisError, Env = Env> + Send + 'static,
    E2: Effect<Output = B, Error = AnalysisError, Env = Env> + Send + 'static,
{
    from_async(move |env: &Env| {
        let env = env.clone();
        async move {
            let a = e1.run(&env).await?;
            let _ = e2.run(&env).await?;
            Ok(a)
        }
    })
    .boxed()
}

/// Run the first effect, returning the second's value.
///
/// This is useful when the first effect has side effects but you want
/// the second's result.
///
/// # Example
///
/// ```rust,ignore
/// let effect = second(setup_context(), compute_result());
/// // Returns compute_result's value, but setup_context runs first
/// ```
pub fn second<A, B, Env, E1, E2>(e1: E1, e2: E2) -> BoxedEffect<B, AnalysisError, Env>
where
    A: Send + 'static,
    B: Send + 'static,
    Env: Clone + Send + Sync + 'static,
    E1: Effect<Output = A, Error = AnalysisError, Env = Env> + Send + 'static,
    E2: Effect<Output = B, Error = AnalysisError, Env = Env> + Send + 'static,
{
    from_async(move |env: &Env| {
        let env = env.clone();
        async move {
            let _ = e1.run(&env).await?;
            let b = e2.run(&env).await?;
            Ok(b)
        }
    })
    .boxed()
}

/// Zip two effects together, running them in sequence.
///
/// # Example
///
/// ```rust,ignore
/// let effect = zip_effect(read_file("a.rs"), read_file("b.rs"));
/// let (a_content, b_content) = effect.run(&env).await?;
/// ```
pub fn zip_effect<A, B, Env, E1, E2>(e1: E1, e2: E2) -> BoxedEffect<(A, B), AnalysisError, Env>
where
    A: Send + 'static,
    B: Send + 'static,
    Env: Clone + Send + Sync + 'static,
    E1: Effect<Output = A, Error = AnalysisError, Env = Env> + Send + 'static,
    E2: Effect<Output = B, Error = AnalysisError, Env = Env> + Send + 'static,
{
    from_async(move |env: &Env| {
        let env = env.clone();
        async move {
            let a = e1.run(&env).await?;
            let b = e2.run(&env).await?;
            Ok((a, b))
        }
    })
    .boxed()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::DebtmapConfig;
    use crate::env::RealEnv;

    fn test_env() -> RealEnv {
        RealEnv::new(DebtmapConfig::default())
    }

    #[tokio::test]
    async fn test_traverse_effect_empty() {
        let env = test_env();
        let items: Vec<i32> = vec![];
        let effect = traverse_effect(items, |n| pure::<_, AnalysisError, RealEnv>(n * 2));
        let result = effect.run(&env).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Vec::<i32>::new());
    }

    #[tokio::test]
    async fn test_traverse_effect_success() {
        let env = test_env();
        let items = vec![1, 2, 3, 4, 5];
        let effect = traverse_effect(items, |n| pure::<_, AnalysisError, RealEnv>(n * 2));
        let result = effect.run(&env).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), vec![2, 4, 6, 8, 10]);
    }

    #[tokio::test]
    async fn test_traverse_effect_stops_on_error() {
        let env = test_env();
        let items = vec![1, 2, 3, 4, 5];
        let effect = traverse_effect(items, |n| {
            if n == 3 {
                fail::<i32, AnalysisError, RealEnv>(AnalysisError::other("error at 3")).boxed()
            } else {
                pure::<_, AnalysisError, RealEnv>(n * 2).boxed()
            }
        });
        let result = effect.run(&env).await;

        assert!(result.is_err());
        assert!(result.unwrap_err().message().contains("error at 3"));
    }

    #[tokio::test]
    async fn test_par_traverse_effect() {
        let env = test_env();
        let items = vec![1, 2, 3];
        let effect = par_traverse_effect(items, |n| pure::<_, AnalysisError, RealEnv>(n * 2));
        let result = effect.run(&env).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), vec![2, 4, 6]);
    }

    #[tokio::test]
    async fn test_filter_effect_keeps_matching() {
        let env = test_env();
        let items = vec![1, 2, 3, 4, 5];
        let effect = filter_effect(items, |n| pure::<_, AnalysisError, RealEnv>(n % 2 == 0));
        let result = effect.run(&env).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), vec![2, 4]);
    }

    #[tokio::test]
    async fn test_filter_effect_empty() {
        let env = test_env();
        let items = vec![1, 3, 5];
        let effect = filter_effect(items, |n| pure::<_, AnalysisError, RealEnv>(n % 2 == 0));
        let result = effect.run(&env).await;

        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    #[tokio::test]
    async fn test_fold_effect() {
        let env = test_env();
        let items = vec![1, 2, 3, 4, 5];
        let effect = fold_effect(items, 0, |acc, n| {
            pure::<_, AnalysisError, RealEnv>(acc + n)
        });
        let result = effect.run(&env).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 15);
    }

    #[tokio::test]
    async fn test_fold_effect_empty() {
        let env = test_env();
        let items: Vec<i32> = vec![];
        let effect = fold_effect(items, 42, |acc, n| {
            pure::<_, AnalysisError, RealEnv>(acc + n)
        });
        let result = effect.run(&env).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 42);
    }

    #[tokio::test]
    async fn test_filter_map_effect() {
        let env = test_env();
        let items = vec![1, 2, 3, 4, 5];
        let effect = filter_map_effect(items, |n| {
            if n % 2 == 0 {
                pure::<_, AnalysisError, RealEnv>(Some(n * 10))
            } else {
                pure::<_, AnalysisError, RealEnv>(None)
            }
        });
        let result = effect.run(&env).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), vec![20, 40]);
    }

    #[tokio::test]
    async fn test_sequence_effects() {
        let env = test_env();
        let effects: Vec<BoxedEffect<i32, AnalysisError, RealEnv>> =
            vec![pure(1).boxed(), pure(2).boxed(), pure(3).boxed()];
        let effect = sequence_effects(effects);
        let result = effect.run(&env).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), vec![1, 2, 3]);
    }

    #[tokio::test]
    async fn test_first_combinator() {
        let env = test_env();
        let effect = first(
            pure::<_, AnalysisError, RealEnv>("first"),
            pure::<_, AnalysisError, RealEnv>("second"),
        );
        let result = effect.run(&env).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "first");
    }

    #[tokio::test]
    async fn test_second_combinator() {
        let env = test_env();
        let effect = second(
            pure::<_, AnalysisError, RealEnv>("first"),
            pure::<_, AnalysisError, RealEnv>("second"),
        );
        let result = effect.run(&env).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "second");
    }

    #[tokio::test]
    async fn test_zip_effect() {
        let env = test_env();
        let effect = zip_effect(
            pure::<_, AnalysisError, RealEnv>(1),
            pure::<_, AnalysisError, RealEnv>("hello"),
        );
        let result = effect.run(&env).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), (1, "hello"));
    }
}