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
//! This crate has procedural macros for compiling shader source into SPIR-V
//! bytes at compile time.
//!
//! # Nightly Only
//!
//! Requires the use of the `proc_macro_hygiene` feature because [unfortunately
//! 1.30 was a lie](https://github.com/rust-lang/blog.rust-lang.org/issues/285).

// Note(Lokathor): this extern crate is necessary even in 2018 for whatever
// reason that I'm sure is stupid.
extern crate proc_macro;

use core::str::FromStr;
use proc_macro::TokenStream;
use shaderc::ShaderKind;
use std::{
  fs::File,
  io::{prelude::*, BufReader},
};
use syn::{
  parse::{Parse, ParseStream, Result},
  parse_macro_input, Error, Ident, LitStr, Token,
};

struct SPIRVFromFile {
  kind: ShaderKind,
  filename: LitStr,
  entry_point: LitStr,
}

impl Parse for SPIRVFromFile {
  fn parse(input: ParseStream) -> Result<Self> {
    let kind_ident = input.parse::<Ident>()?;
    let kind_string = kind_ident.to_string();
    let kind = match kind_string.as_ref() {
      "Vertex" => ShaderKind::Vertex,
      "Fragment" => ShaderKind::Fragment,
      "Compute" => ShaderKind::Compute,
      "Geometry" => ShaderKind::Geometry,
      "TessControl" => ShaderKind::TessControl,
      "TessEvaluation" => ShaderKind::TessEvaluation,
      "InferFromSource" => ShaderKind::InferFromSource,
      "DefaultVertex" => ShaderKind::DefaultVertex,
      "DefaultFragment" => ShaderKind::DefaultFragment,
      "DefaultCompute" => ShaderKind::DefaultCompute,
      "DefaultGeometry" => ShaderKind::DefaultGeometry,
      "DefaultTessControl" => ShaderKind::DefaultTessControl,
      "DefaultTessEvaluation" => ShaderKind::DefaultTessEvaluation,
      "SpirvAssembly" => ShaderKind::SpirvAssembly,
      _ => {
        return Err(Error::new(
          kind_ident.span(),
          format!("Unknown ShaderKind value: {:?}", kind_string),
        ));
      }
    };
    let _ = input.parse::<Token![,]>()?;
    let filename = input.parse::<LitStr>()?;
    let _ = input.parse::<Token![,]>()?;
    let entry_point = input.parse::<LitStr>()?;
    Ok(SPIRVFromFile {
      kind,
      filename,
      entry_point,
    })
  }
}

/// `spirv_from_file!(ShaderKind, "file_path", "entry_point")`
///
/// * [ShaderKind](shaderc::ShaderKind) is just the final variant bit of the
///   enum from the `shaderc` crate. So use `Fragment`, not
///   `ShaderKind::Fragment` or anything else. Technically this just parses an
///   Ident, so you actually don't even need the `ShaderKind` type to be in
///   scope at all, you just write the name of one of those variants.
/// * String literal containing the path to the shader source. This is passed
///   directly to [File::open](std::fs::File::open). The "present working
///   directory" for proc macros is the crate root, so relative paths should
///   start from there.
/// * String literal for the name of the entry point of the shader module. By
///   convention this is is usually "main", but do what you want.
///
/// Success produces a `&[u8]` TokenStream. You probably want to assign this
/// into a `const` somewhere in your program.
///
/// Like this:
///
/// ```
/// #![feature(proc_macro_hygiene)]
///
/// use proc_spirv::spirv_from_file;
///
/// const FRAG_SPIRV: &[u8] = spirv_from_file!(Fragment, "tests/frag_glsl.frag", "main");
/// ```
#[proc_macro]
pub fn spirv_from_file(input: TokenStream) -> TokenStream {
  let SPIRVFromFile {
    kind,
    filename,
    entry_point,
  } = parse_macro_input!(input as SPIRVFromFile);

  let filename_string = filename.value();
  let file_handle = File::open(&filename_string)
    .unwrap_or_else(|e| panic!("Failed to open the file specified: {:?}", e));
  let mut buf_reader = BufReader::new(file_handle);
  let mut file_contents = String::new();
  buf_reader
    .read_to_string(&mut file_contents)
    .unwrap_or_else(|e| panic!("Failed to read the file contents: {:?}", e));

  let entry_point_string = entry_point.value();

  let mut compiler = shaderc::Compiler::new().expect("Could not initialize the shaderc compiler!");
  //
  let source_text: &str = &file_contents;
  let shader_kind: ShaderKind = kind;
  let input_file_name: &str = &filename_string;
  let entry_point_name: &str = &entry_point_string;
  let additional_options: Option<&shaderc::CompileOptions> = None;
  //
  let compile_result = compiler.compile_into_spirv(
    source_text,
    shader_kind,
    input_file_name,
    entry_point_name,
    additional_options,
  );

  let artifact = compile_result.unwrap_or_else(|e| panic!("SPIR-V compilation error: {}", e));

  let out_string = format!("&{:?}", artifact.as_binary_u8());

  TokenStream::from_str(&out_string).unwrap_or_else(|e| panic!("SPIR-V compilation error: {:?}", e))
}