Skip to main content

fontoxide_misc/
ps_lib.rs

1//! Port of `fontTools.misc.psLib`: a tokenizer and a minimal PostScript
2//! interpreter, just about enough to parse Type 1 fonts ([`suckfont`]).
3
4use std::cell::RefCell;
5use std::rc::Rc;
6
7use indexmap::IndexMap;
8use thiserror::Error;
9
10use crate::eexec;
11use crate::ps_operators::{DictRef, Key, Kind, ObjRef, PsObject, PsString};
12
13/// Errors of the tokenizer and the interpreter.
14#[derive(Debug, Clone, PartialEq, Eq, Error)]
15pub enum PsError {
16	/// `PSTokenError`.
17	#[error("{0}")]
18	Token(String),
19	/// `PSError`.
20	#[error("{0}")]
21	Ps(String),
22	/// The other Python exceptions the interpreter raises on bad input
23	/// (`RuntimeError`, `TypeError`, `KeyError`, `IndexError`, ...), with the
24	/// exception name.
25	#[error("{0}")]
26	Python(String),
27}
28
29type Result<T> = std::result::Result<T, PsError>;
30
31fn py_err(msg: impl Into<String>) -> PsError {
32	PsError::Python(msg.into())
33}
34
35/// `string.whitespace`.
36fn is_white(b: u8) -> bool {
37	matches!(b, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C)
38}
39
40/// `ps_special`; `/` is handled separately.
41const PS_SPECIAL: &[u8] = b"()<>[]{}%";
42
43/// The end of a name or number: `endofthingRE` stops at these.
44fn ends_thing(b: u8) -> bool {
45	is_white(b) || b"[](){}<>/%".contains(&b)
46}
47
48/// `bytes.decode(encoding)` for the codecs psLib may be given.
49fn decode(encoding: &str, data: &[u8]) -> Result<String> {
50	let name = fontoxide_encodings::codecs::normalize(encoding);
51	if matches!(name.as_str(), "utf_8" | "utf8" | "u8" | "utf") {
52		return String::from_utf8(data.to_vec()).map_err(|e| {
53			py_err(format!(
54				"UnicodeDecodeError: 'utf-8' codec can't decode byte at position {}",
55				e.utf8_error().valid_up_to()
56			))
57		});
58	}
59	fontoxide_encodings::codecs::decode(encoding, data)
60		.map_err(|e| py_err(format!("UnicodeDecodeError: {e}")))
61}
62
63/// Matches `stringRE` at `pos` (which holds `(`): a string literal with one
64/// level of balanced embedded parentheses, where a backslash escapes the byte
65/// after it. Returns the end of the match.
66fn match_string(buf: &[u8], pos: usize) -> Option<usize> {
67	let mut i = pos + 1;
68	loop {
69		match *buf.get(i)? {
70			b')' => return Some(i + 1),
71			b'\\' => {
72				buf.get(i + 1)?;
73				i += 2;
74			}
75			b'(' => {
76				i += 1;
77				loop {
78					match *buf.get(i)? {
79						b')' => {
80							i += 1;
81							break;
82						}
83						b'\\' => {
84							buf.get(i + 1)?;
85							i += 2;
86						}
87						// A second level of nesting is not supported: the
88						// whole match fails.
89						b'(' => return None,
90						_ => i += 1,
91					}
92				}
93			}
94			_ => i += 1,
95		}
96	}
97}
98
99/// Matches `hexstringRE` at `pos` (which holds `<`).
100fn match_hexstring(buf: &[u8], pos: usize) -> Option<usize> {
101	let mut i = pos + 1;
102	while let Some(&b) = buf.get(i) {
103		if b == b'>' {
104			return Some(i + 1);
105		}
106		if !(is_white(b) || b.is_ascii_hexdigit()) {
107			return None;
108		}
109		i += 1;
110	}
111	None
112}
113
114/// The tokenizer (`PSTokenizer`): reads PostScript tokens from a buffer, which
115/// can switch to the decrypted `eexec` part and back.
116#[derive(Debug, Clone)]
117pub struct PsTokenizer {
118	buf: Vec<u8>,
119	len: usize,
120	pos: usize,
121	closed: bool,
122	encoding: String,
123	dirtybuf: Option<Vec<u8>>,
124	id: u64,
125}
126
127thread_local! {
128	static NEXT_ID: std::cell::Cell<u64> = const { std::cell::Cell::new(1) };
129}
130
131fn next_id() -> u64 {
132	NEXT_ID.with(|c| {
133		let id = c.get();
134		c.set(id + 1);
135		id
136	})
137}
138
139impl PsTokenizer {
140	/// A tokenizer over `buf`, whose tokens are decoded with `encoding`
141	/// (`PSTokenizer(buf, encoding)`).
142	pub fn new(buf: &[u8], encoding: &str) -> Self {
143		PsTokenizer {
144			buf: buf.to_vec(),
145			len: buf.len(),
146			pos: 0,
147			closed: false,
148			encoding: encoding.to_owned(),
149			dirtybuf: None,
150			id: next_id(),
151		}
152	}
153
154	fn check_open(&self) -> Result<()> {
155		if self.closed {
156			return Err(py_err(
157				"AttributeError: 'PSTokenizer' object has no attribute 'buf'",
158			));
159		}
160		Ok(())
161	}
162
163	/// The position in the buffer.
164	pub fn pos(&self) -> usize {
165		self.pos
166	}
167
168	/// Reads at most `n` bytes, or all the rest when `n` is `None` (`read`).
169	pub fn read(&mut self, n: Option<usize>) -> Result<Vec<u8>> {
170		if self.closed {
171			return Err(py_err("ValueError: I/O operation on closed file"));
172		}
173		let newpos = match n {
174			None => self.len,
175			Some(n) => (self.pos + n).min(self.len),
176		};
177		let start = self.pos.min(self.buf.len());
178		let r = self.buf[start..newpos.clamp(start, self.buf.len())].to_vec();
179		self.pos = newpos;
180		Ok(r)
181	}
182
183	/// `close`.
184	pub fn close(&mut self) {
185		if !self.closed {
186			self.closed = true;
187			self.buf = Vec::new();
188			self.dirtybuf = None;
189		}
190	}
191
192	/// The next token and its type (`getnexttoken`): `"do_special"`,
193	/// `"do_comment"`, `"do_string"`, `"do_hexstring"`, `"do_literal"`, or `""`
194	/// for names and numbers; `None` at the end.
195	pub fn get_next_token(&mut self) -> Result<Option<(&'static str, String)>> {
196		self.skipwhite()?;
197		if self.pos >= self.len {
198			return Ok(None);
199		}
200		let pos = self.pos;
201		let buf = &self.buf;
202		let ch = buf[pos];
203		let (tokentype, end) = if PS_SPECIAL.contains(&ch) {
204			match ch {
205				b'{' | b'}' | b'[' | b']' => ("do_special", pos + 1),
206				b'%' => {
207					let mut end = pos + 1;
208					while end < buf.len() && !matches!(buf[end], b'\n' | b'\r') {
209						end += 1;
210					}
211					("do_comment", end)
212				}
213				b'(' => match match_string(buf, pos) {
214					Some(end) => ("do_string", end),
215					None => {
216						return Err(PsError::Token(format!("bad string at character {pos}")));
217					}
218				},
219				b'<' => match match_hexstring(buf, pos) {
220					Some(end) => ("do_hexstring", end),
221					None => {
222						return Err(PsError::Token(format!("bad hexstring at character {pos}")));
223					}
224				},
225				_ => return Err(PsError::Token(format!("bad token at character {pos}"))),
226			}
227		} else {
228			let (tokentype, start) = if ch == b'/' {
229				("do_literal", pos + 1)
230			} else {
231				("", pos)
232			};
233			let mut end = start;
234			while end < buf.len() && !ends_thing(buf[end]) {
235				end += 1;
236			}
237			(tokentype, end)
238		};
239		let token = decode(&self.encoding, &buf[pos..end])?;
240		self.pos = end;
241		Ok(Some((tokentype, token)))
242	}
243
244	/// Skips whitespace (`skipwhite`).
245	pub fn skipwhite(&mut self) -> Result<()> {
246		self.check_open()?;
247		while self.pos < self.buf.len() && is_white(self.buf[self.pos]) {
248			self.pos += 1;
249		}
250		Ok(())
251	}
252
253	/// Switches to the decrypted `eexec` part, after the byte that follows
254	/// `eexec` (`starteexec`).
255	pub fn starteexec(&mut self) -> Result<()> {
256		self.check_open()?;
257		self.pos += 1;
258		let dirty = self.buf.get(self.pos..).unwrap_or_default().to_vec();
259		let (buf, _) = eexec::decrypt(&dirty, 55665);
260		self.dirtybuf = Some(dirty);
261		self.len = buf.len();
262		self.buf = buf;
263		self.pos = 4;
264		Ok(())
265	}
266
267	/// Switches back to the encrypted data, at the same position
268	/// (`stopeexec`).
269	pub fn stopeexec(&mut self) -> Result<()> {
270		self.check_open()?;
271		if let Some(dirty) = self.dirtybuf.take() {
272			self.buf = dirty;
273		}
274		Ok(())
275	}
276}
277
278/// A Python number of the interpreter's arithmetic.
279#[derive(Debug, Clone, Copy)]
280enum Num {
281	Int(i64),
282	Float(f64),
283}
284
285impl Num {
286	fn f(self) -> f64 {
287		match self {
288			Num::Int(i) => i as f64,
289			Num::Float(f) => f,
290		}
291	}
292
293	fn gt(self, o: Num) -> bool {
294		match (self, o) {
295			(Num::Int(a), Num::Int(b)) => a > b,
296			_ => self.f() > o.f(),
297		}
298	}
299
300	fn lt(self, o: Num) -> bool {
301		match (self, o) {
302			(Num::Int(a), Num::Int(b)) => a < b,
303			_ => self.f() < o.f(),
304		}
305	}
306
307	fn add(self, o: Num) -> Result<Num> {
308		Ok(match (self, o) {
309			(Num::Int(a), Num::Int(b)) => Num::Int(
310				a.checked_add(b)
311					.ok_or_else(|| py_err("OverflowError: integer overflow"))?,
312			),
313			_ => Num::Float(self.f() + o.f()),
314		})
315	}
316
317	fn is_positive(self) -> bool {
318		match self {
319			Num::Int(i) => i > 0,
320			Num::Float(f) => f > 0.0,
321		}
322	}
323}
324
325/// Normalizes a Python index into a list of `len` elements.
326fn py_index(len: usize, i: i64) -> Option<usize> {
327	let i = if i < 0 { i + len as i64 } else { i };
328	usize::try_from(i).ok().filter(|&i| i < len)
329}
330
331/// The range of `seq[start:stop]`.
332fn py_slice(len: usize, start: i64, stop: i64) -> (usize, usize) {
333	let clamp = |i: i64| -> usize {
334		let i = if i < 0 { i + len as i64 } else { i };
335		i.clamp(0, len as i64) as usize
336	};
337	let (a, b) = (clamp(start), clamp(stop));
338	(a, b.max(a))
339}
340
341fn index_error() -> PsError {
342	py_err("IndexError: list index out of range")
343}
344
345/// The unpacked value of a PostScript object (`unpack_item`): the Python
346/// values fontTools' T1 font dictionaries hold.
347#[derive(Debug, Clone, PartialEq)]
348pub enum PsValue {
349	/// `None`: the value of operators and `null`.
350	None,
351	/// A `bool`, from the comparison operators.
352	Bool(bool),
353	/// An `int`; `true` and `false` unpack to 1 and 0.
354	Int(i64),
355	/// A `float`.
356	Float(f64),
357	/// A `str`: names, literals, text strings.
358	Str(String),
359	/// A `bytes`: strings read by `readstring`, e.g. encrypted charstrings.
360	Bytes(Vec<u8>),
361	/// A `list`: arrays.
362	List(Vec<PsValue>),
363	/// A `tuple`: procedures.
364	Tuple(Vec<PsValue>),
365	/// A `dict`: dictionaries and fonts.
366	Dict(IndexMap<Key, PsValue>),
367	/// A file object (the tokenizer).
368	File,
369}
370
371const MAX_DEPTH: usize = 900;
372
373/// The interpreter (`PSInterpreter`), with the operators of `PSOperators`.
374#[derive(Debug)]
375pub struct PsInterpreter {
376	encoding: String,
377	/// The dictionary stack (`dictstack`): `systemdict`, `userdict`, then the
378	/// dictionaries of `begin`.
379	pub dictstack: Vec<DictRef>,
380	/// The operand stack (`stack`).
381	pub stack: Vec<ObjRef>,
382	proclevel: usize,
383	procmark: ObjRef,
384	mark: ObjRef,
385	tokenizer: Option<PsTokenizer>,
386	depth: usize,
387}
388
389/// The operators, in the order `dir()` lists their methods (`suckoperators`).
390const OPERATORS: [&str; 48] = [
391	"anchorsearch",
392	"array",
393	"astore",
394	"begin",
395	"bind",
396	"cleartomark",
397	"closefile",
398	"count",
399	"currentdict",
400	"currentfile",
401	"cvn",
402	"cvx",
403	"def",
404	"definefont",
405	"dict",
406	"dup",
407	"eexec",
408	"end",
409	"eq",
410	"exch",
411	"exec",
412	"executeonly",
413	"findfont",
414	"for",
415	"forall",
416	"get",
417	"getinterval",
418	"if",
419	"ifelse",
420	"index",
421	"known",
422	"load",
423	"matrix",
424	"ne",
425	"noaccess",
426	"not",
427	"pop",
428	"print",
429	"put",
430	"putinterval",
431	"readonly",
432	"readstring",
433	"store",
434	"string",
435	"systemdict",
436	"type",
437	"userdict",
438	"where",
439];
440
441fn new_dict() -> DictRef {
442	Rc::new(RefCell::new(IndexMap::new()))
443}
444
445fn obj(kind: Kind) -> ObjRef {
446	PsObject::new(kind)
447}
448
449fn boolean(value: bool, py_bool: bool) -> ObjRef {
450	obj(Kind::Boolean { value, py_bool })
451}
452
453impl Default for PsInterpreter {
454	fn default() -> Self {
455		Self::new("ascii")
456	}
457}
458
459impl PsInterpreter {
460	/// A new interpreter whose tokens are decoded with `encoding`
461	/// (`PSInterpreter(encoding)`).
462	pub fn new(encoding: &str) -> Self {
463		let mut interp = PsInterpreter {
464			encoding: encoding.to_owned(),
465			dictstack: vec![new_dict(), new_dict()],
466			stack: Vec::new(),
467			proclevel: 0,
468			procmark: obj(Kind::ProcMark),
469			mark: obj(Kind::Mark),
470			tokenizer: None,
471			depth: 0,
472		};
473		interp.fillsystemdict();
474		interp
475	}
476
477	fn fillsystemdict(&mut self) {
478		let mut d = self.dictstack[0].borrow_mut();
479		d.insert("[".into(), self.mark.clone());
480		d.insert("mark".into(), self.mark.clone());
481		d.insert("]".into(), obj(Kind::Operator("]")));
482		d.insert("true".into(), boolean(true, false));
483		d.insert("false".into(), boolean(false, false));
484		let encoding = fontoxide_encodings::standard_encoding::STANDARD_ENCODING
485			.iter()
486			.map(|n| Some(obj(Kind::Name((*n).to_owned()))))
487			.collect();
488		d.insert("StandardEncoding".into(), obj(Kind::Array(encoding)));
489		d.insert("FontDirectory".into(), obj(Kind::Dict(new_dict())));
490		for name in OPERATORS {
491			d.insert((*name).into(), obj(Kind::Operator(name)));
492		}
493	}
494
495	/// Interprets PostScript code (`interpret`).
496	pub fn interpret(&mut self, data: &[u8]) -> Result<()> {
497		self.tokenizer = Some(PsTokenizer::new(data, &self.encoding));
498		let result = self.interpret_loop();
499		match result {
500			Ok(()) => {
501				if let Some(t) = self.tokenizer.as_mut() {
502					t.close();
503				}
504				self.tokenizer = None;
505				Ok(())
506			}
507			Err(e) => {
508				if let Some(t) = &self.tokenizer {
509					let pos = t.pos.min(t.buf.len());
510					log::debug!(
511						"ps error:\n- - - - - - -\n{}\n>>>\n{}\n- - - - - - -",
512						crate::py::bytes_repr(&t.buf[pos.saturating_sub(50)..pos]),
513						crate::py::bytes_repr(&t.buf[pos..(pos + 50).min(t.buf.len())])
514					);
515				}
516				Err(e)
517			}
518		}
519	}
520
521	fn tokenizer_mut(&mut self) -> Result<&mut PsTokenizer> {
522		self.tokenizer
523			.as_mut()
524			.ok_or_else(|| py_err("AttributeError: 'NoneType' object has no attribute"))
525	}
526
527	fn interpret_loop(&mut self) -> Result<()> {
528		while let Some((tokentype, token)) = self.tokenizer_mut()?.get_next_token()? {
529			let object = match tokentype {
530				"" => Some(self.do_token(&token)),
531				"do_comment" => None,
532				"do_literal" => Some(obj(Kind::Literal(token[1..].to_owned()))),
533				"do_string" => {
534					let mut chars = token.chars();
535					chars.next();
536					chars.next_back();
537					Some(obj(Kind::String(PsString::Text(chars.as_str().to_owned()))))
538				}
539				"do_hexstring" => Some(self.do_hexstring(&token)?),
540				_ => Some(self.do_special(&token)?),
541			};
542			if let Some(object) = object {
543				self.handle_object(object)?;
544			}
545		}
546		Ok(())
547	}
548
549	/// `handle_object`: pushes literal objects and objects inside procedures,
550	/// runs the others.
551	fn handle_object(&mut self, object: ObjRef) -> Result<()> {
552		let (literal, is_proc, is_op) = {
553			let o = object.borrow();
554			(
555				o.literal,
556				matches!(o.kind, Kind::Procedure(_)),
557				matches!(o.kind, Kind::Operator(_)),
558			)
559		};
560		if !(self.proclevel > 0 || literal || is_proc) {
561			let object = if is_op {
562				object
563			} else {
564				let key = key_of(&object)?;
565				self.resolve_name(&key)?
566			};
567			let (literal, kind) = {
568				let o = object.borrow();
569				(o.literal, o.kind.clone())
570			};
571			if literal {
572				self.push(object);
573			} else {
574				match kind {
575					Kind::Procedure(_) => self.call_procedure(&object)?,
576					Kind::Operator(name) => self.call_operator(name)?,
577					_ => {
578						return Err(py_err(format!(
579							"AttributeError: '{}' object has no attribute 'function'",
580							object.borrow().type_name()
581						)));
582					}
583				}
584			}
585		} else {
586			self.push(object);
587		}
588		Ok(())
589	}
590
591	fn call_procedure(&mut self, proc: &ObjRef) -> Result<()> {
592		self.depth += 1;
593		if self.depth > MAX_DEPTH {
594			self.depth -= 1;
595			return Err(py_err("RecursionError: maximum recursion depth exceeded"));
596		}
597		let mut i = 0;
598		let result = loop {
599			let item = match &proc.borrow().kind {
600				Kind::Procedure(items) => match items.get(i) {
601					Some(item) => item.clone(),
602					None => break Ok(()),
603				},
604				_ => break Err(py_err("TypeError: not a procedure")),
605			};
606			i += 1;
607			if let Err(e) = self.handle_object(item) {
608				break Err(e);
609			}
610		};
611		self.depth -= 1;
612		result
613	}
614
615	/// `resolve_name`: looks a name up in the dictionary stack, from the top.
616	pub fn resolve_name(&self, name: &Key) -> Result<ObjRef> {
617		for d in self.dictstack.iter().rev() {
618			if let Some(o) = d.borrow().get(name) {
619				return Ok(o.clone());
620			}
621		}
622		Err(PsError::Ps(format!("name error: {name}")))
623	}
624
625	/// `do_token`: a number, or an executable name.
626	fn do_token(&self, token: &str) -> ObjRef {
627		if let Some(i) = crate::py::parse_int(token) {
628			// LENIENT(L45): integers beyond 64 bits (Python's are unbounded) become
629			// names.
630			if let Ok(i) = i64::try_from(i) {
631				return obj(Kind::Integer(i));
632			}
633			return obj(Kind::Name(token.to_owned()));
634		}
635		if let Some(f) = crate::py::parse_float(token) {
636			return obj(Kind::Real(f));
637		}
638		if let Some(hashpos) = token.find('#') {
639			let num = crate::py::parse_int(&token[..hashpos]).and_then(|base| {
640				let digits = &token[hashpos + 1..];
641				match base {
642					0 => crate::text_tools::parse_int_literal(digits),
643					2..=36 => crate::text_tools::parse_int_radix(digits, base as u32),
644					_ => None,
645				}
646			});
647			if let Some(i) = num.and_then(|n| i64::try_from(n).ok()) {
648				return obj(Kind::Integer(i));
649			}
650		}
651		obj(Kind::Name(token.to_owned()))
652	}
653
654	fn do_hexstring(&self, token: &str) -> Result<ObjRef> {
655		let mut hex: String = token[1..token.len() - 1]
656			.chars()
657			.filter(|c| !crate::py::is_space(*c))
658			.collect();
659		if hex.len() % 2 == 1 {
660			hex.push('0');
661		}
662		let mut s = String::new();
663		for pair in hex.as_bytes().chunks(2) {
664			let v = std::str::from_utf8(pair)
665				.ok()
666				.and_then(|p| u8::from_str_radix(p, 16).ok())
667				.ok_or_else(|| py_err("ValueError: invalid literal for int() with base 16"))?;
668			s.push(v as char);
669		}
670		Ok(obj(Kind::String(PsString::Text(s))))
671	}
672
673	fn do_special(&mut self, token: &str) -> Result<ObjRef> {
674		match token {
675			"{" => {
676				self.proclevel += 1;
677				Ok(self.procmark.clone())
678			}
679			"}" => {
680				let mut proc = Vec::new();
681				loop {
682					let top = self.pop(&[])?;
683					if Rc::ptr_eq(&top, &self.procmark) {
684						break;
685					}
686					proc.push(top);
687				}
688				self.proclevel = self.proclevel.saturating_sub(1);
689				proc.reverse();
690				Ok(obj(Kind::Procedure(proc)))
691			}
692			"[" => Ok(self.mark.clone()),
693			"]" => Ok(obj(Kind::Name("]".into()))),
694			_ => Err(PsError::Token("huh?".into())),
695		}
696	}
697
698	/// Pushes an object (`push`).
699	pub fn push(&mut self, object: ObjRef) {
700		self.stack.push(object);
701	}
702
703	/// Pops an object, checking its type if `types` is not empty (`pop`).
704	pub fn pop(&mut self, types: &[&str]) -> Result<ObjRef> {
705		let Some(top) = self.stack.last() else {
706			return Err(PsError::Ps("stack underflow".into()));
707		};
708		if !types.is_empty() {
709			let t = top.borrow().type_name();
710			if !types.contains(&t) {
711				let repr = if types.len() == 1 {
712					format!("('{}',)", types[0])
713				} else {
714					format!(
715						"({})",
716						types
717							.iter()
718							.map(|t| format!("'{t}'"))
719							.collect::<Vec<_>>()
720							.join(", ")
721					)
722				};
723				return Err(PsError::Ps(format!(
724					"typecheck, expected {repr}, found {t}"
725				)));
726			}
727		}
728		Ok(self.stack.pop().unwrap_or_else(|| obj(Kind::Null)))
729	}
730
731	fn do_makearray(&mut self) -> Result<()> {
732		let mut array = Vec::new();
733		loop {
734			let top = self.pop(&[])?;
735			if Rc::ptr_eq(&top, &self.mark) {
736				break;
737			}
738			array.push(Some(top));
739		}
740		array.reverse();
741		self.push(obj(Kind::Array(array)));
742		Ok(())
743	}
744
745	/// Breaks the reference cycles the dictionaries may hold (`close`).
746	pub fn close(&mut self) {
747		self.stack.clear();
748		for d in self.dictstack.drain(..) {
749			d.borrow_mut().clear();
750		}
751	}
752
753	fn int_value(o: &ObjRef) -> Result<i64> {
754		match o.borrow().kind {
755			Kind::Integer(i) => Ok(i),
756			Kind::Boolean { value, .. } => Ok(value as i64),
757			_ => Err(py_err("TypeError: list indices must be integers or slices")),
758		}
759	}
760
761	fn num_value(o: &ObjRef) -> Result<Num> {
762		match o.borrow().kind {
763			Kind::Integer(i) => Ok(Num::Int(i)),
764			Kind::Real(f) => Ok(Num::Float(f)),
765			_ => Err(py_err("TypeError: not a number")),
766		}
767	}
768
769	fn truthy(o: &ObjRef) -> bool {
770		match &o.borrow().kind {
771			Kind::Boolean { value, .. } => *value,
772			Kind::Integer(i) => *i != 0,
773			Kind::Real(f) => *f != 0.0,
774			_ => true,
775		}
776	}
777
778	fn font_directory(&self) -> Result<DictRef> {
779		let fd = self.dictstack[0]
780			.borrow()
781			.get(&Key::from("FontDirectory"))
782			.cloned()
783			.ok_or_else(|| py_err("KeyError: 'FontDirectory'"))?;
784		let d = match &fd.borrow().kind {
785			Kind::Dict(d) | Kind::Font(d) => d.clone(),
786			_ => return Err(py_err("TypeError: FontDirectory is not a dict")),
787		};
788		Ok(d)
789	}
790
791	fn file_check(&mut self, f: &ObjRef) -> Result<&mut PsTokenizer> {
792		let id = match f.borrow().kind {
793			Kind::File(id) => id,
794			_ => return Err(py_err("TypeError: not a file")),
795		};
796		let t = self.tokenizer_mut()?;
797		if t.id != id {
798			// LENIENT(L45): a file object of an earlier `interpret` call; fontTools
799			// would operate on that closed tokenizer and fail.
800			return Err(py_err("ValueError: I/O operation on closed file"));
801		}
802		Ok(t)
803	}
804
805	fn proc_bind(&self, proc: &ObjRef) {
806		let n = proc_len(proc);
807		for i in 0..n {
808			let item = match &proc.borrow().kind {
809				Kind::Procedure(items) => match items.get(i) {
810					Some(item) => item.clone(),
811					None => return,
812				},
813				_ => return,
814			};
815			let (is_proc, literal) = {
816				let o = item.borrow();
817				(matches!(o.kind, Kind::Procedure(_)), o.literal)
818			};
819			if is_proc {
820				self.proc_bind(&item);
821			} else if !literal
822				&& let Ok(key) = key_of(&item)
823				&& let Ok(resolved) = self.resolve_name(&key)
824				&& matches!(resolved.borrow().kind, Kind::Operator(_))
825				&& let Kind::Procedure(items) = &mut proc.borrow_mut().kind
826			{
827				items[i] = resolved;
828			}
829		}
830	}
831
832	/// Runs an operator (`ps_*` methods, and `]`).
833	fn call_operator(&mut self, name: &str) -> Result<()> {
834		match name {
835			"]" => self.do_makearray()?,
836			"def" => {
837				let o = self.pop(&[])?;
838				let name = self.pop(&[])?;
839				let key = key_of(&name)?;
840				let top = self.dictstack.last().cloned().ok_or_else(index_error)?;
841				top.borrow_mut().insert(key, o);
842			}
843			"bind" => {
844				let proc = self.pop(&["proceduretype"])?;
845				self.proc_bind(&proc);
846				self.push(proc);
847			}
848			"exch" => {
849				if self.stack.len() < 2 {
850					return Err(py_err("RuntimeError: stack underflow"));
851				}
852				let a = self.pop(&[])?;
853				let b = self.pop(&[])?;
854				self.push(a);
855				self.push(b);
856			}
857			"dup" => {
858				let top = self
859					.stack
860					.last()
861					.cloned()
862					.ok_or_else(|| py_err("RuntimeError: stack underflow"))?;
863				self.push(top);
864			}
865			"exec" => {
866				let o = self.pop(&[])?;
867				if matches!(o.borrow().kind, Kind::Procedure(_)) {
868					self.call_procedure(&o)?;
869				} else {
870					self.handle_object(o)?;
871				}
872			}
873			"count" => {
874				let n = self.stack.len() as i64;
875				self.push(obj(Kind::Integer(n)));
876			}
877			"eq" | "ne" => {
878				let a = self.pop(&[])?;
879				let b = self.pop(&[])?;
880				let eq = py_eq(&a, &b);
881				self.push(boolean(if name == "eq" { eq } else { !eq }, true));
882			}
883			"cvx" => {
884				let o = self.pop(&[])?;
885				o.borrow_mut().literal = false;
886				self.push(o);
887			}
888			"matrix" => {
889				let m = vec![
890					Some(obj(Kind::Real(1.0))),
891					Some(obj(Kind::Integer(0))),
892					Some(obj(Kind::Integer(0))),
893					Some(obj(Kind::Real(1.0))),
894					Some(obj(Kind::Integer(0))),
895					Some(obj(Kind::Integer(0))),
896				];
897				self.push(obj(Kind::Array(m)));
898			}
899			"string" => {
900				let num = Self::int_value(&self.pop(&["integertype"])?)?;
901				let s = "\0".repeat(num.max(0) as usize);
902				self.push(obj(Kind::String(PsString::Text(s))));
903			}
904			"type" => {
905				let o = self.pop(&[])?;
906				let t = o.borrow().type_name();
907				self.push(obj(Kind::String(PsString::Text(t.to_owned()))));
908			}
909			"store" => {
910				let value = self.pop(&[])?;
911				let key = self.pop(&[])?;
912				let name = key_of(&key)?;
913				for d in self.dictstack.iter().rev() {
914					let mut d = d.borrow_mut();
915					if d.contains_key(&name) {
916						d.insert(name.clone(), value.clone());
917						break;
918					}
919				}
920				// UPSTREAM-BUG(B62): fontTools also stores the value in the current
921				// dictionary, whether or not it found the name elsewhere.
922				let top = self.dictstack.last().cloned().ok_or_else(index_error)?;
923				top.borrow_mut().insert(name, value);
924			}
925			"where" => {
926				self.pop(&[])?;
927				self.push(boolean(false, false));
928			}
929			"systemdict" | "userdict" | "currentdict" => {
930				let d = match name {
931					"systemdict" => self.dictstack[0].clone(),
932					"userdict" => self.dictstack.get(1).cloned().ok_or_else(index_error)?,
933					_ => self.dictstack.last().cloned().ok_or_else(index_error)?,
934				};
935				self.push(obj(Kind::Dict(d)));
936			}
937			"currentfile" => {
938				let id = self.tokenizer_mut()?.id;
939				self.push(obj(Kind::File(id)));
940			}
941			"eexec" => {
942				let f = self.pop(&["filetype"])?;
943				self.file_check(&f)?.starteexec()?;
944			}
945			"closefile" => {
946				let f = self.pop(&["filetype"])?;
947				let t = self.file_check(&f)?;
948				t.skipwhite()?;
949				t.stopeexec()?;
950			}
951			"cleartomark" => {
952				let mut o = self.pop(&[])?;
953				while !Rc::ptr_eq(&o, &self.mark) {
954					o = self.pop(&[])?;
955				}
956			}
957			"readstring" => {
958				let s = self.pop(&["stringtype"])?;
959				let old_len = match &s.borrow().kind {
960					Kind::String(v) => v.len(),
961					_ => 0,
962				};
963				let f = self.pop(&["filetype"])?;
964				let t = self.file_check(&f)?;
965				t.pos += 1;
966				let new = t.read(Some(old_len))?;
967				let same = new.len() == old_len;
968				s.borrow_mut().kind = Kind::String(PsString::Bytes(new));
969				self.push(s);
970				self.push(boolean(same, true));
971			}
972			"known" => {
973				let key = self.pop(&[])?;
974				let d = self.pop(&["dicttype", "fonttype"])?;
975				let key = key_of(&key)?;
976				let known = match &d.borrow().kind {
977					Kind::Dict(d) | Kind::Font(d) => d.borrow().contains_key(&key),
978					_ => false,
979				};
980				self.push(boolean(known, true));
981			}
982			"if" => {
983				let proc = self.pop(&["proceduretype"])?;
984				if Self::truthy(&self.pop(&["booleantype"])?) {
985					self.call_procedure(&proc)?;
986				}
987			}
988			"ifelse" => {
989				let proc2 = self.pop(&["proceduretype"])?;
990				let proc1 = self.pop(&["proceduretype"])?;
991				if Self::truthy(&self.pop(&["booleantype"])?) {
992					self.call_procedure(&proc1)?;
993				} else {
994					self.call_procedure(&proc2)?;
995				}
996			}
997			"readonly" | "executeonly" | "noaccess" => {
998				let level = match name {
999					"readonly" => 1,
1000					"executeonly" => 2,
1001					_ => 3,
1002				};
1003				let o = self.pop(&[])?;
1004				{
1005					let mut b = o.borrow_mut();
1006					if b.access < level {
1007						b.access = level;
1008					}
1009				}
1010				self.push(o);
1011			}
1012			"not" => {
1013				let o = self.pop(&["booleantype", "integertype"])?;
1014				let new = match o.borrow().kind {
1015					Kind::Boolean { value, .. } => boolean(!value, true),
1016					Kind::Integer(i) => obj(Kind::Integer(!i)),
1017					_ => return Err(py_err("TypeError: bad operand type for not")),
1018				};
1019				self.push(new);
1020			}
1021			"print" => {
1022				let s = self.pop(&["stringtype"])?;
1023				if let Kind::String(v) = &s.borrow().kind {
1024					match v {
1025						PsString::Text(t) => println!("PS output ---> {t}"),
1026						PsString::Bytes(b) => {
1027							println!("PS output ---> {}", crate::py::bytes_repr(b));
1028						}
1029					}
1030				}
1031			}
1032			"anchorsearch" => {
1033				let seek = self.pop(&["stringtype"])?;
1034				let s = self.pop(&["stringtype"])?;
1035				let (sv, seekv) = (string_value(&s), string_value(&seek));
1036				let found = match (&sv, &seekv) {
1037					(PsString::Text(a), PsString::Text(b)) => {
1038						let n = b.chars().count();
1039						let head: String = a.chars().take(n).collect();
1040						(head == *b).then(|| PsString::Text(a.chars().skip(n).collect()))
1041					}
1042					(PsString::Bytes(a), PsString::Bytes(b)) => {
1043						let n = b.len().min(a.len());
1044						(a[..n] == b[..]).then(|| PsString::Bytes(a[n..].to_vec()))
1045					}
1046					_ => None,
1047				};
1048				match found {
1049					Some(rest) => {
1050						self.push(obj(Kind::String(rest)));
1051						self.push(seek);
1052						self.push(boolean(true, false));
1053					}
1054					None => {
1055						self.push(s);
1056						self.push(boolean(false, false));
1057					}
1058				}
1059			}
1060			"array" => {
1061				let n = Self::int_value(&self.pop(&["integertype"])?)?;
1062				self.push(obj(Kind::Array(vec![None; n.max(0) as usize])));
1063			}
1064			"astore" => {
1065				let array = self.pop(&["arraytype"])?;
1066				let n = match &array.borrow().kind {
1067					Kind::Array(v) => v.len(),
1068					_ => 0,
1069				};
1070				for i in (0..n).rev() {
1071					let o = self.pop(&[])?;
1072					if let Kind::Array(v) = &mut array.borrow_mut().kind {
1073						v[i] = Some(o);
1074					}
1075				}
1076				self.push(array);
1077			}
1078			"load" => {
1079				let n = self.pop(&[])?;
1080				let key = key_of(&n)?;
1081				let o = self.resolve_name(&key)?;
1082				self.push(o);
1083			}
1084			"put" => self.ps_put()?,
1085			"get" => self.ps_get()?,
1086			"getinterval" => {
1087				let count = Self::int_value(&self.pop(&["integertype"])?)?;
1088				let start = Self::int_value(&self.pop(&["integertype"])?)?;
1089				let src = self.pop(&["arraytype", "stringtype"])?;
1090				let new = match &src.borrow().kind {
1091					Kind::Array(v) => {
1092						let (a, b) = py_slice(v.len(), start, start.saturating_add(count));
1093						Kind::Array(v[a..b].to_vec())
1094					}
1095					Kind::String(s) => {
1096						Kind::String(slice_string(s, start, start.saturating_add(count)))
1097					}
1098					_ => return Err(py_err("TypeError")),
1099				};
1100				self.push(obj(new));
1101			}
1102			"putinterval" => {
1103				let src = self.pop(&["arraytype", "stringtype"])?;
1104				let start = Self::int_value(&self.pop(&["integertype"])?)?;
1105				let dst = self.pop(&["arraytype", "stringtype"])?;
1106				let src_kind = src.borrow().kind.clone();
1107				let mut d = dst.borrow_mut();
1108				match (&mut d.kind, src_kind) {
1109					(Kind::Array(v), Kind::Array(s)) => {
1110						let (a, b) = py_slice(v.len(), start, start.saturating_add(s.len() as i64));
1111						v.splice(a..b, s);
1112					}
1113					(Kind::String(PsString::Text(v)), Kind::String(PsString::Text(s))) => {
1114						let chars: Vec<char> = v.chars().collect();
1115						let n = s.chars().count() as i64;
1116						let (a, _) = py_slice(chars.len(), 0, start);
1117						let (b, _) = py_slice(chars.len(), start.saturating_add(n), i64::MAX);
1118						let mut new: String = chars[..a].iter().collect();
1119						new.push_str(&s);
1120						new.extend(&chars[b..]);
1121						*v = new;
1122					}
1123					(Kind::String(PsString::Bytes(v)), Kind::String(PsString::Bytes(s))) => {
1124						let n = s.len() as i64;
1125						let (a, _) = py_slice(v.len(), 0, start);
1126						let (b, _) = py_slice(v.len(), start.saturating_add(n), i64::MAX);
1127						let mut new = v[..a].to_vec();
1128						new.extend_from_slice(&s);
1129						new.extend_from_slice(&v[b..]);
1130						*v = new;
1131					}
1132					// LENIENT(L45): fontTools mixes the types (e.g. characters into an
1133					// array) or fails with a TypeError.
1134					_ => return Err(py_err("TypeError: putinterval of different types")),
1135				}
1136			}
1137			"cvn" => {
1138				let s = self.pop(&["stringtype"])?;
1139				let v = string_value(&s);
1140				match v {
1141					PsString::Text(t) => self.push(obj(Kind::Name(t))),
1142					// LENIENT(L45): fontTools makes a name with a bytes value.
1143					PsString::Bytes(_) => return Err(py_err("TypeError: cvn of bytes")),
1144				}
1145			}
1146			"index" => {
1147				let n = Self::int_value(&self.pop(&["integertype"])?)?;
1148				if n < 0 {
1149					return Err(py_err("RuntimeError: index may not be negative"));
1150				}
1151				let len = self.stack.len() as i64;
1152				let at = py_index(self.stack.len(), -1 - n).filter(|_| -1 - n >= -len);
1153				let o = self
1154					.stack
1155					.get(at.ok_or_else(index_error)?)
1156					.cloned()
1157					.ok_or_else(index_error)?;
1158				self.push(o);
1159			}
1160			"for" => {
1161				let proc = self.pop(&["proceduretype"])?;
1162				let limit = Self::num_value(&self.pop(&["integertype", "realtype"])?)?;
1163				let increment = Self::num_value(&self.pop(&["integertype", "realtype"])?)?;
1164				let mut i = Self::num_value(&self.pop(&["integertype", "realtype"])?)?;
1165				loop {
1166					if increment.is_positive() {
1167						if i.gt(limit) {
1168							break;
1169						}
1170					} else if i.lt(limit) {
1171						break;
1172					}
1173					self.push(match i {
1174						Num::Int(v) => obj(Kind::Integer(v)),
1175						Num::Float(f) => obj(Kind::Real(f)),
1176					});
1177					self.call_procedure(&proc)?;
1178					i = i.add(increment)?;
1179				}
1180			}
1181			"forall" => self.ps_forall()?,
1182			"definefont" => {
1183				let font = self.pop(&["dicttype"])?;
1184				let name = self.pop(&[])?;
1185				let d = match &font.borrow().kind {
1186					Kind::Dict(d) => d.clone(),
1187					_ => return Err(py_err("TypeError")),
1188				};
1189				let font = obj(Kind::Font(d));
1190				let key = key_of(&name)?;
1191				self.font_directory()?
1192					.borrow_mut()
1193					.insert(key, font.clone());
1194				self.push(font);
1195			}
1196			"findfont" => {
1197				let name = self.pop(&[])?;
1198				let key = key_of(&name)?;
1199				let font = self
1200					.font_directory()?
1201					.borrow()
1202					.get(&key)
1203					.cloned()
1204					.ok_or_else(|| py_err(format!("KeyError: {key}")))?;
1205				self.push(font);
1206			}
1207			"pop" => {
1208				self.pop(&[])?;
1209			}
1210			"dict" => {
1211				self.pop(&["integertype"])?;
1212				self.push(obj(Kind::Dict(new_dict())));
1213			}
1214			"begin" => {
1215				let d = self.pop(&["dicttype"])?;
1216				let d = match &d.borrow().kind {
1217					Kind::Dict(d) => d.clone(),
1218					_ => return Err(py_err("TypeError")),
1219				};
1220				self.dictstack.push(d);
1221			}
1222			"end" => {
1223				if self.dictstack.len() > 2 {
1224					self.dictstack.pop();
1225				} else {
1226					return Err(py_err("RuntimeError: dictstack underflow"));
1227				}
1228			}
1229			_ => return Err(py_err(format!("AttributeError: no operator {name}"))),
1230		}
1231		Ok(())
1232	}
1233
1234	fn ps_put(&mut self) -> Result<()> {
1235		let value = self.pop(&[])?;
1236		let key = self.pop(&[])?;
1237		let target = self.pop(&["arraytype", "dicttype", "stringtype", "proceduretype"])?;
1238		let mut t = target.borrow_mut();
1239		match &mut t.kind {
1240			Kind::Array(v) => {
1241				let i = Self::int_value(&key)?;
1242				let at = py_index(v.len(), i)
1243					.ok_or_else(|| py_err("IndexError: list assignment index out of range"))?;
1244				v[at] = Some(value);
1245			}
1246			Kind::Procedure(v) => {
1247				let i = Self::int_value(&key)?;
1248				let at = py_index(v.len(), i)
1249					.ok_or_else(|| py_err("IndexError: list assignment index out of range"))?;
1250				v[at] = value;
1251			}
1252			Kind::Dict(d) => {
1253				let key = key_of(&key)?;
1254				d.borrow_mut().insert(key, value);
1255			}
1256			Kind::String(PsString::Text(s)) => {
1257				let index = Self::int_value(&key)?;
1258				let c = match value.borrow().kind {
1259					Kind::Integer(c) => u32::try_from(c)
1260						.ok()
1261						.and_then(char::from_u32)
1262						.ok_or_else(|| py_err("ValueError: chr() arg not in range"))?,
1263					_ => return Err(py_err("TypeError: an integer is required")),
1264				};
1265				let chars: Vec<char> = s.chars().collect();
1266				let (a, _) = py_slice(chars.len(), 0, index);
1267				let (b, _) = py_slice(chars.len(), index.saturating_add(1), i64::MAX);
1268				let mut new: String = chars[..a].iter().collect();
1269				new.push(c);
1270				new.extend(&chars[b..]);
1271				*s = new;
1272			}
1273			_ => return Err(py_err("TypeError: can't concat str to bytes")),
1274		}
1275		Ok(())
1276	}
1277
1278	fn ps_get(&mut self) -> Result<()> {
1279		let key = self.pop(&[])?;
1280		let src = self.pop(&[
1281			"arraytype",
1282			"dicttype",
1283			"stringtype",
1284			"proceduretype",
1285			"fonttype",
1286		])?;
1287		let result = match &src.borrow().kind {
1288			Kind::Array(v) => {
1289				let at = py_index(v.len(), Self::int_value(&key)?).ok_or_else(index_error)?;
1290				// LENIENT(L45): fontTools pushes `None` and fails when it is used.
1291				v[at]
1292					.clone()
1293					.ok_or_else(|| py_err("AttributeError: 'NoneType' object"))?
1294			}
1295			Kind::Procedure(v) => {
1296				let at = py_index(v.len(), Self::int_value(&key)?).ok_or_else(index_error)?;
1297				v[at].clone()
1298			}
1299			Kind::Dict(d) | Kind::Font(d) => {
1300				let k = key_of(&key)?;
1301				d.borrow()
1302					.get(&k)
1303					.cloned()
1304					.ok_or_else(|| py_err(format!("KeyError: {k}")))?
1305			}
1306			Kind::String(PsString::Text(s)) => {
1307				let chars: Vec<char> = s.chars().collect();
1308				let at = py_index(chars.len(), Self::int_value(&key)?)
1309					.ok_or_else(|| py_err("IndexError: string index out of range"))?;
1310				obj(Kind::Integer(chars[at] as i64))
1311			}
1312			_ => {
1313				return Err(py_err(
1314					"TypeError: ord() expected string of length 1, but int found",
1315				));
1316			}
1317		};
1318		self.push(result);
1319		Ok(())
1320	}
1321
1322	fn ps_forall(&mut self) -> Result<()> {
1323		let proc = self.pop(&["proceduretype"])?;
1324		let src = self.pop(&["arraytype", "stringtype", "dicttype"])?;
1325		let kind = src.borrow().kind.clone();
1326		match kind {
1327			Kind::Array(_) => {
1328				let mut i = 0;
1329				loop {
1330					let item = match &src.borrow().kind {
1331						Kind::Array(v) => match v.get(i) {
1332							Some(item) => item.clone(),
1333							None => break,
1334						},
1335						_ => break,
1336					};
1337					i += 1;
1338					// LENIENT(L45): fontTools pushes `None` and fails when it is used.
1339					let item = item.ok_or_else(|| py_err("AttributeError: 'NoneType' object"))?;
1340					self.push(item);
1341					self.call_procedure(&proc)?;
1342				}
1343			}
1344			Kind::String(PsString::Text(s)) => {
1345				for c in s.chars() {
1346					self.push(obj(Kind::Integer(c as i64)));
1347					self.call_procedure(&proc)?;
1348				}
1349			}
1350			Kind::String(PsString::Bytes(b)) => {
1351				if !b.is_empty() {
1352					return Err(py_err(
1353						"TypeError: ord() expected string of length 1, but int found",
1354					));
1355				}
1356			}
1357			Kind::Dict(d) => {
1358				let items: Vec<(Key, ObjRef)> = d
1359					.borrow()
1360					.iter()
1361					.map(|(k, v)| (k.clone(), v.clone()))
1362					.collect();
1363				let len = items.len();
1364				for (k, v) in items {
1365					let name = match k {
1366						Key::Str(s) => s,
1367						other => other.to_string(),
1368					};
1369					self.push(obj(Kind::Name(name)));
1370					self.push(v);
1371					self.call_procedure(&proc)?;
1372					if d.borrow().len() != len {
1373						return Err(py_err(
1374							"RuntimeError: dictionary changed size during iteration",
1375						));
1376					}
1377				}
1378			}
1379			_ => {}
1380		}
1381		Ok(())
1382	}
1383}
1384
1385fn proc_len(proc: &ObjRef) -> usize {
1386	match &proc.borrow().kind {
1387		Kind::Procedure(v) => v.len(),
1388		Kind::Array(v) => v.len(),
1389		_ => 0,
1390	}
1391}
1392
1393fn string_value(o: &ObjRef) -> PsString {
1394	match &o.borrow().kind {
1395		Kind::String(s) => s.clone(),
1396		_ => PsString::Text(String::new()),
1397	}
1398}
1399
1400fn slice_string(s: &PsString, start: i64, stop: i64) -> PsString {
1401	match s {
1402		PsString::Text(t) => {
1403			let chars: Vec<char> = t.chars().collect();
1404			let (a, b) = py_slice(chars.len(), start, stop);
1405			PsString::Text(chars[a..b].iter().collect())
1406		}
1407		PsString::Bytes(v) => {
1408			let (a, b) = py_slice(v.len(), start, stop);
1409			PsString::Bytes(v[a..b].to_vec())
1410		}
1411	}
1412}
1413
1414/// The value of an object as a dictionary key (`hash(obj.value)`).
1415pub fn key_of(o: &ObjRef) -> Result<Key> {
1416	Ok(match &o.borrow().kind {
1417		Kind::Operator(_) | Kind::Null => Key::None,
1418		Kind::Name(s) | Kind::Literal(s) => Key::Str(s.clone()),
1419		Kind::Mark => Key::from("mark"),
1420		Kind::ProcMark => Key::from("procmark"),
1421		Kind::String(PsString::Text(s)) => Key::Str(s.clone()),
1422		Kind::String(PsString::Bytes(b)) => Key::Bytes(b.clone()),
1423		Kind::Integer(i) => Key::Int(*i),
1424		Kind::Boolean { value, .. } => Key::Int(*value as i64),
1425		Kind::Real(f) => {
1426			if f.fract() == 0.0 && f.abs() < 9.2e18 {
1427				Key::Int(*f as i64)
1428			} else {
1429				Key::Float(f.to_bits())
1430			}
1431		}
1432		Kind::File(id) => Key::File(*id),
1433		Kind::Procedure(_) | Kind::Array(_) => {
1434			return Err(py_err("TypeError: unhashable type: 'list'"));
1435		}
1436		Kind::Dict(_) | Kind::Font(_) => {
1437			return Err(py_err("TypeError: unhashable type: 'dict'"));
1438		}
1439	})
1440}
1441
1442/// `a.value == b.value`, with Python's equality.
1443fn py_eq(a: &ObjRef, b: &ObjRef) -> bool {
1444	if Rc::ptr_eq(a, b) {
1445		return true;
1446	}
1447	let (a, b) = (a.borrow(), b.borrow());
1448	let num = |k: &Kind| -> Option<f64> {
1449		match k {
1450			Kind::Integer(i) => Some(*i as f64),
1451			Kind::Real(f) => Some(*f),
1452			Kind::Boolean { value, .. } => Some(*value as i64 as f64),
1453			_ => None,
1454		}
1455	};
1456	match (&a.kind, &b.kind) {
1457		(Kind::Integer(x), Kind::Integer(y)) => return x == y,
1458		(Kind::Boolean { value: x, .. }, Kind::Integer(y))
1459		| (Kind::Integer(y), Kind::Boolean { value: x, .. }) => return *x as i64 == *y,
1460		_ => {}
1461	}
1462	if let (Some(x), Some(y)) = (num(&a.kind), num(&b.kind)) {
1463		return x == y;
1464	}
1465	let text = |k: &Kind| -> Option<String> {
1466		match k {
1467			Kind::Name(s) | Kind::Literal(s) | Kind::String(PsString::Text(s)) => Some(s.clone()),
1468			Kind::Mark => Some("mark".into()),
1469			Kind::ProcMark => Some("procmark".into()),
1470			_ => None,
1471		}
1472	};
1473	if let (Some(x), Some(y)) = (text(&a.kind), text(&b.kind)) {
1474		return x == y;
1475	}
1476	match (&a.kind, &b.kind) {
1477		(Kind::String(PsString::Bytes(x)), Kind::String(PsString::Bytes(y))) => x == y,
1478		(Kind::Operator(_) | Kind::Null, Kind::Operator(_) | Kind::Null) => true,
1479		(Kind::File(x), Kind::File(y)) => x == y,
1480		(Kind::Procedure(x), Kind::Procedure(y)) => {
1481			x.len() == y.len() && x.iter().zip(y).all(|(p, q)| Rc::ptr_eq(p, q))
1482		}
1483		(Kind::Array(x), Kind::Array(y)) => {
1484			x.len() == y.len()
1485				&& x.iter().zip(y).all(|(p, q)| match (p, q) {
1486					(Some(p), Some(q)) => Rc::ptr_eq(p, q),
1487					(None, None) => true,
1488					_ => false,
1489				})
1490		}
1491		(Kind::Procedure(x), Kind::Array(y)) | (Kind::Array(y), Kind::Procedure(x)) => {
1492			x.len() == y.len()
1493				&& x.iter()
1494					.zip(y)
1495					.all(|(p, q)| q.as_ref().is_some_and(|q| Rc::ptr_eq(p, q)))
1496		}
1497		(Kind::Dict(x) | Kind::Font(x), Kind::Dict(y) | Kind::Font(y)) => {
1498			if Rc::ptr_eq(x, y) {
1499				return true;
1500			}
1501			let (x, y) = (x.borrow(), y.borrow());
1502			x.len() == y.len()
1503				&& x.iter()
1504					.all(|(k, v)| y.get(k).is_some_and(|w| Rc::ptr_eq(v, w)))
1505		}
1506		_ => false,
1507	}
1508}
1509
1510/// `unpack_item`: the Python value of an object, with its dictionaries, arrays
1511/// and procedures unpacked recursively.
1512pub fn unpack_item(item: &ObjRef) -> Result<PsValue> {
1513	unpack(item, 0)
1514}
1515
1516fn unpack(item: &ObjRef, depth: usize) -> Result<PsValue> {
1517	if depth > MAX_DEPTH {
1518		return Err(py_err("RecursionError: maximum recursion depth exceeded"));
1519	}
1520	let o = item.borrow();
1521	Ok(match &o.kind {
1522		Kind::Dict(d) | Kind::Font(d) => {
1523			let d = d.clone();
1524			drop(o);
1525			let mut out = IndexMap::new();
1526			for (k, v) in d.borrow().iter() {
1527				out.insert(k.clone(), unpack(v, depth + 1)?);
1528			}
1529			PsValue::Dict(out)
1530		}
1531		Kind::Array(v) => {
1532			let v = v.clone();
1533			drop(o);
1534			let mut out = Vec::with_capacity(v.len());
1535			for item in &v {
1536				let item = item.as_ref().ok_or_else(|| {
1537					py_err("AttributeError: 'NoneType' object has no attribute 'value'")
1538				})?;
1539				out.push(unpack(item, depth + 1)?);
1540			}
1541			PsValue::List(out)
1542		}
1543		Kind::Procedure(v) => {
1544			let v = v.clone();
1545			drop(o);
1546			PsValue::Tuple(
1547				v.iter()
1548					.map(|i| unpack(i, depth + 1))
1549					.collect::<Result<_>>()?,
1550			)
1551		}
1552		Kind::Operator(_) | Kind::Null => PsValue::None,
1553		Kind::Name(s) | Kind::Literal(s) => PsValue::Str(s.clone()),
1554		Kind::Mark => PsValue::Str("mark".into()),
1555		Kind::ProcMark => PsValue::Str("procmark".into()),
1556		Kind::File(_) => PsValue::File,
1557		Kind::Boolean { value, py_bool } => {
1558			if *py_bool {
1559				PsValue::Bool(*value)
1560			} else {
1561				PsValue::Int(*value as i64)
1562			}
1563		}
1564		Kind::String(PsString::Text(s)) => PsValue::Str(s.clone()),
1565		Kind::String(PsString::Bytes(b)) => PsValue::Bytes(b.clone()),
1566		Kind::Integer(i) => PsValue::Int(*i),
1567		Kind::Real(f) => PsValue::Float(*f),
1568	})
1569}
1570
1571/// Finds `/FontName\s+/([^ \t\n\r]+)\s+def` and returns the name.
1572fn find_font_name(data: &[u8]) -> Option<&[u8]> {
1573	let is_space = |b: u8| matches!(b, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C);
1574	let pat = b"/FontName";
1575	let mut from = 0;
1576	while let Some(found) = data[from..].windows(pat.len()).position(|w| w == pat) {
1577		let start = from + found;
1578		from = start + 1;
1579		let mut i = start + pat.len();
1580		let ws = i;
1581		while i < data.len() && is_space(data[i]) {
1582			i += 1;
1583		}
1584		if i == ws || data.get(i) != Some(&b'/') {
1585			continue;
1586		}
1587		let g = i + 1;
1588		let mut e = g;
1589		while e < data.len() && !matches!(data[e], b' ' | b'\t' | b'\n' | b'\r') {
1590			e += 1;
1591		}
1592		// Backtrack the greedy group until `\s+def` follows.
1593		let mut p = e;
1594		while p > g {
1595			let mut q = p;
1596			while q < data.len() && is_space(data[q]) {
1597				q += 1;
1598			}
1599			if q > p && data[q..].starts_with(b"def") {
1600				return Some(&data[g..p]);
1601			}
1602			p -= 1;
1603		}
1604	}
1605	None
1606}
1607
1608/// Interprets a Type 1 font program and returns its font dictionary
1609/// (`suckfont`).
1610pub fn suckfont(data: &[u8], encoding: &str) -> Result<IndexMap<Key, PsValue>> {
1611	let font_name = match find_font_name(data) {
1612		Some(name) => Some(
1613			String::from_utf8(name.to_vec())
1614				.map_err(|_| py_err("UnicodeDecodeError: 'utf-8' codec can't decode"))?,
1615		),
1616		None => None,
1617	};
1618	let mut interpreter = PsInterpreter::new(encoding);
1619	interpreter
1620		.interpret(b"/Helvetica 4 dict dup /Encoding StandardEncoding put definefont pop")?;
1621	interpreter.interpret(data)?;
1622	let fontdir = interpreter.font_directory()?;
1623	let rawfont = {
1624		let fd = fontdir.borrow();
1625		match font_name.and_then(|n| fd.get(&Key::Str(n)).cloned()) {
1626			Some(f) => f,
1627			None => {
1628				// Fall back, in case the font name wasn't found.
1629				let mut names: Vec<Key> = fd.keys().cloned().collect();
1630				if names.len() > 1 {
1631					let at = names
1632						.iter()
1633						.position(|k| *k == Key::from("Helvetica"))
1634						.ok_or_else(|| py_err("ValueError: list.remove(x): x not in list"))?;
1635					names.remove(at);
1636				}
1637				if names.iter().any(|k| !matches!(k, Key::Str(_))) && names.len() > 1 {
1638					return Err(py_err("TypeError: '<' not supported between instances"));
1639				}
1640				names.sort();
1641				let first = names.first().ok_or_else(index_error)?;
1642				fd.get(first).cloned().ok_or_else(index_error)?
1643			}
1644		}
1645	};
1646	let font = unpack_item(&rawfont)?;
1647	interpreter.close();
1648	match font {
1649		PsValue::Dict(d) => Ok(d),
1650		_ => Err(py_err("TypeError: the font is not a dictionary")),
1651	}
1652}
1653
1654#[cfg(test)]
1655mod tests {
1656	use super::*;
1657
1658	#[test]
1659	fn find_font_name_backtracks() {
1660		assert_eq!(find_font_name(b"/FontName /Foo def"), Some(&b"Foo"[..]));
1661		assert_eq!(find_font_name(b"/FontName  /Foo\x0cdef"), Some(&b"Foo"[..]));
1662		assert_eq!(find_font_name(b"/FontName /Foo"), None);
1663		assert_eq!(
1664			find_font_name(b"/FontName/Foo def /FontName /Bar def"),
1665			Some(&b"Bar"[..])
1666		);
1667	}
1668
1669	#[test]
1670	fn interpreter_basics() -> Result<()> {
1671		let mut i = PsInterpreter::new("ascii");
1672		i.interpret(b"/a 1 def /b [1 2.5 (x) <41 4>] def /c {1 add} def 16#ff 2 eq")?;
1673		let user = i.dictstack[1].clone();
1674		assert_eq!(
1675			unpack_item(&user.borrow()[&Key::from("a")])?,
1676			PsValue::Int(1)
1677		);
1678		assert_eq!(
1679			unpack_item(&user.borrow()[&Key::from("b")])?,
1680			PsValue::List(vec![
1681				PsValue::Int(1),
1682				PsValue::Float(2.5),
1683				PsValue::Str("x".into()),
1684				PsValue::Str("A@".into()),
1685			])
1686		);
1687		assert_eq!(
1688			unpack_item(&user.borrow()[&Key::from("c")])?,
1689			PsValue::Tuple(vec![PsValue::Int(1), PsValue::Str("add".into())])
1690		);
1691		assert_eq!(unpack_item(&i.stack[0])?, PsValue::Bool(false));
1692		Ok(())
1693	}
1694}