]> git.proxmox.com Git - rustc.git/blob - vendor/term-0.6.1/src/terminfo/parm.rs
New upstream version 1.62.1+dfsg1
[rustc.git] / vendor / term-0.6.1 / src / terminfo / parm.rs
1 // Copyright 2019 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Parameterized string expansion
12
13 use self::Param::*;
14 use self::States::*;
15
16 use std::iter::repeat;
17
18 #[derive(Clone, Copy, PartialEq)]
19 enum States {
20 Nothing,
21 Delay,
22 Percent,
23 SetVar,
24 GetVar,
25 PushParam,
26 CharConstant,
27 CharClose,
28 IntConstant(i32),
29 FormatPattern(Flags, FormatState),
30 SeekIfElse(usize),
31 SeekIfElsePercent(usize),
32 SeekIfEnd(usize),
33 SeekIfEndPercent(usize),
34 }
35
36 #[derive(Copy, PartialEq, Clone)]
37 enum FormatState {
38 Flags,
39 Width,
40 Precision,
41 }
42
43 /// Types of parameters a capability can use
44 #[allow(missing_docs)]
45 #[derive(Clone)]
46 pub enum Param {
47 Number(i32),
48 Words(String),
49 }
50
51 impl Default for Param {
52 fn default() -> Self {
53 Param::Number(0)
54 }
55 }
56
57 /// An error from interpreting a parameterized string.
58 #[derive(Debug, Eq, PartialEq)]
59 pub enum Error {
60 /// Data was requested from the stack, but the stack didn't have enough elements.
61 StackUnderflow,
62 /// The type of the element(s) on top of the stack did not match the type that the operator
63 /// wanted.
64 TypeMismatch,
65 /// An unrecognized format option was used.
66 UnrecognizedFormatOption(char),
67 /// An invalid variable name was used.
68 InvalidVariableName(char),
69 /// An invalid parameter index was used.
70 InvalidParameterIndex(char),
71 /// A malformed character constant was used.
72 MalformedCharacterConstant,
73 /// An integer constant was too large (overflowed an i32)
74 IntegerConstantOverflow,
75 /// A malformed integer constant was used.
76 MalformedIntegerConstant,
77 /// A format width constant was too large (overflowed a usize)
78 FormatWidthOverflow,
79 /// A format precision constant was too large (overflowed a usize)
80 FormatPrecisionOverflow,
81 }
82
83 impl ::std::fmt::Display for Error {
84 fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
85 use std::error::Error;
86 f.write_str(self.description())
87 }
88 }
89
90 impl ::std::error::Error for Error {
91 fn description(&self) -> &str {
92 use self::Error::*;
93 match *self {
94 StackUnderflow => "not enough elements on the stack",
95 TypeMismatch => "type mismatch",
96 UnrecognizedFormatOption(_) => "unrecognized format option",
97 InvalidVariableName(_) => "invalid variable name",
98 InvalidParameterIndex(_) => "invalid parameter index",
99 MalformedCharacterConstant => "malformed character constant",
100 IntegerConstantOverflow => "integer constant computation overflowed",
101 MalformedIntegerConstant => "malformed integer constant",
102 FormatWidthOverflow => "format width constant computation overflowed",
103 FormatPrecisionOverflow => "format precision constant computation overflowed",
104 }
105 }
106
107 fn cause(&self) -> Option<&dyn (::std::error::Error)> {
108 None
109 }
110 }
111
112 /// Container for static and dynamic variable arrays
113 #[derive(Default)]
114 pub struct Variables {
115 /// Static variables A-Z
116 sta_vars: [Param; 26],
117 /// Dynamic variables a-z
118 dyn_vars: [Param; 26],
119 }
120
121 impl Variables {
122 /// Return a new zero-initialized Variables
123 pub fn new() -> Variables {
124 Default::default()
125 }
126 }
127
128 /// Expand a parameterized capability
129 ///
130 /// # Arguments
131 /// * `cap` - string to expand
132 /// * `params` - vector of params for %p1 etc
133 /// * `vars` - Variables struct for %Pa etc
134 ///
135 /// To be compatible with ncurses, `vars` should be the same between calls to `expand` for
136 /// multiple capabilities for the same terminal.
137 pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables) -> Result<Vec<u8>, Error> {
138 let mut state = Nothing;
139
140 // expanded cap will only rarely be larger than the cap itself
141 let mut output = Vec::with_capacity(cap.len());
142
143 let mut stack: Vec<Param> = Vec::new();
144
145 // Copy parameters into a local vector for mutability
146 let mut mparams = [
147 Number(0),
148 Number(0),
149 Number(0),
150 Number(0),
151 Number(0),
152 Number(0),
153 Number(0),
154 Number(0),
155 Number(0),
156 ];
157 for (dst, src) in mparams.iter_mut().zip(params.iter()) {
158 *dst = (*src).clone();
159 }
160
161 for &c in cap.iter() {
162 let cur = c as char;
163 let mut old_state = state;
164 match state {
165 Nothing => {
166 if cur == '%' {
167 state = Percent;
168 } else if cur == '$' {
169 state = Delay;
170 } else {
171 output.push(c);
172 }
173 }
174 Delay => {
175 old_state = Nothing;
176 if cur == '>' {
177 state = Nothing;
178 }
179 }
180 Percent => {
181 match cur {
182 '%' => {
183 output.push(c);
184 state = Nothing
185 }
186 'c' => {
187 match stack.pop() {
188 // if c is 0, use 0200 (128) for ncurses compatibility
189 Some(Number(0)) => output.push(128u8),
190 // Don't check bounds. ncurses just casts and truncates.
191 Some(Number(c)) => output.push(c as u8),
192 Some(_) => return Err(Error::TypeMismatch),
193 None => return Err(Error::StackUnderflow),
194 }
195 }
196 'p' => state = PushParam,
197 'P' => state = SetVar,
198 'g' => state = GetVar,
199 '\'' => state = CharConstant,
200 '{' => state = IntConstant(0),
201 'l' => match stack.pop() {
202 Some(Words(s)) => stack.push(Number(s.len() as i32)),
203 Some(_) => return Err(Error::TypeMismatch),
204 None => return Err(Error::StackUnderflow),
205 },
206 '+' | '-' | '/' | '*' | '^' | '&' | '|' | 'm' => {
207 match (stack.pop(), stack.pop()) {
208 (Some(Number(y)), Some(Number(x))) => stack.push(Number(match cur {
209 '+' => x + y,
210 '-' => x - y,
211 '*' => x * y,
212 '/' => x / y,
213 '|' => x | y,
214 '&' => x & y,
215 '^' => x ^ y,
216 'm' => x % y,
217 _ => unreachable!("logic error"),
218 })),
219 (Some(_), Some(_)) => return Err(Error::TypeMismatch),
220 _ => return Err(Error::StackUnderflow),
221 }
222 }
223 '=' | '>' | '<' | 'A' | 'O' => match (stack.pop(), stack.pop()) {
224 (Some(Number(y)), Some(Number(x))) => stack.push(Number(
225 if match cur {
226 '=' => x == y,
227 '<' => x < y,
228 '>' => x > y,
229 'A' => x > 0 && y > 0,
230 'O' => x > 0 || y > 0,
231 _ => unreachable!("logic error"),
232 } {
233 1
234 } else {
235 0
236 },
237 )),
238 (Some(_), Some(_)) => return Err(Error::TypeMismatch),
239 _ => return Err(Error::StackUnderflow),
240 },
241 '!' | '~' => match stack.pop() {
242 Some(Number(x)) => stack.push(Number(match cur {
243 '!' if x > 0 => 0,
244 '!' => 1,
245 '~' => !x,
246 _ => unreachable!("logic error"),
247 })),
248 Some(_) => return Err(Error::TypeMismatch),
249 None => return Err(Error::StackUnderflow),
250 },
251 'i' => match (&mparams[0], &mparams[1]) {
252 (&Number(x), &Number(y)) => {
253 mparams[0] = Number(x + 1);
254 mparams[1] = Number(y + 1);
255 }
256 (_, _) => return Err(Error::TypeMismatch),
257 },
258
259 // printf-style support for %doxXs
260 'd' | 'o' | 'x' | 'X' | 's' => {
261 if let Some(arg) = stack.pop() {
262 let flags = Flags::default();
263 let res = format(arg, FormatOp::from_char(cur), flags)?;
264 output.extend(res);
265 } else {
266 return Err(Error::StackUnderflow);
267 }
268 }
269 ':' | '#' | ' ' | '.' | '0'..='9' => {
270 let mut flags = Flags::default();
271 let mut fstate = FormatState::Flags;
272 match cur {
273 ':' => (),
274 '#' => flags.alternate = true,
275 ' ' => flags.space = true,
276 '.' => fstate = FormatState::Precision,
277 '0'..='9' => {
278 flags.width = cur as usize - '0' as usize;
279 fstate = FormatState::Width;
280 }
281 _ => unreachable!("logic error"),
282 }
283 state = FormatPattern(flags, fstate);
284 }
285
286 // conditionals
287 '?' | ';' => (),
288 't' => match stack.pop() {
289 Some(Number(0)) => state = SeekIfElse(0),
290 Some(Number(_)) => (),
291 Some(_) => return Err(Error::TypeMismatch),
292 None => return Err(Error::StackUnderflow),
293 },
294 'e' => state = SeekIfEnd(0),
295 c => return Err(Error::UnrecognizedFormatOption(c)),
296 }
297 }
298 PushParam => {
299 // params are 1-indexed
300 stack.push(
301 mparams[match cur.to_digit(10) {
302 Some(d) => d as usize - 1,
303 None => return Err(Error::InvalidParameterIndex(cur)),
304 }]
305 .clone(),
306 );
307 }
308 SetVar => {
309 if cur >= 'A' && cur <= 'Z' {
310 if let Some(arg) = stack.pop() {
311 let idx = (cur as u8) - b'A';
312 vars.sta_vars[idx as usize] = arg;
313 } else {
314 return Err(Error::StackUnderflow);
315 }
316 } else if cur >= 'a' && cur <= 'z' {
317 if let Some(arg) = stack.pop() {
318 let idx = (cur as u8) - b'a';
319 vars.dyn_vars[idx as usize] = arg;
320 } else {
321 return Err(Error::StackUnderflow);
322 }
323 } else {
324 return Err(Error::InvalidVariableName(cur));
325 }
326 }
327 GetVar => {
328 if cur >= 'A' && cur <= 'Z' {
329 let idx = (cur as u8) - b'A';
330 stack.push(vars.sta_vars[idx as usize].clone());
331 } else if cur >= 'a' && cur <= 'z' {
332 let idx = (cur as u8) - b'a';
333 stack.push(vars.dyn_vars[idx as usize].clone());
334 } else {
335 return Err(Error::InvalidVariableName(cur));
336 }
337 }
338 CharConstant => {
339 stack.push(Number(i32::from(c)));
340 state = CharClose;
341 }
342 CharClose => {
343 if cur != '\'' {
344 return Err(Error::MalformedCharacterConstant);
345 }
346 }
347 IntConstant(i) => {
348 if cur == '}' {
349 stack.push(Number(i));
350 state = Nothing;
351 } else if let Some(digit) = cur.to_digit(10) {
352 match i
353 .checked_mul(10)
354 .and_then(|i_ten| i_ten.checked_add(digit as i32))
355 {
356 Some(i) => {
357 state = IntConstant(i);
358 old_state = Nothing;
359 }
360 None => return Err(Error::IntegerConstantOverflow),
361 }
362 } else {
363 return Err(Error::MalformedIntegerConstant);
364 }
365 }
366 FormatPattern(ref mut flags, ref mut fstate) => {
367 old_state = Nothing;
368 match (*fstate, cur) {
369 (_, 'd') | (_, 'o') | (_, 'x') | (_, 'X') | (_, 's') => {
370 if let Some(arg) = stack.pop() {
371 let res = format(arg, FormatOp::from_char(cur), *flags)?;
372 output.extend(res);
373 // will cause state to go to Nothing
374 old_state = FormatPattern(*flags, *fstate);
375 } else {
376 return Err(Error::StackUnderflow);
377 }
378 }
379 (FormatState::Flags, '#') => {
380 flags.alternate = true;
381 }
382 (FormatState::Flags, '-') => {
383 flags.left = true;
384 }
385 (FormatState::Flags, '+') => {
386 flags.sign = true;
387 }
388 (FormatState::Flags, ' ') => {
389 flags.space = true;
390 }
391 (FormatState::Flags, '0'..='9') => {
392 flags.width = cur as usize - '0' as usize;
393 *fstate = FormatState::Width;
394 }
395 (FormatState::Width, '0'..='9') => {
396 flags.width = match flags
397 .width
398 .checked_mul(10)
399 .and_then(|w| w.checked_add(cur as usize - '0' as usize))
400 {
401 Some(width) => width,
402 None => return Err(Error::FormatWidthOverflow),
403 }
404 }
405 (FormatState::Width, '.') | (FormatState::Flags, '.') => {
406 *fstate = FormatState::Precision;
407 }
408 (FormatState::Precision, '0'..='9') => {
409 flags.precision = match flags
410 .precision
411 .checked_mul(10)
412 .and_then(|w| w.checked_add(cur as usize - '0' as usize))
413 {
414 Some(precision) => precision,
415 None => return Err(Error::FormatPrecisionOverflow),
416 }
417 }
418 _ => return Err(Error::UnrecognizedFormatOption(cur)),
419 }
420 }
421 SeekIfElse(level) => {
422 if cur == '%' {
423 state = SeekIfElsePercent(level);
424 }
425 old_state = Nothing;
426 }
427 SeekIfElsePercent(level) => {
428 if cur == ';' {
429 if level == 0 {
430 state = Nothing;
431 } else {
432 state = SeekIfElse(level - 1);
433 }
434 } else if cur == 'e' && level == 0 {
435 state = Nothing;
436 } else if cur == '?' {
437 state = SeekIfElse(level + 1);
438 } else {
439 state = SeekIfElse(level);
440 }
441 }
442 SeekIfEnd(level) => {
443 if cur == '%' {
444 state = SeekIfEndPercent(level);
445 }
446 old_state = Nothing;
447 }
448 SeekIfEndPercent(level) => {
449 if cur == ';' {
450 if level == 0 {
451 state = Nothing;
452 } else {
453 state = SeekIfEnd(level - 1);
454 }
455 } else if cur == '?' {
456 state = SeekIfEnd(level + 1);
457 } else {
458 state = SeekIfEnd(level);
459 }
460 }
461 }
462 if state == old_state {
463 state = Nothing;
464 }
465 }
466 Ok(output)
467 }
468
469 #[derive(Copy, PartialEq, Clone, Default)]
470 struct Flags {
471 width: usize,
472 precision: usize,
473 alternate: bool,
474 left: bool,
475 sign: bool,
476 space: bool,
477 }
478
479 #[derive(Copy, Clone)]
480 enum FormatOp {
481 Digit,
482 Octal,
483 Hex,
484 HEX,
485 String,
486 }
487
488 impl FormatOp {
489 fn from_char(c: char) -> FormatOp {
490 use self::FormatOp::*;
491 match c {
492 'd' => Digit,
493 'o' => Octal,
494 'x' => Hex,
495 'X' => HEX,
496 's' => String,
497 _ => panic!("bad FormatOp char"),
498 }
499 }
500 }
501
502 fn format(val: Param, op: FormatOp, flags: Flags) -> Result<Vec<u8>, Error> {
503 use self::FormatOp::*;
504 let mut s = match val {
505 Number(d) => {
506 match op {
507 Digit => {
508 if flags.sign {
509 format!("{:+01$}", d, flags.precision)
510 } else if d < 0 {
511 // C doesn't take sign into account in precision calculation.
512 format!("{:01$}", d, flags.precision + 1)
513 } else if flags.space {
514 format!(" {:01$}", d, flags.precision)
515 } else {
516 format!("{:01$}", d, flags.precision)
517 }
518 }
519 Octal => {
520 if flags.alternate {
521 // Leading octal zero counts against precision.
522 format!("0{:01$o}", d, flags.precision.saturating_sub(1))
523 } else {
524 format!("{:01$o}", d, flags.precision)
525 }
526 }
527 Hex => {
528 if flags.alternate && d != 0 {
529 format!("0x{:01$x}", d, flags.precision)
530 } else {
531 format!("{:01$x}", d, flags.precision)
532 }
533 }
534 HEX => {
535 if flags.alternate && d != 0 {
536 format!("0X{:01$X}", d, flags.precision)
537 } else {
538 format!("{:01$X}", d, flags.precision)
539 }
540 }
541 String => return Err(Error::TypeMismatch),
542 }
543 .into_bytes()
544 }
545 Words(s) => match op {
546 String => {
547 let mut s = s.into_bytes();
548 if flags.precision > 0 && flags.precision < s.len() {
549 s.truncate(flags.precision);
550 }
551 s
552 }
553 _ => return Err(Error::TypeMismatch),
554 },
555 };
556 if flags.width > s.len() {
557 let n = flags.width - s.len();
558 if flags.left {
559 s.extend(repeat(b' ').take(n));
560 } else {
561 let mut s_ = Vec::with_capacity(flags.width);
562 s_.extend(repeat(b' ').take(n));
563 s_.extend(s.into_iter());
564 s = s_;
565 }
566 }
567 Ok(s)
568 }
569
570 #[cfg(test)]
571 mod test {
572 use super::Param::{self, Number, Words};
573 use super::{expand, Variables};
574 use std::result::Result::Ok;
575
576 #[test]
577 fn test_basic_setabf() {
578 let s = b"\\E[48;5;%p1%dm";
579 assert_eq!(
580 expand(s, &[Number(1)], &mut Variables::new()).unwrap(),
581 "\\E[48;5;1m".bytes().collect::<Vec<_>>()
582 );
583 }
584
585 #[test]
586 fn test_multiple_int_constants() {
587 assert_eq!(
588 expand(b"%{1}%{2}%d%d", &[], &mut Variables::new()).unwrap(),
589 "21".bytes().collect::<Vec<_>>()
590 );
591 }
592
593 #[test]
594 fn test_op_i() {
595 let mut vars = Variables::new();
596 assert_eq!(
597 expand(
598 b"%p1%d%p2%d%p3%d%i%p1%d%p2%d%p3%d",
599 &[Number(1), Number(2), Number(3)],
600 &mut vars
601 ),
602 Ok("123233".bytes().collect::<Vec<_>>())
603 );
604 assert_eq!(
605 expand(b"%p1%d%p2%d%i%p1%d%p2%d", &[], &mut vars),
606 Ok("0011".bytes().collect::<Vec<_>>())
607 );
608 }
609
610 #[test]
611 fn test_param_stack_failure_conditions() {
612 let mut varstruct = Variables::new();
613 let vars = &mut varstruct;
614 fn get_res(
615 fmt: &str,
616 cap: &str,
617 params: &[Param],
618 vars: &mut Variables,
619 ) -> Result<Vec<u8>, super::Error> {
620 let mut u8v: Vec<_> = fmt.bytes().collect();
621 u8v.extend(cap.as_bytes().iter().cloned());
622 expand(&u8v, params, vars)
623 }
624
625 let caps = ["%d", "%c", "%s", "%Pa", "%l", "%!", "%~"];
626 for &cap in &caps {
627 let res = get_res("", cap, &[], vars);
628 assert!(
629 res.is_err(),
630 "Op {} succeeded incorrectly with 0 stack entries",
631 cap
632 );
633 let p = if cap == "%s" || cap == "%l" {
634 Words("foo".to_owned())
635 } else {
636 Number(97)
637 };
638 let res = get_res("%p1", cap, &[p], vars);
639 assert!(
640 res.is_ok(),
641 "Op {} failed with 1 stack entry: {}",
642 cap,
643 res.err().unwrap()
644 );
645 }
646 let caps = ["%+", "%-", "%*", "%/", "%m", "%&", "%|", "%A", "%O"];
647 for &cap in &caps {
648 let res = expand(cap.as_bytes(), &[], vars);
649 assert!(
650 res.is_err(),
651 "Binop {} succeeded incorrectly with 0 stack entries",
652 cap
653 );
654 let res = get_res("%{1}", cap, &[], vars);
655 assert!(
656 res.is_err(),
657 "Binop {} succeeded incorrectly with 1 stack entry",
658 cap
659 );
660 let res = get_res("%{1}%{2}", cap, &[], vars);
661 assert!(
662 res.is_ok(),
663 "Binop {} failed with 2 stack entries: {}",
664 cap,
665 res.err().unwrap()
666 );
667 }
668 }
669
670 #[test]
671 fn test_push_bad_param() {
672 assert!(expand(b"%pa", &[], &mut Variables::new()).is_err());
673 }
674
675 #[test]
676 fn test_comparison_ops() {
677 let v = [
678 ('<', [1u8, 0u8, 0u8]),
679 ('=', [0u8, 1u8, 0u8]),
680 ('>', [0u8, 0u8, 1u8]),
681 ];
682 for &(op, bs) in &v {
683 let s = format!("%{{1}}%{{2}}%{}%d", op);
684 let res = expand(s.as_bytes(), &[], &mut Variables::new());
685 assert!(res.is_ok(), res.err().unwrap());
686 assert_eq!(res.unwrap(), vec![b'0' + bs[0]]);
687 let s = format!("%{{1}}%{{1}}%{}%d", op);
688 let res = expand(s.as_bytes(), &[], &mut Variables::new());
689 assert!(res.is_ok(), res.err().unwrap());
690 assert_eq!(res.unwrap(), vec![b'0' + bs[1]]);
691 let s = format!("%{{2}}%{{1}}%{}%d", op);
692 let res = expand(s.as_bytes(), &[], &mut Variables::new());
693 assert!(res.is_ok(), res.err().unwrap());
694 assert_eq!(res.unwrap(), vec![b'0' + bs[2]]);
695 }
696 }
697
698 #[test]
699 fn test_conditionals() {
700 let mut vars = Variables::new();
701 let s = b"\\E[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m";
702 let res = expand(s, &[Number(1)], &mut vars);
703 assert!(res.is_ok(), res.err().unwrap());
704 assert_eq!(res.unwrap(), "\\E[31m".bytes().collect::<Vec<_>>());
705 let res = expand(s, &[Number(8)], &mut vars);
706 assert!(res.is_ok(), res.err().unwrap());
707 assert_eq!(res.unwrap(), "\\E[90m".bytes().collect::<Vec<_>>());
708 let res = expand(s, &[Number(42)], &mut vars);
709 assert!(res.is_ok(), res.err().unwrap());
710 assert_eq!(res.unwrap(), "\\E[38;5;42m".bytes().collect::<Vec<_>>());
711 }
712
713 #[test]
714 fn test_format() {
715 let mut varstruct = Variables::new();
716 let vars = &mut varstruct;
717 assert_eq!(
718 expand(
719 b"%p1%s%p2%2s%p3%2s%p4%.2s",
720 &[
721 Words("foo".to_owned()),
722 Words("foo".to_owned()),
723 Words("f".to_owned()),
724 Words("foo".to_owned())
725 ],
726 vars
727 ),
728 Ok("foofoo ffo".bytes().collect::<Vec<_>>())
729 );
730 assert_eq!(
731 expand(b"%p1%:-4.2s", &[Words("foo".to_owned())], vars),
732 Ok("fo ".bytes().collect::<Vec<_>>())
733 );
734
735 assert_eq!(
736 expand(b"%p1%d%p1%.3d%p1%5d%p1%:+d", &[Number(1)], vars),
737 Ok("1001 1+1".bytes().collect::<Vec<_>>())
738 );
739 assert_eq!(
740 expand(
741 b"%p1%o%p1%#o%p2%6.4x%p2%#6.4X",
742 &[Number(15), Number(27)],
743 vars
744 ),
745 Ok("17017 001b0X001B".bytes().collect::<Vec<_>>())
746 );
747 }
748 }