Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a "rune inspect" subcommand for inspecting runes #183

Merged
merged 4 commits into from
May 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions codegen/src/code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,9 +394,12 @@ fn preamble(
rune: &Rune,
build_info: Option<serde_json::Value>,
) -> Result<TokenStream, Error> {
let rune_graph = custom_section("rune_graph", "RUNE_GRAPH", rune)?;
let rune_graph =
custom_section(crate::GRAPH_CUSTOM_SECTION, "RUNE_GRAPH", rune)?;
let build_info = match build_info {
Some(v) => custom_section("rune_version", "RUNE_VERSION", &v)?,
Some(v) => {
custom_section(crate::VERSION_CUSTOM_SECTION, "RUNE_VERSION", &v)?
},
None => quote!(),
};

Expand Down
3 changes: 3 additions & 0 deletions codegen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ pub use crate::{
project::Project,
};

pub const GRAPH_CUSTOM_SECTION: &str = ".rune_graph";
pub const VERSION_CUSTOM_SECTION: &str = ".rune_version";

use std::path::{PathBuf};
use anyhow::{Context, Error};
use rune_syntax::hir::Rune;
Expand Down
2 changes: 2 additions & 0 deletions rune/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ rand = "0.8.3"
build-info = { version = "0.0.23", features = ["serde"] }
serde = { version = "1.0.125", features = ["derive"] }
tflite = "0.9.5"
strum = { version = "0.20.0", features = ["derive"] }
wasmparser = "0.78.2"

[dev-dependencies]
assert_cmd = "1.0.3"
Expand Down
253 changes: 253 additions & 0 deletions rune/src/inspect.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,253 @@
use std::{
collections::{BTreeMap, HashMap},
path::PathBuf,
};
use anyhow::{Context, Error};
use build_info::BuildInfo;
use rune_syntax::{
hir::{HirId, Rune, SourceKind},
yaml::{Type, Value},
};
use serde::{Serialize, Serializer};
use strum::VariantNames;
use wasmparser::{Parser, Payload};
use crate::Format;

#[derive(Debug, Clone, PartialEq, structopt::StructOpt)]
pub struct Inspect {
#[structopt(
short,
long,
help = "The format to use when printing output",
default_value = "text",
possible_values = Format::VARIANTS,
parse(try_from_str)
)]
format: Format,
#[structopt(help = "The Rune to inspect", parse(from_os_str))]
rune: PathBuf,
}

impl Inspect {
pub fn execute(self) -> Result<(), Error> {
let wasm = std::fs::read(&self.rune).with_context(|| {
format!("Unable to read \"{}\"", self.rune.display())
})?;
let meta = Metadata::from_custom_sections(wasm_custom_sections(&wasm));

match self.format {
Format::Json => {
let s = serde_json::to_string_pretty(&meta)
.context("Unable to format the metadata as JSON")?;
println!("{}", s);
},
Format::Text => print_meta(&meta),
}

Ok(())
}
}

fn print_meta(meta: &Metadata) {
if let Some(build_info) = &meta.rune_cli_build_info {
let git = build_info
.version_control
.as_ref()
.expect("The project uses version control")
.git()
.expect("The project uses git");

println!(
"Compiled by: {} v{} ({} {})",
build_info.crate_info.name,
build_info.crate_info.version,
git.commit_short_id,
git.commit_timestamp.date().naive_utc(),
);
}

if let Some(SimplifiedRune { capabilities }) = &meta.rune {
if !capabilities.is_empty() {
print_capabilities(&capabilities);
}
}
}

fn print_capabilities(capabilities: &BTreeMap<String, SimplifiedCapability>) {
println!("Capabilities:");

for (name, value) in capabilities {
let SimplifiedCapability {
capability_type,
outputs,
parameters,
} = value;
println!(" {} ({})", name, capability_type);

if !outputs.is_empty() {
println!(" Outputs:");
for output in outputs {
println!(" - {}{:?}", output.name, output.dimensions);
}
}

if !parameters.is_empty() {
println!(" Parameters:");
for (key, value) in parameters {
println!(" - {}: {:?}", key, value);
}
}
}
}

#[derive(Debug, Clone, serde::Serialize)]
struct Metadata {
rune_cli_build_info: Option<BuildInfo>,
rune: Option<SimplifiedRune>,
}

impl Metadata {
fn from_custom_sections<'a>(
sections: impl Iterator<Item = CustomSection<'a>>,
) -> Self {
let mut rune_cli_build_info = None;
let mut graph = None;

for section in sections {
match section.name {
rune_codegen::GRAPH_CUSTOM_SECTION => {
match serde_json::from_slice(section.data) {
Ok(rune) => {
graph = Some(SimplifiedRune::from_rune(rune));
},
Err(e) => {
log::warn!(
"Unable to deserialize the Rune graph: {}",
e
);
},
}
},
rune_codegen::VERSION_CUSTOM_SECTION => {
match serde_json::from_slice(section.data) {
Ok(v) => {
rune_cli_build_info = Some(v);
},
Err(e) => {
log::warn!(
"Unable to deserialize the version: {}",
e
);
},
}
},
_ => {},
}
}

Metadata {
rune_cli_build_info,
rune: graph,
}
}
}

#[derive(Debug, Clone, serde::Serialize)]
struct SimplifiedRune {
capabilities: BTreeMap<String, SimplifiedCapability>,
}

impl SimplifiedRune {
fn from_rune(rune: Rune) -> Self {
let mut capabilities = BTreeMap::new();

for (&id, node) in &rune.stages {
let name = rune.names[id].to_string();
let outputs = node
.output_slots
.iter()
.map(|slot| rune.slots[slot].element_type)
.map(|type_id| resolve_type(&rune, type_id))
.collect();

match &node.stage {
rune_syntax::hir::Stage::Source(rune_syntax::hir::Source {
kind,
parameters,
}) => {
let kind = kind.clone();
let parameters = parameters.clone();
capabilities.insert(
name,
SimplifiedCapability {
capability_type: kind,
parameters,
outputs,
},
);
},
rune_syntax::hir::Stage::Sink(_) => {},
rune_syntax::hir::Stage::Model(_) => {},
rune_syntax::hir::Stage::ProcBlock(_) => {},
}
}

SimplifiedRune { capabilities }
}
}

fn resolve_type(rune: &Rune, type_id: HirId) -> Type {
let (primitive, dims) = match &rune.types[&type_id] {
rune_syntax::hir::Type::Primitive(p) => (p, vec![1]),
rune_syntax::hir::Type::Buffer {
underlying_type,
dimensions,
} => match &rune.types[underlying_type] {
rune_syntax::hir::Type::Primitive(p) => (p, dimensions.clone()),
_ => unreachable!(),
},
rune_syntax::hir::Type::Unknown | rune_syntax::hir::Type::Any => {
unreachable!("All types should have been resolved")
},
};

Type {
name: primitive.rust_name().to_string(),
dimensions: dims,
}
}

#[derive(Debug, Clone, serde::Serialize)]
struct SimplifiedCapability {
#[serde(serialize_with = "serialize_source_kind")]
capability_type: SourceKind,
outputs: Vec<Type>,
parameters: HashMap<String, Value>,
}

fn serialize_source_kind<S: Serializer>(
kind: &SourceKind,
ser: S,
) -> Result<S::Ok, S::Error> {
kind.to_string().serialize(ser)
}

fn wasm_custom_sections(
wasm: &[u8],
) -> impl Iterator<Item = CustomSection<'_>> + '_ {
Parser::default()
.parse_all(wasm)
.filter_map(Result::ok)
.filter_map(|payload| match payload {
Payload::CustomSection { name, data, .. } => {
Some(CustomSection { name, data })
},
_ => None,
})
}

#[derive(Debug, Copy, Clone, PartialEq)]
struct CustomSection<'a> {
name: &'a str,
data: &'a [u8],
}
Loading