feat(ir): replace Rpl with GraphIr

Semi-broken as atm the CLI just does nothing except printing the parsed
IR, instead of actually executing it.
This commit is contained in:
multisn8 2024-01-12 17:23:17 +01:00
parent ccbccfb11b
commit fcf7e909ee
Signed by untrusted user: multisamplednight
GPG key ID: 6D525AA147CBDAE2
14 changed files with 198 additions and 143 deletions

View file

@ -8,7 +8,7 @@ edition = "2021"
[dependencies]
clap = { workspace = true, features = [ "derive" ] }
image = "0.24"
rpl = { path = "../rpl" }
ir = { path = "../ir" }
[lints]
workspace = true

View file

@ -1,6 +1,6 @@
pub mod read {
use image::{io::Reader as ImageReader, DynamicImage};
use rpl::instructions::read::{Read, SourceType};
use ir::instruction::read::{Read, SourceType};
pub fn read(Read { source, .. }: Read) -> DynamicImage {
// TODO: actual error handling
@ -15,7 +15,7 @@ pub mod read {
pub mod write {
use image::{DynamicImage, ImageFormat};
use rpl::instructions::write::{TargetFormat, TargetType, Write};
use ir::instruction::write::{TargetFormat, TargetType, Write};
pub fn write(Write { target, format }: Write, input_data: &DynamicImage) {
input_data

View file

@ -1,4 +1,4 @@
use rpl::instructions::{Filter, Instruction};
use ir::instruction::{Filter, Kind};
use crate::value::Dynamic;
mod instructions;
@ -6,12 +6,12 @@ mod instructions;
pub struct Executor;
impl crate::Executor for Executor {
fn execute(instruction: Instruction, input: Option<Dynamic>) -> Option<Dynamic> {
fn execute(instruction: Kind, input: Option<Dynamic>) -> Option<Dynamic> {
match instruction {
Instruction::Read(read_instruction) => {
Kind::Read(read_instruction) => {
Some(Dynamic::Image(instructions::read::read(read_instruction)))
}
Instruction::Write(write_instruction) => {
Kind::Write(write_instruction) => {
instructions::write::write(
write_instruction,
match input {
@ -21,10 +21,10 @@ impl crate::Executor for Executor {
);
None
}
Instruction::Math(_) => todo!(),
Instruction::Blend(_) => todo!(),
Instruction::Noise(_) => todo!(),
Instruction::Filter(filter_instruction) => match filter_instruction {
Kind::Math(_) => todo!(),
Kind::Blend(_) => todo!(),
Kind::Noise(_) => todo!(),
Kind::Filter(filter_instruction) => match filter_instruction {
Filter::Invert => Some(Dynamic::Image(instructions::filters::invert::invert(
match input {
Some(Dynamic::Image(img)) => img,

View file

@ -1,4 +1,4 @@
use rpl::instructions::Instruction;
use ir::instruction::Kind;
use value::Dynamic;
mod debug;
@ -17,10 +17,10 @@ pub enum Executors {
}
trait Executor {
fn execute(instruction: Instruction, input: Option<Dynamic>) -> Option<Dynamic>;
fn execute(instruction: Kind, input: Option<Dynamic>) -> Option<Dynamic>;
}
pub fn execute_all(instructions: Vec<Instruction>) {
pub fn execute_all(instructions: Vec<Kind>) {
let mut tmp = None;
for instruction in instructions {

View file

@ -1,13 +1,14 @@
[package]
name = "rpl"
name = "ir"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serde = { workspace = true, features = [ "derive" ] }
ahash = { version = "0.8.7", features = ["serde"] }
ron = "0.8"
serde = { version = "1.0.193", features = ["derive"] }
[lints]
workspace = true

View file

@ -3,8 +3,8 @@ use serde::{Deserialize, Serialize};
pub mod read;
pub mod write;
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
pub enum Instruction {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Kind {
Read(read::Read),
Write(write::Write),
Math(Math),
@ -13,7 +13,7 @@ pub enum Instruction {
Filter(Filter),
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Math {
Add,
Subtract,
@ -21,7 +21,7 @@ pub enum Math {
Divide,
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Blend {
Normal,
Multiply,
@ -34,14 +34,14 @@ pub enum Blend {
Lighten,
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Noise {
Perlin,
Simplex,
Voronoi,
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Filter {
Invert,
}

View file

@ -1,18 +1,18 @@
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Read {
pub source: SourceType,
pub format: SourceFormat,
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SourceType {
File(PathBuf),
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SourceFormat {
Jpeg,
Png,

View file

@ -1,18 +1,18 @@
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Write {
pub target: TargetType,
pub format: TargetFormat,
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum TargetType {
File(PathBuf),
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum TargetFormat {
Jpeg,
Png,

108
crates/ir/src/lib.rs Normal file
View file

@ -0,0 +1,108 @@
use std::ops::RangeInclusive;
use serde::{Deserialize, Serialize};
pub mod instruction;
pub type Map<K, V> = ahash::AHashMap<K, V>;
pub type Set<V> = ahash::AHashSet<V>;
/// # Errors
///
/// Returns an error if the parsed source is not a valid graph IR.
pub fn from_ron(source: &str) -> ron::error::SpannedResult<GraphIr> {
ron::from_str(source)
}
/// The toplevel representation of a whole pipeline.
///
/// Pipelines may not be fully linear. They may branch out and recombine later on.
/// As such, the representation for them which is currently used is a
/// [**D**irected **A**cyclic **G**raph](https://en.wikipedia.org/wiki/Directed_acyclic_graph)
/// .
///
/// For those who are already familiar with graphs, a DAG is one, except that:
///
/// - It is **directed**: Edges have a direction they point to.
/// In this case, edges point from the outputs of streamers to inputs of consumers.
/// - It is **acyclic**: Those directed edges may not form loops.
/// In other words, if one follows edges only in their direction, it must be impossible
/// to come back to an already visited node.
///
/// Here, if an edge points from _A_ to _B_ (`A --> B`),
/// then _A_ is called a **dependency** of _B_,
/// and _B_ is called a **dependent** of _A_.
///
/// The DAG also enables another neat operation:
/// [Topological sorting](https://en.wikipedia.org/wiki/Topological_sorting).
/// This allows to put the entire graph into a linear list,
/// where it's guaranteed that once a vertex is visited,
/// all dependencies of it will have been visited already as well.
///
/// The representation used here in specific is a bit more complicated,
/// since **instructions** directly aren't just connected to one another,
/// but their **sockets** are instead.
///
/// So the vertices of the DAG are the **sockets**
/// (which are either [`id::Input`] or [`id::Output`] depending on the direction),
/// and each **socket** in turn belongs to an **instruction**.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct GraphIr {
/// "Backbone" storage of all **instruction** IDs to
/// what **kind of instruction** they are.
instructions: Map<id::Instruction, instruction::Kind>,
/// How the data flows forward. **Dependencies** map to **dependents** here.
edges: Map<id::Output, Set<id::Input>>,
/// How the data flows backward. **Dependents** map to **dependencies** here.
rev_edges: Map<id::Input, Set<id::Output>>,
}
pub mod id {
use serde::{Deserialize, Serialize};
use crate::Span;
/// One specific instruction, and where it is found in code.
///
/// It does **not** contain what kind of instruction this is.
/// Refer to [`crate::instruction::Kind`] for this instead.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct Instruction(Span);
impl Instruction {
/// Where this instruction is written down.
pub fn span(&self) -> &Span {
&self.0
}
}
/// On an **instruction**, accepts incoming data.
///
/// An **instruction** cannot run if any of these are not connected.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct Input(Socket);
/// On an **instruction**, returns outgoing data to be fed to [`Input`]s.
///
/// In contrast to [`Input`]s, [`Output`]s may be used or unused.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct Output(Socket);
/// An unspecified socket on a specific **instruction**,
/// and where it is on that **instruction**.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct Socket {
pub belongs_to: Instruction,
pub index: SocketIdx,
}
/// Where a [`Socket`] is on an **instruction**.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct SocketIdx(pub u16);
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct Span {
range: RangeInclusive<usize>,
}

View file

@ -1,51 +0,0 @@
use instructions::Instruction;
use serde::{Deserialize, Serialize};
pub mod instructions;
/// # Panics
///
/// Panics if deserialization fails. lol.
#[must_use]
pub fn from_ron(raw: &str) -> Rpl {
ron::from_str(raw).expect("come back later and handle me correctly")
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
pub struct Rpl(pub Vec<Instruction>);
#[cfg(test)]
mod tests {
use super::*;
use crate::instructions::{
read::{SourceFormat, SourceType},
write::{TargetFormat, TargetType},
Math,
};
#[test]
fn test_simple_deserialize() {
const TEST_DATA: &str = concat!(
"([",
"Read( (source: File(\"~/example/file.png\"), format: Png) ),",
"Math(Add),",
"Write(( target: File(\"~/example/out.jpg\"), format: Jpeg)),",
"])",
);
assert_eq!(
from_ron(TEST_DATA),
Rpl(vec![
Instruction::Read(instructions::read::Read {
source: SourceType::File("~/example/file.png".into()),
format: SourceFormat::Png
}),
Instruction::Math(Math::Add),
Instruction::Write(instructions::write::Write {
target: TargetType::File("~/example/out.jpg".into()),
format: TargetFormat::Jpeg
})
])
);
}
}