/
common.rs
2208 lines (2021 loc) · 78.2 KB
/
common.rs
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
//! Prototypes for various functions, mostly string utilities, that are used by most parts of fish.
use crate::expand::{
BRACE_BEGIN, BRACE_END, BRACE_SEP, BRACE_SPACE, HOME_DIRECTORY, INTERNAL_SEPARATOR,
PROCESS_EXPAND_SELF, PROCESS_EXPAND_SELF_STR, VARIABLE_EXPAND, VARIABLE_EXPAND_SINGLE,
};
use crate::fallback::fish_wcwidth;
use crate::future_feature_flags::{feature_test, FeatureFlag};
use crate::global_safety::AtomicRef;
use crate::global_safety::RelaxedAtomicBool;
use crate::key;
use crate::libc::MB_CUR_MAX;
use crate::parse_util::parse_util_escape_string_with_quote;
use crate::termsize::Termsize;
use crate::wchar::{decode_byte_from_char, encode_byte_to_char, prelude::*};
use crate::wcstringutil::wcs2string_callback;
use crate::wildcard::{ANY_CHAR, ANY_STRING, ANY_STRING_RECURSIVE};
use crate::wutil::encoding::{mbrtowc, wcrtomb, zero_mbstate, AT_LEAST_MB_LEN_MAX};
use crate::wutil::fish_iswalnum;
use bitflags::bitflags;
use core::slice;
use libc::{EIO, O_WRONLY, SIGTTOU, SIG_IGN, STDERR_FILENO, STDIN_FILENO, STDOUT_FILENO};
use once_cell::sync::OnceCell;
use std::env;
use std::ffi::{CStr, CString, OsStr, OsString};
use std::io::{Read, Write};
use std::mem;
use std::ops::{Deref, DerefMut};
use std::os::unix::prelude::*;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicI32, AtomicU32, Ordering};
use std::sync::{Arc, MutexGuard};
use std::time;
pub const PACKAGE_NAME: &str = env!("CARGO_PKG_NAME");
// Highest legal ASCII value.
pub const ASCII_MAX: char = 127 as char;
// Highest legal 16-bit Unicode value.
pub const UCS2_MAX: char = '\u{FFFF}';
// Highest legal byte value.
pub const BYTE_MAX: char = 0xFF as char;
// Unicode BOM value.
pub const UTF8_BOM_WCHAR: char = '\u{FEFF}';
// Use Unicode "non-characters" for internal characters as much as we can. This
// gives us 32 "characters" for internal use that we can guarantee should not
// appear in our input stream. See http://www.unicode.org/faq/private_use.html.
pub const RESERVED_CHAR_BASE: char = '\u{FDD0}';
pub const RESERVED_CHAR_END: char = '\u{FDF0}';
// Split the available non-character values into two ranges to ensure there are
// no conflicts among the places we use these special characters.
pub const EXPAND_RESERVED_BASE: char = RESERVED_CHAR_BASE;
pub const EXPAND_RESERVED_END: char = char_offset(EXPAND_RESERVED_BASE, 16);
pub const WILDCARD_RESERVED_BASE: char = EXPAND_RESERVED_END;
pub const WILDCARD_RESERVED_END: char = char_offset(WILDCARD_RESERVED_BASE, 16);
// Make sure the ranges defined above don't exceed the range for non-characters.
// This is to make sure we didn't do something stupid in subdividing the
// Unicode range for our needs.
const _: () = assert!(WILDCARD_RESERVED_END <= RESERVED_CHAR_END);
// These are in the Unicode private-use range. We really shouldn't use this
// range but have little choice in the matter given how our lexer/parser works.
// We can't use non-characters for these two ranges because there are only 66 of
// them and we need at least 256 + 64.
//
// If sizeof(wchar_t))==4 we could avoid using private-use chars; however, that
// would result in fish having different behavior on machines with 16 versus 32
// bit wchar_t. It's better that fish behave the same on both types of systems.
//
// Note: We don't use the highest 8 bit range (0xF800 - 0xF8FF) because we know
// of at least one use of a codepoint in that range: the Apple symbol (0xF8FF)
// on Mac OS X. See http://www.unicode.org/faq/private_use.html.
pub const ENCODE_DIRECT_BASE: char = '\u{F600}';
pub const ENCODE_DIRECT_END: char = char_offset(ENCODE_DIRECT_BASE, 256);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EscapeStringStyle {
Script(EscapeFlags),
Url,
Var,
Regex,
}
impl Default for EscapeStringStyle {
fn default() -> Self {
Self::Script(EscapeFlags::default())
}
}
impl TryFrom<&wstr> for EscapeStringStyle {
type Error = &'static wstr;
fn try_from(s: &wstr) -> Result<Self, Self::Error> {
use EscapeStringStyle::*;
match s {
s if s == "script" => Ok(Self::default()),
s if s == "var" => Ok(Var),
s if s == "url" => Ok(Url),
s if s == "regex" => Ok(Regex),
_ => Err(L!("Invalid escape style")),
}
}
}
bitflags! {
/// Flags for the [`escape_string()`] function. These are only applicable when the escape style is
/// [`EscapeStringStyle::Script`].
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct EscapeFlags: u32 {
/// Do not escape special fish syntax characters like the semicolon. Only escape non-printable
/// characters and backslashes.
const NO_PRINTABLES = 1 << 0;
/// Do not try to use 'simplified' quoted escapes, and do not use empty quotes as the empty
/// string.
const NO_QUOTED = 1 << 1;
/// Do not escape tildes.
const NO_TILDE = 1 << 2;
/// Replace non-printable control characters with Unicode symbols.
const SYMBOLIC = 1 << 3;
/// Escape : and =
const SEPARATORS = 1 << 4;
/// Escape ,
const COMMA = 1 << 5;
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnescapeStringStyle {
Script(UnescapeFlags),
Url,
Var,
}
impl Default for UnescapeStringStyle {
fn default() -> Self {
Self::Script(UnescapeFlags::default())
}
}
impl TryFrom<&wstr> for UnescapeStringStyle {
type Error = &'static wstr;
fn try_from(s: &wstr) -> Result<Self, Self::Error> {
use UnescapeStringStyle::*;
match s {
s if s == "script" => Ok(Self::default()),
s if s == "var" => Ok(Var),
s if s == "url" => Ok(Url),
_ => Err(L!("Invalid escape style")),
}
}
}
bitflags! {
/// Flags for unescape_string functions.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct UnescapeFlags: u32 {
/// escape special fish syntax characters like the semicolon
const SPECIAL = 1 << 0;
/// allow incomplete escape sequences
const INCOMPLETE = 1 << 1;
/// don't handle backslash escapes
const NO_BACKSLASHES = 1 << 2;
}
}
/// Replace special characters with backslash escape sequences. Newline is replaced with `\n`, etc.
pub fn escape(s: &wstr) -> WString {
escape_string(s, EscapeStringStyle::Script(EscapeFlags::default()))
}
/// Replace special characters with backslash escape sequences. Newline is replaced with `\n`, etc.
pub fn escape_string(s: &wstr, style: EscapeStringStyle) -> WString {
match style {
EscapeStringStyle::Script(flags) => escape_string_script(s, flags),
EscapeStringStyle::Url => escape_string_url(s),
EscapeStringStyle::Var => escape_string_var(s),
EscapeStringStyle::Regex => escape_string_pcre2(s),
}
}
/// Escape a string in a fashion suitable for using in fish script.
fn escape_string_script(input: &wstr, flags: EscapeFlags) -> WString {
let escape_printables = !flags.contains(EscapeFlags::NO_PRINTABLES);
let escape_separators = flags.contains(EscapeFlags::SEPARATORS);
let escape_comma = flags.contains(EscapeFlags::COMMA);
let no_quoted = flags.contains(EscapeFlags::NO_QUOTED);
let no_tilde = flags.contains(EscapeFlags::NO_TILDE);
let no_qmark = feature_test(FeatureFlag::qmark_noglob);
let symbolic = flags.contains(EscapeFlags::SYMBOLIC) && MB_CUR_MAX() > 1;
assert!(
!symbolic || !escape_printables,
"symbolic implies escape-no-printables"
);
let mut need_escape = false;
let mut need_complex_escape = false;
let mut double_quotes = 0;
let mut single_quotes = 0;
let mut dollars = 0;
if !no_quoted && input.is_empty() {
return L!("''").to_owned();
}
let mut out = WString::new();
for c in input.chars() {
if let Some(val) = decode_byte_from_char(c) {
out += "\\X";
let nibble1 = val / 16;
let nibble2 = val % 16;
out.push(char::from_digit(nibble1.into(), 16).unwrap());
out.push(char::from_digit(nibble2.into(), 16).unwrap());
need_escape = true;
need_complex_escape = true;
continue;
}
match c {
'\t' => {
if symbolic {
out.push('␉');
} else {
out += L!("\\t");
}
need_escape = true;
need_complex_escape = true;
}
'\n' => {
if symbolic {
out.push('');
} else {
out += L!("\\n");
}
need_escape = true;
need_complex_escape = true;
}
'\x08' => {
if symbolic {
out.push('␈');
} else {
out += L!("\\b");
}
need_escape = true;
need_complex_escape = true;
}
'\r' => {
if symbolic {
out.push('␍');
} else {
out += L!("\\r");
}
need_escape = true;
need_complex_escape = true;
}
'\x1B' => {
if symbolic {
out.push('␛');
} else {
out += L!("\\e");
}
need_escape = true;
need_complex_escape = true;
}
'\x7F' => {
if symbolic {
out.push('␡');
} else {
out += L!("\\x7f");
}
need_escape = true;
need_complex_escape = true;
}
'\\' | '\'' => {
need_escape = true;
if c == '\'' {
single_quotes += 1;
}
if escape_printables || (c == '\\' && !symbolic) {
out.push('\\');
}
out.push(c);
}
ANY_CHAR => {
// See #1614
out.push('?');
}
ANY_STRING => {
out.push('*');
}
ANY_STRING_RECURSIVE => {
out += L!("**");
}
':' | '=' => {
if escape_separators {
need_escape = true;
out.push('\\');
}
out.push(c);
}
',' => {
if escape_comma {
need_escape = true;
out.push('\\');
}
out.push(c);
}
'&' | '$' | ' ' | '#' | '<' | '>' | '(' | ')' | '[' | ']' | '{' | '}' | '?' | '*'
| '|' | ';' | '"' | '%' | '~' => {
if c == '"' {
double_quotes += 1;
}
if c == '$' {
dollars += 1;
}
let char_is_normal = (c == '~' && no_tilde) || (c == '?' && no_qmark);
if !char_is_normal {
need_escape = true;
if escape_printables {
out.push('\\')
};
}
out.push(c);
}
'\x00'..='\x19' => {
let cval = u32::from(c);
need_escape = true;
need_complex_escape = true;
if symbolic {
out.push(char::from_u32(0x2400 + cval).unwrap());
continue;
}
if cval < 27 && cval != 0 {
out.push('\\');
out.push('c');
out.push(char::from_u32(u32::from(b'a') + cval - 1).unwrap());
continue;
}
let nibble = cval % 16;
out.push('\\');
out.push('x');
out.push(if cval > 15 { '1' } else { '0' });
out.push(char::from_digit(nibble, 16).unwrap());
}
_ => out.push(c),
}
}
// Use quoted escaping if possible, since most people find it easier to read.
if !no_quoted && need_escape && !need_complex_escape && escape_printables {
let quote = if single_quotes > double_quotes + dollars {
'"'
} else {
'\''
};
out.clear();
out.reserve(2 + input.len());
out.push(quote);
out.push_utfstr(&parse_util_escape_string_with_quote(
input,
Some(quote),
EscapeFlags::empty(),
));
out.push(quote);
}
out
}
/// Test whether the char is a valid hex digit as used by the `escape_string_*()` functions.
/// Note this only considers uppercase characters.
fn is_upper_hex_digit(c: char) -> bool {
matches!(c, '0'..='9' | 'A'..='F')
}
/// Return the high and low nibbles of a byte, as uppercase hex characters.
fn byte_to_hex(byte: u8) -> (char, char) {
const HEX: [u8; 16] = *b"0123456789ABCDEF";
let high = byte >> 4;
let low = byte & 0xF;
(HEX[high as usize].into(), HEX[low as usize].into())
}
/// Escape a string in a fashion suitable for using as a URL. Store the result in out_str.
fn escape_string_url(input: &wstr) -> WString {
let narrow = wcs2string(input);
let mut out = WString::new();
for byte in narrow.into_iter() {
if (byte & 0x80) == 0 {
let c = char::from_u32(u32::from(byte)).unwrap();
if c.is_alphanumeric() || [b'/', b'.', b'~', b'-', b'_'].contains(&byte) {
// The above characters don't need to be encoded.
out.push(c);
continue;
}
}
// All other chars need to have their narrow representation encoded in hex.
let (high, low) = byte_to_hex(byte);
out.push('%');
out.push(high);
out.push(low);
}
out
}
/// Escape a string in a fashion suitable for using as a fish var name. Store the result in out_str.
fn escape_string_var(input: &wstr) -> WString {
let mut prev_was_hex_encoded = false;
let narrow = wcs2string(input);
let mut out = WString::new();
for c in narrow.into_iter() {
let ch: char = c.into();
if ((c & 0x80) == 0 && ch.is_alphanumeric())
&& (!prev_was_hex_encoded || !is_upper_hex_digit(ch))
{
// ASCII alphanumerics don't need to be encoded.
if prev_was_hex_encoded {
out.push('_');
prev_was_hex_encoded = false;
}
out.push(ch);
} else if c == b'_' {
// Underscores are encoded by doubling them.
out.push_str("__");
prev_was_hex_encoded = false;
} else {
// All other chars need to have their narrow representation encoded in hex.
let (high, low) = byte_to_hex(c);
out.push('_');
out.push(high);
out.push(low);
prev_was_hex_encoded = true;
}
}
if prev_was_hex_encoded {
out.push('_');
}
out
}
/// Escapes a string for use in a regex string. Not safe for use with `eval` as only
/// characters reserved by PCRE2 are escaped.
/// \param in is the raw string to be searched for literally when substituted in a PCRE2 expression.
fn escape_string_pcre2(input: &wstr) -> WString {
let mut out = WString::new();
out.reserve(input.len());
for c in input.chars() {
if [
'.', '^', '$', '*', '+', '(', ')', '?', '[', '{', '}', '\\', '|',
// these two only *need* to be escaped within a character class, and technically it
// makes no sense to ever use process substitution output to compose a character class,
// but...
'-', ']',
]
.contains(&c)
{
out.push('\\');
}
out.push(c);
}
out
}
/// Escape a string so that it may be inserted into a double-quoted string.
/// This permits ownership transfer.
pub fn escape_string_for_double_quotes(input: &wstr) -> WString {
// We need to escape backslashes, double quotes, and dollars only.
let mut result = input.to_owned();
let mut idx = result.len();
while idx > 0 {
idx -= 1;
if ['\\', '$', '"'].contains(&result.char_at(idx)) {
result.insert(idx, '\\');
}
}
result
}
pub fn unescape_string(input: &wstr, style: UnescapeStringStyle) -> Option<WString> {
match style {
UnescapeStringStyle::Script(flags) => unescape_string_internal(input, flags),
UnescapeStringStyle::Url => unescape_string_url(input),
UnescapeStringStyle::Var => unescape_string_var(input),
}
}
// TODO Delete this.
pub fn unescape_string_in_place(s: &mut WString, style: UnescapeStringStyle) -> bool {
unescape_string(s, style)
.map(|unescaped| *s = unescaped)
.is_some()
}
/// Returns the unescaped version of input, or None on error.
fn unescape_string_internal(input: &wstr, flags: UnescapeFlags) -> Option<WString> {
let mut result = WString::new();
result.reserve(input.len());
let unescape_special = flags.contains(UnescapeFlags::SPECIAL);
let allow_incomplete = flags.contains(UnescapeFlags::INCOMPLETE);
let ignore_backslashes = flags.contains(UnescapeFlags::NO_BACKSLASHES);
let allow_percent_self = !feature_test(FeatureFlag::remove_percent_self);
// The positions of open braces.
let mut braces = vec![];
// The positions of variable expansions or brace ","s.
// We only read braces as expanders if there's a variable expansion or "," in them.
let mut vars_or_seps = vec![];
let mut brace_count = 0;
let mut errored = false;
#[derive(PartialEq, Eq)]
enum Mode {
Unquoted,
SingleQuotes,
DoubleQuotes,
}
let mut mode = Mode::Unquoted;
let mut input_position = 0;
while input_position < input.len() && !errored {
let c = input.char_at(input_position);
// Here's the character we'll append to result, or none() to suppress it.
let mut to_append_or_none = Some(c);
if mode == Mode::Unquoted {
match c {
'\\' => {
if !ignore_backslashes {
// Backslashes (escapes) are complicated and may result in errors, or
// appending INTERNAL_SEPARATORs, so we have to handle them specially.
if let Some(escape_chars) = read_unquoted_escape(
&input[input_position..],
&mut result,
allow_incomplete,
unescape_special,
) {
// Skip over the characters we read, minus one because the outer loop
// will increment it.
assert!(escape_chars > 0);
input_position += escape_chars - 1;
} else {
// A none() return indicates an error.
errored = true;
}
// We've already appended, don't append anything else.
to_append_or_none = None;
}
}
'~' => {
if unescape_special && input_position == 0 {
to_append_or_none = Some(HOME_DIRECTORY);
}
}
'%' => {
// Note that this only recognizes %self if the string is literally %self.
// %self/foo will NOT match this.
if allow_percent_self
&& unescape_special
&& input_position == 0
&& input == PROCESS_EXPAND_SELF_STR
{
to_append_or_none = Some(PROCESS_EXPAND_SELF);
input_position += PROCESS_EXPAND_SELF_STR.len() - 1; // skip over 'self's
}
}
'*' => {
if unescape_special {
// In general, this is ANY_STRING. But as a hack, if the last appended char
// is ANY_STRING, delete the last char and store ANY_STRING_RECURSIVE to
// reflect the fact that ** is the recursive wildcard.
if result.chars().next_back() == Some(ANY_STRING) {
assert!(!result.is_empty());
result.truncate(result.len() - 1);
to_append_or_none = Some(ANY_STRING_RECURSIVE);
} else {
to_append_or_none = Some(ANY_STRING);
}
}
}
'?' => {
if unescape_special && !feature_test(FeatureFlag::qmark_noglob) {
to_append_or_none = Some(ANY_CHAR);
}
}
'$' => {
if unescape_special {
let is_cmdsub = input_position + 1 < input.len()
&& input.char_at(input_position + 1) == '(';
if !is_cmdsub {
to_append_or_none = Some(VARIABLE_EXPAND);
vars_or_seps.push(input_position);
}
}
}
'{' => {
if unescape_special {
brace_count += 1;
to_append_or_none = Some(BRACE_BEGIN);
// We need to store where the brace *ends up* in the output.
braces.push(result.len());
}
}
'}' => {
if unescape_special {
// HACK: The completion machinery sometimes hands us partial tokens.
// We can't parse them properly, but it shouldn't hurt,
// so we don't assert here.
// See #4954.
// assert(brace_count > 0 && "imbalanced brackets are a tokenizer error, we
// shouldn't be able to get here");
brace_count -= 1;
to_append_or_none = Some(BRACE_END);
if let Some(brace) = braces.pop() {
// HACK: To reduce accidental use of brace expansion, treat a brace
// with zero or one items as literal input. See #4632. (The hack is
// doing it here and like this.)
if vars_or_seps.last().map(|i| *i < brace).unwrap_or(true) {
result.as_char_slice_mut()[brace] = '{';
// We also need to turn all spaces back.
for i in brace + 1..result.len() {
if result.char_at(i) == BRACE_SPACE {
result.as_char_slice_mut()[i] = ' ';
}
}
to_append_or_none = Some('}');
}
// Remove all seps inside the current brace pair, so if we have a
// surrounding pair we only get seps inside *that*.
if !vars_or_seps.is_empty() {
while vars_or_seps.last().map(|i| *i > brace).unwrap_or_default() {
vars_or_seps.pop();
}
}
}
}
}
',' => {
if unescape_special && brace_count > 0 {
to_append_or_none = Some(BRACE_SEP);
vars_or_seps.push(input_position);
}
}
' ' => {
if unescape_special && brace_count > 0 {
to_append_or_none = Some(BRACE_SPACE);
}
}
'\'' => {
mode = Mode::SingleQuotes;
to_append_or_none = if unescape_special {
Some(INTERNAL_SEPARATOR)
} else {
None
};
}
'"' => {
mode = Mode::DoubleQuotes;
to_append_or_none = if unescape_special {
Some(INTERNAL_SEPARATOR)
} else {
None
};
}
_ => (),
}
} else if mode == Mode::SingleQuotes {
if c == '\\' {
// A backslash may or may not escape something in single quotes.
match input.char_at(input_position + 1) {
'\\' | '\'' => {
to_append_or_none = Some(input.char_at(input_position + 1));
input_position += 1; // skip over the backslash
}
'\0' => {
if !allow_incomplete {
errored = true;
} else {
// PCA this line had the following cryptic comment: 'We may ever escape
// a NULL character, but still appending a \ in case I am wrong.' Not
// sure what it means or the importance of this.
input_position += 1; /* Skip over the backslash */
to_append_or_none = Some('\\');
}
}
_ => {
// Literal backslash that doesn't escape anything! Leave things alone; we'll
// append the backslash itself.
}
}
} else if c == '\'' {
to_append_or_none = if unescape_special {
Some(INTERNAL_SEPARATOR)
} else {
None
};
mode = Mode::Unquoted;
}
} else if mode == Mode::DoubleQuotes {
match c {
'"' => {
mode = Mode::Unquoted;
to_append_or_none = if unescape_special {
Some(INTERNAL_SEPARATOR)
} else {
None
};
}
'\\' => {
match input.char_at(input_position + 1) {
'\0' => {
if !allow_incomplete {
errored = true;
} else {
to_append_or_none = Some('\0');
}
}
'\\' | '$' | '"' => {
to_append_or_none = Some(input.char_at(input_position + 1));
input_position += 1; /* Skip over the backslash */
}
'\n' => {
/* Swallow newline */
to_append_or_none = None;
input_position += 1; /* Skip over the backslash */
}
_ => {
/* Literal backslash that doesn't escape anything! Leave things alone;
* we'll append the backslash itself */
}
}
}
'$' => {
if unescape_special {
to_append_or_none = Some(VARIABLE_EXPAND_SINGLE);
vars_or_seps.push(input_position);
}
}
_ => (),
}
}
// Now maybe append the char.
if let Some(c) = to_append_or_none {
result.push(c);
}
input_position += 1;
}
// Return the string by reference, and then success.
if errored {
return None;
}
Some(result)
}
/// Reverse the effects of `escape_string_url()`. By definition the input should consist of just
/// ASCII chars.
fn unescape_string_url(input: &wstr) -> Option<WString> {
let mut result: Vec<u8> = Vec::with_capacity(input.len());
let mut i = 0;
while i < input.len() {
let c = input.char_at(i);
if c > '\u{7F}' {
return None; // invalid character means we can't decode the string
}
if c == '%' {
let c1 = input.char_at(i + 1);
if c1 == '\0' {
return None;
} else if c1 == '%' {
result.push(b'%');
i += 1;
} else {
let d1 = c1.to_digit(16)?;
let c2 = input.char_at(i + 2);
let d2 = c2.to_digit(16)?; // also fails if '\0' i.e. premature end
result.push((16 * d1 + d2) as u8);
i += 2;
}
} else {
result.push(c as u8);
}
i += 1
}
Some(str2wcstring(&result))
}
/// Reverse the effects of `escape_string_var()`. By definition the string should consist of just
/// ASCII chars.
fn unescape_string_var(input: &wstr) -> Option<WString> {
let mut result: Vec<u8> = Vec::with_capacity(input.len());
let mut prev_was_hex_encoded = false;
let mut i = 0;
while i < input.len() {
let c = input.char_at(i);
if c > '\u{7F}' {
return None; // invalid character means we can't decode the string
}
if c == '_' {
let c1 = input.char_at(i + 1);
if c1 == '\0' {
if prev_was_hex_encoded {
break;
}
return None; // found unexpected escape char at end of string
} else if c1 == '_' {
result.push(b'_');
i += 1;
} else if is_upper_hex_digit(c1) {
let d1 = c1.to_digit(16)?;
let c2 = input.char_at(i + 2);
let d2 = c2.to_digit(16)?; // also fails if '\0' i.e. premature end
result.push((16 * d1 + d2) as u8);
i += 2;
prev_was_hex_encoded = true;
}
// No "else" clause because if the first char after an underscore is not another
// underscore or a valid hex character then the underscore is there to improve
// readability after we've encoded a character not valid in a var name.
} else {
result.push(c as u8);
}
i += 1;
}
Some(str2wcstring(&result))
}
/// Given a string starting with a backslash, read the escape as if it is unquoted, appending
/// to result. Return the number of characters consumed, or none on error.
pub fn read_unquoted_escape(
input: &wstr,
result: &mut WString,
allow_incomplete: bool,
unescape_special: bool,
) -> Option<usize> {
assert!(input.char_at(0) == '\\', "not an escape");
// Here's the character we'll ultimately append, or none. Note that '\0' is a
// valid thing to append.
let mut result_char_or_none: Option<char> = None;
let mut errored = false;
let mut in_pos = 1; // in_pos always tracks the next character to read (and therefore the number
// of characters read so far)
// For multibyte \X sequences.
let mut byte_buff: Vec<u8> = vec![];
loop {
let c = input.char_at(in_pos);
in_pos += 1;
match c {
// A null character after a backslash is an error.
'\0' => {
// Adjust in_pos to only include the backslash.
assert!(in_pos > 0);
in_pos -= 1;
// It's an error, unless we're allowing incomplete escapes.
if !allow_incomplete {
errored = true;
}
}
// Numeric escape sequences. No prefix means octal escape, otherwise hexadecimal.
'0'..='7' | 'u' | 'U' | 'x' | 'X' => {
let mut res: u64 = 0;
let mut chars = 2;
let mut base = 16;
let mut byte_literal = false;
let mut max_val = ASCII_MAX;
match c {
'u' => {
chars = 4;
max_val = UCS2_MAX;
}
'U' => {
chars = 8;
// Don't exceed the largest Unicode code point - see #1107.
max_val = char::MAX;
}
'x' | 'X' => {
byte_literal = true;
max_val = BYTE_MAX;
}
_ => {
base = 8;
chars = 3;
// Note that in_pos currently is just after the first post-backslash
// character; we want to start our escape from there.
assert!(in_pos > 0);
in_pos -= 1;
}
}
for i in 0..chars {
let Some(d) = input.char_at(in_pos).to_digit(base) else {
// If we have no digit, this is a tokenizer error.
if i == 0 {
errored = true;
}
break;
};
res = (res * u64::from(base)) + u64::from(d);
in_pos += 1;
}
if !errored && res <= u64::from(max_val) {
if byte_literal {
// Multibyte encodings necessitate that we keep adjacent byte escapes.
// - `\Xc3\Xb6` is "ö", but only together.
// (this assumes a valid codepoint can't consist of multiple bytes
// that are valid on their own, which is true for UTF-8)
byte_buff.push(res.try_into().unwrap());
result_char_or_none = None;
if input[in_pos..].starts_with("\\X") || input[in_pos..].starts_with("\\x")
{
in_pos += 1;
continue;
}
} else {
result_char_or_none =
Some(char::from_u32(res.try_into().unwrap()).unwrap_or('\u{FFFD}'));
}
} else {
errored = true;
}
}
// \a means bell (alert).
'a' => {
result_char_or_none = Some('\x07');
}
// \b means backspace.
'b' => {
result_char_or_none = Some('\x08');
}
// \cX means control sequence X.
'c' => {
let sequence_char = u32::from(input.char_at(in_pos));
in_pos += 1;
if sequence_char >= u32::from('a') && sequence_char <= u32::from('a') + 32 {
result_char_or_none =
Some(char::from_u32(sequence_char - u32::from('a') + 1).unwrap());
} else if sequence_char >= u32::from('A') && sequence_char <= u32::from('A') + 32 {
result_char_or_none =
Some(char::from_u32(sequence_char - u32::from('A') + 1).unwrap());
} else {
errored = true;
}
}
// \x1B means escape.
'e' => {
result_char_or_none = Some('\x1B');
}
// \f means form feed.
'f' => {
result_char_or_none = Some('\x0C');
}
// \n means newline.
'n' => {
result_char_or_none = Some('\n');
}
// \r means carriage return.
'r' => {
result_char_or_none = Some('\x0D');
}
// \t means tab.
't' => {
result_char_or_none = Some('\t');
}
// \v means vertical tab.
'v' => {
result_char_or_none = Some('\x0b');
}
// If a backslash is followed by an actual newline, swallow them both.
'\n' => {
result_char_or_none = None;
}
_ => {
if unescape_special {
result.push(INTERNAL_SEPARATOR);
}
result_char_or_none = Some(c);
}
}