Skip to main content

fontoxide_ttlib/tables/graphite/
silf.rs

1//! The Graphite Rules table, `Silf` (`S__i_l_f`).
2
3use std::collections::BTreeMap;
4
5use fontoxide_misc::Tag;
6use fontoxide_misc::text_tools::parse_int_radix;
7use fontoxide_misc::xml_reader::Element;
8use fontoxide_misc::xml_writer::{AttrValue, XmlWriter};
9
10use super::{
11	Pack, at_least, attr, bininfo, compress, content_string, count, decompress, dict_set, entries,
12	eval_float, eval_int, exact, py_get, py_int, py_slice, py_split, py_tail, read_fixed,
13	round_version,
14};
15use crate::binary::Reader;
16use crate::table::{Table, TableType, TableXml};
17use crate::{Error, Font, Result};
18
19// ---------------------------------------------------------------------------
20// Action code
21
22/// The operands of an instruction (the second item of `aCode_info`).
23#[derive(Clone, Copy)]
24enum Operands {
25	/// `0`: none.
26	None,
27	/// `-1`: a count, then that many bytes.
28	Counted,
29	/// A `struct` format of fixed operands, without the byte order prefix.
30	Fixed(&'static str),
31}
32
33/// `aCode_info`: the instructions by opcode.
34const ACODE_INFO: [(&str, Operands); 67] = {
35	use Operands::{Counted, Fixed, None};
36	[
37		("NOP", None),
38		("PUSH_BYTE", Fixed("b")),
39		("PUSH_BYTE_U", Fixed("B")),
40		("PUSH_SHORT", Fixed("h")),
41		("PUSH_SHORT_U", Fixed("H")),
42		("PUSH_LONG", Fixed("L")),
43		("ADD", None),
44		("SUB", None),
45		("MUL", None),
46		("DIV", None),
47		("MIN", None),
48		("MAX", None),
49		("NEG", None),
50		("TRUNC8", None),
51		("TRUNC16", None),
52		("COND", None),
53		("AND", None),
54		("OR", None),
55		("NOT", None),
56		("EQUAL", None),
57		("NOT_EQ", None),
58		("LESS", None),
59		("GTR", None),
60		("LESS_EQ", None),
61		("GTR_EQ", None),
62		("NEXT", None),
63		("NEXT_N", Fixed("b")),
64		("COPY_NEXT", None),
65		("PUT_GLYPH_8BIT_OBS", Fixed("B")),
66		("PUT_SUBS_8BIT_OBS", Fixed("bBB")),
67		("PUT_COPY", Fixed("b")),
68		("INSERT", None),
69		("DELETE", None),
70		("ASSOC", Counted),
71		("CNTXT_ITEM", Fixed("bB")),
72		("ATTR_SET", Fixed("B")),
73		("ATTR_ADD", Fixed("B")),
74		("ATTR_SUB", Fixed("B")),
75		("ATTR_SET_SLOT", Fixed("B")),
76		("IATTR_SET_SLOT", Fixed("BB")),
77		("PUSH_SLOT_ATTR", Fixed("Bb")),
78		("PUSH_GLYPH_ATTR_OBS", Fixed("Bb")),
79		("PUSH_GLYPH_METRIC", Fixed("Bbb")),
80		("PUSH_FEAT", Fixed("Bb")),
81		("PUSH_ATT_TO_GATTR_OBS", Fixed("Bb")),
82		("PUSH_ATT_TO_GLYPH_METRIC", Fixed("Bbb")),
83		("PUSH_ISLOT_ATTR", Fixed("Bbb")),
84		("PUSH_IGLYPH_ATTR", Fixed("Bbb")),
85		("POP_RET", None),
86		("RET_ZERO", None),
87		("RET_TRUE", None),
88		("IATTR_SET", Fixed("BB")),
89		("IATTR_ADD", Fixed("BB")),
90		("IATTR_SUB", Fixed("BB")),
91		("PUSH_PROC_STATE", Fixed("B")),
92		("PUSH_VERSION", None),
93		("PUT_SUBS", Fixed("bHH")),
94		("PUT_SUBS2", None),
95		("PUT_SUBS3", None),
96		("PUT_GLYPH", Fixed("H")),
97		("PUSH_GLYPH_ATTR", Fixed("Hb")),
98		("PUSH_ATT_TO_GLYPH_ATTR", Fixed("Hb")),
99		("BITOR", None),
100		("BITAND", None),
101		("BITNOT", None),
102		("BITSET", Fixed("HH")),
103		("SET_FEAT", Fixed("Bb")),
104	]
105};
106
107fn format_size(c: char) -> usize {
108	match c {
109		'h' | 'H' => 2,
110		'L' => 4,
111		_ => 1,
112	}
113}
114
115/// `disassemble`: the instructions of an action or constraint code, as text.
116pub fn disassemble(code: &[u8]) -> Result<Vec<String>> {
117	let mut res = Vec::new();
118	let mut pc = 0;
119	while pc < code.len() {
120		let opcode = code[pc] as usize;
121		// UPSTREAM-BUG(B71): opcodes past the table are taken as NOP, except the first
122		// one, which fails (`>` instead of `>=`).
123		let (name, operands) = if opcode > ACODE_INFO.len() {
124			ACODE_INFO[0]
125		} else {
126			*ACODE_INFO
127				.get(opcode)
128				.ok_or_else(|| Error::ttlib("IndexError: tuple index out of range"))?
129		};
130		pc += 1;
131		if !matches!(operands, Operands::None) && pc >= code.len() {
132			return Ok(res);
133		}
134		let format: Vec<char> = match operands {
135			Operands::None => {
136				res.push(name.to_owned());
137				continue;
138			}
139			Operands::Counted => {
140				let n = code[pc] as usize;
141				pc += 1;
142				vec!['B'; n]
143			}
144			Operands::Fixed(f) => f.chars().collect(),
145		};
146		let size: usize = format.iter().map(|&c| format_size(c)).sum();
147		let mut r = at_least(py_tail(code, pc as i64), size)?;
148		let mut params = Vec::with_capacity(format.len());
149		for c in format {
150			params.push(match c {
151				'b' => r.i8()? as i64,
152				'B' => r.u8()? as i64,
153				'h' => r.i16()? as i64,
154				'H' => r.u16()? as i64,
155				_ => r.u32()? as i64,
156			});
157		}
158		let params: Vec<String> = params.iter().map(i64::to_string).collect();
159		res.push(format!("{name}({})", params.join(", ")));
160		pc += size;
161	}
162	Ok(res)
163}
164
165/// The instruction name and operand text of a line
166/// (`^\s*([^(]+)\s*(?:\(([^)]+)\))?`).
167fn match_instruction(line: &str) -> Option<(&str, Option<&str>)> {
168	let line = line.trim_start_matches(fontoxide_misc::py::is_space);
169	let end = line.find('(').unwrap_or(line.len());
170	if end == 0 {
171		return None;
172	}
173	let name = &line[..end];
174	let rest = &line[end..];
175	let params = rest.strip_prefix('(').and_then(|r| {
176		let close = r.find(')')?;
177		(close > 0).then(|| &r[..close])
178	});
179	Some((name, params))
180}
181
182/// `assemble`: the code of instructions as text; unknown instructions are
183/// skipped.
184pub fn assemble<S: AsRef<str>>(instrs: &[S]) -> Result<Vec<u8>> {
185	let mut res = Vec::new();
186	for inst in instrs {
187		let Some((name, params)) = match_instruction(inst.as_ref()) else {
188			continue;
189		};
190		let Some(opcode) = ACODE_INFO.iter().position(|(n, _)| *n == name) else {
191			continue;
192		};
193		res.push(opcode as u8);
194		let Some(params) = params else {
195			continue;
196		};
197		let operands = ACODE_INFO[opcode].1;
198		if matches!(operands, Operands::None) {
199			continue;
200		}
201		let params: Vec<i64> = params.split(',').map(py_int).collect::<Result<_>>()?;
202		match operands {
203			Operands::Counted => {
204				res.pack_u8(params.len() as i64)?;
205				for p in params {
206					res.pack_u8(p)?;
207				}
208			}
209			Operands::Fixed(f) => {
210				if f.len() != params.len() {
211					return Err(Error::Struct(format!(
212						"pack expected {} items for packing (got {})",
213						f.len(),
214						params.len()
215					)));
216				}
217				for (c, p) in f.chars().zip(params) {
218					match c {
219						'b' => res.pack_i8(p)?,
220						'B' => res.pack_u8(p)?,
221						'h' => res.pack_i16(p)?,
222						'H' => res.pack_u16(p)?,
223						_ => res.pack_u32(p)?,
224					}
225				}
226			}
227			Operands::None => {}
228		}
229	}
230	Ok(res)
231}
232
233/// `writecode`.
234fn write_code(tag: &str, writer: &mut XmlWriter, code: &[u8]) -> Result<()> {
235	writer.begintag(tag, &[]);
236	writer.newline();
237	for l in disassemble(code)? {
238		writer.write(&l);
239		writer.newline();
240	}
241	writer.endtag(tag);
242	writer.newline();
243	Ok(())
244}
245
246/// `readcode`.
247fn read_code(e: &Element) -> Result<Vec<u8>> {
248	let text = content_string(e);
249	let lines: Vec<&str> = text
250		.split('\n')
251		.map(fontoxide_misc::py::strip)
252		.filter(|l| !l.is_empty())
253		.collect();
254	assemble(&lines)
255}
256
257/// `wrapline`: words on lines of a little over 80 characters.
258fn wrap_line(writer: &mut XmlWriter, words: &[String]) {
259	let mut line = String::new();
260	for w in words {
261		if line.chars().count() > 80 {
262			line.pop();
263			writer.write(&line);
264			writer.newline();
265			line.clear();
266		}
267		line.push_str(w);
268		line.push(' ');
269	}
270	if !line.is_empty() {
271		line.pop();
272		writer.write(&line);
273		writer.newline();
274	}
275}
276
277/// `writesimple`.
278fn write_simple(writer: &mut XmlWriter, tag: &str, attrs: &[(&str, i64)]) {
279	let attrs: Vec<(&str, &dyn AttrValue)> = attrs
280		.iter()
281		.map(|(n, v)| (*n, v as &dyn AttrValue))
282		.collect();
283	writer.simpletag(tag, &attrs);
284	writer.newline();
285}
286
287/// `getSimple`: sets the fields whose attributes are present.
288fn get_simple(e: &Element, fields: &mut [(&str, &mut i64)]) -> Result<()> {
289	for (name, field) in fields {
290		if let Some(v) = e.attr(name) {
291			**field = eval_int(v)?;
292		}
293	}
294	Ok(())
295}
296
297/// Python's `hex(n)`.
298fn py_hex(n: i64) -> String {
299	if n < 0 {
300		format!("-0x{:x}", n.unsigned_abs())
301	} else {
302		format!("0x{n:x}")
303	}
304}
305
306fn pack_count_error(expected: usize, got: usize) -> Error {
307	Error::Struct(format!(
308		"pack expected {expected} items for packing (got {got})"
309	))
310}
311
312/// The start of each item, and the end, from `start` (the `reduce` calls of
313/// `Pass.compile`).
314fn cumulative<T>(items: &[T], start: i64, len: impl Fn(&T) -> usize) -> Vec<i64> {
315	let mut out = Vec::with_capacity(items.len() + 1);
316	let mut at = start;
317	for item in items {
318		out.push(at);
319		at += len(item) as i64;
320	}
321	out.push(at);
322	out
323}
324
325// ---------------------------------------------------------------------------
326// Pass
327
328/// A pass of a [`SilfSubtable`] (`Pass`).
329#[derive(Debug, Clone, PartialEq, Default)]
330pub struct Pass {
331	/// `flags`.
332	pub flags: i64,
333	/// `maxRuleLoop`.
334	pub max_rule_loop: i64,
335	/// `maxRuleContext`.
336	pub max_rule_context: i64,
337	/// `maxBackup`.
338	pub max_backup: i64,
339	/// `numRules`, set when compiling.
340	pub num_rules: i64,
341	/// `fsmOffset`, set when compiling.
342	pub fsm_offset: i64,
343	/// `pcCode`, set when compiling.
344	pub pc_code: i64,
345	/// `rcCode`, set when compiling.
346	pub rc_code: i64,
347	/// `aCode`, set when compiling.
348	pub a_code: i64,
349	/// `oDebug`, set when compiling.
350	pub o_debug: i64,
351	/// `numRows`.
352	pub num_rows: i64,
353	/// `numTransitional`.
354	pub num_transitional: i64,
355	/// `numSuccess`.
356	pub num_success: i64,
357	/// `numColumns`.
358	pub num_columns: i64,
359	/// The column of each glyph (`colMap`).
360	pub col_map: BTreeMap<u32, i64>,
361	/// The rules of each success state (`rules`).
362	pub rules: Vec<Vec<i64>>,
363	/// `rulePreContexts`.
364	pub rule_pre_contexts: Vec<i64>,
365	/// `ruleSortKeys`.
366	pub rule_sort_keys: Vec<i64>,
367	/// The constraint code of each rule (`ruleConstraints`).
368	pub rule_constraints: Vec<Vec<u8>>,
369	/// `passConstraints`.
370	pub pass_constraints: Vec<u8>,
371	/// The action code of each rule (`actions`).
372	pub actions: Vec<Vec<u8>>,
373	/// The rows of the transition table (`stateTrans`).
374	pub state_trans: Vec<Vec<u16>>,
375	/// `startStates`.
376	pub start_states: Vec<i64>,
377	/// `minRulePreContext`.
378	pub min_rule_pre_context: i64,
379	/// `maxRulePreContext`.
380	pub max_rule_pre_context: i64,
381	/// `collisionThreshold`.
382	pub collision_threshold: i64,
383}
384
385impl Pass {
386	/// `Pass.decompile`.
387	pub fn decompile(data: &[u8], _version: f64) -> Result<Self> {
388		let mut p = Pass::default();
389		let mut r = at_least(data, 32)?;
390		p.flags = r.u8()? as i64;
391		p.max_rule_loop = r.u8()? as i64;
392		p.max_rule_context = r.u8()? as i64;
393		p.max_backup = r.u8()? as i64;
394		p.num_rules = r.u16()? as i64;
395		p.fsm_offset = r.u16()? as i64;
396		p.pc_code = r.u32()? as i64;
397		p.rc_code = r.u32()? as i64;
398		p.a_code = r.u32()? as i64;
399		p.o_debug = r.u32()? as i64;
400		p.num_rows = r.u16()? as i64;
401		p.num_transitional = r.u16()? as i64;
402		p.num_success = r.u16()? as i64;
403		p.num_columns = r.u16()? as i64;
404		let data = r.rest();
405		let num_range = exact(py_slice(data, 0, 8), 8)?.u16()? as i64;
406		let data = py_tail(data, 8);
407		for i in 0..num_range {
408			let mut r = exact(py_slice(data, 6 * i, 6 * i + 6), 6)?;
409			let (first, last, col) = (r.u16()? as u32, r.u16()? as u32, r.u16()? as i64);
410			for g in first..=last {
411				p.col_map.insert(g, col);
412			}
413		}
414		let data = py_tail(data, 6 * num_range);
415		let ns = p.num_success as usize;
416		let o_rule_map: Vec<i64> = at_least(data, 2 * (ns + 1))?
417			.u16_array(ns + 1)?
418			.into_iter()
419			.map(i64::from)
420			.collect();
421		let data = py_tail(data, 2 + 2 * ns as i64);
422		let total = o_rule_map[ns];
423		let rules: Vec<i64> = at_least(data, 2 * total as usize)?
424			.u16_array(total as usize)?
425			.into_iter()
426			.map(i64::from)
427			.collect();
428		p.rules = o_rule_map
429			.windows(2)
430			.map(|w| py_slice(&rules, w[0], w[1]).to_vec())
431			.collect();
432		let data = py_tail(data, 2 * total);
433		let mut r = exact(py_slice(data, 0, 2), 2)?;
434		p.min_rule_pre_context = r.u8()? as i64;
435		p.max_rule_pre_context = r.u8()? as i64;
436		let n = p.max_rule_pre_context - p.min_rule_pre_context + 1;
437		let nss = count(n)?;
438		p.start_states = exact(py_slice(data, 2, 2 + n * 2), 2 * nss)?
439			.u16_array(nss)?
440			.into_iter()
441			.map(i64::from)
442			.collect();
443		let data = py_tail(data, 2 + n * 2);
444		let nr = p.num_rules;
445		let nru = nr as usize;
446		p.rule_sort_keys = exact(py_slice(data, 0, 2 * nr), 2 * nru)?
447			.u16_array(nru)?
448			.into_iter()
449			.map(i64::from)
450			.collect();
451		let data = py_tail(data, 2 * nr);
452		p.rule_pre_contexts = exact(py_slice(data, 0, nr), nru)?
453			.bytes(nru)?
454			.iter()
455			.map(|&b| b as i64)
456			.collect();
457		let data = py_tail(data, nr);
458		let mut r = exact(py_slice(data, 0, 3), 3)?;
459		p.collision_threshold = r.u8()? as i64;
460		let p_constraint = r.u16()? as i64;
461		let mut o_constraints: Vec<i64> = exact(py_slice(data, 3, 5 + nr * 2), 2 * (nru + 1))?
462			.u16_array(nru + 1)?
463			.into_iter()
464			.map(i64::from)
465			.collect();
466		let data = py_tail(data, 5 + nr * 2);
467		let o_actions: Vec<i64> = exact(py_slice(data, 0, 2 + nr * 2), 2 * (nru + 1))?
468			.u16_array(nru + 1)?
469			.into_iter()
470			.map(i64::from)
471			.collect();
472		let data = py_tail(data, 2 * nr + 2);
473		let row = p.num_columns * 2;
474		for i in 0..p.num_transitional {
475			let chunk = py_slice(data, i * row, (i + 1) * row);
476			if chunk.len() % 2 != 0 {
477				return Err(Error::value("bytes length not a multiple of item size"));
478			}
479			p.state_trans
480				.push(Reader::new(chunk).u16_array(chunk.len() / 2)?);
481		}
482		let data = py_tail(data, p.num_transitional * row + 1);
483		p.pass_constraints = py_slice(data, 0, p_constraint).to_vec();
484		let data = py_tail(data, p_constraint);
485		for i in (0..o_constraints.len() - 1).rev() {
486			if o_constraints[i] == 0 {
487				o_constraints[i] = o_constraints[i + 1];
488			}
489		}
490		let codes = |data: &[u8], offsets: &[i64]| -> Vec<Vec<u8>> {
491			offsets
492				.windows(2)
493				.map(|w| {
494					if w[1] - w[0] > 1 {
495						py_slice(data, w[0], w[1]).to_vec()
496					} else {
497						Vec::new()
498					}
499				})
500				.collect()
501		};
502		p.rule_constraints = codes(data, &o_constraints);
503		let data = py_tail(data, o_constraints[nru]);
504		p.actions = codes(data, &o_actions);
505		// Not using debug.
506		Ok(p)
507	}
508
509	/// `Pass.compile`; `base` is the offset of the pass in the subtable.
510	pub fn compile(&mut self, base: i64, _version: f64) -> Result<Vec<u8>> {
511		// Build it all up backwards.
512		let o_actions = cumulative(&self.actions, 0, Vec::len);
513		let o_constraints = cumulative(&self.rule_constraints, 1, Vec::len);
514		let mut constraint_code = vec![0u8];
515		for c in &self.rule_constraints {
516			constraint_code.extend_from_slice(c);
517		}
518		let mut transes = Vec::new();
519		for t in &self.state_trans {
520			for v in t {
521				transes.extend_from_slice(&v.to_be_bytes());
522			}
523		}
524		if self.state_trans.is_empty() {
525			self.start_states = vec![0];
526		}
527		let o_rule_map = cumulative(&self.rules, 0, Vec::len);
528		let gid_col_map: BTreeMap<i64, i64> =
529			self.col_map.iter().map(|(&g, &c)| (g as i64, c)).collect();
530		let pass_ranges: Vec<(i64, i64, i64)> = entries(&gid_col_map, true)
531			.into_iter()
532			.filter(|e| e.1 != 0)
533			.map(|(first, n, vals)| (first, first + n as i64 - 1, vals[0]))
534			.collect();
535		let nr = self.actions.len();
536		self.num_rules = nr as i64;
537		let nr = nr as i64;
538		let total = o_rule_map[o_rule_map.len() - 1];
539		self.fsm_offset = 32
540			+ 8
541			+ pass_ranges.len() as i64 * 6
542			+ o_rule_map.len() as i64 * 2
543			+ 2 * total
544			+ 2
545			+ 2 * self.start_states.len() as i64
546			+ 3 * nr
547			+ 3
548			+ 4 * nr
549			+ 4;
550		self.pc_code = self.fsm_offset + 2 * self.num_transitional * self.num_columns + 1 + base;
551		self.rc_code = self.pc_code + self.pass_constraints.len() as i64;
552		self.a_code = self.rc_code + constraint_code.len() as i64;
553		self.o_debug = 0;
554		let mut data = Vec::new();
555		for v in [
556			self.flags,
557			self.max_rule_loop,
558			self.max_rule_context,
559			self.max_backup,
560		] {
561			data.pack_u8(v)?;
562		}
563		data.pack_u16(self.num_rules)?;
564		data.pack_u16(self.fsm_offset)?;
565		for v in [self.pc_code, self.rc_code, self.a_code, self.o_debug] {
566			data.pack_u32(v)?;
567		}
568		for v in [
569			self.num_rows,
570			self.num_transitional,
571			self.num_success,
572			self.num_columns,
573		] {
574			data.pack_u16(v)?;
575		}
576		data.extend(bininfo(pass_ranges.len() as i64, 6)?);
577		for (first, last, col) in &pass_ranges {
578			data.pack_u16(*first)?;
579			data.pack_u16(*last)?;
580			data.pack_u16(*col)?;
581		}
582		for v in &o_rule_map {
583			data.pack_u16(*v)?;
584		}
585		for v in self.rules.iter().flatten() {
586			data.pack_u16(*v)?;
587		}
588		data.pack_u8(self.min_rule_pre_context)?;
589		data.pack_u8(self.max_rule_pre_context)?;
590		for v in &self.start_states {
591			data.pack_u16(*v)?;
592		}
593		if self.rule_sort_keys.len() as i64 != nr {
594			return Err(pack_count_error(nr as usize, self.rule_sort_keys.len()));
595		}
596		for v in &self.rule_sort_keys {
597			data.pack_u16(*v)?;
598		}
599		if self.rule_pre_contexts.len() as i64 != nr {
600			return Err(pack_count_error(nr as usize, self.rule_pre_contexts.len()));
601		}
602		for v in &self.rule_pre_contexts {
603			data.pack_u8(*v)?;
604		}
605		data.pack_u8(self.collision_threshold)?;
606		data.pack_u16(self.pass_constraints.len() as i64)?;
607		if o_constraints.len() as i64 != nr + 1 {
608			return Err(pack_count_error(nr as usize + 1, o_constraints.len()));
609		}
610		for v in o_constraints.iter().chain(&o_actions) {
611			data.pack_u16(*v)?;
612		}
613		data.extend(transes);
614		data.push(0);
615		data.extend_from_slice(&self.pass_constraints);
616		data.extend(constraint_code);
617		for a in &self.actions {
618			data.extend_from_slice(a);
619		}
620		Ok(data)
621	}
622
623	/// `Pass.toXML`.
624	pub fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font, _version: f64) -> Result<()> {
625		write_simple(
626			writer,
627			"info",
628			&[
629				("flags", self.flags),
630				("maxRuleLoop", self.max_rule_loop),
631				("maxRuleContext", self.max_rule_context),
632				("maxBackup", self.max_backup),
633				("minRulePreContext", self.min_rule_pre_context),
634				("maxRulePreContext", self.max_rule_pre_context),
635				("collisionThreshold", self.collision_threshold),
636			],
637		);
638		write_simple(
639			writer,
640			"fsminfo",
641			&[
642				("numRows", self.num_rows),
643				("numTransitional", self.num_transitional),
644				("numSuccess", self.num_success),
645				("numColumns", self.num_columns),
646			],
647		);
648		let order = font.glyph_order()?;
649		writer.begintag("colmap", &[]);
650		writer.newline();
651		let words: Vec<String> = self
652			.col_map
653			.iter()
654			.map(|(&g, c)| format!("{}={c}", order.name(g)))
655			.collect();
656		wrap_line(writer, &words);
657		writer.endtag("colmap");
658		writer.newline();
659		writer.begintag("staterulemap", &[]);
660		writer.newline();
661		for (i, r) in self.rules.iter().enumerate() {
662			let rules: Vec<String> = r.iter().map(i64::to_string).collect();
663			writer.simpletag(
664				"state",
665				&[
666					("number", &(self.num_rows - self.num_success + i as i64)),
667					("rules", &rules.join(" ")),
668				],
669			);
670			writer.newline();
671		}
672		writer.endtag("staterulemap");
673		writer.newline();
674		writer.begintag("rules", &[]);
675		writer.newline();
676		for (i, action) in self.actions.iter().enumerate() {
677			let index = i as i64;
678			writer.begintag(
679				"rule",
680				&[
681					("index", &index),
682					("precontext", py_get(&self.rule_pre_contexts, index)?),
683					("sortkey", py_get(&self.rule_sort_keys, index)?),
684				],
685			);
686			writer.newline();
687			let constraint = py_get(&self.rule_constraints, index)?;
688			if !constraint.is_empty() {
689				write_code("constraint", writer, constraint)?;
690			}
691			write_code("action", writer, action)?;
692			writer.endtag("rule");
693			writer.newline();
694		}
695		writer.endtag("rules");
696		writer.newline();
697		if !self.pass_constraints.is_empty() {
698			write_code("passConstraint", writer, &self.pass_constraints)?;
699		}
700		if !self.state_trans.is_empty() {
701			writer.begintag("fsm", &[]);
702			writer.newline();
703			writer.begintag("starts", &[]);
704			let starts: Vec<String> = self.start_states.iter().map(i64::to_string).collect();
705			writer.write(&starts.join(" "));
706			writer.endtag("starts");
707			writer.newline();
708			for (i, s) in self.state_trans.iter().enumerate() {
709				writer.begintag("row", &[("_i", &i)]);
710				// No newlines here.
711				let row: Vec<String> = s.iter().map(u16::to_string).collect();
712				writer.write(&row.join(" "));
713				writer.endtag("row");
714				writer.newline();
715			}
716			writer.endtag("fsm");
717			writer.newline();
718		}
719		Ok(())
720	}
721
722	/// `Pass.fromXML`.
723	pub fn from_xml(&mut self, e: &Element, font: &mut Font, _version: f64) -> Result<()> {
724		match e.name.as_str() {
725			"info" => get_simple(
726				e,
727				&mut [
728					("flags", &mut self.flags),
729					("maxRuleLoop", &mut self.max_rule_loop),
730					("maxRuleContext", &mut self.max_rule_context),
731					("maxBackup", &mut self.max_backup),
732					("minRulePreContext", &mut self.min_rule_pre_context),
733					("maxRulePreContext", &mut self.max_rule_pre_context),
734					("collisionThreshold", &mut self.collision_threshold),
735				],
736			)?,
737			"fsminfo" => get_simple(
738				e,
739				&mut [
740					("numRows", &mut self.num_rows),
741					("numTransitional", &mut self.num_transitional),
742					("numSuccess", &mut self.num_success),
743					("numColumns", &mut self.num_columns),
744				],
745			)?,
746			"colmap" => {
747				for w in py_split(&content_string(e)) {
748					let x: Vec<&str> = w.split('=').collect();
749					if x.len() != 2 || x[0].is_empty() || x[1].is_empty() {
750						continue;
751					}
752					let gid = font.glyph_id(x[0])?;
753					self.col_map.insert(gid, py_int(x[1])?);
754				}
755			}
756			"staterulemap" => {
757				for c in e.elements().filter(|c| c.name == "state") {
758					self.rules.push(
759						attr(c, "rules")?
760							.split(' ')
761							.map(py_int)
762							.collect::<Result<_>>()?,
763					);
764				}
765			}
766			"rules" => {
767				for c in e.elements().filter(|c| c.name == "rule") {
768					self.rule_pre_contexts.push(py_int(attr(c, "precontext")?)?);
769					self.rule_sort_keys.push(py_int(attr(c, "sortkey")?)?);
770					let mut constraint = Vec::new();
771					let mut action = Vec::new();
772					for code in c.elements() {
773						match code.name.as_str() {
774							"constraint" => constraint = read_code(code)?,
775							"action" => action = read_code(code)?,
776							_ => {}
777						}
778					}
779					self.actions.push(action);
780					self.rule_constraints.push(constraint);
781				}
782			}
783			"passConstraint" => self.pass_constraints = read_code(e)?,
784			"fsm" => {
785				for c in e.elements() {
786					match c.name.as_str() {
787						"row" => {
788							let row = py_split(&content_string(c))
789								.map(|v| {
790									let v = py_int(v)?;
791									u16::try_from(v).map_err(|_| {
792										Error::ttlib(if v < 0 {
793											"OverflowError: unsigned short is less than minimum"
794										} else {
795											"OverflowError: unsigned short is greater than maximum"
796										})
797									})
798								})
799								.collect::<Result<_>>()?;
800							self.state_trans.push(row);
801						}
802						"starts" => {
803							self.start_states = py_split(&content_string(c))
804								.map(py_int)
805								.collect::<Result<_>>()?;
806						}
807						_ => {}
808					}
809				}
810			}
811			_ => {}
812		}
813		Ok(())
814	}
815}
816
817// ---------------------------------------------------------------------------
818// Classes
819
820/// The glyph classes of a [`SilfSubtable`] (`Classes`).
821#[derive(Debug, Clone, PartialEq, Default)]
822pub struct Classes {
823	/// `numClass`, as read or compiled.
824	pub num_class: Option<i64>,
825	/// `numLinear`, as read or compiled; the TTX numbers the non-linear classes
826	/// after the linear ones with it.
827	pub num_linear: Option<i64>,
828	/// The linear classes: glyphs in order (`linear`).
829	pub linear: Vec<Vec<u32>>,
830	/// The non-linear classes: glyph and index, in insertion order
831	/// (`nonLinear`).
832	pub non_linear: Vec<Vec<(u32, i64)>>,
833}
834
835impl Classes {
836	/// `Classes.decompile`.
837	pub fn decompile(data: &[u8], version: f64) -> Result<Self> {
838		let mut r = at_least(data, 4)?;
839		let nc = r.u16()? as i64;
840		let nl = r.u16()? as i64;
841		let n = nc as usize + 1;
842		let o_classes: Vec<i64> = if version >= 4.0 {
843			exact(py_slice(data, 4, 8 + 4 * nc), 4 * n)?
844				.u32_array(n)?
845				.into_iter()
846				.map(i64::from)
847				.collect()
848		} else {
849			exact(py_slice(data, 4, 6 + 2 * nc), 2 * n)?
850				.u16_array(n)?
851				.into_iter()
852				.map(i64::from)
853				.collect()
854		};
855		let mut classes = Classes {
856			num_class: Some(nc),
857			num_linear: Some(nl),
858			..Default::default()
859		};
860		let starts = py_slice(&o_classes, 0, nl);
861		let ends = py_slice(&o_classes, 1, nl + 1);
862		for (&s, &e) in starts.iter().zip(ends) {
863			// `"%d" % ((e - s) / 2)`.
864			let n = count(((e - s) as f64 / 2.0).trunc() as i64)?;
865			let glyphs = exact(py_slice(data, s, e), 2 * n)?.u16_array(n)?;
866			classes
867				.linear
868				.push(glyphs.into_iter().map(u32::from).collect());
869		}
870		let starts = py_slice(&o_classes, nl, nc);
871		let ends = py_slice(&o_classes, nl + 1, nc + 1);
872		for (&s, &e) in starts.iter().zip(ends) {
873			let mut non_linear = Vec::new();
874			let mut x = s + 8;
875			while x < e {
876				let mut r = exact(py_slice(data, x, x + 4), 4)?;
877				let glyph = r.u16()? as u32;
878				dict_set(&mut non_linear, glyph, r.u16()? as i64);
879				x += 4;
880			}
881			classes.non_linear.push(non_linear);
882		}
883		Ok(classes)
884	}
885
886	/// `Classes.compile`.
887	pub fn compile(&mut self, version: f64) -> Result<Vec<u8>> {
888		let mut data = Vec::new();
889		let mut o_classes = Vec::new();
890		let n = (self.linear.len() + self.non_linear.len()) as i64;
891		let offset = if version >= 4.0 { 8 + 4 * n } else { 6 + 2 * n };
892		for l in &self.linear {
893			o_classes.push(data.len() as i64 + offset);
894			for &g in l {
895				data.pack_u16(g as i64)?;
896			}
897		}
898		for l in &self.non_linear {
899			o_classes.push(data.len() as i64 + offset);
900			let mut gs: Vec<(i64, i64)> = l.iter().map(|&(g, i)| (g as i64, i)).collect();
901			data.extend(bininfo(gs.len() as i64, 1)?);
902			gs.sort();
903			for (g, i) in gs {
904				data.pack_u16(g)?;
905				data.pack_u16(i)?;
906			}
907		}
908		o_classes.push(data.len() as i64 + offset);
909		let num_class = o_classes.len() as i64 - 1;
910		self.num_class = Some(num_class);
911		self.num_linear = Some(self.linear.len() as i64);
912		let mut out = Vec::new();
913		out.pack_u16(num_class)?;
914		out.pack_u16(self.linear.len() as i64)?;
915		for o in o_classes {
916			if version >= 4.0 {
917				out.pack_u32(o)?;
918			} else {
919				out.pack_u16(o)?;
920			}
921		}
922		out.extend(data);
923		Ok(out)
924	}
925
926	/// `Classes.toXML`.
927	pub fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font, _version: f64) -> Result<()> {
928		let order = font.glyph_order()?;
929		writer.begintag("classes", &[]);
930		writer.newline();
931		writer.begintag("linearClasses", &[]);
932		writer.newline();
933		for (i, l) in self.linear.iter().enumerate() {
934			writer.begintag("linear", &[("_index", &i)]);
935			writer.newline();
936			let names: Vec<String> = l.iter().map(|&g| order.name(g).into_owned()).collect();
937			wrap_line(writer, &names);
938			writer.endtag("linear");
939			writer.newline();
940		}
941		writer.endtag("linearClasses");
942		writer.newline();
943		writer.begintag("nonLinearClasses", &[]);
944		writer.newline();
945		for (i, l) in self.non_linear.iter().enumerate() {
946			let num_linear = self.num_linear.ok_or_else(|| {
947				Error::ttlib("AttributeError: 'Classes' object has no attribute 'numLinear'")
948			})?;
949			writer.begintag("nonLinear", &[("_index", &(i as i64 + num_linear))]);
950			writer.newline();
951			for (g, index) in l {
952				writer.simpletag("map", &[("glyph", &order.name(*g)), ("index", index)]);
953				writer.newline();
954			}
955			writer.endtag("nonLinear");
956			writer.newline();
957		}
958		writer.endtag("nonLinearClasses");
959		writer.newline();
960		writer.endtag("classes");
961		writer.newline();
962		Ok(())
963	}
964
965	/// `Classes.fromXML`.
966	pub fn from_xml(&mut self, e: &Element, font: &mut Font, _version: f64) -> Result<()> {
967		match e.name.as_str() {
968			"linearClasses" => {
969				for c in e.elements().filter(|c| c.name == "linear") {
970					let glyphs = py_split(&content_string(c))
971						.map(|n| font.glyph_id(n))
972						.collect::<Result<_>>()?;
973					self.linear.push(glyphs);
974				}
975			}
976			"nonLinearClasses" => {
977				for c in e.elements().filter(|c| c.name == "nonLinear") {
978					let mut l = Vec::new();
979					for m in c.elements().filter(|m| m.name == "map") {
980						let glyph = font.glyph_id(attr(m, "glyph")?)?;
981						dict_set(&mut l, glyph, eval_int(attr(m, "index")?)?);
982					}
983					self.non_linear.push(l);
984				}
985			}
986			_ => {}
987		}
988		Ok(())
989	}
990
991	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
992		for l in &mut self.linear {
993			for g in l {
994				*g = f(*g)?;
995			}
996		}
997		for l in &mut self.non_linear {
998			for (g, _) in l {
999				*g = f(*g)?;
1000			}
1001		}
1002		Ok(())
1003	}
1004}
1005
1006// ---------------------------------------------------------------------------
1007// Silf subtables
1008
1009/// A justification level (`Silf_justify_format`).
1010#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1011pub struct Justify {
1012	/// `attrStretch`.
1013	pub attr_stretch: i64,
1014	/// `attrShrink`.
1015	pub attr_shrink: i64,
1016	/// `attrStep`.
1017	pub attr_step: i64,
1018	/// `attrWeight`.
1019	pub attr_weight: i64,
1020	/// `runto`.
1021	pub runto: i64,
1022}
1023
1024impl Justify {
1025	const NAMES: [&'static str; 5] = [
1026		"attrStretch",
1027		"attrShrink",
1028		"attrStep",
1029		"attrWeight",
1030		"runto",
1031	];
1032
1033	fn fields(&self) -> [i64; 5] {
1034		[
1035			self.attr_stretch,
1036			self.attr_shrink,
1037			self.attr_step,
1038			self.attr_weight,
1039			self.runto,
1040		]
1041	}
1042
1043	fn fields_mut(&mut self) -> [&mut i64; 5] {
1044		[
1045			&mut self.attr_stretch,
1046			&mut self.attr_shrink,
1047			&mut self.attr_step,
1048			&mut self.attr_weight,
1049			&mut self.runto,
1050		]
1051	}
1052}
1053
1054/// A `Silf` subtable (`Silf`).
1055#[derive(Debug, Clone, PartialEq, Default)]
1056pub struct SilfSubtable {
1057	/// `ruleVersion` (version 3 and later).
1058	pub rule_version: f64,
1059	/// `passOffset`, set when compiling.
1060	pub pass_offset: i64,
1061	/// `pseudosOffset`, set when compiling.
1062	pub pseudos_offset: i64,
1063	/// `maxGlyphID`.
1064	pub max_glyph_id: i64,
1065	/// `extraAscent`.
1066	pub extra_ascent: i64,
1067	/// `extraDescent`.
1068	pub extra_descent: i64,
1069	/// `numPasses`, set when compiling.
1070	pub num_passes: i64,
1071	/// `iSubst`.
1072	pub i_subst: i64,
1073	/// `iPos`.
1074	pub i_pos: i64,
1075	/// `iJust`.
1076	pub i_just: i64,
1077	/// `iBidi`.
1078	pub i_bidi: i64,
1079	/// `flags`.
1080	pub flags: i64,
1081	/// `maxPreContext`.
1082	pub max_pre_context: i64,
1083	/// `maxPostContext`.
1084	pub max_post_context: i64,
1085	/// `attrPseudo`.
1086	pub attr_pseudo: i64,
1087	/// `attrBreakWeight`.
1088	pub attr_break_weight: i64,
1089	/// `attrDirectionality`.
1090	pub attr_directionality: i64,
1091	/// `attrMirroring`.
1092	pub attr_mirroring: i64,
1093	/// `attrSkipPasses`.
1094	pub attr_skip_passes: i64,
1095	/// `numJLevels`, set when compiling.
1096	pub num_j_levels: i64,
1097	/// `jLevels`.
1098	pub j_levels: Vec<Justify>,
1099	/// `numLigComp`.
1100	pub num_lig_comp: i64,
1101	/// `numUserDefn`.
1102	pub num_user_defn: i64,
1103	/// `maxCompPerLig`.
1104	pub max_comp_per_lig: i64,
1105	/// `direction`.
1106	pub direction: i64,
1107	/// `attCollisions`.
1108	pub att_collisions: i64,
1109	/// `numCritFeatures`, set when compiling.
1110	pub num_crit_features: i64,
1111	/// `critFeatures`.
1112	pub crit_features: Vec<i64>,
1113	/// `scriptTags`.
1114	pub script_tags: Vec<String>,
1115	/// `lbGID`.
1116	pub lb_gid: i64,
1117	/// `oPasses`, as read.
1118	pub o_passes: Vec<i64>,
1119	/// The pseudo-glyph of each code point (`pMap`).
1120	pub p_map: BTreeMap<i64, u32>,
1121	/// `classes`.
1122	pub classes: Classes,
1123	/// `passes`.
1124	pub passes: Vec<Pass>,
1125}
1126
1127fn script_tag(data: &[u8]) -> Result<String> {
1128	if !data.is_ascii() {
1129		return Err(Error::value(
1130			"UnicodeDecodeError: 'ascii' codec can't decode byte",
1131		));
1132	}
1133	Ok(data.iter().map(|&b| b as char).collect())
1134}
1135
1136impl SilfSubtable {
1137	/// `Silf.decompile`.
1138	pub fn decompile(data: &[u8], version: f64) -> Result<Self> {
1139		let mut s = SilfSubtable::default();
1140		let mut data = data;
1141		if version >= 3.0 {
1142			let mut r = at_least(data, 8)?;
1143			s.rule_version = round_version(read_fixed(&mut r)?)?;
1144			s.pass_offset = r.u16()? as i64;
1145			s.pseudos_offset = r.u16()? as i64;
1146			data = r.rest();
1147		}
1148		let mut r = at_least(data, 20)?;
1149		s.max_glyph_id = r.u16()? as i64;
1150		s.extra_ascent = r.i16()? as i64;
1151		s.extra_descent = r.i16()? as i64;
1152		for f in [
1153			&mut s.num_passes,
1154			&mut s.i_subst,
1155			&mut s.i_pos,
1156			&mut s.i_just,
1157			&mut s.i_bidi,
1158			&mut s.flags,
1159			&mut s.max_pre_context,
1160			&mut s.max_post_context,
1161			&mut s.attr_pseudo,
1162			&mut s.attr_break_weight,
1163			&mut s.attr_directionality,
1164			&mut s.attr_mirroring,
1165			&mut s.attr_skip_passes,
1166			&mut s.num_j_levels,
1167		] {
1168			*f = r.u8()? as i64;
1169		}
1170		data = r.rest();
1171		for _ in 0..s.num_j_levels {
1172			let mut r = at_least(data, 8)?;
1173			let mut j = Justify::default();
1174			for f in j.fields_mut() {
1175				*f = r.u8()? as i64;
1176			}
1177			s.j_levels.push(j);
1178			data = &data[8..];
1179		}
1180		let mut r = at_least(data, 10)?;
1181		s.num_lig_comp = r.u16()? as i64;
1182		s.num_user_defn = r.u8()? as i64;
1183		s.max_comp_per_lig = r.u8()? as i64;
1184		s.direction = r.u8()? as i64;
1185		s.att_collisions = r.u8()? as i64;
1186		r.skip(3)?;
1187		s.num_crit_features = r.u8()? as i64;
1188		data = r.rest();
1189		let ncf = s.num_crit_features;
1190		if ncf != 0 {
1191			s.crit_features = at_least(data, 2 * ncf as usize)?
1192				.u16_array(ncf as usize)?
1193				.into_iter()
1194				.map(i64::from)
1195				.collect();
1196		}
1197		data = py_tail(data, ncf * 2 + 1);
1198		let nst = at_least(data, 1)?.u8()? as i64;
1199		for x in (1..1 + 4 * nst).step_by(4) {
1200			s.script_tags
1201				.push(script_tag(exact(py_slice(data, x, x + 4), 4)?.bytes(4)?)?);
1202		}
1203		data = py_tail(data, 1 + 4 * nst);
1204		s.lb_gid = exact(py_slice(data, 0, 2), 2)?.u16()? as i64;
1205		let np = s.num_passes;
1206		if np != 0 {
1207			let n = np as usize + 1;
1208			s.o_passes = exact(py_slice(data, 2, 6 + 4 * np), 4 * n)?
1209				.u32_array(n)?
1210				.into_iter()
1211				.map(i64::from)
1212				.collect();
1213		}
1214		data = py_tail(data, 6 + 4 * np);
1215		let num_pseudo = exact(py_slice(data, 0, 2), 2)?.u16()? as i64;
1216		for i in 0..num_pseudo {
1217			let (unicode, pseudo) = if version >= 3.0 {
1218				let mut r = exact(py_slice(data, 8 + 6 * i, 14 + 6 * i), 6)?;
1219				(r.u32()? as i64, r.u16()? as u32)
1220			} else {
1221				let mut r = exact(py_slice(data, 8 + 4 * i, 12 + 4 * i), 4)?;
1222				(r.u16()? as i64, r.u16()? as u32)
1223			};
1224			s.p_map.insert(unicode, pseudo);
1225		}
1226		// UPSTREAM-BUG(B70): before version 3, the pseudo-glyph entries are read as 4
1227		// bytes but skipped as 6, so the classes and passes after them are misread.
1228		data = py_tail(data, 8 + 6 * num_pseudo);
1229		let mut currpos = 20
1230			+ 8 * s.num_j_levels
1231			+ 10
1232			+ 2 * ncf
1233			+ 1
1234			+ 1
1235			+ 4 * nst
1236			+ 6
1237			+ 4 * np
1238			+ 8
1239			+ 6 * num_pseudo;
1240		if version >= 3.0 {
1241			currpos += 8;
1242		}
1243		s.classes = Classes::decompile(data, version)?;
1244		for i in 0..np as usize {
1245			let pass = py_slice(data, s.o_passes[i] - currpos, s.o_passes[i + 1] - currpos);
1246			s.passes.push(Pass::decompile(pass, version)?);
1247		}
1248		Ok(s)
1249	}
1250
1251	/// `Silf.compile`.
1252	pub fn compile(&mut self, version: f64) -> Result<Vec<u8>> {
1253		self.num_passes = self.passes.len() as i64;
1254		self.num_j_levels = self.j_levels.len() as i64;
1255		self.num_crit_features = self.crit_features.len() as i64;
1256		let num_pseudo = self.p_map.len() as i64;
1257		let hdroffset = if version >= 3.0 { 8 } else { 0 };
1258		let mut data = Vec::new();
1259		data.pack_u16(self.max_glyph_id)?;
1260		data.pack_i16(self.extra_ascent)?;
1261		data.pack_i16(self.extra_descent)?;
1262		for v in [
1263			self.num_passes,
1264			self.i_subst,
1265			self.i_pos,
1266			self.i_just,
1267			self.i_bidi,
1268			self.flags,
1269			self.max_pre_context,
1270			self.max_post_context,
1271			self.attr_pseudo,
1272			self.attr_break_weight,
1273			self.attr_directionality,
1274			self.attr_mirroring,
1275			self.attr_skip_passes,
1276			self.num_j_levels,
1277		] {
1278			data.pack_u8(v)?;
1279		}
1280		for j in &self.j_levels {
1281			for v in j.fields() {
1282				data.pack_u8(v)?;
1283			}
1284			data.extend_from_slice(&[0; 3]);
1285		}
1286		data.pack_u16(self.num_lig_comp)?;
1287		for v in [
1288			self.num_user_defn,
1289			self.max_comp_per_lig,
1290			self.direction,
1291			self.att_collisions,
1292		] {
1293			data.pack_u8(v)?;
1294		}
1295		data.extend_from_slice(&[0; 3]);
1296		data.pack_u8(self.num_crit_features)?;
1297		// LENIENT(L49), UPSTREAM-BUG(B80): fontTools misspells `numCritFeatures` here, so
1298		// it cannot compile subtables with critical features.
1299		for &v in &self.crit_features {
1300			data.pack_u16(v)?;
1301		}
1302		data.pack_u8(0)?;
1303		data.pack_u8(self.script_tags.len() as i64)?;
1304		for t in &self.script_tags {
1305			if !t.is_ascii() {
1306				return Err(Error::value(
1307					"UnicodeEncodeError: 'ascii' codec can't encode character",
1308				));
1309			}
1310			data.pack_4s(t.as_bytes());
1311		}
1312		data.pack_u16(self.lb_gid)?;
1313		self.pass_offset = data.len() as i64;
1314
1315		let mut data1 = bininfo(num_pseudo, 6)?;
1316		let mut currpos = hdroffset + data.len() as i64 + 4 * (self.num_passes + 1);
1317		self.pseudos_offset = currpos + data1.len() as i64;
1318		for (&u, &p) in &self.p_map {
1319			if version >= 3.0 {
1320				data1.pack_u32(u)?;
1321			} else {
1322				data1.pack_u16(u)?;
1323			}
1324			data1.pack_u16(p as i64)?;
1325		}
1326		data1.extend(self.classes.compile(version)?);
1327		currpos += data1.len() as i64;
1328		let mut data2 = Vec::new();
1329		let mut datao = Vec::new();
1330		for p in &mut self.passes {
1331			let base = currpos + data2.len() as i64;
1332			datao.pack_u32(base)?;
1333			data2.extend(p.compile(base, version)?);
1334		}
1335		datao.pack_u32(currpos + data2.len() as i64)?;
1336
1337		let mut out = Vec::new();
1338		if version >= 3.0 {
1339			out.pack_fixed(self.rule_version)?;
1340			out.pack_u16(self.pass_offset)?;
1341			out.pack_u16(self.pseudos_offset)?;
1342		}
1343		out.extend(data);
1344		out.extend(datao);
1345		out.extend(data1);
1346		out.extend(data2);
1347		Ok(out)
1348	}
1349
1350	/// `Silf.toXML`.
1351	pub fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font, version: f64) -> Result<()> {
1352		if version >= 3.0 {
1353			writer.simpletag("version", &[("ruleVersion", &self.rule_version)]);
1354			writer.newline();
1355		}
1356		write_simple(
1357			writer,
1358			"info",
1359			&[
1360				("flags", self.flags),
1361				("extraAscent", self.extra_ascent),
1362				("extraDescent", self.extra_descent),
1363				("maxGlyphID", self.max_glyph_id),
1364				("numLigComp", self.num_lig_comp),
1365				("numUserDefn", self.num_user_defn),
1366				("maxCompPerLig", self.max_comp_per_lig),
1367				("direction", self.direction),
1368				("lbGID", self.lb_gid),
1369			],
1370		);
1371		write_simple(
1372			writer,
1373			"passindexes",
1374			&[
1375				("iSubst", self.i_subst),
1376				("iPos", self.i_pos),
1377				("iJust", self.i_just),
1378				("iBidi", self.i_bidi),
1379			],
1380		);
1381		write_simple(
1382			writer,
1383			"contexts",
1384			&[
1385				("maxPreContext", self.max_pre_context),
1386				("maxPostContext", self.max_post_context),
1387			],
1388		);
1389		write_simple(
1390			writer,
1391			"attributes",
1392			&[
1393				("attrPseudo", self.attr_pseudo),
1394				("attrBreakWeight", self.attr_break_weight),
1395				("attrDirectionality", self.attr_directionality),
1396				("attrMirroring", self.attr_mirroring),
1397				("attrSkipPasses", self.attr_skip_passes),
1398				("attCollisions", self.att_collisions),
1399			],
1400		);
1401		if !self.j_levels.is_empty() {
1402			writer.begintag("justifications", &[]);
1403			writer.newline();
1404			for j in &self.j_levels {
1405				let attrs: Vec<(&str, i64)> = Justify::NAMES.into_iter().zip(j.fields()).collect();
1406				write_simple(writer, "justify", &attrs);
1407			}
1408			writer.endtag("justifications");
1409			writer.newline();
1410		}
1411		if !self.crit_features.is_empty() {
1412			writer.begintag("critFeatures", &[]);
1413			writer.newline();
1414			let v: Vec<String> = self.crit_features.iter().map(i64::to_string).collect();
1415			writer.write(&v.join(" "));
1416			writer.newline();
1417			writer.endtag("critFeatures");
1418			writer.newline();
1419		}
1420		if !self.script_tags.is_empty() {
1421			writer.begintag("scriptTags", &[]);
1422			writer.newline();
1423			writer.write(&self.script_tags.join(" "));
1424			writer.newline();
1425			writer.endtag("scriptTags");
1426			writer.newline();
1427		}
1428		if !self.p_map.is_empty() {
1429			let order = font.glyph_order()?;
1430			writer.begintag("pseudoMap", &[]);
1431			writer.newline();
1432			for (&k, &v) in &self.p_map {
1433				writer.simpletag(
1434					"pseudo",
1435					&[("unicode", &py_hex(k)), ("pseudo", &order.name(v))],
1436				);
1437				writer.newline();
1438			}
1439			writer.endtag("pseudoMap");
1440			writer.newline();
1441		}
1442		self.classes.to_xml(writer, font, version)?;
1443		if !self.passes.is_empty() {
1444			writer.begintag("passes", &[]);
1445			writer.newline();
1446			for (i, p) in self.passes.iter().enumerate() {
1447				writer.begintag("pass", &[("_index", &i)]);
1448				writer.newline();
1449				p.to_xml(writer, font, version)?;
1450				writer.endtag("pass");
1451				writer.newline();
1452			}
1453			writer.endtag("passes");
1454			writer.newline();
1455		}
1456		Ok(())
1457	}
1458
1459	/// `Silf.fromXML`.
1460	pub fn from_xml(&mut self, e: &Element, font: &mut Font, version: f64) -> Result<()> {
1461		match e.name.as_str() {
1462			"version" => self.rule_version = eval_float(e.attr("ruleVersion").unwrap_or("0"))?,
1463			"info" => get_simple(
1464				e,
1465				&mut [
1466					("flags", &mut self.flags),
1467					("extraAscent", &mut self.extra_ascent),
1468					("extraDescent", &mut self.extra_descent),
1469					("maxGlyphID", &mut self.max_glyph_id),
1470					("numLigComp", &mut self.num_lig_comp),
1471					("numUserDefn", &mut self.num_user_defn),
1472					("maxCompPerLig", &mut self.max_comp_per_lig),
1473					("direction", &mut self.direction),
1474					("lbGID", &mut self.lb_gid),
1475				],
1476			)?,
1477			"passindexes" => get_simple(
1478				e,
1479				&mut [
1480					("iSubst", &mut self.i_subst),
1481					("iPos", &mut self.i_pos),
1482					("iJust", &mut self.i_just),
1483					("iBidi", &mut self.i_bidi),
1484				],
1485			)?,
1486			"contexts" => get_simple(
1487				e,
1488				&mut [
1489					("maxPreContext", &mut self.max_pre_context),
1490					("maxPostContext", &mut self.max_post_context),
1491				],
1492			)?,
1493			"attributes" => get_simple(
1494				e,
1495				&mut [
1496					("attrPseudo", &mut self.attr_pseudo),
1497					("attrBreakWeight", &mut self.attr_break_weight),
1498					("attrDirectionality", &mut self.attr_directionality),
1499					("attrMirroring", &mut self.attr_mirroring),
1500					("attrSkipPasses", &mut self.attr_skip_passes),
1501					("attCollisions", &mut self.att_collisions),
1502				],
1503			)?,
1504			"justifications" => {
1505				for c in e.elements().filter(|c| c.name == "justify") {
1506					let mut j = Justify::default();
1507					for (k, v) in &c.attrs {
1508						let v = py_int(v)?;
1509						if let Some(i) = Justify::NAMES.iter().position(|n| n == k) {
1510							*j.fields_mut()[i] = v;
1511						}
1512					}
1513					self.j_levels.push(j);
1514				}
1515			}
1516			"critFeatures" => {
1517				self.crit_features = py_split(&content_string(e))
1518					.map(py_int)
1519					.collect::<Result<_>>()?;
1520			}
1521			"scriptTags" => {
1522				self.script_tags = py_split(&content_string(e)).map(str::to_owned).collect();
1523			}
1524			"pseudoMap" => {
1525				self.p_map.clear();
1526				let mut last = None;
1527				for c in e.elements() {
1528					if c.name == "pseudo" {
1529						let unicode = attr(c, "unicode")?;
1530						let k = parse_int_radix(unicode, 16)
1531							.and_then(|v| i64::try_from(v).ok())
1532							.ok_or_else(|| {
1533								Error::value(format!(
1534									"invalid literal for int() with base 16: {unicode:?}"
1535								))
1536							})?;
1537						last = Some((k, font.glyph_id(attr(c, "pseudo")?)?));
1538					}
1539					// As in fontTools, other elements repeat the last mapping.
1540					let (k, v) = last.ok_or_else(|| {
1541						Error::ttlib("NameError: cannot access free variable 'k'")
1542					})?;
1543					self.p_map.insert(k, v);
1544				}
1545			}
1546			"classes" => {
1547				self.classes = Classes::default();
1548				for c in e.elements() {
1549					self.classes.from_xml(c, font, version)?;
1550				}
1551			}
1552			"passes" => {
1553				for c in e.elements().filter(|c| c.name == "pass") {
1554					let mut p = Pass::default();
1555					for pe in c.elements() {
1556						p.from_xml(pe, font, version)?;
1557					}
1558					self.passes.push(p);
1559				}
1560			}
1561			_ => {}
1562		}
1563		Ok(())
1564	}
1565
1566	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
1567		for v in self.p_map.values_mut() {
1568			*v = f(*v)?;
1569		}
1570		self.classes.remap_glyphs(f)?;
1571		for p in &mut self.passes {
1572			p.col_map = crate::ot::aat::remap_keys(std::mem::take(&mut p.col_map), f)?;
1573		}
1574		Ok(())
1575	}
1576}
1577
1578// ---------------------------------------------------------------------------
1579// The table
1580
1581/// Graphite Rules table (`table_S__i_l_f`).
1582#[derive(Debug, Clone, PartialEq, Default)]
1583pub struct Silf {
1584	/// The table version (`version`).
1585	pub version: f64,
1586	/// `compilerVersion` (version 3 and later; 0 before).
1587	pub compiler_version: i64,
1588	/// The compression scheme (`scheme`).
1589	pub scheme: i64,
1590	/// The subtables (`silfs`).
1591	pub silfs: Vec<SilfSubtable>,
1592}
1593
1594impl TableType for Silf {
1595	const TAG: Tag = Tag::new(b"Silf");
1596
1597	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
1598		let mut silf = Silf {
1599			version: round_version(read_fixed(&mut at_least(data, 4)?)?)?,
1600			..Default::default()
1601		};
1602		let mut owned = None;
1603		if silf.version >= 5.0 {
1604			let (d, scheme) = decompress(data)?;
1605			silf.scheme = scheme;
1606			owned = Some(d);
1607		}
1608		let data = owned.as_deref().unwrap_or(data);
1609		let (num_silf, base) = if silf.version < 3.0 {
1610			(exact(py_slice(data, 4, 6), 2)?.u16()? as usize, 8)
1611		} else {
1612			let mut r = at_least(data, 12)?;
1613			silf.version = read_fixed(&mut r)?;
1614			silf.compiler_version = r.u32()? as i64;
1615			(r.u16()? as usize, 12)
1616		};
1617		let offsets = at_least(py_tail(data, base), 4 * num_silf)?.u32_array(num_silf)?;
1618		for offset in offsets {
1619			let sub = py_tail(data, offset as i64);
1620			silf.silfs.push(SilfSubtable::decompile(sub, silf.version)?);
1621		}
1622		Ok(silf)
1623	}
1624}
1625
1626impl Table for Silf {
1627	fn tag(&self) -> Tag {
1628		Self::TAG
1629	}
1630
1631	fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
1632		let num_silf = self.silfs.len() as i64;
1633		let mut hdr = Vec::new();
1634		hdr.pack_fixed(self.version)?;
1635		if self.version < 3.0 {
1636			hdr.pack_u16(num_silf)?;
1637			hdr.pack_u16(0)?;
1638		} else {
1639			hdr.pack_u32(self.compiler_version)?;
1640			hdr.pack_u16(num_silf)?;
1641			hdr.extend_from_slice(&[0; 2]);
1642		}
1643		let mut offset = hdr.len() as i64 + 4 * num_silf;
1644		let mut data = Vec::new();
1645		let version = self.version;
1646		for s in &mut self.silfs {
1647			hdr.pack_u32(offset)?;
1648			let sub = s.compile(version)?;
1649			offset += sub.len() as i64;
1650			data.extend(sub);
1651		}
1652		hdr.extend(data);
1653		if self.version >= 5.0 {
1654			return compress(self.scheme, &hdr);
1655		}
1656		Ok(hdr)
1657	}
1658
1659	fn clone_table(&self) -> Box<dyn Table> {
1660		Box::new(self.clone())
1661	}
1662
1663	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
1664		for s in &mut self.silfs {
1665			s.remap_glyphs(f)?;
1666		}
1667		Ok(())
1668	}
1669}
1670
1671impl TableXml for Silf {
1672	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
1673		writer.comment("Attributes starting with _ are informative only");
1674		writer.newline();
1675		writer.simpletag(
1676			"version",
1677			&[
1678				("version", &self.version),
1679				("compilerVersion", &self.compiler_version),
1680				("compressionScheme", &self.scheme),
1681			],
1682		);
1683		writer.newline();
1684		for s in &self.silfs {
1685			writer.begintag("silf", &[]);
1686			writer.newline();
1687			s.to_xml(writer, font, self.version)?;
1688			writer.endtag("silf");
1689			writer.newline();
1690		}
1691		Ok(())
1692	}
1693
1694	fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
1695		match element.name.as_str() {
1696			"version" => {
1697				self.scheme = eval_int(attr(element, "compressionScheme")?)?;
1698				self.version = eval_float(attr(element, "version")?)?;
1699				self.compiler_version = eval_int(attr(element, "compilerVersion")?)?;
1700			}
1701			"silf" => {
1702				let mut s = SilfSubtable::default();
1703				for e in element.elements() {
1704					s.from_xml(e, font, self.version)?;
1705				}
1706				self.silfs.push(s);
1707			}
1708			_ => {}
1709		}
1710		Ok(())
1711	}
1712}
1713
1714#[cfg(test)]
1715mod tests {
1716	use super::*;
1717
1718	#[test]
1719	fn code_round_trip() -> Result<()> {
1720		let lines = [
1721			"PUT_GLYPH_8BIT_OBS(0)",
1722			"ASSOC(0, 1)",
1723			"NEXT",
1724			"PUSH_BYTE(-1)",
1725			"PUT_SUBS(-1, 300, 2)",
1726			"ASSOC()",
1727		];
1728		let code = assemble(&lines)?;
1729		// `ASSOC()` has no operands to match, so it is just the opcode.
1730		assert_eq!(
1731			disassemble(&code)?,
1732			[
1733				"PUT_GLYPH_8BIT_OBS(0)",
1734				"ASSOC(0, 1)",
1735				"NEXT",
1736				"PUSH_BYTE(-1)",
1737				"PUT_SUBS(-1, 300, 2)",
1738			]
1739		);
1740		// A truncated operand ends the listing.
1741		assert_eq!(disassemble(&[25, 1])?, ["NEXT"]);
1742		assert_eq!(disassemble(&[33, 0])?, ["ASSOC()"]);
1743		assert!(disassemble(&[67]).is_err());
1744		assert_eq!(disassemble(&[68])?, ["NOP"]);
1745		assert_eq!(assemble(&["PUSH_BYTE (1)", "UNKNOWN", "NEXT(3)"])?, [25]);
1746		Ok(())
1747	}
1748}