Skip to main content

Program

Struct Program 

Source
pub struct Program {
    pub fugue_program: u32,
    pub body: Vec<Stmt>,
    pub ret: Expr,
}
Expand description

A program: statements and a return expression, plus the format version.

A Program is plain data. Build one with Program::parse (the text syntax), Program::from_json, or directly from the AST types; then compile it against a Registry and Data to get a CompiledProgram that builds real Models.

Display prints the canonical text form, which Program::parse reads back to an equal program.

use fugue::program::Program;

let text = Program::parse(
    r#"let p <- sample(addr!("p"), Beta(2.0, 2.0));
       observe(addr!("y"), Bernoulli(p), true);
       pure(p)"#,
)
.unwrap();
let json = Program::from_json(&text.to_json().unwrap()).unwrap();
assert_eq!(text, json);
assert_eq!(Program::parse(&text.to_string()).unwrap(), text);

Fields§

§fugue_program: u32

Format version; FORMAT_VERSION for programs this build writes.

§body: Vec<Stmt>

The statements, in order.

§ret: Expr

The expression pure(..) returns.

Implementations§

Source§

impl Program

Source

pub fn new(body: Vec<Stmt>, ret: Expr) -> Program

A program at the current FORMAT_VERSION.

Source

pub fn from_json(json: &str) -> Result<Program, ProgramError>

Read a program from its JSON form.

The fugue_program version is checked before the rest of the document is decoded, so a program written by a newer format fails with ProgramError::UnsupportedVersion rather than with whatever node its newer syntax trips over first. Unknown fields are rejected, so a misspelt key is an error, not a silently different program.

use fugue::program::{Program, ProgramError};

let p = Program::from_json(
    r#"{"fugue_program": 1, "body": [], "ret": {"op": "f64", "value": 1.5}}"#,
)
.unwrap();
assert_eq!(p, Program::parse("pure(1.5)").unwrap());

let newer = r#"{"fugue_program": 2, "body": [], "ret": {"op": "f64", "value": 1.5}}"#;
assert!(matches!(
    Program::from_json(newer),
    Err(ProgramError::UnsupportedVersion { found: 2, supported: 1 })
));
Source

pub fn to_json(&self) -> Result<String, ProgramError>

The program’s JSON form (compact). Fails for a program that would not read back: a non-current version, a non-finite literal, a name that is not an identifier, or nesting beyond MAX_NESTING.

Source

pub fn to_json_pretty(&self) -> Result<String, ProgramError>

The program’s JSON form, pretty-printed. Same checks as to_json.

Source§

impl Program

Source

pub fn parse(src: &str) -> Result<Program, ProgramError>

Parse the text syntax (the grammar is in the module docs).

Parsing needs no registry: names are resolved by compile, so an unknown distribution is a compile error, not a syntax error.

use fugue::program::{Program, ProgramError};

let p = Program::parse(
    r#"let mu <- sample(addr!("mu"), Normal::new(0.0, 1.0).unwrap());
       observe(addr!("y"), Normal(mu, 1.0), 0.5);
       pure(mu)"#,
)
.unwrap();
assert_eq!(p.body.len(), 2);

match Program::parse("let x = 1.0;\nlet y = ;\npure(x)") {
    Err(ProgramError::Syntax { line, .. }) => assert_eq!(line, 2),
    other => panic!("{other:?}"),
}
Source

pub fn compile( &self, registry: &Registry, data: &Data, ) -> Result<CompiledProgram, ProgramError>

Check the program against a registry and data, resolving every name, and prepare it for building models.

Everything that can be known before running is checked here: unknown variables (including assignment to one), unknown distributions and functions, argument counts, break outside a loop, and the structural checks of to_json. The data’s names are bound as variables in an outer scope (a program’s own let may shadow them).

use fugue::program::{Data, Program, Registry};

let program = Program::parse("pure(y.len())").unwrap();
let registry = Registry::new();
assert!(program.compile(&registry, &Data::new()).is_err()); // unknown `y`
let compiled = program
    .compile(&registry, &Data::new().with("y", vec![1.0, 2.0]))
    .unwrap();

Trait Implementations§

Source§

impl Clone for Program

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Program

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Program

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Program

The canonical text form; Program::parse reads it back to an equal program (for any program to_json accepts).

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl FromStr for Program

Source§

fn from_str(s: &str) -> Result<Program, ProgramError>

Same as Program::parse.

Source§

type Err = ProgramError

The associated error which can be returned from parsing.
Source§

impl PartialEq for Program

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for Program

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Program

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V