bashexpand 0.1.1

Bash-style parameter expansion (${var:-default}, ${var@L}, ${var##pat}, ...) over any variable source: maps, closures, the environment, or your own backend.
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
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
//! Bash-style parameter expansion over **any** variable source.
//!
//! `bashexpand` implements the familiar `${...}` expansion syntax from bash,
//! including the advanced operators (`${var:-default}`, `${var@L}`,
//! `${var##*/}`, `${var/pat/repl}`, ...), but lets *you* decide where
//! variables come from: a `HashMap`, a closure, the process environment, a
//! config store, a database — anything that implements the small [`Context`]
//! trait.
//!
//! # Quick start
//!
//! ```
//! use bashexpand::expand;
//! use std::collections::HashMap;
//!
//! let mut vars = HashMap::from([
//!     ("name".to_string(), "world".to_string()),
//!     ("path".to_string(), "/usr/local/bin/tool.tar.gz".to_string()),
//! ]);
//!
//! assert_eq!(expand("Hello, ${name^}!", &mut vars).unwrap(), "Hello, World!");
//! assert_eq!(expand("${path##*/}", &mut vars).unwrap(), "tool.tar.gz");
//! assert_eq!(expand("${missing:-fallback}", &mut vars).unwrap(), "fallback");
//! ```
//!
//! Or with an inline closure — no map required:
//!
//! ```
//! use bashexpand::expand;
//!
//! let mut ctx = |name: &str| match name {
//!     "user" => Some("alice".to_string()),
//!     "host" => Some("example.com".to_string()),
//!     _ => None,
//! };
//! assert_eq!(expand("${user}@${host}", &mut ctx).unwrap(), "alice@example.com");
//! assert_eq!(expand("${port:-22}", &mut ctx).unwrap(), "22");
//! ```
//!
//! # Supported syntax
//!
//! | Syntax | Meaning |
//! |---|---|
//! | `$var`, `${var}` | plain expansion (unset expands to `""`) |
//! | `${var:-word}` / `${var-word}` | default if unset-or-empty / if unset |
//! | `${var:=word}` / `${var=word}` | like `:-`, but also assigns (needs a writable context) |
//! | `${var:+word}` / `${var+word}` | `word` if set, else `""` |
//! | `${var:?msg}` / `${var?msg}` | error ([`Error::Required`]) if unset |
//! | `${#var}` | length in characters |
//! | `${!var}` | indirection: expand the variable *named by* `var` |
//! | `${var:off}` / `${var:off:len}` | substring; negative offsets/lengths count from the end |
//! | `${var#pat}` / `${var##pat}` | remove shortest/longest matching prefix (glob) |
//! | `${var%pat}` / `${var%%pat}` | remove shortest/longest matching suffix (glob) |
//! | `${var/pat/repl}` | replace first match |
//! | `${var//pat/repl}` | replace all matches |
//! | `${var/#pat/repl}` / `${var/%pat/repl}` | replace anchored prefix / suffix match |
//! | `${var^}` / `${var^^}` | uppercase first char / all chars (optional glob: `${var^^[ab]}`) |
//! | `${var,}` / `${var,,}` | lowercase first char / all chars |
//! | `${var@U}` `@u` `@L` | uppercase / capitalize / lowercase |
//! | `${var@Q}` | shell-quote the value |
//! | `${var@E}` | interpret `\n`, `\t`, `\r`, `\0`, `\\` escapes |
//! | `\$` | a literal dollar sign |
//!
//! Globs support `*`, `?`, `[a-z]`, `[!a-z]` and `\x` escapes. Words inside
//! operators are themselves expanded, so `${a:-${b:-c}}` works.
//!
//! Variable names are `_` and alphanumerics and may start with a digit:
//! `$1` / `${1}` look up the variable named `1` in the context, just as bash
//! reads its positional parameters. Like bash ("cannot assign in this way"),
//! assigning to such a name (`${1=x}`, `${1:=x}`) is an error —
//! [`Error::AssignUnsupported`].
//!
//! **Non-goals** (kept out deliberately; reach for a full shell like
//! [`brush`](https://github.com/reubeno/brush) if you need them): arrays,
//! positional/special parameter semantics (`$@`, `$?`), command substitution,
//! arithmetic expansion, extglobs `@(...)`, POSIX classes `[[:alpha:]]`, and
//! the `@P/@A/@K/@a` transforms.
//!
//! # Choosing a context
//!
//! | You have... | Use |
//! |---|---|
//! | `HashMap<String, String>` / `BTreeMap<String, String>` | pass `&mut map` directly (writable: `:=` works) |
//! | only a shared `&map` | pass `&mut &map` (read-only: `:=` errors) |
//! | a lookup function | pass `&mut` closure `FnMut(&str) -> Option<String>` (read-only) |
//! | process environment | [`Env`] |
//! | a fallible backend (DB, RPC, files) | [`TryFn`] or implement [`Context`] |
//! | several sources with priority | [`ContextExt::chain`] |
//! | custom needs (case-insensitive names, prefixes, ...) | implement [`Context`] (two methods, one optional) |
//!
//! # Recipes
//!
//! **Environment variables with defaults** — nested fallbacks work anywhere a
//! word does:
//!
//! ```
//! use bashexpand::{expand, Env};
//!
//! let editor = expand("${EDITOR:-${VISUAL:-vi}}", &mut Env).unwrap();
//! assert!(!editor.is_empty());
//! ```
//!
//! **Layered lookup** — CLI overrides beat environment beat defaults; first
//! hit wins and chains nest:
//!
//! ```
//! use bashexpand::{expand, ContextExt};
//! use std::collections::HashMap;
//!
//! let cli = HashMap::from([("PORT".to_string(), "9999".to_string())]);
//! let defaults = HashMap::from([
//!     ("PORT".to_string(), "8080".to_string()),
//!     ("HOST".to_string(), "0.0.0.0".to_string()),
//! ]);
//!
//! let mut ctx = cli.chain(defaults);
//! assert_eq!(expand("${HOST}:${PORT}", &mut ctx).unwrap(), "0.0.0.0:9999");
//! ```
//!
//! **Path one-liners** — the classic bash idioms all work:
//!
//! ```
//! use bashexpand::expand;
//! use std::collections::HashMap;
//!
//! let mut v = HashMap::from([("f".to_string(), "/opt/app/logs/app.tar.gz".to_string())]);
//!
//! assert_eq!(expand("${f##*/}", &mut v).unwrap(), "app.tar.gz");             // basename
//! assert_eq!(expand("${f%/*}", &mut v).unwrap(), "/opt/app/logs");           // dirname
//! assert_eq!(expand("${f##*.}", &mut v).unwrap(), "gz");                     // extension
//! assert_eq!(expand("${f%.*}", &mut v).unwrap(), "/opt/app/logs/app.tar");   // strip extension
//! assert_eq!(expand("${f%.gz}.xz", &mut v).unwrap(), "/opt/app/logs/app.tar.xz"); // swap extension
//! ```
//!
//! **Hard-required variables** — turn missing configuration into a typed
//! error with your own message:
//!
//! ```
//! use bashexpand::{expand, Error};
//! use std::collections::HashMap;
//!
//! let mut vars: HashMap<String, String> = HashMap::new();
//! match expand("data = ${DATA_DIR:?DATA_DIR is required}", &mut vars) {
//!     Err(Error::Required { var, message }) => {
//!         assert_eq!(var, "DATA_DIR");
//!         assert_eq!(message, "DATA_DIR is required");
//!     }
//!     other => panic!("expected Error::Required, got {other:?}"),
//! }
//! ```
//!
//! **Read-only expansion over a shared `&map`** — no clone, and assignment
//! (`:=`) is a hard error instead of a silent mutation:
//!
//! ```
//! use bashexpand::{expand, Error};
//! use std::collections::HashMap;
//!
//! let vars = HashMap::from([("host".to_string(), "example.com".to_string())]);
//!
//! assert_eq!(expand("${host}", &mut &vars).unwrap(), "example.com");
//! assert!(matches!(
//!     expand("${port:=8080}", &mut &vars),
//!     Err(Error::AssignUnsupported { .. })
//! ));
//! ```
//!
//! **Fallible backends** (databases, RPC, files) — lookup failures surface as
//! [`Error::Context`], never as "unset":
//!
//! ```
//! use bashexpand::{expand, Error, TryFn};
//!
//! fn read_secret(name: &str) -> Result<Option<String>, std::io::Error> {
//!     match name {
//!         "DB_PASSWORD" => Ok(Some("hunter2".to_string())),
//!         _ => Err(std::io::Error::new(std::io::ErrorKind::NotFound, name.to_string())),
//!     }
//! }
//!
//! let mut ctx = TryFn(read_secret);
//! assert_eq!(expand("pw=${DB_PASSWORD}", &mut ctx).unwrap(), "pw=hunter2");
//! assert!(matches!(expand("${MISSING}", &mut ctx), Err(Error::Context(_))));
//! ```
//!
//! **Untrusted templates** — glob matching is already linear-time and there
//! is no command substitution; tighten the nesting limit and hostile inputs
//! fail fast:
//!
//! ```
//! use bashexpand::{Error, Expander};
//! use std::collections::HashMap;
//!
//! let mut vars: HashMap<String, String> = HashMap::new();
//! let expander = Expander::new().max_depth(4);
//!
//! assert_eq!(expander.expand("${a:-${b:-ok}}", &mut vars).unwrap(), "ok");
//! let hostile = "${a:-${a:-${a:-${a:-${a:-x}}}}}";
//! assert_eq!(expander.expand(hostile, &mut vars), Err(Error::TooDeep));
//! ```
//!
//! # Error handling
//!
//! [`expand`] returns [`Error<E>`] where `E` is the context's own error type.
//! Contexts that cannot fail use [`Infallible`],
//! and you can `.unwrap()`-free convert with `?` in functions returning your
//! error type. `${var:?}`, malformed input, assignment to read-only contexts,
//! and over-deep nesting are all distinct variants — nothing is silently
//! swallowed.
//!
//! # Safety & robustness
//!
//! - Glob matching is compiled and iterative — `O(pattern × text)`, immune to
//!   the exponential blow-up of naive backtracking (`a*a*a*a*b`).
//! - Recursive expansions are depth-limited (configurable via
//!   [`Expander::max_depth`]) to prevent stack exhaustion on adversarial
//!   input.
//! - All operations are `char`-based, so Unicode values behave correctly.
//! - No dependencies, no `unsafe`.

#![forbid(unsafe_code)]
#![warn(missing_docs)]

// Compile and run the README's code samples as doctests (V19), so the README
// cannot drift from the implementation. Exists only under `cargo test --doc`.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
pub struct ReadmeDoctests;

use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::convert::Infallible;
use std::fmt;

/// Default maximum nesting depth of recursive expansions (`${a:-${b:-...}}`).
///
/// Override per call with [`Expander::max_depth`].
pub const DEFAULT_MAX_DEPTH: usize = 64;

// ---------------------------------------------------------------------------
// Context abstraction
// ---------------------------------------------------------------------------

/// A source of variables.
///
/// Implementations are provided for:
///
/// - `HashMap<String, String>` and `BTreeMap<String, String>` — writable,
///   so `${var:=default}` stores the default back into the map;
/// - `&HashMap<String, String>` and `&BTreeMap<String, String>` — read-only
///   views for when you only hold a shared borrow;
/// - any `FnMut(&str) -> Option<String>` closure — read-only;
/// - [`Env`] — the process environment, read-only;
/// - [`TryFn`] — a fallible closure returning `Result<Option<String>, E>`;
/// - [`Chain`] — two contexts layered with fallback (see
///   [`ContextExt::chain`]).
///
/// # Implementing your own
///
/// ```
/// use bashexpand::{expand, Context};
/// use std::borrow::Cow;
/// use std::convert::Infallible;
///
/// /// Case-insensitive variable names.
/// struct CaseInsensitive(std::collections::HashMap<String, String>);
///
/// impl Context for CaseInsensitive {
///     type Error = Infallible;
///
///     fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Infallible> {
///         let key = name.to_lowercase();
///         Ok(self.0.get(&key).map(|v| Cow::Borrowed(v.as_str())))
///     }
///
///     fn set(&mut self, name: &str, value: &str) -> Result<bool, Infallible> {
///         self.0.insert(name.to_lowercase(), value.to_string());
///         Ok(true) // writable: `${var:=default}` is allowed
///     }
/// }
///
/// let map = std::collections::HashMap::from([("home".to_string(), "/root".to_string())]);
/// let mut ctx = CaseInsensitive(map);
/// assert_eq!(expand("${HOME} ${Home} ${home}", &mut ctx).unwrap(), "/root /root /root");
/// ```
pub trait Context {
    /// Error produced by lookups/assignments.
    ///
    /// Use [`Infallible`] if lookups cannot fail; the expander then only
    /// returns its own error variants.
    type Error;

    /// Return the value of `name`, or `Ok(None)` if the variable is unset.
    ///
    /// Returning `Cow::Borrowed` avoids an allocation when the value lives in
    /// the context (as the map implementations do); return `Cow::Owned` when
    /// the value is computed on the fly.
    fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Self::Error>;

    /// Store a value. Only called by `${var:=word}` / `${var=word}`.
    ///
    /// Return `Ok(true)` if the value was stored, `Ok(false)` if this context
    /// is read-only — the expander then reports [`Error::AssignUnsupported`]
    /// instead of silently continuing. The default implementation is
    /// read-only.
    fn set(&mut self, _name: &str, _value: &str) -> Result<bool, Self::Error> {
        Ok(false)
    }
}

impl Context for HashMap<String, String> {
    type Error = Infallible;
    fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Infallible> {
        Ok(HashMap::get(self, name).map(|v| Cow::Borrowed(v.as_str())))
    }
    fn set(&mut self, name: &str, value: &str) -> Result<bool, Infallible> {
        self.insert(name.to_string(), value.to_string());
        Ok(true)
    }
}

impl Context for BTreeMap<String, String> {
    type Error = Infallible;
    fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Infallible> {
        Ok(BTreeMap::get(self, name).map(|v| Cow::Borrowed(v.as_str())))
    }
    fn set(&mut self, name: &str, value: &str) -> Result<bool, Infallible> {
        self.insert(name.to_string(), value.to_string());
        Ok(true)
    }
}

/// Read-only view: a shared reference to a map is itself a [`Context`].
///
/// Use this when you only hold a shared borrow of the map, or to guarantee
/// the expansion cannot modify it; `${var:=default}` yields
/// [`Error::AssignUnsupported`].
///
/// ```
/// use bashexpand::expand;
/// use std::collections::HashMap;
///
/// let vars = HashMap::from([("name".to_string(), "world".to_string())]);
/// assert_eq!(expand("Hello, ${name}!", &mut &vars).unwrap(), "Hello, world!");
/// ```
impl Context for &HashMap<String, String> {
    type Error = Infallible;
    fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Infallible> {
        Ok((**self).get(name).map(|v| Cow::Borrowed(v.as_str())))
    }
}

/// Read-only view: a shared reference to a map is itself a [`Context`].
///
/// See the [`&HashMap` impl](Context#impl-Context-for-%26HashMap<String,+String>)
/// for details.
impl Context for &BTreeMap<String, String> {
    type Error = Infallible;
    fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Infallible> {
        Ok((**self).get(name).map(|v| Cow::Borrowed(v.as_str())))
    }
}

/// Any `FnMut(&str) -> Option<String>` closure is a read-only [`Context`].
///
/// ```
/// use bashexpand::expand;
///
/// // Tip: annotate the argument type so inference picks `&str`.
/// let mut ctx = |name: &str| (name == "who").then(|| "world".to_string());
/// assert_eq!(expand("hello ${who}", &mut ctx).unwrap(), "hello world");
/// ```
impl<F: FnMut(&str) -> Option<String>> Context for F {
    type Error = Infallible;
    fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Infallible> {
        Ok(self(name).map(Cow::Owned))
    }
}

/// Read-only [`Context`] backed by the process environment
/// ([`std::env::var`]).
///
/// ```no_run
/// use bashexpand::{expand, Env};
///
/// let cmd = expand("${EDITOR:-vi} ${HOME}/notes.txt", &mut Env).unwrap();
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct Env;

impl Context for Env {
    type Error = Infallible;
    fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Infallible> {
        Ok(std::env::var(name).ok().map(Cow::Owned))
    }
}

/// Adapter turning a **fallible** closure into a [`Context`].
///
/// Use this when lookups can genuinely fail (I/O, RPC, poisoned locks, ...)
/// and you want the failure surfaced as [`Error::Context`] rather than
/// treated as "unset".
///
/// ```
/// use bashexpand::{expand, Error, TryFn};
///
/// let mut ctx = TryFn(|name: &str| -> Result<Option<String>, String> {
///     match name {
///         "ok" => Ok(Some("value".to_string())),
///         "missing" => Ok(None),
///         other => Err(format!("backend error fetching {other}")),
///     }
/// });
///
/// assert_eq!(expand("${ok}", &mut ctx).unwrap(), "value");
/// assert_eq!(expand("${missing:-d}", &mut ctx).unwrap(), "d");
/// assert!(matches!(expand("${boom}", &mut ctx), Err(Error::Context(_))));
/// ```
#[derive(Debug, Clone)]
pub struct TryFn<F>(pub F);

impl<F, E> Context for TryFn<F>
where
    F: FnMut(&str) -> Result<Option<String>, E>,
{
    type Error = E;
    fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, E> {
        Ok((self.0)(name)?.map(Cow::Owned))
    }
}

/// Two contexts layered with fallback; created by [`ContextExt::chain`].
///
/// Lookups try the first context, then the second. Assignments
/// (`${var:=word}`) go to the first writable context.
#[derive(Debug, Clone)]
pub struct Chain<A, B>(A, B);

impl<A, B> Context for Chain<A, B>
where
    A: Context,
    B: Context<Error = A::Error>,
{
    type Error = A::Error;

    fn get(&mut self, name: &str) -> Result<Option<Cow<'_, str>>, Self::Error> {
        match self.0.get(name)? {
            Some(v) => Ok(Some(Cow::Owned(v.into_owned()))),
            None => Ok(self.1.get(name)?.map(|v| Cow::Owned(v.into_owned()))),
        }
    }

    fn set(&mut self, name: &str, value: &str) -> Result<bool, Self::Error> {
        if self.0.set(name, value)? {
            return Ok(true);
        }
        self.1.set(name, value)
    }
}

/// Extension methods for every [`Context`].
pub trait ContextExt: Context + Sized {
    /// Layer `self` over `fallback`: lookups try `self` first, then
    /// `fallback`. Perfect for "overrides beat environment beat defaults":
    ///
    /// ```
    /// use bashexpand::{expand, ContextExt};
    /// use std::collections::HashMap;
    ///
    /// let overrides = HashMap::from([("port".to_string(), "8080".to_string())]);
    /// let defaults = HashMap::from([
    ///     ("port".to_string(), "80".to_string()),
    ///     ("host".to_string(), "localhost".to_string()),
    /// ]);
    ///
    /// let mut ctx = overrides.chain(defaults);
    /// assert_eq!(expand("${host}:${port}", &mut ctx).unwrap(), "localhost:8080");
    /// ```
    ///
    /// Both contexts must share the same `Error` type. Chains nest:
    /// `a.chain(b).chain(c)`.
    fn chain<B: Context<Error = Self::Error>>(self, fallback: B) -> Chain<Self, B> {
        Chain(self, fallback)
    }
}

impl<C: Context + Sized> ContextExt for C {}

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// Everything that can go wrong during expansion.
///
/// `E` is the [`Context::Error`] of the context in use; for infallible
/// contexts it is [`Infallible`] and the [`Error::Context`] variant can never
/// be constructed.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Error<E> {
    /// `${var:?message}` fired because the variable was unset (or empty, with
    /// the `:` form).
    Required {
        /// The variable that was required.
        var: String,
        /// The (already expanded) message after `?`; may be empty.
        message: String,
    },
    /// Malformed expansion: unterminated `${`, an unknown operator, an
    /// invalid substring specification, or an unknown `@` transform.
    BadSubstitution(String),
    /// `${var:=word}` was used with a read-only context.
    AssignUnsupported {
        /// The variable that could not be assigned.
        var: String,
    },
    /// Expansions nested deeper than the configured limit
    /// (see [`Expander::max_depth`]).
    TooDeep,
    /// The context itself failed; carries the context's own error.
    Context(E),
}

impl<E: fmt::Display> fmt::Display for Error<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Required { var, message } if message.is_empty() => {
                write!(f, "{var}: parameter null or not set")
            }
            Error::Required { var, message } => write!(f, "{var}: {message}"),
            Error::BadSubstitution(s) => write!(f, "bad substitution: ${{{s}}}"),
            Error::AssignUnsupported { var } => {
                write!(f, "{var}: assignment not supported by this context")
            }
            Error::TooDeep => write!(f, "expansion nested too deeply"),
            Error::Context(e) => write!(f, "variable lookup failed: {e}"),
        }
    }
}

impl<E: fmt::Debug + fmt::Display> std::error::Error for Error<E> {}

impl<E> From<E> for Error<E> {
    fn from(e: E) -> Self {
        Error::Context(e)
    }
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Expand all `$var` / `${...}` expressions in `input` using `ctx`, with
/// default settings.
///
/// Equivalent to `Expander::new().expand(input, ctx)`.
///
/// ```
/// use bashexpand::expand;
/// use std::collections::HashMap;
///
/// let mut vars = HashMap::from([("v".to_string(), "1.2.3".to_string())]);
/// assert_eq!(expand("major=${v%%.*}", &mut vars).unwrap(), "major=1");
/// ```
pub fn expand<C: Context>(input: &str, ctx: &mut C) -> Result<String, Error<C::Error>> {
    Expander::new().expand(input, ctx)
}

/// Configurable expander (builder style).
///
/// Use this instead of the free [`expand`] function when you need to tweak
/// limits, or when you want to make the configuration explicit at call sites:
///
/// ```
/// use bashexpand::{Expander, Error};
/// use std::collections::HashMap;
///
/// let expander = Expander::new().max_depth(4);
/// let mut vars: HashMap<String, String> = HashMap::new();
///
/// // Fine: three levels of nesting.
/// assert_eq!(
///     expander.expand("${a:-${b:-${c:-deep}}}", &mut vars).unwrap(),
///     "deep",
/// );
///
/// // Rejected: deeper than the configured limit.
/// let deep = "${a:-${a:-${a:-${a:-${a:-x}}}}}";
/// assert_eq!(expander.expand(deep, &mut vars), Err(Error::TooDeep));
/// ```
#[derive(Debug, Clone)]
pub struct Expander {
    max_depth: usize,
}

impl Default for Expander {
    fn default() -> Self {
        Self::new()
    }
}

impl Expander {
    /// Create an expander with default settings
    /// (`max_depth = `[`DEFAULT_MAX_DEPTH`]).
    pub fn new() -> Self {
        Expander {
            max_depth: DEFAULT_MAX_DEPTH,
        }
    }

    /// Set the maximum nesting depth of recursive expansions.
    ///
    /// Nesting occurs in operator words (`${a:-${b}}`), patterns, and
    /// replacements. Inputs exceeding the limit yield [`Error::TooDeep`].
    /// Lower this when expanding untrusted templates in stack-constrained
    /// environments.
    pub fn max_depth(mut self, depth: usize) -> Self {
        self.max_depth = depth;
        self
    }

    /// Expand all `$var` / `${...}` expressions in `input` using `ctx`.
    pub fn expand<C: Context>(&self, input: &str, ctx: &mut C) -> Result<String, Error<C::Error>> {
        self.expand_depth(input, ctx, 0)
    }

    fn expand_depth<C: Context>(
        &self,
        input: &str,
        ctx: &mut C,
        depth: usize,
    ) -> Result<String, Error<C::Error>> {
        if depth > self.max_depth {
            return Err(Error::TooDeep);
        }
        let mut out = String::with_capacity(input.len());
        let chars: Vec<char> = input.chars().collect();
        let mut i = 0;
        while i < chars.len() {
            match chars[i] {
                '\\' if i + 1 < chars.len() && chars[i + 1] == '$' => {
                    out.push('$');
                    i += 2;
                }
                '$' if i + 1 < chars.len() => {
                    if chars[i + 1] == '{' {
                        let (inner, end) = read_braced(&chars, i + 2)?;
                        out.push_str(&self.expand_braced(&inner, ctx, depth)?);
                        i = end;
                    } else if let Some((name, end)) = read_name(&chars, i + 1) {
                        if let Some(v) = get(ctx, &name)? {
                            out.push_str(&v);
                        }
                        i = end;
                    } else {
                        out.push('$');
                        i += 1;
                    }
                }
                c => {
                    out.push(c);
                    i += 1;
                }
            }
        }
        Ok(out)
    }

    fn expand_braced<C: Context>(
        &self,
        body: &str,
        ctx: &mut C,
        depth: usize,
    ) -> Result<String, Error<C::Error>> {
        // ${#var} -> length in characters
        if let Some(rest) = body.strip_prefix('#') {
            if is_name(rest) {
                let len = get(ctx, rest)?.map(|v| v.chars().count()).unwrap_or(0);
                return Ok(len.to_string());
            }
        }
        // ${!var} -> indirection
        if let Some(rest) = body.strip_prefix('!') {
            if is_name(rest) {
                let target = get(ctx, rest)?.unwrap_or_default();
                return Ok(get(ctx, &target)?.unwrap_or_default());
            }
        }

        let chars: Vec<char> = body.chars().collect();
        let (name, op_start) =
            read_name(&chars, 0).ok_or_else(|| Error::BadSubstitution(body.to_string()))?;
        let op: String = chars[op_start..].iter().collect();
        let value = get(ctx, &name)?;

        if op.is_empty() {
            return Ok(value.unwrap_or_default());
        }

        // Default/assign/alternate/error operators, with and without the
        // colon. The colon form also treats set-but-empty as "missing".
        let (colon, op) = match op.strip_prefix(':') {
            Some(rest) if rest.starts_with(['-', '=', '+', '?']) => (true, rest.to_string()),
            _ => (false, op),
        };
        let missing = match &value {
            None => true,
            Some(s) => colon && s.is_empty(),
        };

        match op.chars().next().unwrap() {
            '-' => {
                let word = &op[1..];
                return if missing {
                    self.expand_depth(word, ctx, depth + 1)
                } else {
                    Ok(value.unwrap())
                };
            }
            '=' => {
                let word = &op[1..];
                return if missing {
                    // Digit-leading names mirror bash positional parameters:
                    // readable, but "cannot assign in this way".
                    if name.starts_with(|c: char| c.is_ascii_digit()) {
                        return Err(Error::AssignUnsupported { var: name });
                    }
                    let w = self.expand_depth(word, ctx, depth + 1)?;
                    match ctx.set(&name, &w) {
                        Ok(true) => Ok(w),
                        Ok(false) => Err(Error::AssignUnsupported { var: name }),
                        Err(e) => Err(Error::Context(e)),
                    }
                } else {
                    Ok(value.unwrap())
                };
            }
            '+' => {
                let word = &op[1..];
                return if missing {
                    Ok(String::new())
                } else {
                    self.expand_depth(word, ctx, depth + 1)
                };
            }
            '?' => {
                let word = &op[1..];
                return if missing {
                    Err(Error::Required {
                        var: name,
                        message: self.expand_depth(word, ctx, depth + 1)?,
                    })
                } else {
                    Ok(value.unwrap())
                };
            }
            _ => {}
        }

        // Remaining operators act on the (possibly empty) value.
        let unset = value.is_none();
        let val = value.unwrap_or_default();

        if let Some(spec) = op.strip_prefix(':') {
            return substring(&val, &self.expand_depth(spec, ctx, depth + 1)?);
        }
        if let Some(pat) = op.strip_prefix("##") {
            let g = Glob::compile(&self.expand_depth(pat, ctx, depth + 1)?);
            return Ok(strip_prefix_glob(&val, &g, true));
        }
        if let Some(pat) = op.strip_prefix('#') {
            let g = Glob::compile(&self.expand_depth(pat, ctx, depth + 1)?);
            return Ok(strip_prefix_glob(&val, &g, false));
        }
        if let Some(pat) = op.strip_prefix("%%") {
            let g = Glob::compile(&self.expand_depth(pat, ctx, depth + 1)?);
            return Ok(strip_suffix_glob(&val, &g, true));
        }
        if let Some(pat) = op.strip_prefix('%') {
            let g = Glob::compile(&self.expand_depth(pat, ctx, depth + 1)?);
            return Ok(strip_suffix_glob(&val, &g, false));
        }
        if let Some(spec) = op.strip_prefix('/') {
            return self.replace(&val, spec, ctx, depth);
        }
        if op.starts_with('^') || op.starts_with(',') {
            return Ok(case_modify(&val, &op));
        }
        if let Some(t) = op.strip_prefix('@') {
            // Bash expands any transform of an unset variable to "" — even an
            // unknown one like `${u@Z}`; validation applies to set vars only.
            if unset {
                return Ok(String::new());
            }
            return transform(&val, t).ok_or_else(|| Error::BadSubstitution(body.to_string()));
        }

        Err(Error::BadSubstitution(body.to_string()))
    }

    fn replace<C: Context>(
        &self,
        val: &str,
        spec: &str,
        ctx: &mut C,
        depth: usize,
    ) -> Result<String, Error<C::Error>> {
        enum Mode {
            First,
            Global,
            Prefix,
            Suffix,
        }
        let (mode, rest) = match spec.chars().next() {
            Some('/') => (Mode::Global, &spec[1..]),
            Some('#') => (Mode::Prefix, &spec[1..]),
            Some('%') => (Mode::Suffix, &spec[1..]),
            _ => (Mode::First, spec),
        };

        // Split pattern from replacement at the first unescaped '/'.
        let mut pat = String::new();
        let mut repl = String::new();
        let mut in_repl = false;
        let mut it = rest.chars().peekable();
        while let Some(c) = it.next() {
            if in_repl {
                repl.push(c);
            } else if c == '\\' && it.peek().is_some() {
                pat.push('\\');
                pat.push(it.next().unwrap());
            } else if c == '/' {
                in_repl = true;
            } else {
                pat.push(c);
            }
        }
        let pat = Glob::compile(&self.expand_depth(&pat, ctx, depth + 1)?);
        let repl = self.expand_depth(&repl, ctx, depth + 1)?;
        let chars: Vec<char> = val.chars().collect();

        match mode {
            Mode::Prefix => Ok(match pat.longest_prefix(&chars) {
                Some(l) => format!("{repl}{}", chars[l..].iter().collect::<String>()),
                None => val.to_string(),
            }),
            Mode::Suffix => {
                for start in 0..=chars.len() {
                    if pat.matches(&chars[start..]) {
                        return Ok(format!(
                            "{}{repl}",
                            chars[..start].iter().collect::<String>()
                        ));
                    }
                }
                Ok(val.to_string())
            }
            Mode::First | Mode::Global => {
                let global = matches!(mode, Mode::Global);
                let mut out = String::new();
                let mut i = 0;
                let mut replaced = false;
                while i < chars.len() {
                    let m = if replaced && !global {
                        None
                    } else {
                        pat.longest_prefix(&chars[i..]).filter(|&l| l > 0)
                    };
                    match m {
                        Some(l) => {
                            out.push_str(&repl);
                            i += l;
                            replaced = true;
                        }
                        None => {
                            out.push(chars[i]);
                            i += 1;
                        }
                    }
                }
                Ok(out)
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Parsing helpers
// ---------------------------------------------------------------------------

fn get<C: Context>(ctx: &mut C, name: &str) -> Result<Option<String>, Error<C::Error>> {
    match ctx.get(name) {
        Ok(v) => Ok(v.map(Cow::into_owned)),
        Err(e) => Err(Error::Context(e)),
    }
}

/// Read the contents of `${ ... }`, honoring nested braces and `\x` escapes.
/// Returns (content, index just past `}`).
fn read_braced<E>(chars: &[char], start: usize) -> Result<(String, usize), Error<E>> {
    let mut depth = 1usize;
    let mut i = start;
    let mut buf = String::new();
    while i < chars.len() {
        match chars[i] {
            '{' => depth += 1,
            '}' => {
                depth -= 1;
                if depth == 0 {
                    return Ok((buf, i + 1));
                }
            }
            '\\' if i + 1 < chars.len() => {
                buf.push('\\');
                buf.push(chars[i + 1]);
                i += 2;
                continue;
            }
            _ => {}
        }
        buf.push(chars[i]);
        i += 1;
    }
    Err(Error::BadSubstitution(chars[start..].iter().collect()))
}

fn read_name(chars: &[char], start: usize) -> Option<(String, usize)> {
    let mut i = start;
    let mut name = String::new();
    while i < chars.len() && (chars[i] == '_' || chars[i].is_alphanumeric()) {
        name.push(chars[i]);
        i += 1;
    }
    if name.is_empty() {
        None
    } else {
        Some((name, i))
    }
}

fn is_name(s: &str) -> bool {
    !s.is_empty() && s.chars().all(|c| c == '_' || c.is_alphanumeric())
}

// ---------------------------------------------------------------------------
// Operators
// ---------------------------------------------------------------------------

fn substring<E>(val: &str, spec: &str) -> Result<String, Error<E>> {
    let bad = || Error::BadSubstitution(format!("var:{spec}"));
    let mut parts = spec.splitn(2, ':');
    let off: i64 = parts.next().unwrap().trim().parse().map_err(|_| bad())?;
    let len: Option<i64> = match parts.next() {
        Some(l) => Some(l.trim().parse().map_err(|_| bad())?),
        None => None,
    };
    let chars: Vec<char> = val.chars().collect();
    let n = chars.len() as i64;
    let start = if off < 0 {
        // Bash: a negative offset reaching before the start of the value
        // expands to "" (no clamping to 0), regardless of any length.
        if n + off < 0 {
            return Ok(String::new());
        }
        n + off
    } else {
        off.min(n)
    } as usize;
    let end = match len {
        None => n as usize,
        // Negative length means "up to that offset from the end", as in bash.
        Some(l) if l < 0 => (n + l).max(start as i64) as usize,
        Some(l) => (start as i64 + l).min(n) as usize,
    };
    Ok(chars[start..end.max(start)].iter().collect())
}

fn strip_prefix_glob(val: &str, pat: &Glob, longest: bool) -> String {
    let chars: Vec<char> = val.chars().collect();
    let range: Box<dyn Iterator<Item = usize>> = if longest {
        Box::new((0..=chars.len()).rev())
    } else {
        Box::new(0..=chars.len())
    };
    for l in range {
        if pat.matches(&chars[..l]) {
            return chars[l..].iter().collect();
        }
    }
    val.to_string()
}

fn strip_suffix_glob(val: &str, pat: &Glob, longest: bool) -> String {
    let chars: Vec<char> = val.chars().collect();
    let n = chars.len();
    let range: Box<dyn Iterator<Item = usize>> = if longest {
        Box::new(0..=n)
    } else {
        Box::new((0..=n).rev())
    };
    for start in range {
        if pat.matches(&chars[start..]) {
            return chars[..start].iter().collect();
        }
    }
    val.to_string()
}

fn case_modify(val: &str, op: &str) -> String {
    let (upper, all) = match op {
        _ if op.starts_with("^^") => (true, true),
        _ if op.starts_with(",,") => (false, true),
        _ if op.starts_with('^') => (true, false),
        _ => (false, false),
    };
    let pat = &op[if all { 2 } else { 1 }..];
    let glob = (!pat.is_empty()).then(|| Glob::compile(pat));
    let convert = |c: char| -> String {
        let hit = glob.as_ref().map_or(true, |g| g.matches(&[c]));
        match (hit, upper) {
            (false, _) => c.to_string(),
            (true, true) => c.to_uppercase().to_string(),
            (true, false) => c.to_lowercase().to_string(),
        }
    };
    if all {
        val.chars().map(convert).collect()
    } else {
        let mut it = val.chars();
        match it.next() {
            Some(f) => convert(f) + it.as_str(),
            None => String::new(),
        }
    }
}

fn transform(val: &str, t: &str) -> Option<String> {
    Some(match t {
        "U" => val.to_uppercase(),
        "L" => val.to_lowercase(),
        "u" => {
            let mut it = val.chars();
            match it.next() {
                Some(f) => f.to_uppercase().to_string() + it.as_str(),
                None => String::new(),
            }
        }
        "Q" => format!("'{}'", val.replace('\'', r"'\''")),
        "E" => unescape(val),
        _ => return None,
    })
}

fn unescape(s: &str) -> String {
    let mut out = String::new();
    let mut it = s.chars();
    while let Some(c) = it.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        match it.next() {
            Some('n') => out.push('\n'),
            Some('t') => out.push('\t'),
            Some('r') => out.push('\r'),
            Some('0') => out.push('\0'),
            Some('\\') => out.push('\\'),
            Some(o) => {
                out.push('\\');
                out.push(o);
            }
            None => out.push('\\'),
        }
    }
    out
}

// ---------------------------------------------------------------------------
// Glob matching: `*`, `?`, `[...]` (ranges, `!`/`^` negation), `\x` escapes.
// Compiled once, matched iteratively in O(pattern * text) — no exponential
// backtracking on inputs like "a*a*a*a*b".
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq)]
enum Tok {
    Star,
    Any,
    Lit(char),
    Class {
        negate: bool,
        ranges: Vec<(char, char)>,
    },
}

#[derive(Debug, Clone)]
struct Glob {
    toks: Vec<Tok>,
}

impl Glob {
    fn compile(pat: &str) -> Glob {
        let chars: Vec<char> = pat.chars().collect();
        let mut toks = Vec::new();
        let mut i = 0;
        while i < chars.len() {
            match chars[i] {
                '*' => {
                    if toks.last() != Some(&Tok::Star) {
                        toks.push(Tok::Star);
                    }
                    i += 1;
                }
                '?' => {
                    toks.push(Tok::Any);
                    i += 1;
                }
                '\\' if i + 1 < chars.len() => {
                    toks.push(Tok::Lit(chars[i + 1]));
                    i += 2;
                }
                '[' => match parse_class(&chars, i) {
                    Some((tok, next)) => {
                        toks.push(tok);
                        i = next;
                    }
                    None => {
                        toks.push(Tok::Lit('['));
                        i += 1;
                    }
                },
                c => {
                    toks.push(Tok::Lit(c));
                    i += 1;
                }
            }
        }
        Glob { toks }
    }

    fn tok_matches(tok: &Tok, c: char) -> bool {
        match tok {
            Tok::Star => false, // handled by the matcher, never reached here
            Tok::Any => true,
            Tok::Lit(l) => *l == c,
            Tok::Class { negate, ranges } => {
                ranges.iter().any(|&(a, b)| c >= a && c <= b) != *negate
            }
        }
    }

    /// Does the pattern match the whole of `text`?
    /// Iterative two-pointer algorithm with single-star backtracking: O(p*t).
    fn matches(&self, text: &[char]) -> bool {
        let (mut p, mut t) = (0usize, 0usize);
        let (mut star, mut star_t) = (None::<usize>, 0usize);
        loop {
            if t < text.len() {
                match self.toks.get(p) {
                    Some(Tok::Star) => {
                        star = Some(p);
                        star_t = t;
                        p += 1;
                    }
                    Some(tok) if Self::tok_matches(tok, text[t]) => {
                        p += 1;
                        t += 1;
                    }
                    _ => match star {
                        Some(sp) => {
                            p = sp + 1;
                            star_t += 1;
                            t = star_t;
                        }
                        None => return false,
                    },
                }
            } else {
                while self.toks.get(p) == Some(&Tok::Star) {
                    p += 1;
                }
                return p == self.toks.len();
            }
        }
    }

    /// Length (in chars) of the longest prefix of `text` this pattern matches.
    fn longest_prefix(&self, text: &[char]) -> Option<usize> {
        (0..=text.len()).rev().find(|&l| self.matches(&text[..l]))
    }
}

fn parse_class(chars: &[char], start: usize) -> Option<(Tok, usize)> {
    let mut i = start + 1;
    let negate = matches!(chars.get(i), Some('!') | Some('^'));
    if negate {
        i += 1;
    }
    let first = i;
    let mut ranges = Vec::new();
    while i < chars.len() {
        let c = chars[i];
        if c == ']' && i > first {
            return Some((Tok::Class { negate, ranges }, i + 1));
        }
        if i + 2 < chars.len() && chars[i + 1] == '-' && chars[i + 2] != ']' {
            ranges.push((c, chars[i + 2]));
            i += 3;
        } else {
            ranges.push((c, c));
            i += 1;
        }
    }
    None // unterminated class: caller treats '[' as a literal
}

// ---------------------------------------------------------------------------
// Unit tests (integration tests live in tests/)
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn v() -> HashMap<String, String> {
        HashMap::from([
            ("x".to_string(), "abc".to_string()),
            ("file".to_string(), "dir/sub/name.tar.gz".to_string()),
            ("empty".to_string(), String::new()),
        ])
    }

    #[test]
    fn basics() {
        let mut m = v();
        assert_eq!(expand("$x-${x}", &mut m).unwrap(), "abc-abc");
        assert_eq!(expand("$", &mut m).unwrap(), "$");
        assert_eq!(expand("$1", &mut m).unwrap(), "");
        m.insert("1".to_string(), "one".to_string());
        assert_eq!(expand("$1-${1}", &mut m).unwrap(), "one-one");
        // Set numeric name: operators fine, `=` never fires — like bash.
        assert_eq!(expand("${1=x}-${1:-d}-${#1}", &mut m).unwrap(), "one-one-3");
        // Assignment that would fire → bash "cannot assign in this way".
        assert!(matches!(
            expand("${9:=x}", &mut m),
            Err(Error::AssignUnsupported { .. })
        ));
        assert!(!m.contains_key("9"));
        assert_eq!(expand(r"\$x", &mut m).unwrap(), "$x");
        assert_eq!(expand("no vars here", &mut m).unwrap(), "no vars here");
        assert_eq!(expand("", &mut m).unwrap(), "");
    }

    #[test]
    fn defaults() {
        let mut m = v();
        assert_eq!(expand("${nope-d}", &mut m).unwrap(), "d");
        assert_eq!(expand("${empty-d}", &mut m).unwrap(), "");
        assert_eq!(expand("${empty:-d}", &mut m).unwrap(), "d");
        assert_eq!(expand("${nope:=set}", &mut m).unwrap(), "set");
        assert_eq!(m["nope"], "set");
        assert_eq!(expand("${x:+alt}", &mut m).unwrap(), "alt");
        assert_eq!(expand("${empty:+alt}", &mut m).unwrap(), "");
        assert!(matches!(
            expand("${nada:?boom}", &mut m),
            Err(Error::Required { .. })
        ));
        assert_eq!(expand("${nope2:-${x}!}", &mut m).unwrap(), "abc!");
    }

    #[test]
    fn length_indirection() {
        let mut m = v();
        m.insert("p".into(), "x".into());
        assert_eq!(expand("${#file}", &mut m).unwrap(), "19");
        assert_eq!(expand("${#nope}", &mut m).unwrap(), "0");
        assert_eq!(expand("${!p}", &mut m).unwrap(), "abc");
    }

    #[test]
    fn substrings() {
        let mut m = v();
        assert_eq!(expand("${file:0:3}", &mut m).unwrap(), "dir");
        assert_eq!(expand("${file:4}", &mut m).unwrap(), "sub/name.tar.gz");
        assert_eq!(expand("${file: -2}", &mut m).unwrap(), "gz");
        assert_eq!(expand("${file:4:-7}", &mut m).unwrap(), "sub/name");
        assert_eq!(expand("${file:100}", &mut m).unwrap(), "");
        assert_eq!(expand("${file:0:0}", &mut m).unwrap(), "");
        // V15: negative offset beyond -len expands to "" as in bash.
        assert_eq!(expand("${x: -3}", &mut m).unwrap(), "abc");
        assert_eq!(expand("${x: -4}", &mut m).unwrap(), "");
        assert_eq!(expand("${x: -4:2}", &mut m).unwrap(), "");
    }

    #[test]
    fn pattern_removal() {
        let mut m = v();
        assert_eq!(expand("${file#*/}", &mut m).unwrap(), "sub/name.tar.gz");
        assert_eq!(expand("${file##*/}", &mut m).unwrap(), "name.tar.gz");
        assert_eq!(expand("${file%.*}", &mut m).unwrap(), "dir/sub/name.tar");
        assert_eq!(expand("${file%%.*}", &mut m).unwrap(), "dir/sub/name");
        assert_eq!(
            expand("${file#zzz}", &mut m).unwrap(),
            "dir/sub/name.tar.gz"
        );
    }

    #[test]
    fn replacement() {
        let mut m = v();
        assert_eq!(
            expand("${file/sub/S}", &mut m).unwrap(),
            "dir/S/name.tar.gz"
        );
        assert_eq!(
            expand("${file//\\//_}", &mut m).unwrap(),
            "dir_sub_name.tar.gz"
        );
        assert_eq!(
            expand("${file/#dir/R}", &mut m).unwrap(),
            "R/sub/name.tar.gz"
        );
        assert_eq!(
            expand("${file/%gz/xz}", &mut m).unwrap(),
            "dir/sub/name.tar.xz"
        );
        assert_eq!(expand("${x/b}", &mut m).unwrap(), "ac");
    }

    #[test]
    fn case_ops() {
        let mut m = HashMap::from([
            ("g".to_string(), "hello world".to_string()),
            ("G".to_string(), "HELLO".to_string()),
        ]);
        assert_eq!(expand("${g^}", &mut m).unwrap(), "Hello world");
        assert_eq!(expand("${g^^}", &mut m).unwrap(), "HELLO WORLD");
        assert_eq!(expand("${g^^[lo]}", &mut m).unwrap(), "heLLO wOrLd");
        assert_eq!(expand("${G,,}", &mut m).unwrap(), "hello");
        assert_eq!(expand("${G,}", &mut m).unwrap(), "hELLO");
    }

    #[test]
    fn at_transforms() {
        let mut m = HashMap::from([("g".to_string(), "Hello World".to_string())]);
        assert_eq!(expand("${g@U}", &mut m).unwrap(), "HELLO WORLD");
        assert_eq!(expand("${g@L}", &mut m).unwrap(), "hello world");
        assert_eq!(expand("${g@u}", &mut m).unwrap(), "Hello World");
        assert_eq!(expand("${g@Q}", &mut m).unwrap(), "'Hello World'");
        assert!(matches!(
            expand("${g@Z}", &mut m),
            Err(Error::BadSubstitution(_))
        ));
        // V14: any transform of an unset variable is "" (bash parity),
        // including transforms that would be invalid on a set variable.
        assert_eq!(expand("${nope@Q}", &mut m).unwrap(), "");
        assert_eq!(expand("${nope@U}", &mut m).unwrap(), "");
        assert_eq!(expand("${nope@Z}", &mut m).unwrap(), "");
    }

    #[test]
    fn quoting_is_safe() {
        let mut m = HashMap::from([("s".to_string(), "it's a 'test'".to_string())]);
        assert_eq!(
            expand("${s@Q}", &mut m).unwrap(),
            r#"'it'\''s a '\''test'\'''"#
        );
    }

    #[test]
    fn shared_ref_maps_read_only() {
        // V16: expansion works with only a shared borrow of the map.
        let m = v();
        assert_eq!(expand("${x}-${nope:-d}", &mut &m).unwrap(), "abc-d");
        assert!(matches!(
            expand("${nope:=d}", &mut &m),
            Err(Error::AssignUnsupported { .. })
        ));
        assert_eq!(m.len(), 3);

        let b = BTreeMap::from([("k".to_string(), "v".to_string())]);
        assert_eq!(expand("${k}", &mut &b).unwrap(), "v");
        assert!(matches!(
            expand("${z:=d}", &mut &b),
            Err(Error::AssignUnsupported { .. })
        ));
    }

    #[test]
    fn depth_limit() {
        let mut s = String::from("x");
        for _ in 0..(DEFAULT_MAX_DEPTH + 2) {
            s = format!("${{a:-{s}}}");
        }
        let mut m: HashMap<String, String> = HashMap::new();
        assert_eq!(expand(&s, &mut m), Err(Error::TooDeep));
    }

    #[test]
    fn glob_no_blowup() {
        // Would take exponential time with naive recursive backtracking.
        let g = Glob::compile("a*a*a*a*a*a*a*a*a*a*b");
        let text: Vec<char> = "a".repeat(200).chars().collect();
        assert!(!g.matches(&text));
        assert!(glob_ok("*.tar.gz", "name.tar.gz"));
        assert!(glob_ok("a?c", "abc"));
        assert!(glob_ok("[a-c]x", "bx"));
        assert!(glob_ok("[!a-c]x", "dx"));
        assert!(!glob_ok("[a-c]x", "dx"));
        assert!(glob_ok(r"\*x", "*x"));
        assert!(!glob_ok(r"\*x", "ax"));
        assert!(glob_ok("", ""));
        assert!(!glob_ok("", "a"));
        assert!(glob_ok("*", ""));
    }

    fn glob_ok(p: &str, t: &str) -> bool {
        Glob::compile(p).matches(&t.chars().collect::<Vec<_>>())
    }

    #[test]
    fn bad_substitution() {
        let mut m = v();
        assert!(matches!(
            expand("${x&}", &mut m),
            Err(Error::BadSubstitution(_))
        ));
        assert!(matches!(
            expand("${unclosed", &mut m),
            Err(Error::BadSubstitution(_))
        ));
        assert!(matches!(
            expand("${x:zz}", &mut m),
            Err(Error::BadSubstitution(_))
        ));
    }

    #[test]
    fn unicode() {
        let mut m = HashMap::from([("s".to_string(), "héllo wörld".to_string())]);
        assert_eq!(expand("${#s}", &mut m).unwrap(), "11");
        assert_eq!(expand("${s:1:4}", &mut m).unwrap(), "éllo");
        assert_eq!(expand("${s^^}", &mut m).unwrap(), "HÉLLO WÖRLD");
    }
}