1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
// Copyright (c) 2021 The Vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
//! Parsing and analysis utilities for SPIR-V shader binaries.
//!
//! This can be used to inspect and validate a SPIR-V module at runtime. The `Spirv` type does some
//! validation, but you should not assume that code that is read successfully is valid.
//!
//! For more information about SPIR-V modules, instructions and types, see the
//! [SPIR-V specification](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html).
use crate::{shader::SpecializationConstant, Version};
use ahash::HashMap;
use smallvec::{smallvec, SmallVec};
use std::{
borrow::Cow,
error::Error,
fmt::{Display, Error as FmtError, Formatter},
string::FromUtf8Error,
};
mod specialization;
// Generated by build.rs
include!(concat!(env!("OUT_DIR"), "/spirv_parse.rs"));
/// A parsed and analyzed SPIR-V module.
#[derive(Clone, Debug)]
pub struct Spirv {
version: Version,
bound: u32,
ids: HashMap<Id, IdInfo>,
// Items described in the spec section "Logical Layout of a Module"
instructions_capability: Vec<Instruction>,
instructions_extension: Vec<Instruction>,
instructions_ext_inst_import: Vec<Instruction>,
instruction_memory_model: Instruction,
instructions_entry_point: Vec<Instruction>,
instructions_execution_mode: Vec<Instruction>,
instructions_name: Vec<Instruction>,
instructions_decoration: Vec<Instruction>,
instructions_global: Vec<Instruction>,
functions: HashMap<Id, FunctionInfo>,
}
impl Spirv {
/// Parses a SPIR-V document from a list of words.
pub fn new(words: &[u32]) -> Result<Spirv, SpirvError> {
if words.len() < 5 {
return Err(SpirvError::InvalidHeader);
}
if words[0] != 0x07230203 {
return Err(SpirvError::InvalidHeader);
}
let version = Version {
major: (words[1] & 0x00ff0000) >> 16,
minor: (words[1] & 0x0000ff00) >> 8,
patch: words[1] & 0x000000ff,
};
// For safety, we recalculate the bound ourselves.
let mut bound = 0;
let mut ids = HashMap::default();
let mut instructions_capability = Vec::new();
let mut instructions_extension = Vec::new();
let mut instructions_ext_inst_import = Vec::new();
let mut instructions_memory_model = Vec::new();
let mut instructions_entry_point = Vec::new();
let mut instructions_execution_mode = Vec::new();
let mut instructions_name = Vec::new();
let mut instructions_decoration = Vec::new();
let mut instructions_global = Vec::new();
let mut functions = HashMap::default();
let mut current_function: Option<&mut Vec<Instruction>> = None;
for instruction in iter_instructions(&words[5..]) {
let instruction = instruction?;
if let Some(id) = instruction.result_id() {
bound = bound.max(u32::from(id) + 1);
let members = if let Instruction::TypeStruct {
ref member_types, ..
} = instruction
{
member_types
.iter()
.map(|_| StructMemberInfo::default())
.collect()
} else {
Vec::new()
};
let data = IdInfo {
instruction: instruction.clone(),
names: Vec::new(),
decorations: Vec::new(),
members,
};
if ids.insert(id, data).is_some() {
return Err(SpirvError::DuplicateId { id });
}
}
if matches!(
instruction,
Instruction::Line { .. } | Instruction::NoLine { .. }
) {
continue;
}
if current_function.is_some() {
match instruction {
Instruction::FunctionEnd { .. } => {
current_function.take().unwrap().push(instruction);
}
_ => current_function.as_mut().unwrap().push(instruction),
}
} else {
let destination = match instruction {
Instruction::Function { result_id, .. } => {
current_function = None;
let function = functions.entry(result_id).or_insert_with(|| {
let entry_point = instructions_entry_point
.iter()
.find(|instruction| {
matches!(
**instruction,
Instruction::EntryPoint { entry_point, .. }
if entry_point == result_id
)
})
.cloned();
let execution_modes = instructions_execution_mode
.iter()
.filter(|instruction| {
matches!(
**instruction,
Instruction::ExecutionMode { entry_point, .. }
| Instruction::ExecutionModeId { entry_point, .. }
if entry_point == result_id
)
})
.cloned()
.collect();
FunctionInfo {
instructions: Vec::new(),
entry_point,
execution_modes,
}
});
current_function.insert(&mut function.instructions)
}
Instruction::Capability { .. } => &mut instructions_capability,
Instruction::Extension { .. } => &mut instructions_extension,
Instruction::ExtInstImport { .. } => &mut instructions_ext_inst_import,
Instruction::MemoryModel { .. } => &mut instructions_memory_model,
Instruction::EntryPoint { .. } => &mut instructions_entry_point,
Instruction::ExecutionMode { .. } | Instruction::ExecutionModeId { .. } => {
&mut instructions_execution_mode
}
Instruction::Name { .. } | Instruction::MemberName { .. } => {
&mut instructions_name
}
Instruction::Decorate { .. }
| Instruction::MemberDecorate { .. }
| Instruction::DecorationGroup { .. }
| Instruction::GroupDecorate { .. }
| Instruction::GroupMemberDecorate { .. }
| Instruction::DecorateId { .. }
| Instruction::DecorateString { .. }
| Instruction::MemberDecorateString { .. } => &mut instructions_decoration,
Instruction::TypeVoid { .. }
| Instruction::TypeBool { .. }
| Instruction::TypeInt { .. }
| Instruction::TypeFloat { .. }
| Instruction::TypeVector { .. }
| Instruction::TypeMatrix { .. }
| Instruction::TypeImage { .. }
| Instruction::TypeSampler { .. }
| Instruction::TypeSampledImage { .. }
| Instruction::TypeArray { .. }
| Instruction::TypeRuntimeArray { .. }
| Instruction::TypeStruct { .. }
| Instruction::TypeOpaque { .. }
| Instruction::TypePointer { .. }
| Instruction::TypeFunction { .. }
| Instruction::TypeEvent { .. }
| Instruction::TypeDeviceEvent { .. }
| Instruction::TypeReserveId { .. }
| Instruction::TypeQueue { .. }
| Instruction::TypePipe { .. }
| Instruction::TypeForwardPointer { .. }
| Instruction::TypePipeStorage { .. }
| Instruction::TypeNamedBarrier { .. }
| Instruction::TypeRayQueryKHR { .. }
| Instruction::TypeAccelerationStructureKHR { .. }
| Instruction::TypeCooperativeMatrixNV { .. }
| Instruction::TypeVmeImageINTEL { .. }
| Instruction::TypeAvcImePayloadINTEL { .. }
| Instruction::TypeAvcRefPayloadINTEL { .. }
| Instruction::TypeAvcSicPayloadINTEL { .. }
| Instruction::TypeAvcMcePayloadINTEL { .. }
| Instruction::TypeAvcMceResultINTEL { .. }
| Instruction::TypeAvcImeResultINTEL { .. }
| Instruction::TypeAvcImeResultSingleReferenceStreamoutINTEL { .. }
| Instruction::TypeAvcImeResultDualReferenceStreamoutINTEL { .. }
| Instruction::TypeAvcImeSingleReferenceStreaminINTEL { .. }
| Instruction::TypeAvcImeDualReferenceStreaminINTEL { .. }
| Instruction::TypeAvcRefResultINTEL { .. }
| Instruction::TypeAvcSicResultINTEL { .. }
| Instruction::ConstantTrue { .. }
| Instruction::ConstantFalse { .. }
| Instruction::Constant { .. }
| Instruction::ConstantComposite { .. }
| Instruction::ConstantSampler { .. }
| Instruction::ConstantNull { .. }
| Instruction::ConstantPipeStorage { .. }
| Instruction::SpecConstantTrue { .. }
| Instruction::SpecConstantFalse { .. }
| Instruction::SpecConstant { .. }
| Instruction::SpecConstantComposite { .. }
| Instruction::SpecConstantOp { .. }
| Instruction::Variable { .. }
| Instruction::Undef { .. } => &mut instructions_global,
_ => continue,
};
destination.push(instruction);
}
}
let instruction_memory_model = instructions_memory_model.drain(..).next().unwrap();
// Add decorations to ids,
// while also expanding decoration groups into individual decorations.
let mut decoration_groups: HashMap<Id, Vec<Instruction>> = HashMap::default();
let instructions_decoration = instructions_decoration
.into_iter()
.flat_map(|instruction| -> SmallVec<[Instruction; 1]> {
match instruction {
Instruction::Decorate { target, .. }
| Instruction::DecorateId { target, .. }
| Instruction::DecorateString { target, .. } => {
let id_info = ids.get_mut(&target).unwrap();
if matches!(id_info.instruction(), Instruction::DecorationGroup { .. }) {
decoration_groups
.entry(target)
.or_default()
.push(instruction);
smallvec![]
} else {
id_info.decorations.push(instruction.clone());
smallvec![instruction]
}
}
Instruction::MemberDecorate {
structure_type: target,
member,
..
}
| Instruction::MemberDecorateString {
struct_type: target,
member,
..
} => {
ids.get_mut(&target).unwrap().members[member as usize]
.decorations
.push(instruction.clone());
smallvec![instruction]
}
Instruction::DecorationGroup { result_id } => {
// Drop the instruction altogether.
decoration_groups.entry(result_id).or_default();
ids.remove(&result_id);
smallvec![]
}
Instruction::GroupDecorate {
decoration_group,
ref targets,
} => {
let decorations = &decoration_groups[&decoration_group];
(targets.iter().copied())
.flat_map(|target| {
decorations
.iter()
.map(move |instruction| (target, instruction))
})
.map(|(target, instruction)| {
let id_info = ids.get_mut(&target).unwrap();
match instruction {
Instruction::Decorate { ref decoration, .. } => {
let instruction = Instruction::Decorate {
target,
decoration: decoration.clone(),
};
id_info.decorations.push(instruction.clone());
instruction
}
Instruction::DecorateId { ref decoration, .. } => {
let instruction = Instruction::DecorateId {
target,
decoration: decoration.clone(),
};
id_info.decorations.push(instruction.clone());
instruction
}
_ => unreachable!(),
}
})
.collect()
}
Instruction::GroupMemberDecorate {
decoration_group,
ref targets,
} => {
let decorations = &decoration_groups[&decoration_group];
(targets.iter().copied())
.flat_map(|target| {
decorations
.iter()
.map(move |instruction| (target, instruction))
})
.map(|((structure_type, member), instruction)| {
let member_info =
&mut ids.get_mut(&structure_type).unwrap().members
[member as usize];
match instruction {
Instruction::Decorate { ref decoration, .. } => {
let instruction = Instruction::MemberDecorate {
structure_type,
member,
decoration: decoration.clone(),
};
member_info.decorations.push(instruction.clone());
instruction
}
Instruction::DecorateId { .. } => {
panic!(
"a DecorateId instruction targets a decoration group, \
and that decoration group is applied using a \
GroupMemberDecorate instruction, but there is no \
MemberDecorateId instruction"
);
}
_ => unreachable!(),
}
})
.collect()
}
_ => smallvec![instruction],
}
})
.collect();
instructions_name.retain(|instruction| match *instruction {
Instruction::Name { target, .. } => {
if let Some(id_info) = ids.get_mut(&target) {
id_info.names.push(instruction.clone());
true
} else {
false
}
}
Instruction::MemberName { ty, member, .. } => {
if let Some(id_info) = ids.get_mut(&ty) {
id_info.members[member as usize]
.names
.push(instruction.clone());
true
} else {
false
}
}
_ => unreachable!(),
});
Ok(Spirv {
version,
bound,
ids,
instructions_capability,
instructions_extension,
instructions_ext_inst_import,
instruction_memory_model,
instructions_entry_point,
instructions_execution_mode,
instructions_name,
instructions_decoration,
instructions_global,
functions,
})
}
/// Returns the SPIR-V version that the module is compiled for.
#[inline]
pub fn version(&self) -> Version {
self.version
}
/// Returns information about an `Id`.
///
/// # Panics
///
/// - Panics if `id` is not defined in this module. This can in theory only happpen if you are
/// mixing `Id`s from different modules.
#[inline]
pub fn id(&self, id: Id) -> &IdInfo {
&self.ids[&id]
}
/// Returns the function with the given `id`, if it exists.
///
/// # Panics
///
/// - Panics if `id` is not defined in this module. This can in theory only happpen if you are
/// mixing `Id`s from different modules.
#[inline]
pub fn function(&self, id: Id) -> &FunctionInfo {
&self.functions[&id]
}
/// Returns an iterator over all `Capability` instructions.
#[inline]
pub fn iter_capability(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions_capability.iter()
}
/// Returns an iterator over all `Extension` instructions.
#[inline]
pub fn iter_extension(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions_extension.iter()
}
/// Returns an iterator over all `ExtInstImport` instructions.
#[inline]
pub fn iter_ext_inst_import(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions_ext_inst_import.iter()
}
/// Returns the `MemoryModel` instruction.
#[inline]
pub fn memory_model(&self) -> &Instruction {
&self.instruction_memory_model
}
/// Returns an iterator over all `EntryPoint` instructions.
#[inline]
pub fn iter_entry_point(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions_entry_point.iter()
}
/// Returns an iterator over all execution mode instructions.
#[inline]
pub fn iter_execution_mode(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions_execution_mode.iter()
}
/// Returns an iterator over all name debug instructions.
#[inline]
pub fn iter_name(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions_name.iter()
}
/// Returns an iterator over all decoration instructions.
#[inline]
pub fn iter_decoration(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions_decoration.iter()
}
/// Returns an iterator over all global declaration instructions: types,
/// constants and global variables.
#[inline]
pub fn iter_global(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions_global.iter()
}
/// Returns an iterator over all functions.
#[inline]
pub fn iter_functions(&self) -> impl ExactSizeIterator<Item = &FunctionInfo> {
self.functions.values()
}
pub fn apply_specialization(
&mut self,
specialization_info: &HashMap<u32, SpecializationConstant>,
) {
self.instructions_global = specialization::replace_specialization_instructions(
specialization_info,
self.instructions_global.drain(..),
&self.ids,
self.bound,
);
for instruction in &self.instructions_global {
if let Some(id) = instruction.result_id() {
if let Some(id_info) = self.ids.get_mut(&id) {
id_info.instruction = instruction.clone();
id_info.decorations.retain(|instruction| {
!matches!(
instruction,
Instruction::Decorate {
decoration: Decoration::SpecId { .. },
..
}
)
});
} else {
self.ids.insert(
id,
IdInfo {
instruction: instruction.clone(),
names: Vec::new(),
decorations: Vec::new(),
members: Vec::new(),
},
);
self.bound = self.bound.max(u32::from(id) + 1);
}
}
}
self.instructions_decoration.retain(|instruction| {
!matches!(
instruction,
Instruction::Decorate {
decoration: Decoration::SpecId { .. },
..
}
)
});
}
}
/// Used in SPIR-V to refer to the result of another instruction.
///
/// Ids are global across a module, and are always assigned by exactly one instruction.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct Id(u32);
impl Id {
// Returns the raw numeric value of this Id.
#[inline]
pub const fn as_raw(self) -> u32 {
self.0
}
}
impl From<Id> for u32 {
#[inline]
fn from(id: Id) -> u32 {
id.as_raw()
}
}
impl Display for Id {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
write!(f, "%{}", self.0)
}
}
/// Information associated with an `Id`.
#[derive(Clone, Debug)]
pub struct IdInfo {
instruction: Instruction,
names: Vec<Instruction>,
decorations: Vec<Instruction>,
members: Vec<StructMemberInfo>,
}
impl IdInfo {
/// Returns the instruction that defines this `Id` with a `result_id` operand.
#[inline]
pub fn instruction(&self) -> &Instruction {
&self.instruction
}
/// Returns an iterator over all name debug instructions that target this `Id`.
#[inline]
pub fn iter_name(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.names.iter()
}
/// Returns an iterator over all decorate instructions, that target this `Id`.
#[inline]
pub fn iter_decoration(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.decorations.iter()
}
/// If this `Id` refers to a `TypeStruct`, returns an iterator of information about each member
/// of the struct. Empty otherwise.
#[inline]
pub fn iter_members(&self) -> impl ExactSizeIterator<Item = &StructMemberInfo> {
self.members.iter()
}
}
/// Information associated with a member of a `TypeStruct` instruction.
#[derive(Clone, Debug, Default)]
pub struct StructMemberInfo {
names: Vec<Instruction>,
decorations: Vec<Instruction>,
}
impl StructMemberInfo {
/// Returns an iterator over all name debug instructions that target this struct member.
#[inline]
pub fn iter_name(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.names.iter()
}
/// Returns an iterator over all decorate instructions that target this struct member.
#[inline]
pub fn iter_decoration(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.decorations.iter()
}
}
/// Information associated with a function.
#[derive(Clone, Debug)]
pub struct FunctionInfo {
instructions: Vec<Instruction>,
entry_point: Option<Instruction>,
execution_modes: Vec<Instruction>,
}
impl FunctionInfo {
/// Returns an iterator over all instructions in the function.
#[inline]
pub fn iter_instructions(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.instructions.iter()
}
/// Returns the `EntryPoint` instruction that targets this function, if there is one.
#[inline]
pub fn entry_point(&self) -> Option<&Instruction> {
self.entry_point.as_ref()
}
/// Returns an iterator over all execution mode instructions that target this function.
#[inline]
pub fn iter_execution_mode(&self) -> impl ExactSizeIterator<Item = &Instruction> {
self.execution_modes.iter()
}
}
fn iter_instructions(
mut words: &[u32],
) -> impl Iterator<Item = Result<Instruction, ParseError>> + '_ {
let mut index = 0;
let next = move || -> Option<Result<Instruction, ParseError>> {
if words.is_empty() {
return None;
}
let word_count = (words[0] >> 16) as usize;
assert!(word_count >= 1);
if words.len() < word_count {
return Some(Err(ParseError {
instruction: index,
word: words.len(),
error: ParseErrors::UnexpectedEOF,
words: words.to_owned(),
}));
}
let mut reader = InstructionReader::new(&words[0..word_count], index);
let instruction = match Instruction::parse(&mut reader) {
Ok(x) => x,
Err(err) => return Some(Err(err)),
};
if !reader.is_empty() {
return Some(Err(reader.map_err(ParseErrors::LeftoverOperands)));
}
words = &words[word_count..];
index += 1;
Some(Ok(instruction))
};
std::iter::from_fn(next)
}
/// Helper type for parsing the words of an instruction.
#[derive(Debug)]
struct InstructionReader<'a> {
words: &'a [u32],
next_word: usize,
instruction: usize,
}
impl<'a> InstructionReader<'a> {
/// Constructs a new reader from a slice of words for a single instruction, including the opcode
/// word. `instruction` is the number of the instruction currently being read, and is used for
/// error reporting.
fn new(words: &'a [u32], instruction: usize) -> Self {
debug_assert!(!words.is_empty());
Self {
words,
next_word: 0,
instruction,
}
}
/// Returns whether the reader has reached the end of the current instruction.
fn is_empty(&self) -> bool {
self.next_word >= self.words.len()
}
/// Converts the `ParseErrors` enum to the `ParseError` struct, adding contextual information.
fn map_err(&self, error: ParseErrors) -> ParseError {
ParseError {
instruction: self.instruction,
word: self.next_word - 1, // -1 because the word has already been read
error,
words: self.words.to_owned(),
}
}
/// Returns the next word in the sequence.
fn next_word(&mut self) -> Result<u32, ParseError> {
let word = *self.words.get(self.next_word).ok_or(ParseError {
instruction: self.instruction,
word: self.next_word, // No -1 because we didn't advance yet
error: ParseErrors::MissingOperands,
words: self.words.to_owned(),
})?;
self.next_word += 1;
Ok(word)
}
/*
/// Returns the next two words as a single `u64`.
#[inline]
fn next_u64(&mut self) -> Result<u64, ParseError> {
Ok(self.next_word()? as u64 | (self.next_word()? as u64) << 32)
}
*/
/// Reads a nul-terminated string.
fn next_string(&mut self) -> Result<String, ParseError> {
let mut bytes = Vec::new();
loop {
let word = self.next_word()?.to_le_bytes();
if let Some(nul) = word.iter().position(|&b| b == 0) {
bytes.extend(&word[0..nul]);
break;
} else {
bytes.extend(word);
}
}
String::from_utf8(bytes).map_err(|err| self.map_err(ParseErrors::FromUtf8Error(err)))
}
/// Reads all remaining words.
fn remainder(&mut self) -> Vec<u32> {
let vec = self.words[self.next_word..].to_owned();
self.next_word = self.words.len();
vec
}
}
/// Error that can happen when reading a SPIR-V module.
#[derive(Clone, Debug)]
pub enum SpirvError {
DuplicateId { id: Id },
InvalidHeader,
ParseError(ParseError),
}
impl Display for SpirvError {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
match self {
Self::DuplicateId { id } => write!(f, "id {} is assigned more than once", id,),
Self::InvalidHeader => write!(f, "the SPIR-V module header is invalid"),
Self::ParseError(_) => write!(f, "parse error"),
}
}
}
impl Error for SpirvError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::ParseError(err) => Some(err),
_ => None,
}
}
}
impl From<ParseError> for SpirvError {
fn from(err: ParseError) -> Self {
Self::ParseError(err)
}
}
/// Error that can happen when parsing SPIR-V instructions into Rust data structures.
#[derive(Clone, Debug)]
pub struct ParseError {
/// The instruction number the error happened at, starting from 0.
pub instruction: usize,
/// The word from the start of the instruction that the error happened at, starting from 0.
pub word: usize,
/// The error.
pub error: ParseErrors,
/// The words of the instruction.
pub words: Vec<u32>,
}
impl Display for ParseError {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
write!(
f,
"at instruction {}, word {}: {}",
self.instruction, self.word, self.error,
)
}
}
impl Error for ParseError {}
/// Individual types of parse error that can happen.
#[derive(Clone, Debug)]
pub enum ParseErrors {
FromUtf8Error(FromUtf8Error),
LeftoverOperands,
MissingOperands,
UnexpectedEOF,
UnknownEnumerant(&'static str, u32),
UnknownOpcode(u16),
UnknownSpecConstantOpcode(u16),
}
impl Display for ParseErrors {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
match self {
Self::FromUtf8Error(_) => write!(f, "invalid UTF-8 in string literal"),
Self::LeftoverOperands => write!(f, "unparsed operands remaining"),
Self::MissingOperands => write!(
f,
"the instruction and its operands require more words than are present in the \
instruction",
),
Self::UnexpectedEOF => write!(f, "encountered unexpected end of file"),
Self::UnknownEnumerant(ty, enumerant) => {
write!(f, "invalid enumerant {} for enum {}", enumerant, ty)
}
Self::UnknownOpcode(opcode) => write!(f, "invalid instruction opcode {}", opcode),
Self::UnknownSpecConstantOpcode(opcode) => {
write!(f, "invalid spec constant instruction opcode {}", opcode)
}
}
}
}
/// Converts SPIR-V bytes to words. If necessary, the byte order is swapped from little-endian
/// to native-endian.
pub fn bytes_to_words(bytes: &[u8]) -> Result<Cow<'_, [u32]>, SpirvBytesNotMultipleOf4> {
// If the current target is little endian, and the slice already has the right size and
// alignment, then we can just transmute the slice with bytemuck.
#[cfg(target_endian = "little")]
if let Ok(words) = bytemuck::try_cast_slice(bytes) {
return Ok(Cow::Borrowed(words));
}
if bytes.len() % 4 != 0 {
return Err(SpirvBytesNotMultipleOf4);
}
// TODO: Use `slice::array_chunks` once it's stable.
let words: Vec<u32> = bytes
.chunks_exact(4)
.map(|chunk| u32::from_le_bytes(chunk.try_into().unwrap()))
.collect();
Ok(Cow::Owned(words))
}
#[derive(Clone, Copy, Debug, Default)]
pub struct SpirvBytesNotMultipleOf4;
impl Error for SpirvBytesNotMultipleOf4 {}
impl Display for SpirvBytesNotMultipleOf4 {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "the length of the provided slice is not a multiple of 4")
}
}