├── .envrc ├── .gitignore ├── src ├── lib.rs ├── natural.rs ├── parser.rs └── ast.rs ├── tests ├── parser.rs └── parser │ ├── sexprs.rs │ ├── naturals.rs │ ├── symbols.rs │ ├── unresolved_references.rs │ ├── labels.rs │ └── resolved_references.rs ├── Cargo.toml ├── .gitconfig ├── nix └── packages │ └── ari.nix ├── flake.nix ├── flake.lock ├── Cargo.lock ├── ari.svg ├── README.md └── COPYING /.envrc: -------------------------------------------------------------------------------- 1 | use flake 2 | 3 | source_env_if_exists .envrc.local 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.envrc.local 2 | /flake.lock 3 | /result 4 | /target 5 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(coverage_nightly, feature(coverage_attribute))] 2 | #[rustfmt::skip] pub mod ast; 3 | #[rustfmt::skip] pub mod natural; 4 | #[rustfmt::skip] pub mod parser; 5 | -------------------------------------------------------------------------------- /tests/parser.rs: -------------------------------------------------------------------------------- 1 | mod parser { 2 | #[rustfmt::skip] mod labels; 3 | #[rustfmt::skip] mod naturals; 4 | #[rustfmt::skip] mod resolved_references; 5 | #[rustfmt::skip] mod sexprs; 6 | #[rustfmt::skip] mod symbols; 7 | #[rustfmt::skip] mod unresolved_references; 8 | } 9 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ari" 3 | description = "A type-centred purely functional programming language designed to type binary files" 4 | version = "0.1.0" 5 | edition = "2021" 6 | license = "GPL-3.0-or-later" 7 | 8 | [dependencies] 9 | chumsky = "0.9.3" 10 | num-bigint = "0.4.4" 11 | num-traits = "0.2.17" 12 | 13 | [dev-dependencies] 14 | pretty_assertions = "1.4.0" 15 | -------------------------------------------------------------------------------- /.gitconfig: -------------------------------------------------------------------------------- 1 | # git config include.path ../.gitconfig 2 | [remote "gitlab"] 3 | url = https://gitlab.com/ari-lang/ari.git 4 | fetch = +refs/heads/*:refs/remotes/gitlab/* 5 | fetch = +refs/merge-requests/*/head:refs/pullreqs/* 6 | [remote "github"] 7 | url = https://github.com/ari-language/ari.git 8 | fetch = +refs/heads/*:refs/remotes/github/* 9 | [remote "all"] 10 | url = https://gitlab.com/ari-lang/ari.git 11 | fetch = +refs/heads/*:refs/remotes/all/* 12 | pushurl = git@gitlab.com:ari-lang/ari.git 13 | pushurl = git@github.com:ari-language/ari.git 14 | [remote] 15 | pushDefault = all 16 | -------------------------------------------------------------------------------- /nix/packages/ari.nix: -------------------------------------------------------------------------------- 1 | { lib 2 | , craneLib 3 | , craneLibLLvmTools 4 | , cargo-nextest 5 | }: 6 | 7 | let 8 | src = craneLib.cleanCargoSource (craneLib.path ../..); 9 | cargoArtifacts = craneLib.buildDepsOnly { 10 | inherit src; 11 | }; 12 | in 13 | craneLib.buildPackage { 14 | pname = "ari"; 15 | version = "0.1"; 16 | inherit src cargoArtifacts; 17 | 18 | doCheck = false; 19 | 20 | passthru = { 21 | clippy = craneLib.cargoClippy { 22 | inherit src cargoArtifacts; 23 | cargoClippyExtraArgs = "--all-targets -- --deny warnings"; 24 | }; 25 | 26 | coverage = craneLibLLvmTools.cargoLlvmCov { 27 | inherit src cargoArtifacts; 28 | nativeBuildInputs = [ cargo-nextest ]; 29 | cargoLLvmCovCommand = "nextest"; 30 | cargoLlvmCovExtraArgs = "--ignore-filename-regex /nix/store --show-missing-lines --lcov --output-path $out"; 31 | }; 32 | }; 33 | 34 | meta = with lib; { 35 | description = "A type-centred purely functional programming language designed to type binary files"; 36 | homepage = "https://gitlab.com/ari-lang/ari"; 37 | license = licenses.gpl3Plus; 38 | maintainers = with maintainers; [ kira-bruneau ]; 39 | }; 40 | } 41 | -------------------------------------------------------------------------------- /tests/parser/sexprs.rs: -------------------------------------------------------------------------------- 1 | use pretty_assertions::assert_eq; 2 | 3 | use ari::{ 4 | ast::{Expr, Label, Scope}, 5 | parser::{parser, Error, ErrorLabel}, 6 | }; 7 | 8 | use chumsky::Parser; 9 | 10 | #[test] 11 | fn sexpr() { 12 | assert_eq!( 13 | parser().parse_recovery("(* :r 256 :g 256 :b 256)"), 14 | ( 15 | Some( 16 | Scope::try_from_exprs([Expr::sexpr( 17 | [], 18 | 0..24, 19 | Scope::try_from_exprs([ 20 | Expr::unresolved_symbol([], 1..2, "*"), 21 | Expr::natural([Label::new(3..5, "r")], 6..9, 256u16), 22 | Expr::natural([Label::new(10..12, "g")], 13..16, 256u16), 23 | Expr::natural([Label::new(17..19, "b")], 20..23, 256u16), 24 | ]) 25 | .unwrap(), 26 | )]) 27 | .unwrap() 28 | ), 29 | vec![], 30 | ) 31 | ); 32 | } 33 | 34 | #[test] 35 | fn empty() { 36 | assert_eq!( 37 | parser().parse_recovery("()"), 38 | ( 39 | Some( 40 | Scope::try_from_exprs([Expr::sexpr([], 0..2, Scope::try_from_exprs([]).unwrap())]) 41 | .unwrap() 42 | ), 43 | vec![] 44 | ) 45 | ); 46 | } 47 | 48 | #[test] 49 | fn empty_with_padding() { 50 | assert_eq!( 51 | parser().parse_recovery("( )"), 52 | ( 53 | Some( 54 | Scope::try_from_exprs([Expr::sexpr([], 0..3, Scope::try_from_exprs([]).unwrap())]) 55 | .unwrap() 56 | ), 57 | vec![] 58 | ) 59 | ); 60 | } 61 | 62 | #[test] 63 | fn cant_have_left_paren() { 64 | assert_eq!( 65 | parser().parse_recovery("("), 66 | ( 67 | Some( 68 | Scope::try_from_exprs([Expr::sexpr([], 0..1, Scope::try_from_exprs([]).unwrap())]) 69 | .unwrap() 70 | ), 71 | vec![Error::unexpected_end(1) 72 | .with_label(ErrorLabel::SExpr) 73 | .with_label(ErrorLabel::Reference)], 74 | ) 75 | ); 76 | } 77 | 78 | #[test] 79 | fn cant_have_right_paren() { 80 | assert_eq!( 81 | parser().parse_recovery(")"), 82 | ( 83 | Some(Scope::try_from_exprs([]).unwrap()), 84 | vec![Error::trailing_garbage(0..1)], 85 | ) 86 | ); 87 | } 88 | -------------------------------------------------------------------------------- /tests/parser/naturals.rs: -------------------------------------------------------------------------------- 1 | use pretty_assertions::assert_eq; 2 | 3 | use std::str::FromStr; 4 | 5 | use ari::{ 6 | ast::{Expr, Scope}, 7 | parser::{parser, Error}, 8 | }; 9 | 10 | use chumsky::Parser; 11 | use num_bigint::BigUint; 12 | 13 | #[test] 14 | fn bottom() { 15 | assert_eq!( 16 | parser().parse_recovery("0"), 17 | ( 18 | Some(Scope::try_from_exprs([Expr::natural([], 0..1, 0u8)]).unwrap()), 19 | vec![] 20 | ) 21 | ); 22 | } 23 | 24 | #[test] 25 | fn unit() { 26 | assert_eq!( 27 | parser().parse_recovery("1"), 28 | ( 29 | Some(Scope::try_from_exprs([Expr::natural([], 0..1, 1u8)]).unwrap()), 30 | vec![] 31 | ) 32 | ); 33 | } 34 | 35 | #[test] 36 | fn decimal() { 37 | assert_eq!( 38 | parser().parse_recovery("256"), 39 | ( 40 | Some(Scope::try_from_exprs([Expr::natural([], 0..3, 256u16)]).unwrap()), 41 | vec![], 42 | ) 43 | ); 44 | } 45 | 46 | #[test] 47 | fn binary() { 48 | assert_eq!( 49 | parser().parse_recovery("0b100000000"), 50 | ( 51 | Some(Scope::try_from_exprs([Expr::natural([], 0..11, 256u16)]).unwrap()), 52 | vec![], 53 | ) 54 | ); 55 | } 56 | 57 | #[test] 58 | fn octal() { 59 | assert_eq!( 60 | parser().parse_recovery("0o400"), 61 | ( 62 | Some(Scope::try_from_exprs([Expr::natural([], 0..5, 256u16)]).unwrap()), 63 | vec![], 64 | ) 65 | ); 66 | } 67 | 68 | #[test] 69 | fn hexidecimal() { 70 | assert_eq!( 71 | parser().parse_recovery("0x100"), 72 | ( 73 | Some(Scope::try_from_exprs([Expr::natural([], 0..5, 256u16)]).unwrap()), 74 | vec![], 75 | ) 76 | ); 77 | } 78 | 79 | #[test] 80 | fn supports_big_naturals_that_fit_in_memory() { 81 | assert_eq!( 82 | parser().parse_recovery( 83 | "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" 84 | ), ( 85 | Some(Scope::try_from_exprs([Expr::natural( 86 | [], 87 | 0..100, 88 | BigUint::from_str("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890") 89 | .unwrap() 90 | )]).unwrap()), 91 | vec![], 92 | ) 93 | ); 94 | } 95 | 96 | #[test] 97 | fn cant_have_zero_prefix() { 98 | // TODO: Give better error than just trailing garbage 99 | assert_eq!( 100 | parser().parse_recovery("0123456789"), 101 | ( 102 | Some(Scope::try_from_exprs([Expr::natural([], 0..1, 0u8)]).unwrap()), 103 | vec![Error::trailing_garbage(1..10)] 104 | ) 105 | ); 106 | } 107 | -------------------------------------------------------------------------------- /tests/parser/symbols.rs: -------------------------------------------------------------------------------- 1 | use pretty_assertions::assert_eq; 2 | 3 | use ari::{ 4 | ast::{Expr, Scope}, 5 | parser::{parser, Error, ErrorLabel}, 6 | }; 7 | 8 | use chumsky::Parser; 9 | 10 | #[test] 11 | fn symbol() { 12 | assert_eq!( 13 | parser().parse_recovery("symbol"), 14 | ( 15 | Some(Scope::try_from_exprs([Expr::unresolved_symbol([], 0..6, "symbol")]).unwrap()), 16 | vec![], 17 | ) 18 | ); 19 | } 20 | 21 | #[test] 22 | fn supports_builtin_fn_names() { 23 | #[rustfmt::skip] 24 | let builtin_fn_names = [ 25 | "=", 26 | "+", "-", 27 | "*", "/", 28 | "^", "log", "root", 29 | ".", 30 | "|", "~", 31 | "&", "!", 32 | "..", 33 | ]; 34 | 35 | let (left, right): (Vec<_>, Vec<_>) = builtin_fn_names 36 | .into_iter() 37 | .map(|symbol| { 38 | ( 39 | parser().parse_recovery(symbol), 40 | ( 41 | Some( 42 | Scope::try_from_exprs([Expr::unresolved_symbol( 43 | [], 44 | 0..symbol.len(), 45 | symbol, 46 | )]) 47 | .unwrap(), 48 | ), 49 | vec![], 50 | ), 51 | ) 52 | }) 53 | .unzip(); 54 | 55 | assert_eq!(left, right); 56 | } 57 | 58 | #[test] 59 | fn supports_almost_all_of_unicode_with_exceptions() { 60 | assert_eq!( 61 | parser().parse_recovery("🙃"), 62 | ( 63 | Some(Scope::try_from_exprs([Expr::unresolved_symbol([], 0..1, "🙃")]).unwrap()), 64 | vec![] 65 | ) 66 | ); 67 | } 68 | 69 | #[test] 70 | fn cant_have_whitespace() { 71 | assert_eq!( 72 | parser().parse_recovery("symbol "), 73 | ( 74 | Some(Scope::try_from_exprs([Expr::unresolved_symbol([], 0..6, "symbol")]).unwrap()), 75 | vec![], 76 | ) 77 | ); 78 | } 79 | 80 | #[test] 81 | fn cant_have_colon() { 82 | assert_eq!( 83 | parser().parse_recovery("symbol:"), 84 | ( 85 | Some(Scope::try_from_exprs([]).unwrap()), 86 | vec![Error::unexpected_end(7) 87 | .with_label(ErrorLabel::Symbol) 88 | .with_label(ErrorLabel::Label) 89 | .with_label(ErrorLabel::Path) 90 | .with_label(ErrorLabel::Reference)], 91 | ) 92 | ); 93 | } 94 | 95 | #[test] 96 | fn cant_have_left_paren() { 97 | assert_eq!( 98 | parser().parse_recovery("symbol("), 99 | ( 100 | Some(Scope::try_from_exprs([Expr::unresolved_symbol([], 0..6, "symbol")]).unwrap()), 101 | vec![Error::trailing_garbage(6..7)], 102 | ) 103 | ); 104 | } 105 | 106 | #[test] 107 | fn cant_have_right_paren() { 108 | assert_eq!( 109 | parser().parse_recovery("symbol)"), 110 | ( 111 | Some(Scope::try_from_exprs([Expr::unresolved_symbol([], 0..6, "symbol")]).unwrap()), 112 | vec![Error::trailing_garbage(6..7)], 113 | ), 114 | ); 115 | } 116 | -------------------------------------------------------------------------------- /flake.nix: -------------------------------------------------------------------------------- 1 | { 2 | description = "A type-centred purely functional programming language designed to type binary files"; 3 | 4 | inputs = { 5 | flake-utils.url = "github:numtide/flake-utils"; 6 | 7 | flake-linter = { 8 | url = "gitlab:kira-bruneau/flake-linter"; 9 | inputs = { 10 | flake-utils.follows = "flake-utils"; 11 | nixpkgs.follows = "nixpkgs"; 12 | }; 13 | }; 14 | 15 | nixpkgs.url = "nixpkgs/nixos-23.11"; 16 | 17 | crane = { 18 | url = "github:ipetkov/crane"; 19 | inputs = { 20 | nixpkgs.follows = "nixpkgs"; 21 | }; 22 | }; 23 | 24 | fenix = { 25 | url = "github:nix-community/fenix"; 26 | inputs = { 27 | nixpkgs.follows = "nixpkgs"; 28 | }; 29 | }; 30 | }; 31 | 32 | outputs = { self, flake-utils, flake-linter, nixpkgs, crane, fenix }: 33 | let 34 | lib = nixpkgs.lib; 35 | systems = [ "x86_64-linux" ]; 36 | in 37 | flake-utils.lib.eachSystem systems (system: 38 | let 39 | pkgs = import nixpkgs { 40 | overlays = [ 41 | fenix.overlays.default 42 | (final: prev: { 43 | craneLib = crane.lib.${system}; 44 | craneLibLLvmTools = crane.lib.${system}.overrideToolchain 45 | (fenix.packages.${system}.complete.withComponents [ 46 | "cargo" 47 | "llvm-tools" 48 | "rustc" 49 | ]); 50 | }) 51 | ]; 52 | 53 | inherit system; 54 | }; 55 | 56 | callPackage = pkgs.newScope pkgs; 57 | 58 | flake-linter-lib = flake-linter.lib.${system}; 59 | 60 | paths = flake-linter-lib.partitionToAttrs 61 | flake-linter-lib.commonPaths 62 | (flake-linter-lib.walkFlake ./.); 63 | 64 | linter = flake-linter-lib.makeFlakeLinter { 65 | root = ./.; 66 | 67 | settings = { 68 | markdownlint = { 69 | paths = paths.markdown; 70 | settings = { 71 | default = true; 72 | MD033 = { 73 | allowed_elements = [ "img" "table" "tr" "th" "td" ]; 74 | }; 75 | }; 76 | }; 77 | 78 | nixpkgs-fmt.paths = paths.nix; 79 | rustfmt.paths = paths.rust; 80 | }; 81 | 82 | inherit pkgs; 83 | }; 84 | in 85 | { 86 | packages = { 87 | ari = callPackage ./nix/packages/ari.nix { }; 88 | default = self.packages.${system}.ari; 89 | }; 90 | 91 | checks = { 92 | inherit (self.packages.${system}.default) 93 | clippy 94 | coverage; 95 | 96 | flake-linter = linter.check; 97 | } // self.packages.${system}; 98 | 99 | apps = { 100 | inherit (linter) fix; 101 | }; 102 | 103 | devShells.default = self.packages.${system}.default.overrideAttrs (attrs: { 104 | doCheck = true; 105 | checkInputs = with pkgs; [ 106 | self.packages.${system}.default.clippy.nativeBuildInputs 107 | self.packages.${system}.default.coverage.nativeBuildInputs 108 | linter.nativeBuildInputs 109 | nodePackages.markdown-link-check 110 | ]; 111 | }); 112 | } 113 | ); 114 | } 115 | -------------------------------------------------------------------------------- /src/natural.rs: -------------------------------------------------------------------------------- 1 | use num_bigint::BigUint; 2 | 3 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 4 | pub enum Natural { 5 | Unaligned(BigUint), 6 | ByteAligned(usize), 7 | } 8 | 9 | impl From for Natural { 10 | fn from(value: u8) -> Self { 11 | Natural::ByteAligned(match value { 12 | 0x1 => 0, 13 | value => return Natural::Unaligned(BigUint::from(value)), 14 | }) 15 | } 16 | } 17 | 18 | impl From for Natural { 19 | #[cfg_attr(coverage_nightly, coverage(off))] 20 | fn from(value: u16) -> Self { 21 | Natural::ByteAligned(match value { 22 | 0x1 => 0, 23 | 0x100 => 1, 24 | value => return Natural::Unaligned(BigUint::from(value)), 25 | }) 26 | } 27 | } 28 | 29 | impl From for Natural { 30 | #[cfg_attr(coverage_nightly, coverage(off))] 31 | fn from(value: u32) -> Self { 32 | Natural::ByteAligned(match value { 33 | 0x1 => 0, 34 | 0x100 => 1, 35 | 0x10000 => 2, 36 | 0x1000000 => 3, 37 | value => return Natural::Unaligned(BigUint::from(value)), 38 | }) 39 | } 40 | } 41 | 42 | impl From for Natural { 43 | #[cfg_attr(coverage_nightly, coverage(off))] 44 | fn from(value: u64) -> Self { 45 | Natural::ByteAligned(match value { 46 | 0x1 => 0, 47 | 0x100 => 1, 48 | 0x10000 => 2, 49 | 0x1000000 => 3, 50 | 0x100000000 => 4, 51 | 0x10000000000 => 5, 52 | 0x1000000000000 => 6, 53 | 0x100000000000000 => 7, 54 | value => return Natural::Unaligned(BigUint::from(value)), 55 | }) 56 | } 57 | } 58 | 59 | impl From for Natural { 60 | fn from(value: BigUint) -> Self { 61 | let mut digits = value.iter_u64_digits(); 62 | while let Some(msd) = digits.next_back() { 63 | let mut bytes = match msd { 64 | 0x0 => continue, 65 | 0x1 => 0, 66 | 0x100 => 1, 67 | 0x10000 => 2, 68 | 0x1000000 => 3, 69 | 0x100000000 => 4, 70 | 0x10000000000 => 5, 71 | 0x1000000000000 => 6, 72 | 0x100000000000000 => 7, 73 | _ => return Self::Unaligned(value), 74 | }; 75 | 76 | for lsd in digits.by_ref() { 77 | if lsd != 0 { 78 | return Self::Unaligned(value); 79 | } 80 | 81 | bytes += 8; 82 | } 83 | 84 | return Self::ByteAligned(bytes); 85 | } 86 | 87 | Self::Unaligned(value) 88 | } 89 | } 90 | 91 | #[cfg(test)] 92 | mod tests { 93 | use pretty_assertions::assert_eq; 94 | use std::str::FromStr; 95 | 96 | use super::*; 97 | 98 | #[test] 99 | pub fn zero() { 100 | assert_eq!( 101 | Natural::from(BigUint::from(0u8)), 102 | Natural::Unaligned(BigUint::default()) 103 | ); 104 | } 105 | 106 | #[test] 107 | pub fn one() { 108 | assert_eq!(Natural::from(BigUint::from(1u8)), Natural::ByteAligned(0)); 109 | } 110 | 111 | #[test] 112 | pub fn big_unaligned() { 113 | assert_eq!( 114 | Natural::from(BigUint::from_str("87112285931760246646623899502532662132735").unwrap()), 115 | Natural::Unaligned( 116 | BigUint::from_str("87112285931760246646623899502532662132735").unwrap() 117 | ) 118 | ); 119 | } 120 | 121 | #[test] 122 | pub fn big_byte_aligned() { 123 | assert_eq!( 124 | Natural::from(BigUint::from_str("87112285931760246646623899502532662132736").unwrap()), 125 | Natural::ByteAligned(17) 126 | ); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /flake.lock: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": { 3 | "crane": { 4 | "inputs": { 5 | "nixpkgs": [ 6 | "nixpkgs" 7 | ] 8 | }, 9 | "locked": { 10 | "lastModified": 1703439018, 11 | "narHash": "sha256-VT+06ft/x3eMZ1MJxWzQP3zXFGcrxGo5VR2rB7t88hs=", 12 | "owner": "ipetkov", 13 | "repo": "crane", 14 | "rev": "afdcd41180e3dfe4dac46b5ee396e3b12ccc967a", 15 | "type": "github" 16 | }, 17 | "original": { 18 | "owner": "ipetkov", 19 | "repo": "crane", 20 | "type": "github" 21 | } 22 | }, 23 | "fenix": { 24 | "inputs": { 25 | "nixpkgs": [ 26 | "nixpkgs" 27 | ], 28 | "rust-analyzer-src": "rust-analyzer-src" 29 | }, 30 | "locked": { 31 | "lastModified": 1703744556, 32 | "narHash": "sha256-9bugwfUHJRcjn6ptbzKvXBjqjJsJ0k7xd1AvrsuwDko=", 33 | "owner": "nix-community", 34 | "repo": "fenix", 35 | "rev": "223f5a9fee7b19f33bce7c283027f03525e0884d", 36 | "type": "github" 37 | }, 38 | "original": { 39 | "owner": "nix-community", 40 | "repo": "fenix", 41 | "type": "github" 42 | } 43 | }, 44 | "flake-linter": { 45 | "inputs": { 46 | "flake-utils": [ 47 | "flake-utils" 48 | ], 49 | "nixpkgs": [ 50 | "nixpkgs" 51 | ] 52 | }, 53 | "locked": { 54 | "lastModified": 1702595126, 55 | "narHash": "sha256-uX4oMitqrkKhqCPmUxvaXVuRLj9p+IiQY/FEGOx405U=", 56 | "owner": "kira-bruneau", 57 | "repo": "flake-linter", 58 | "rev": "da1902e3a8d55e26cb44cec92b40314b0f3e4aa9", 59 | "type": "gitlab" 60 | }, 61 | "original": { 62 | "owner": "kira-bruneau", 63 | "repo": "flake-linter", 64 | "type": "gitlab" 65 | } 66 | }, 67 | "flake-utils": { 68 | "inputs": { 69 | "systems": "systems" 70 | }, 71 | "locked": { 72 | "lastModified": 1701680307, 73 | "narHash": "sha256-kAuep2h5ajznlPMD9rnQyffWG8EM/C73lejGofXvdM8=", 74 | "owner": "numtide", 75 | "repo": "flake-utils", 76 | "rev": "4022d587cbbfd70fe950c1e2083a02621806a725", 77 | "type": "github" 78 | }, 79 | "original": { 80 | "owner": "numtide", 81 | "repo": "flake-utils", 82 | "type": "github" 83 | } 84 | }, 85 | "nixpkgs": { 86 | "locked": { 87 | "lastModified": 1703467016, 88 | "narHash": "sha256-/5A/dNPhbQx/Oa2d+Get174eNI3LERQ7u6WTWOlR1eQ=", 89 | "owner": "NixOS", 90 | "repo": "nixpkgs", 91 | "rev": "d02d818f22c777aa4e854efc3242ec451e5d462a", 92 | "type": "github" 93 | }, 94 | "original": { 95 | "id": "nixpkgs", 96 | "ref": "nixos-23.11", 97 | "type": "indirect" 98 | } 99 | }, 100 | "root": { 101 | "inputs": { 102 | "crane": "crane", 103 | "fenix": "fenix", 104 | "flake-linter": "flake-linter", 105 | "flake-utils": "flake-utils", 106 | "nixpkgs": "nixpkgs" 107 | } 108 | }, 109 | "rust-analyzer-src": { 110 | "flake": false, 111 | "locked": { 112 | "lastModified": 1703685114, 113 | "narHash": "sha256-TULflyXwks7yO66LyXAb0QKouBMb2cEnLklPSm82yBY=", 114 | "owner": "rust-lang", 115 | "repo": "rust-analyzer", 116 | "rev": "3ab166637046ab254b11b13ff9108d86b6ed5703", 117 | "type": "github" 118 | }, 119 | "original": { 120 | "owner": "rust-lang", 121 | "ref": "nightly", 122 | "repo": "rust-analyzer", 123 | "type": "github" 124 | } 125 | }, 126 | "systems": { 127 | "locked": { 128 | "lastModified": 1681028828, 129 | "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", 130 | "owner": "nix-systems", 131 | "repo": "default", 132 | "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", 133 | "type": "github" 134 | }, 135 | "original": { 136 | "owner": "nix-systems", 137 | "repo": "default", 138 | "type": "github" 139 | } 140 | } 141 | }, 142 | "root": "root", 143 | "version": 7 144 | } 145 | -------------------------------------------------------------------------------- /tests/parser/unresolved_references.rs: -------------------------------------------------------------------------------- 1 | use pretty_assertions::assert_eq; 2 | 3 | use ari::{ 4 | ast::{Expr, Label, Scope, Symbol}, 5 | parser::{parser, Error, ErrorLabel}, 6 | }; 7 | 8 | use chumsky::Parser; 9 | 10 | #[test] 11 | fn apply_path_to_symbol() { 12 | assert_eq!( 13 | parser().parse_recovery("symbol:path"), 14 | ( 15 | Some( 16 | Scope::try_from_exprs([Expr::unresolved_reference( 17 | [], 18 | 0..11, 19 | Symbol::new(0..6, "symbol"), 20 | [Label::new(6..11, "path")], 21 | )]) 22 | .unwrap() 23 | ), 24 | vec![], 25 | ) 26 | ); 27 | } 28 | 29 | #[test] 30 | fn apply_deep_path_to_symbol() { 31 | assert_eq!( 32 | parser().parse_recovery("symbol:x:y:z"), 33 | ( 34 | Some( 35 | Scope::try_from_exprs([Expr::unresolved_reference( 36 | [], 37 | 0..12, 38 | Symbol::new(0..6, "symbol"), 39 | [ 40 | Label::new(6..8, "x"), 41 | Label::new(8..10, "y"), 42 | Label::new(10..12, "z"), 43 | ], 44 | )]) 45 | .unwrap() 46 | ), 47 | vec![], 48 | ) 49 | ); 50 | } 51 | 52 | #[test] 53 | fn apply_path_to_sexpr() { 54 | assert_eq!( 55 | parser().parse_recovery("(* :r 256 :g 256 :b 256):r"), 56 | ( 57 | Some(Scope::try_from_exprs([Expr::natural([], 0..26, 256u16)]).unwrap()), 58 | vec![], 59 | ) 60 | ); 61 | } 62 | 63 | #[test] 64 | fn path_must_be_complete() { 65 | assert_eq!( 66 | parser().parse_recovery("symbol:"), 67 | ( 68 | Some(Scope::try_from_exprs([]).unwrap()), 69 | vec![Error::unexpected_end(7) 70 | .with_label(ErrorLabel::Symbol) 71 | .with_label(ErrorLabel::Label) 72 | .with_label(ErrorLabel::Path) 73 | .with_label(ErrorLabel::Reference)], 74 | ) 75 | ); 76 | } 77 | 78 | #[test] 79 | fn deep_path_must_be_chained() { 80 | assert_eq!( 81 | parser().parse_recovery("symbol:x:y :z"), 82 | ( 83 | Some( 84 | Scope::try_from_exprs([Expr::unresolved_reference( 85 | [], 86 | 0..10, 87 | Symbol::new(0..6, "symbol"), 88 | [Label::new(6..8, "x"), Label::new(8..10, "y")], 89 | )]) 90 | .unwrap() 91 | ), 92 | vec![Error::unexpected_end(13).with_label(ErrorLabel::LabelledExpr)], 93 | ) 94 | ); 95 | } 96 | 97 | #[test] 98 | fn path_cant_have_left_paren() { 99 | assert_eq!( 100 | parser().parse_recovery("symbol:("), 101 | ( 102 | Some(Scope::try_from_exprs([]).unwrap()), 103 | vec![ 104 | Error::unexpected_char(7..8, '(') 105 | .with_label(ErrorLabel::Symbol) 106 | .with_label(ErrorLabel::Label) 107 | .with_label(ErrorLabel::Path) 108 | .with_label(ErrorLabel::Reference), 109 | Error::trailing_garbage(7..8), 110 | ], 111 | ) 112 | ); 113 | } 114 | 115 | #[test] 116 | fn path_cant_have_right_paren() { 117 | assert_eq!( 118 | parser().parse_recovery("symbol:)"), 119 | ( 120 | Some(Scope::try_from_exprs([]).unwrap()), 121 | vec![ 122 | Error::unexpected_char(7..8, ')') 123 | .with_label(ErrorLabel::Symbol) 124 | .with_label(ErrorLabel::Label) 125 | .with_label(ErrorLabel::Path) 126 | .with_label(ErrorLabel::Reference), 127 | Error::trailing_garbage(7..8), 128 | ], 129 | ) 130 | ); 131 | } 132 | 133 | #[test] 134 | fn cant_apply_path_to_natural() { 135 | assert_eq!( 136 | parser().parse_recovery("256:x"), 137 | ( 138 | Some(Scope::try_from_exprs([]).unwrap()), 139 | vec![Error::invalid_path(3..5).with_label(ErrorLabel::Reference)], 140 | ) 141 | ); 142 | } 143 | 144 | #[test] 145 | fn cant_apply_path_to_natural_in_sexpr() { 146 | assert_eq!( 147 | parser().parse_recovery("(* :x 256):x:y:b"), 148 | ( 149 | Some(Scope::try_from_exprs([]).unwrap()), 150 | vec![Error::invalid_path(12..16).with_label(ErrorLabel::Reference)], 151 | ) 152 | ); 153 | } 154 | 155 | #[test] 156 | fn cant_apply_path_to_missing_path_label_in_sexpr() { 157 | assert_eq!( 158 | parser().parse_recovery("(* :x (* :y (* :z 256))):x:y:b"), 159 | ( 160 | Some(Scope::try_from_exprs([]).unwrap()), 161 | vec![Error::invalid_path(28..30).with_label(ErrorLabel::Reference)], 162 | ) 163 | ); 164 | } 165 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "ahash" 7 | version = "0.8.6" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "91429305e9f0a25f6205c5b8e0d2db09e0708a7a6df0f42212bb56c32c8ac97a" 10 | dependencies = [ 11 | "cfg-if", 12 | "once_cell", 13 | "version_check", 14 | "zerocopy", 15 | ] 16 | 17 | [[package]] 18 | name = "allocator-api2" 19 | version = "0.2.16" 20 | source = "registry+https://github.com/rust-lang/crates.io-index" 21 | checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" 22 | 23 | [[package]] 24 | name = "ari" 25 | version = "0.1.0" 26 | dependencies = [ 27 | "chumsky", 28 | "num-bigint", 29 | "num-traits", 30 | "pretty_assertions", 31 | ] 32 | 33 | [[package]] 34 | name = "autocfg" 35 | version = "1.1.0" 36 | source = "registry+https://github.com/rust-lang/crates.io-index" 37 | checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" 38 | 39 | [[package]] 40 | name = "cc" 41 | version = "1.0.79" 42 | source = "registry+https://github.com/rust-lang/crates.io-index" 43 | checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" 44 | 45 | [[package]] 46 | name = "cfg-if" 47 | version = "1.0.0" 48 | source = "registry+https://github.com/rust-lang/crates.io-index" 49 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 50 | 51 | [[package]] 52 | name = "chumsky" 53 | version = "0.9.3" 54 | source = "registry+https://github.com/rust-lang/crates.io-index" 55 | checksum = "8eebd66744a15ded14960ab4ccdbfb51ad3b81f51f3f04a80adac98c985396c9" 56 | dependencies = [ 57 | "hashbrown", 58 | "stacker", 59 | ] 60 | 61 | [[package]] 62 | name = "diff" 63 | version = "0.1.13" 64 | source = "registry+https://github.com/rust-lang/crates.io-index" 65 | checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" 66 | 67 | [[package]] 68 | name = "hashbrown" 69 | version = "0.14.3" 70 | source = "registry+https://github.com/rust-lang/crates.io-index" 71 | checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" 72 | dependencies = [ 73 | "ahash", 74 | "allocator-api2", 75 | ] 76 | 77 | [[package]] 78 | name = "libc" 79 | version = "0.2.137" 80 | source = "registry+https://github.com/rust-lang/crates.io-index" 81 | checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89" 82 | 83 | [[package]] 84 | name = "num-bigint" 85 | version = "0.4.4" 86 | source = "registry+https://github.com/rust-lang/crates.io-index" 87 | checksum = "608e7659b5c3d7cba262d894801b9ec9d00de989e8a82bd4bef91d08da45cdc0" 88 | dependencies = [ 89 | "autocfg", 90 | "num-integer", 91 | "num-traits", 92 | ] 93 | 94 | [[package]] 95 | name = "num-integer" 96 | version = "0.1.45" 97 | source = "registry+https://github.com/rust-lang/crates.io-index" 98 | checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" 99 | dependencies = [ 100 | "autocfg", 101 | "num-traits", 102 | ] 103 | 104 | [[package]] 105 | name = "num-traits" 106 | version = "0.2.17" 107 | source = "registry+https://github.com/rust-lang/crates.io-index" 108 | checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c" 109 | dependencies = [ 110 | "autocfg", 111 | ] 112 | 113 | [[package]] 114 | name = "once_cell" 115 | version = "1.18.0" 116 | source = "registry+https://github.com/rust-lang/crates.io-index" 117 | checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" 118 | 119 | [[package]] 120 | name = "pretty_assertions" 121 | version = "1.4.0" 122 | source = "registry+https://github.com/rust-lang/crates.io-index" 123 | checksum = "af7cee1a6c8a5b9208b3cb1061f10c0cb689087b3d8ce85fb9d2dd7a29b6ba66" 124 | dependencies = [ 125 | "diff", 126 | "yansi", 127 | ] 128 | 129 | [[package]] 130 | name = "proc-macro2" 131 | version = "1.0.71" 132 | source = "registry+https://github.com/rust-lang/crates.io-index" 133 | checksum = "75cb1540fadbd5b8fbccc4dddad2734eba435053f725621c070711a14bb5f4b8" 134 | dependencies = [ 135 | "unicode-ident", 136 | ] 137 | 138 | [[package]] 139 | name = "psm" 140 | version = "0.1.21" 141 | source = "registry+https://github.com/rust-lang/crates.io-index" 142 | checksum = "5787f7cda34e3033a72192c018bc5883100330f362ef279a8cbccfce8bb4e874" 143 | dependencies = [ 144 | "cc", 145 | ] 146 | 147 | [[package]] 148 | name = "quote" 149 | version = "1.0.33" 150 | source = "registry+https://github.com/rust-lang/crates.io-index" 151 | checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" 152 | dependencies = [ 153 | "proc-macro2", 154 | ] 155 | 156 | [[package]] 157 | name = "stacker" 158 | version = "0.1.15" 159 | source = "registry+https://github.com/rust-lang/crates.io-index" 160 | checksum = "c886bd4480155fd3ef527d45e9ac8dd7118a898a46530b7b94c3e21866259fce" 161 | dependencies = [ 162 | "cc", 163 | "cfg-if", 164 | "libc", 165 | "psm", 166 | "winapi", 167 | ] 168 | 169 | [[package]] 170 | name = "syn" 171 | version = "2.0.43" 172 | source = "registry+https://github.com/rust-lang/crates.io-index" 173 | checksum = "ee659fb5f3d355364e1f3e5bc10fb82068efbf824a1e9d1c9504244a6469ad53" 174 | dependencies = [ 175 | "proc-macro2", 176 | "quote", 177 | "unicode-ident", 178 | ] 179 | 180 | [[package]] 181 | name = "unicode-ident" 182 | version = "1.0.5" 183 | source = "registry+https://github.com/rust-lang/crates.io-index" 184 | checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" 185 | 186 | [[package]] 187 | name = "version_check" 188 | version = "0.9.4" 189 | source = "registry+https://github.com/rust-lang/crates.io-index" 190 | checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" 191 | 192 | [[package]] 193 | name = "winapi" 194 | version = "0.3.9" 195 | source = "registry+https://github.com/rust-lang/crates.io-index" 196 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 197 | dependencies = [ 198 | "winapi-i686-pc-windows-gnu", 199 | "winapi-x86_64-pc-windows-gnu", 200 | ] 201 | 202 | [[package]] 203 | name = "winapi-i686-pc-windows-gnu" 204 | version = "0.4.0" 205 | source = "registry+https://github.com/rust-lang/crates.io-index" 206 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 207 | 208 | [[package]] 209 | name = "winapi-x86_64-pc-windows-gnu" 210 | version = "0.4.0" 211 | source = "registry+https://github.com/rust-lang/crates.io-index" 212 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 213 | 214 | [[package]] 215 | name = "yansi" 216 | version = "0.5.1" 217 | source = "registry+https://github.com/rust-lang/crates.io-index" 218 | checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" 219 | 220 | [[package]] 221 | name = "zerocopy" 222 | version = "0.7.32" 223 | source = "registry+https://github.com/rust-lang/crates.io-index" 224 | checksum = "74d4d3961e53fa4c9a25a8637fc2bfaf2595b3d3ae34875568a5cf64787716be" 225 | dependencies = [ 226 | "zerocopy-derive", 227 | ] 228 | 229 | [[package]] 230 | name = "zerocopy-derive" 231 | version = "0.7.32" 232 | source = "registry+https://github.com/rust-lang/crates.io-index" 233 | checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" 234 | dependencies = [ 235 | "proc-macro2", 236 | "quote", 237 | "syn", 238 | ] 239 | -------------------------------------------------------------------------------- /tests/parser/labels.rs: -------------------------------------------------------------------------------- 1 | use pretty_assertions::assert_eq; 2 | 3 | use ari::{ 4 | ast::{Expr, Label, Scope, ScopeError}, 5 | parser::{parser, Error, ErrorLabel}, 6 | }; 7 | 8 | use chumsky::Parser; 9 | 10 | #[test] 11 | fn single() { 12 | assert_eq!( 13 | parser().parse_recovery(":label 256"), 14 | ( 15 | Some( 16 | Scope::try_from_exprs([Expr::natural([Label::new(0..6, "label")], 7..10, 256u16)]) 17 | .unwrap() 18 | ), 19 | vec![], 20 | ) 21 | ); 22 | } 23 | 24 | #[test] 25 | fn multiple() { 26 | assert_eq!( 27 | parser().parse_recovery(":label1 :label2 256"), 28 | ( 29 | Some( 30 | Scope::try_from_exprs([Expr::natural( 31 | [Label::new(0..7, "label1"), Label::new(8..15, "label2")], 32 | 16..19, 33 | 256u16, 34 | )]) 35 | .unwrap() 36 | ), 37 | vec![], 38 | ) 39 | ); 40 | } 41 | 42 | #[test] 43 | fn multiple_chained() { 44 | assert_eq!( 45 | parser().parse_recovery(":x:y:z 256"), 46 | ( 47 | Some( 48 | Scope::try_from_exprs([Expr::natural( 49 | [ 50 | Label::new(0..2, "x"), 51 | Label::new(2..4, "y"), 52 | Label::new(4..6, "z"), 53 | ], 54 | 7..10, 55 | 256u16, 56 | )]) 57 | .unwrap() 58 | ), 59 | vec![], 60 | ) 61 | ); 62 | } 63 | 64 | #[test] 65 | fn names_cant_have_colon() { 66 | assert_eq!( 67 | parser().parse_recovery(":: 256"), 68 | ( 69 | Some(Scope::try_from_exprs([Expr::natural([], 3..6, 256u16)]).unwrap()), 70 | vec![ 71 | Error::unexpected_char(1..2, ':') 72 | .with_label(ErrorLabel::Symbol) 73 | .with_label(ErrorLabel::Label) 74 | .with_label(ErrorLabel::LabelledExpr), 75 | Error::unexpected_char(2..3, ' ') 76 | .with_label(ErrorLabel::Symbol) 77 | .with_label(ErrorLabel::Label) 78 | .with_label(ErrorLabel::LabelledExpr), 79 | ], 80 | ) 81 | ); 82 | } 83 | 84 | #[test] 85 | fn names_cant_have_left_paren() { 86 | assert_eq!( 87 | parser().parse_recovery(":( 256"), 88 | ( 89 | Some( 90 | Scope::try_from_exprs([Expr::sexpr( 91 | [], 92 | 1..6, 93 | Scope::try_from_exprs([Expr::natural([], 3..6, 256u16)]).unwrap() 94 | )]) 95 | .unwrap() 96 | ), 97 | vec![ 98 | Error::unexpected_char(1..2, '(') 99 | .with_label(ErrorLabel::Symbol) 100 | .with_label(ErrorLabel::Label) 101 | .with_label(ErrorLabel::LabelledExpr), 102 | Error::unexpected_end(6) 103 | .with_label(ErrorLabel::SExpr) 104 | .with_label(ErrorLabel::Reference) 105 | .with_label(ErrorLabel::LabelledExpr) 106 | ], 107 | ) 108 | ); 109 | } 110 | 111 | #[test] 112 | fn names_cant_have_right_paren() { 113 | assert_eq!( 114 | parser().parse_recovery(":) 256"), 115 | ( 116 | Some(Scope::try_from_exprs([]).unwrap()), 117 | vec![ 118 | Error::unexpected_char(1..2, ')') 119 | .with_label(ErrorLabel::Symbol) 120 | .with_label(ErrorLabel::Label) 121 | .with_label(ErrorLabel::LabelledExpr), 122 | Error::trailing_garbage(1..6), 123 | ], 124 | ) 125 | ); 126 | } 127 | 128 | #[test] 129 | fn must_have_name() { 130 | assert_eq!( 131 | parser().parse_recovery(": "), 132 | ( 133 | Some(Scope::try_from_exprs([]).unwrap()), 134 | vec![Error::unexpected_char(1..2, ' ') 135 | .with_label(ErrorLabel::Symbol) 136 | .with_label(ErrorLabel::Label) 137 | .with_label(ErrorLabel::LabelledExpr)], 138 | ) 139 | ); 140 | } 141 | 142 | #[test] 143 | fn must_have_name_in_sexpr() { 144 | assert_eq!( 145 | parser().parse_recovery("(: )"), 146 | ( 147 | Some( 148 | Scope::try_from_exprs([Expr::sexpr([], 0..4, Scope::try_from_exprs([]).unwrap())]) 149 | .unwrap() 150 | ), 151 | vec![Error::unexpected_char(2..3, ' ') 152 | .with_label(ErrorLabel::Symbol) 153 | .with_label(ErrorLabel::Label) 154 | .with_label(ErrorLabel::LabelledExpr) 155 | .with_label(ErrorLabel::SExpr) 156 | .with_label(ErrorLabel::Reference)], 157 | ) 158 | ); 159 | } 160 | 161 | #[test] 162 | fn must_have_associated_expr() { 163 | assert_eq!( 164 | parser().parse_recovery(":label "), 165 | ( 166 | Some(Scope::try_from_exprs([]).unwrap()), 167 | vec![Error::unexpected_end(7).with_label(ErrorLabel::LabelledExpr)] 168 | ) 169 | ); 170 | } 171 | 172 | #[test] 173 | fn must_have_associated_expr_in_sexpr() { 174 | assert_eq!( 175 | parser().parse_recovery("(:label )"), 176 | ( 177 | Some( 178 | Scope::try_from_exprs([Expr::sexpr([], 0..9, Scope::try_from_exprs([]).unwrap())]) 179 | .unwrap() 180 | ), 181 | vec![Error::unexpected_end(8) 182 | .with_label(ErrorLabel::LabelledExpr) 183 | .with_label(ErrorLabel::SExpr) 184 | .with_label(ErrorLabel::Reference)] 185 | ) 186 | ); 187 | } 188 | 189 | #[test] 190 | fn must_be_unique_same_expr() { 191 | let (err, scope) = Scope::try_from_exprs([Expr::natural( 192 | [Label::new(0..7, "label1"), Label::new(8..15, "label1")], 193 | 16..19, 194 | 256u16, 195 | )]) 196 | .unwrap_err(); 197 | 198 | let (start_span, end_span) = match err.as_ref() { 199 | [ScopeError::DuplicateLabel(start_span, end_span)] => { 200 | assert_eq!((start_span, end_span), (&(8..15), &(0..7))); 201 | (start_span.clone(), end_span.clone()) 202 | } 203 | err => panic!("unexpected error: {:?}", err), 204 | }; 205 | 206 | assert_eq!( 207 | parser().parse_recovery(":label1 :label1 256"), 208 | ( 209 | Some(scope), 210 | vec![Error::duplicate_label(start_span, end_span)] 211 | ) 212 | ); 213 | } 214 | 215 | #[test] 216 | fn must_be_unique_different_expr() { 217 | let (err, scope) = Scope::try_from_exprs([ 218 | Expr::natural([Label::new(0..7, "label1")], 8..11, 256u16), 219 | Expr::natural([Label::new(12..19, "label1")], 20..23, 256u16), 220 | ]) 221 | .unwrap_err(); 222 | 223 | let (start_span, end_span) = match err.as_ref() { 224 | [ScopeError::DuplicateLabel(start_span, end_span)] => { 225 | assert_eq!((start_span, end_span), (&(12..19), &(0..7))); 226 | (start_span.clone(), end_span.clone()) 227 | } 228 | err => panic!("unexpected error: {:?}", err), 229 | }; 230 | 231 | assert_eq!( 232 | parser().parse_recovery(":label1 256 :label1 256"), 233 | ( 234 | Some(scope), 235 | vec![Error::duplicate_label(start_span, end_span)], 236 | ) 237 | ); 238 | } 239 | 240 | #[test] 241 | fn expr_span() { 242 | assert_eq!( 243 | parser() 244 | .parse(":label 256") 245 | .unwrap() 246 | .into_iter() 247 | .next() 248 | .unwrap() 249 | .span(), 250 | 0..10 251 | ); 252 | } 253 | -------------------------------------------------------------------------------- /src/parser.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::unit_arg)] 2 | 3 | use std::ops::Range; 4 | 5 | use chumsky::prelude::*; 6 | use num_bigint::BigUint; 7 | use num_traits::Num; 8 | 9 | use crate::{ 10 | ast::{ 11 | path_span, BaseExpr, Expr, ExprVariant, Label, Labels, Reference, Scope, ScopeError, 12 | Symbol, UnresolvedPath, 13 | }, 14 | natural::Natural, 15 | }; 16 | 17 | // TODO: Ref, Deref, extended labels & text expressions 18 | pub fn parser() -> impl Parser { 19 | scope(recursive(|expr| { 20 | labelled(reference(choice(( 21 | sexpr(expr) 22 | .map_with_span(|scope, span| BaseExpr::variant(span, ExprVariant::SExpr(scope))), 23 | natural().map_with_span(|natural, span| { 24 | BaseExpr::variant(span, ExprVariant::Natural(natural)) 25 | }), 26 | symbol().map_with_span(|symbol, span| { 27 | BaseExpr::variant( 28 | span.clone(), 29 | ExprVariant::Reference(Reference::unresolved(Symbol::new(span, symbol), [])), 30 | ) 31 | }), 32 | )))) 33 | })) 34 | .then_ignore( 35 | any() 36 | .ignored() 37 | .repeated() 38 | .validate(|trailing_garbage, span, emit| { 39 | if !trailing_garbage.is_empty() { 40 | emit(Error::trailing_garbage(span)) 41 | } 42 | }), 43 | ) 44 | } 45 | 46 | fn labelled( 47 | expr: impl Parser, Error = Error> + Clone, 48 | ) -> impl Parser, Error = Error> + Clone { 49 | let labels_with_expr = label() 50 | .separated_by(text::whitespace()) 51 | .at_least(1) 52 | .collect::, ()>>() 53 | .then_ignore(text::whitespace().at_least(1).or_not()) 54 | .then(expr.clone().or_not()) 55 | .validate(|(labels, expr), span, emit| match labels { 56 | Ok(labels) => match expr { 57 | Some(expr) => expr.map(|expr| expr.with_labels(labels)), 58 | None => Err(emit(Error::unexpected_end(span.end))), 59 | }, 60 | Err(()) => match expr { 61 | Some(expr) => expr.map(|expr| expr.with_labels(Box::new([]))), 62 | None => Err(()), 63 | }, 64 | }) 65 | .labelled(ErrorLabel::LabelledExpr); 66 | 67 | choice(( 68 | labels_with_expr, 69 | expr.map(|expr| expr.map(|expr| expr.with_labels(Box::new([])))), 70 | )) 71 | } 72 | 73 | fn label() -> impl Parser, Error = Error> + Clone { 74 | just(':') 75 | .ignore_then(symbol().map(Ok).or_else(|err| Ok(Err(err)))) 76 | .validate(|symbol, span, emit| match symbol { 77 | Ok(symbol) => Ok(Label::new(span, symbol)), 78 | Err(err) => Err(emit(err)), 79 | }) 80 | .labelled(ErrorLabel::Label) 81 | } 82 | 83 | fn reference( 84 | expr: impl Parser + Clone, 85 | ) -> impl Parser, Error = Error> + Clone { 86 | expr.then(path()) 87 | .validate(|(expr, path), _span, emit| { 88 | path.and_then(|path| { 89 | expr.take_from_path(path) 90 | .map_err(|(path, depth)| emit(Error::invalid_path(path_span(&path[depth..])))) 91 | }) 92 | }) 93 | .labelled(ErrorLabel::Reference) 94 | } 95 | 96 | fn path() -> impl Parser, ()>, Error = Error> + Clone { 97 | label().repeated().collect().labelled(ErrorLabel::Path) 98 | } 99 | 100 | fn sexpr( 101 | expr: impl Parser, Error = Error> + Clone, 102 | ) -> impl Parser + Clone { 103 | scope(expr) 104 | .delimited_by( 105 | just('('), 106 | just(')') 107 | .map(|_| Ok(())) 108 | .or_else(|err| Ok(Err(err))) 109 | .validate(|result, _span, emit| result.map_err(emit)), 110 | ) 111 | .labelled(ErrorLabel::SExpr) 112 | } 113 | 114 | fn scope( 115 | expr: impl Parser, Error = Error> + Clone, 116 | ) -> impl Parser + Clone { 117 | expr.separated_by(text::whitespace().at_least(1)) 118 | .flatten() 119 | .validate(|exprs, _span, emit| { 120 | Scope::try_from_exprs_with_emit(exprs, &mut |err| { 121 | emit(match err { 122 | ScopeError::DuplicateLabel(span, other_span) => { 123 | Error::duplicate_label(span, other_span) 124 | } 125 | ScopeError::InvalidPath(span) => Error::invalid_path(span), 126 | }) 127 | }) 128 | }) 129 | .padded() 130 | } 131 | 132 | fn natural() -> impl Parser + Clone { 133 | // TODO: Support underscore for separator 134 | // TODO: Manually build natural from digits to avoid overhead of 135 | // converting to string + parse 136 | choice(( 137 | just('0').ignore_then(choice(( 138 | just("b") 139 | .ignore_then(text::int(2).map(|s: String| BigUint::from_str_radix(&s, 2).unwrap())), 140 | just("o") 141 | .ignore_then(text::int(8).map(|s: String| BigUint::from_str_radix(&s, 8).unwrap())), 142 | just("x").ignore_then( 143 | text::int(16).map(|s: String| BigUint::from_str_radix(&s, 16).unwrap()), 144 | ), 145 | ))), 146 | text::int(10).map(|s: String| BigUint::from_str_radix(&s, 10).unwrap()), 147 | )) 148 | .map(Natural::from) 149 | .labelled(ErrorLabel::Natural) 150 | } 151 | 152 | fn symbol() -> impl Parser + Clone { 153 | filter(symbol_char) 154 | .repeated() 155 | .at_least(1) 156 | .collect() 157 | .labelled(ErrorLabel::Symbol) 158 | } 159 | 160 | fn symbol_char(c: &char) -> bool { 161 | match c { 162 | ':' | '(' | ')' => false, 163 | c => !c.is_whitespace(), 164 | } 165 | } 166 | 167 | #[derive(Debug, PartialEq, Eq, Clone)] 168 | pub struct Error { 169 | pub span: Range, 170 | pub variant: ErrorVariant, 171 | pub trace: Vec, 172 | } 173 | 174 | impl Error { 175 | pub fn unexpected_char(span: Range, found: char) -> Self { 176 | Self { 177 | variant: ErrorVariant::UnexpectedChar(Some(found)), 178 | span, 179 | trace: Vec::new(), 180 | } 181 | } 182 | 183 | pub fn unexpected_end(pos: usize) -> Self { 184 | Self { 185 | variant: ErrorVariant::UnexpectedChar(None), 186 | span: pos..pos, 187 | trace: Vec::new(), 188 | } 189 | } 190 | 191 | pub fn duplicate_label(span: Range, other_span: Range) -> Self { 192 | Self { 193 | variant: ErrorVariant::DuplicateLabel(other_span), 194 | span, 195 | trace: Vec::new(), 196 | } 197 | } 198 | 199 | pub fn invalid_path(span: Range) -> Self { 200 | Self { 201 | variant: ErrorVariant::InvalidPath, 202 | span, 203 | trace: Vec::new(), 204 | } 205 | } 206 | 207 | pub fn trailing_garbage(span: Range) -> Self { 208 | Self { 209 | variant: ErrorVariant::TrailingGarbage, 210 | span, 211 | trace: Vec::new(), 212 | } 213 | } 214 | 215 | pub fn with_label(mut self, label: ErrorLabel) -> Self { 216 | self.trace.push(label); 217 | self 218 | } 219 | } 220 | 221 | impl chumsky::Error for Error { 222 | type Span = Range; 223 | 224 | type Label = ErrorLabel; 225 | 226 | fn expected_input_found>>( 227 | span: Self::Span, 228 | _expected: Iter, 229 | found: Option, 230 | ) -> Self { 231 | if let Some(found) = found { 232 | Self::unexpected_char(span, found) 233 | } else { 234 | debug_assert_eq!(span.start, span.end); 235 | Self::unexpected_end(span.end) 236 | } 237 | } 238 | 239 | fn with_label(self, label: Self::Label) -> Self { 240 | Error::with_label(self, label) 241 | } 242 | 243 | fn merge(self, _other: Self) -> Self { 244 | self 245 | } 246 | } 247 | 248 | #[derive(Debug, PartialEq, Eq, Clone)] 249 | pub enum ErrorVariant { 250 | UnexpectedChar(Option), 251 | DuplicateLabel(Range), 252 | InvalidPath, 253 | TrailingGarbage, 254 | } 255 | 256 | #[derive(Debug, PartialEq, Eq, Clone)] 257 | pub enum ErrorLabel { 258 | Natural, 259 | Symbol, 260 | Label, 261 | LabelledExpr, 262 | Path, 263 | Reference, 264 | SExpr, 265 | } 266 | -------------------------------------------------------------------------------- /tests/parser/resolved_references.rs: -------------------------------------------------------------------------------- 1 | use pretty_assertions::assert_eq; 2 | 3 | use ari::{ 4 | ast::{Expr, Label, Scope, Symbol}, 5 | parser::{parser, Error, ErrorLabel}, 6 | }; 7 | 8 | use chumsky::Parser; 9 | 10 | #[test] 11 | fn back_reference() { 12 | assert_eq!( 13 | parser().parse_recovery(":a 256 :b a"), 14 | ( 15 | Some( 16 | Scope::try_from_exprs([ 17 | Expr::natural([Label::new(0..2, "a")], 3..6, 256u16), 18 | Expr::resolved_reference([Label::new(7..9, "b")], 10..11, 0, -1, []), 19 | ]) 20 | .unwrap() 21 | ), 22 | vec![], 23 | ), 24 | ); 25 | } 26 | 27 | #[test] 28 | fn forward_reference() { 29 | assert_eq!( 30 | parser().parse_recovery(":a b :b 256"), 31 | ( 32 | Some( 33 | Scope::try_from_exprs([ 34 | Expr::resolved_reference([Label::new(0..2, "a")], 3..4, 0, 1, []), 35 | Expr::natural([Label::new(5..7, "b")], 8..11, 256u16), 36 | ]) 37 | .unwrap() 38 | ), 39 | vec![], 40 | ), 41 | ); 42 | } 43 | 44 | #[test] 45 | fn direct_self_reference() { 46 | assert_eq!( 47 | parser().parse_recovery(":a a"), 48 | ( 49 | Some( 50 | Scope::try_from_exprs([Expr::resolved_reference( 51 | [Label::new(0..2, "a")], 52 | 3..4, 53 | 0, 54 | 0, 55 | [] 56 | )]) 57 | .unwrap() 58 | ), 59 | vec![], 60 | ), 61 | ); 62 | } 63 | 64 | #[test] 65 | fn nested_self_reference() { 66 | assert_eq!( 67 | parser().parse_recovery(":a (+ a 256)"), 68 | ( 69 | Some( 70 | Scope::try_from_exprs([Expr::sexpr( 71 | [Label::new(0..2, "a")], 72 | 3..12, 73 | Scope::try_from_exprs([ 74 | Expr::unresolved_symbol([], 4..5, "+"), 75 | Expr::resolved_reference([], 6..7, 1, 0, []), 76 | Expr::natural([], 8..11, 256u16), 77 | ]) 78 | .unwrap() 79 | )]) 80 | .unwrap() 81 | ), 82 | vec![], 83 | ), 84 | ); 85 | } 86 | 87 | #[test] 88 | fn indirect_self_reference() { 89 | assert_eq!( 90 | parser().parse_recovery(":a b :b a"), 91 | ( 92 | Some( 93 | Scope::try_from_exprs([ 94 | Expr::resolved_reference([Label::new(0..2, "a")], 3..4, 0, 1, []), 95 | Expr::resolved_reference([Label::new(5..7, "b")], 8..9, 0, -1, []), 96 | ]) 97 | .unwrap() 98 | ), 99 | vec![], 100 | ), 101 | ); 102 | } 103 | 104 | #[test] 105 | fn indirect_unresolved_reference() { 106 | assert_eq!( 107 | parser().parse_recovery(":a c :b a"), 108 | ( 109 | Some( 110 | Scope::try_from_exprs([ 111 | Expr::unresolved_symbol([Label::new(0..2, "a")], 3..4, "c"), 112 | Expr::resolved_reference([Label::new(5..7, "b")], 8..9, 0, -1, []) 113 | ]) 114 | .unwrap() 115 | ), 116 | vec![], 117 | ), 118 | ); 119 | } 120 | 121 | #[test] 122 | fn back_reference_in_parent_scope() { 123 | assert_eq!( 124 | parser().parse_recovery(":a 256 (* :b a)"), 125 | ( 126 | Some( 127 | Scope::try_from_exprs([ 128 | Expr::natural([Label::new(0..2, "a")], 3..6, 256u16), 129 | Expr::sexpr( 130 | [], 131 | 7..15, 132 | Scope::try_from_exprs([ 133 | Expr::unresolved_symbol([], 8..9, "*"), 134 | Expr::resolved_reference([Label::new(10..12, "b")], 13..14, 1, -1, []), 135 | ]) 136 | .unwrap() 137 | ) 138 | ]) 139 | .unwrap() 140 | ), 141 | vec![], 142 | ), 143 | ); 144 | } 145 | 146 | #[test] 147 | fn forward_reference_in_parent_scope() { 148 | assert_eq!( 149 | parser().parse_recovery("(* :a b) :b 256"), 150 | ( 151 | Some( 152 | Scope::try_from_exprs([ 153 | Expr::sexpr( 154 | [], 155 | 0..8, 156 | Scope::try_from_exprs([ 157 | Expr::unresolved_symbol([], 1..2, "*"), 158 | Expr::resolved_reference([Label::new(3..5, "a")], 6..7, 1, 1, []), 159 | ]) 160 | .unwrap() 161 | ), 162 | Expr::natural([Label::new(9..11, "b")], 12..15, 256u16), 163 | ]) 164 | .unwrap() 165 | ), 166 | vec![], 167 | ), 168 | ); 169 | } 170 | 171 | #[test] 172 | fn back_reference_in_sibling_scope() { 173 | assert_eq!( 174 | parser().parse_recovery(":a (* :b 256) :b a:b"), 175 | ( 176 | Some( 177 | Scope::try_from_exprs([ 178 | Expr::sexpr( 179 | [Label::new(0..2, "a")], 180 | 3..13, 181 | Scope::try_from_exprs([ 182 | Expr::unresolved_symbol([], 4..5, "*"), 183 | Expr::natural([Label::new(6..8, "b")], 9..12, 256u16), 184 | ]) 185 | .unwrap() 186 | ), 187 | Expr::resolved_reference([Label::new(14..16, "b")], 17..20, 0, -1, [1]), 188 | ]) 189 | .unwrap() 190 | ), 191 | vec![], 192 | ), 193 | ); 194 | } 195 | 196 | #[test] 197 | fn forward_reference_in_sibling_scope() { 198 | assert_eq!( 199 | parser().parse_recovery(":a b:a :b (* :a 256)"), 200 | ( 201 | Some( 202 | Scope::try_from_exprs([ 203 | Expr::resolved_reference([Label::new(0..2, "a")], 3..6, 0, 1, [1]), 204 | Expr::sexpr( 205 | [Label::new(7..9, "b")], 206 | 10..20, 207 | Scope::try_from_exprs([ 208 | Expr::unresolved_symbol([], 11..12, "*"), 209 | Expr::natural([Label::new(13..15, "a")], 16..19, 256u16), 210 | ]) 211 | .unwrap() 212 | ), 213 | ]) 214 | .unwrap() 215 | ), 216 | vec![], 217 | ), 218 | ); 219 | } 220 | 221 | #[test] 222 | fn invalid_reference_path() { 223 | assert_eq!( 224 | parser().parse_recovery("(* :a 256 :b a:b)"), 225 | ( 226 | Some( 227 | Scope::try_from_exprs([Expr::sexpr( 228 | [], 229 | 0..17, 230 | Scope::try_from_exprs([ 231 | Expr::unresolved_symbol([], 1..2, "*"), 232 | Expr::natural([Label::new(3..5, "a")], 6..9, 256u16), 233 | Expr::unresolved_reference( 234 | [Label::new(10..12, "b")], 235 | 13..16, 236 | Symbol::new(13..14, "a"), 237 | [Label::new(14..16, "b")] 238 | ) 239 | ]) 240 | .unwrap_or_else(|(_err, scope)| scope) 241 | )]) 242 | .unwrap() 243 | ), 244 | vec![Error::invalid_path(14..16) 245 | .with_label(ErrorLabel::SExpr) 246 | .with_label(ErrorLabel::Reference)], 247 | ), 248 | ); 249 | } 250 | 251 | #[test] 252 | fn partially_invalid_reference_path() { 253 | assert_eq!( 254 | parser().parse_recovery(":a (* :x (* :y (* :z 256)) :b a:x:y:b)"), 255 | ( 256 | Some( 257 | Scope::try_from_exprs([Expr::sexpr( 258 | [Label::new(0..2, "a")], 259 | 3..38, 260 | Scope::try_from_exprs([ 261 | Expr::unresolved_symbol([], 4..5, "*"), 262 | Expr::sexpr( 263 | [Label::new(6..8, "x")], 264 | 9..26, 265 | Scope::try_from_exprs([ 266 | Expr::unresolved_symbol([], 10..11, "*"), 267 | Expr::sexpr( 268 | [Label::new(12..14, "y")], 269 | 15..25, 270 | Scope::try_from_exprs([ 271 | Expr::unresolved_symbol([], 16..17, "*"), 272 | Expr::natural([Label::new(18..20, "z")], 21..24, 256u16), 273 | ]) 274 | .unwrap() 275 | ), 276 | ]) 277 | .unwrap() 278 | ), 279 | Expr::unresolved_reference( 280 | [Label::new(27..29, "b")], 281 | 30..37, 282 | Symbol::new(30..31, "a"), 283 | [ 284 | Label::new(31..33, "x"), 285 | Label::new(33..35, "y"), 286 | Label::new(35..37, "b") 287 | ] 288 | ) 289 | ]) 290 | .unwrap() 291 | )]) 292 | .unwrap_or_else(|(_err, scope)| scope) 293 | ), 294 | vec![Error::invalid_path(35..37)], 295 | ), 296 | ); 297 | } 298 | -------------------------------------------------------------------------------- /src/ast.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | cell::{Cell, RefCell}, 3 | collections::{hash_map, HashMap}, 4 | fmt, 5 | ops::Range, 6 | vec::IntoIter, 7 | }; 8 | 9 | use crate::natural::Natural; 10 | 11 | /// A collection of labelled expressions where all references have 12 | /// been resolved by matching labels introduced in the scope. 13 | /// 14 | /// Acts as the root element for Ari's "abstract syntax tree". 15 | #[derive(Default)] 16 | pub struct Scope { 17 | exprs: Box<[Expr]>, 18 | expr_from_label: HashMap, 19 | 20 | // TODO: Redesign `unresolved_map` as a radix tree 21 | #[allow(clippy::type_complexity)] 22 | unresolved_map: Cell>>>, 23 | } 24 | 25 | impl Scope { 26 | pub fn try_from_exprs( 27 | iter: impl IntoIterator, 28 | ) -> Result, Scope)> { 29 | let mut errors = Vec::new(); 30 | let scope = Self::try_from_exprs_with_emit(iter, &mut |err| errors.push(err)); 31 | if errors.is_empty() { 32 | Ok(scope) 33 | } else { 34 | Err((errors.into_boxed_slice(), scope)) 35 | } 36 | } 37 | 38 | pub fn try_from_exprs_with_emit( 39 | iter: impl IntoIterator, 40 | emit: &mut dyn FnMut(ScopeError), 41 | ) -> Self { 42 | let iter = iter.into_iter(); 43 | let mut exprs = Vec::with_capacity(iter.size_hint().0); 44 | let mut expr_from_label: HashMap = HashMap::new(); 45 | for (index, expr) in iter.enumerate() { 46 | exprs.push(expr); 47 | let expr = &exprs[index]; 48 | for (label_index, label) in expr.labels.iter().enumerate() { 49 | if let Some((other_index, other_label_index)) = 50 | expr_from_label.get(&label.name).copied() 51 | { 52 | emit(ScopeError::DuplicateLabel( 53 | label.span.clone(), 54 | exprs[other_index].labels[other_label_index].span.clone(), 55 | )); 56 | } else { 57 | expr_from_label.insert(label.name.clone(), (index, label_index)); 58 | } 59 | } 60 | } 61 | 62 | let mut unresolved_map: HashMap> = 63 | HashMap::new(); 64 | 65 | for (index, expr) in exprs.iter().enumerate() { 66 | match &expr.base.variant { 67 | ExprVariant::Natural(_natural) => (), 68 | ExprVariant::Reference(reference) => { 69 | let resolved = match &*reference.cell.borrow() { 70 | ReferenceVariant::Unresolved(unresolved) => { 71 | let symbol = &unresolved.symbol.name; 72 | if let Some((other_index, _)) = expr_from_label.get(symbol).copied() { 73 | let other_expr = &exprs[other_index]; 74 | match other_expr.base.resolve_path(unresolved.path.as_ref()) { 75 | Ok(path) => { 76 | Some(ReferenceVariant::Resolved(ResolvedReference { 77 | scope: 0, 78 | offset: other_index as isize - index as isize, 79 | path, 80 | })) 81 | } 82 | Err(path) => { 83 | emit(ScopeError::InvalidPath(path_span(path))); 84 | None 85 | } 86 | } 87 | } else { 88 | // Don't need to handle when symbol is already in unresolved_map, since 89 | // we can't have duplicate labels in the same scope 90 | unresolved_map 91 | .insert(symbol.clone(), vec![(1, reference.cell.as_ptr())]); 92 | 93 | None 94 | } 95 | } 96 | ReferenceVariant::Resolved(_path) => None, 97 | }; 98 | 99 | if let Some(resolved) = resolved { 100 | *reference.cell.borrow_mut() = resolved; 101 | } 102 | } 103 | ExprVariant::SExpr(scope) => { 104 | for (symbol, mut references) in 105 | scope.unresolved_map.take().into_iter().flatten() 106 | { 107 | if let Some((other_index, _)) = expr_from_label.get(&symbol).copied() { 108 | let expr = &exprs[other_index]; 109 | for (scope, reference) in references { 110 | // NOTE: Could use paths instead of pointers to avoid unsafe, but 111 | // would be more complicated and less efficient 112 | unsafe { 113 | let ReferenceVariant::Unresolved(unresolved) = &*reference 114 | else { 115 | unreachable!() 116 | }; 117 | 118 | match expr.base.resolve_path(&unresolved.path) { 119 | Ok(path) => { 120 | *reference = 121 | ReferenceVariant::Resolved(ResolvedReference { 122 | scope, 123 | offset: other_index as isize - index as isize, 124 | path, 125 | }); 126 | } 127 | Err(path) => emit(ScopeError::InvalidPath(path_span(path))), 128 | } 129 | } 130 | } 131 | } else { 132 | for unresolved in references.iter_mut() { 133 | unresolved.0 += 1; 134 | } 135 | 136 | match unresolved_map.entry(symbol) { 137 | hash_map::Entry::Occupied(mut entry) => { 138 | entry.get_mut().extend(references); 139 | } 140 | hash_map::Entry::Vacant(entry) => { 141 | entry.insert(references); 142 | } 143 | }; 144 | } 145 | } 146 | } 147 | } 148 | } 149 | 150 | Self { 151 | exprs: exprs.into_boxed_slice(), 152 | expr_from_label, 153 | unresolved_map: Cell::new(Some(unresolved_map)), 154 | } 155 | } 156 | } 157 | 158 | impl fmt::Debug for Scope { 159 | #[cfg_attr(coverage_nightly, coverage(off))] 160 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { 161 | self.exprs.fmt(f) 162 | } 163 | } 164 | 165 | impl Clone for Scope { 166 | #[cfg_attr(coverage_nightly, coverage(off))] 167 | fn clone(&self) -> Self { 168 | Self::try_from_exprs(self.exprs.iter().cloned()).unwrap() 169 | } 170 | } 171 | 172 | impl PartialEq for Scope { 173 | fn eq(&self, other: &Self) -> bool { 174 | self.exprs.eq(&other.exprs) 175 | } 176 | } 177 | 178 | impl Eq for Scope {} 179 | 180 | impl IntoIterator for Scope { 181 | type Item = Expr; 182 | 183 | type IntoIter = IntoIter; 184 | 185 | fn into_iter(self) -> Self::IntoIter { 186 | // into_vec: https://github.com/rust-lang/rust/issues/59878 187 | self.exprs.into_vec().into_iter() 188 | } 189 | } 190 | 191 | #[derive(Debug, Clone, PartialEq, Eq)] 192 | pub enum ScopeError { 193 | DuplicateLabel(Range, Range), 194 | InvalidPath(Range), 195 | } 196 | 197 | #[derive(Debug, Clone, PartialEq, Eq)] 198 | pub struct Expr { 199 | pub labels: Box, 200 | pub base: BaseExpr, 201 | } 202 | 203 | impl Expr { 204 | pub fn variant( 205 | labels: impl Into>, 206 | span: Range, 207 | variant: ExprVariant, 208 | ) -> Self { 209 | Self { 210 | labels: labels.into(), 211 | base: BaseExpr::variant(span, variant), 212 | } 213 | } 214 | 215 | pub fn natural( 216 | labels: impl Into>, 217 | span: Range, 218 | natural: impl Into, 219 | ) -> Self { 220 | Self::variant(labels, span, ExprVariant::Natural(natural.into())) 221 | } 222 | 223 | pub fn unresolved_symbol( 224 | labels: impl Into>, 225 | span: Range, 226 | name: impl Into, 227 | ) -> Self { 228 | Self::unresolved_reference(labels, span.clone(), Symbol::new(span, name), []) 229 | } 230 | 231 | pub fn unresolved_reference( 232 | labels: impl Into>, 233 | span: Range, 234 | symbol: Symbol, 235 | path: impl Into>, 236 | ) -> Self { 237 | Self::variant( 238 | labels, 239 | span, 240 | ExprVariant::Reference(Reference::unresolved(symbol, path)), 241 | ) 242 | } 243 | 244 | pub fn resolved_reference( 245 | labels: impl Into>, 246 | span: Range, 247 | scope: usize, 248 | offset: isize, 249 | path: impl Into>, 250 | ) -> Self { 251 | Self::variant( 252 | labels, 253 | span, 254 | ExprVariant::Reference(Reference::resolved(scope, offset, path)), 255 | ) 256 | } 257 | 258 | pub fn sexpr( 259 | labels: impl Into>, 260 | span: Range, 261 | scope: impl Into, 262 | ) -> Self { 263 | Self::variant(labels, span, ExprVariant::SExpr(scope.into())) 264 | } 265 | 266 | pub fn span(&self) -> Range { 267 | let start = self 268 | .labels 269 | .first() 270 | .map(|Label { span, .. }| span.start) 271 | .unwrap_or(self.base.span.start); 272 | 273 | start..self.base.span.end 274 | } 275 | } 276 | 277 | #[derive(Debug, Clone, PartialEq, Eq)] 278 | pub struct BaseExpr { 279 | pub span: Range, 280 | pub variant: ExprVariant, 281 | } 282 | 283 | impl BaseExpr { 284 | pub(crate) fn variant(span: Range, variant: ExprVariant) -> Self { 285 | Self { span, variant } 286 | } 287 | 288 | pub(crate) fn with_labels(self, labels: Box) -> Expr { 289 | Expr { labels, base: self } 290 | } 291 | 292 | fn resolve_path<'p>( 293 | &self, 294 | mut unresolved: &'p UnresolvedPath, 295 | ) -> Result, &'p UnresolvedPath> { 296 | let mut expr = self; 297 | let mut resolved = Vec::with_capacity(unresolved.len()); 298 | while let Some((label, remainder)) = unresolved.split_first() { 299 | let ExprVariant::SExpr(scope) = &expr.variant else { 300 | return Err(unresolved); 301 | }; 302 | 303 | let Some((index, _)) = scope.expr_from_label.get(&label.name).copied() else { 304 | return Err(unresolved); 305 | }; 306 | 307 | expr = &scope.exprs[index].base; 308 | unresolved = remainder; 309 | resolved.push(index); 310 | } 311 | 312 | Ok(resolved.into_boxed_slice()) 313 | } 314 | 315 | pub(crate) fn take_from_path( 316 | self, 317 | path: Box, 318 | ) -> Result, usize)> { 319 | self.take_from_path_rec(path, 0) 320 | } 321 | 322 | fn take_from_path_rec( 323 | self, 324 | path: Box, 325 | depth: usize, 326 | ) -> Result, usize)> { 327 | Ok(match path.get(depth) { 328 | Some(label) => Self { 329 | span: self.span.start..path.last().unwrap().span.end, 330 | variant: match self.variant { 331 | ExprVariant::Natural(_) => return Err((path, depth)), 332 | ExprVariant::Reference(reference) => ExprVariant::Reference(Reference { 333 | cell: RefCell::new(match reference.cell.into_inner() { 334 | ReferenceVariant::Unresolved(unresolved) => { 335 | // into_vec: https://github.com/rust-lang/rust/issues/59878 336 | ReferenceVariant::Unresolved(unresolved.join(path.into_vec())) 337 | } 338 | ReferenceVariant::Resolved(_) => unreachable!(), 339 | }), 340 | }), 341 | ExprVariant::SExpr(scope) => { 342 | match scope.expr_from_label.get(&label.name).copied() { 343 | Some((index, _)) => { 344 | scope 345 | .into_iter() 346 | .nth(index) 347 | .unwrap() 348 | .base 349 | .take_from_path_rec(path, depth + 1)? 350 | .variant 351 | } 352 | None => return Err((path, depth)), 353 | } 354 | } 355 | }, 356 | }, 357 | None => self, 358 | }) 359 | } 360 | } 361 | 362 | #[derive(Debug, Clone, PartialEq, Eq)] 363 | pub enum ExprVariant { 364 | Natural(Natural), 365 | Reference(Reference), 366 | SExpr(Scope), 367 | } 368 | 369 | #[derive(Debug, Clone, PartialEq, Eq)] 370 | pub struct Reference { 371 | cell: RefCell, 372 | } 373 | 374 | impl Reference { 375 | pub fn unresolved(symbol: Symbol, path: impl Into>) -> Self { 376 | Self { 377 | cell: RefCell::new(ReferenceVariant::Unresolved(UnresolvedReference { 378 | symbol, 379 | path: path.into(), 380 | })), 381 | } 382 | } 383 | 384 | pub fn resolved(scope: usize, offset: isize, path: impl Into>) -> Self { 385 | Self { 386 | cell: RefCell::new(ReferenceVariant::Resolved(ResolvedReference { 387 | scope, 388 | offset, 389 | path: path.into(), 390 | })), 391 | } 392 | } 393 | } 394 | 395 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 396 | pub enum ReferenceVariant { 397 | Unresolved(UnresolvedReference), 398 | Resolved(ResolvedReference), 399 | } 400 | 401 | /// A chain of symbols pointing to an [Expr] within the current scope. 402 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 403 | pub struct UnresolvedReference { 404 | pub symbol: Symbol, 405 | pub path: Box, 406 | } 407 | 408 | impl UnresolvedReference { 409 | fn join(self, other: impl IntoIterator) -> Self { 410 | // into_vec: https://github.com/rust-lang/rust/issues/59878 411 | Self { 412 | symbol: self.symbol, 413 | path: self.path.into_vec().into_iter().chain(other).collect(), 414 | } 415 | } 416 | } 417 | 418 | pub type UnresolvedPath = [Label]; 419 | 420 | pub fn path_span(path: &UnresolvedPath) -> Range { 421 | let start = path.first().expect("at least one label in path").span.start; 422 | let end = path.last().expect("at least one label in path").span.end; 423 | start..end 424 | } 425 | 426 | /// A resolved relative path to a parent [Expr]. 427 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 428 | pub struct ResolvedReference { 429 | pub scope: usize, 430 | pub offset: isize, 431 | pub path: Box, 432 | } 433 | 434 | pub type ResolvedPath = [usize]; 435 | 436 | pub type Labels = [Label]; 437 | 438 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 439 | pub struct Label { 440 | pub span: Range, 441 | pub name: String, 442 | } 443 | 444 | impl Label { 445 | pub fn new(span: Range, name: impl Into) -> Self { 446 | Self { 447 | span, 448 | name: name.into(), 449 | } 450 | } 451 | } 452 | 453 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 454 | pub struct Symbol { 455 | pub span: Range, 456 | pub name: String, 457 | } 458 | 459 | impl Symbol { 460 | pub fn new(span: Range, name: impl Into) -> Self { 461 | Self { 462 | span, 463 | name: name.into(), 464 | } 465 | } 466 | } 467 | -------------------------------------------------------------------------------- /ari.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 19 | 28 | 35 | 39 | 43 | 44 | 51 | 55 | 59 | 63 | 64 | 71 | 76 | 81 | 82 | 89 | 93 | 97 | 101 | 102 | 105 | 112 | 116 | 117 | 120 | 127 | 128 | 137 | 138 | 141 | 149 | 152 | 158 | 164 | 170 | 177 | 183 | 184 | 185 | 186 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ari 2 | 3 | 4 | 5 | A type-centred [purely functional 6 | programming](https://en.wikipedia.org/wiki/Purely_functional_programming) 7 | language designed to type binary files. 8 | 9 | Funding for Ari is provided by [NLnet](https://nlnet.nl) and the 10 | European Commission through the [NGI 11 | Assure](https://www.assure.ngi.eu) initiative. 12 | 13 | ## Why does this exist? 14 | 15 | ### To make binary files more accessible 16 | 17 | Most binary files require specially designed tools to read & write, 18 | but ari types are designed so that you can decompose any binary file 19 | down into its component parts. The language is intended to be a 20 | foundation for other tools to build on top of. 21 | 22 | Some of the tools we plan on building with ari include: 23 | 24 | #### arie 25 | 26 | An editor specially designed to edit files using ari types. 27 | 28 | We'll also build plugins for existing text editors. 29 | 30 | #### ariq 31 | 32 | A command line tool to query components of a file using ari types. 33 | 34 | #### aric 35 | 36 | A command line tool to compile ari types into other languages using 37 | [ari map types](#exponentiate-and-map-expressions). 38 | 39 | #### arid 40 | 41 | A command line tool to structurally diff files of the same ari type. 42 | 43 | #### ariz 44 | 45 | A command line tool to compress files & directories using ari types. 46 | 47 | Ari's type system is designed to act as a guide for [arithmetic 48 | coding](https://en.wikipedia.org/wiki/Arithmetic_coding). 49 | 50 | ### ... but also, not just binary formats 51 | 52 | While the primary focus is to help interpret binary data, ari is also 53 | designed to model grammars for text-based languages. 54 | 55 | Here is a quick comparison of how some formal language concepts map 56 | into ari: 57 | 58 | > **NOTE:** This comparison is meant for people who are already 59 | > familiar with these concepts. 60 | > 61 | > If you want to get a better understanding of what they mean, or what 62 | > the ari equivalents mean, see the [language 63 | > reference](#language-reference). 64 | 65 | 66 | 67 | 68 | 222 | 223 | 280 | 281 | 282 |
69 | 70 | 71 | 72 | 73 | 80 | 87 | 88 | 89 | 90 | 97 | 110 | 111 | 112 | 113 | 120 | 127 | 128 | 129 | 130 | 137 | 144 | 145 | 146 | 147 | 154 | 161 | 162 | 163 | 164 | 171 | 178 | 179 | 180 | 181 | 188 | 201 | 202 | 203 | 204 | 211 | 218 | 219 | 220 |
RegexAri
74 | 75 | ```regex 76 | a|b|c 77 | ``` 78 | 79 | 81 | 82 | ```lisp 83 | (| "a" "b" "c") 84 | ``` 85 | 86 |
91 | 92 | ```regex 93 | abc 94 | ``` 95 | 96 | 98 | 99 | ```lisp 100 | "abc" 101 | ``` 102 | 103 | or 104 | 105 | ```lisp 106 | (* "a" "b" "c") 107 | ``` 108 | 109 |
114 | 115 | ```regex 116 | a? 117 | ``` 118 | 119 | 121 | 122 | ```lisp 123 | (^ "a" ?) 124 | ``` 125 | 126 |
131 | 132 | ```regex 133 | a* 134 | ``` 135 | 136 | 138 | 139 | ```lisp 140 | (^ "a" _) 141 | ``` 142 | 143 |
148 | 149 | ```regex 150 | a+ 151 | ``` 152 | 153 | 155 | 156 | ```lisp 157 | (^ "a" !) 158 | ``` 159 | 160 |
165 | 166 | ```regex 167 | a{3} 168 | ``` 169 | 170 | 172 | 173 | ```lisp 174 | (^ "a" 3) 175 | ``` 176 | 177 |
182 | 183 | ```regex 184 | a{2, 5} 185 | ``` 186 | 187 | 189 | 190 | ```lisp 191 | (^ "a" (.. 2 5)) 192 | ``` 193 | 194 | or 195 | 196 | ```lisp 197 | (^ "a" (| 2 3 4)) 198 | ``` 199 | 200 |
205 | 206 | ```regex 207 | . 208 | ``` 209 | 210 | 212 | 213 | ```lisp 214 | codepoint 215 | ``` 216 | 217 |
221 |
224 | 225 | 226 | 227 | 228 | 235 | 242 | 243 | 244 | 245 | 252 | 259 | 260 | 261 | 262 | 269 | 276 | 277 | 278 |
Backus–Naur formAri
229 | 230 | ```bnf 231 | "terminal" 232 | ``` 233 | 234 | 236 | 237 | ```lisp 238 | "terminal" 239 | ``` 240 | 241 |
246 | 247 | ```bnf 248 | 249 | ``` 250 | 251 | 253 | 254 | ```lisp 255 | non-terminal 256 | ``` 257 | 258 |
263 | 264 | ```bnf 265 | ::= "ab" | "cd" 266 | ``` 267 | 268 | 270 | 271 | ```lisp 272 | :symbol (| "ab" (* "cd" x)) 273 | ``` 274 | 275 |
279 |
283 | 284 | ## What makes ari unique? 285 | 286 | ### Types are the main focus of the language 287 | 288 | In ari, everything is a type. Types and type expressions are the 289 | primary focus of the language. You can add, multiply, and even 290 | exponentiate types, much like you can a number in any other 291 | programming language. 292 | 293 | 294 | 295 | 296 | 297 | 304 | 310 | 311 | 312 | 313 | 320 | 331 | 332 | 333 | 334 | 341 | 354 | 355 |
Ari type expressionsEquivalent types
298 | 299 | ```lisp 300 | :sum (+ a b c) 301 | ``` 302 | 303 | 305 | 306 | - [enum](https://en.wikipedia.org/wiki/Enumerated_type) 307 | - [tagged union](https://en.wikipedia.org/wiki/Tagged_union) 308 | 309 |
314 | 315 | ```lisp 316 | :product (* a b c) 317 | ``` 318 | 319 | 321 | 322 | - [record, struct, 323 | tuple]() 324 | - [class]() 325 | - [trait]() 326 | - [concept, 327 | interface]() 328 | - [protocol]() 329 | 330 |
335 | 336 | ```lisp 337 | :map (^ a b c) 338 | ``` 339 | 340 | 342 | 343 | - [function type 344 | signature](https://en.wikipedia.org/wiki/Type_signature) 345 | - [associative array, map, 346 | dictionary](https://en.wikipedia.org/wiki/Associative_array) 347 | - [array type](https://en.wikipedia.org/wiki/Array_data_type) 348 | - [stack](https://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29) 349 | - [matrix]() 350 | - [vector space](https://en.wikipedia.org/wiki/Vector_space) 351 | - [tensor](https://en.wikipedia.org/wiki/Tensor) 352 | 353 |
356 | 357 | See the [language reference](#language-reference) 358 | 359 | ### Generalizes the idea of primitive types 360 | 361 | In ari, there are infinitely many primitives types generalized by a 362 | single concept, [natural 363 | numbers](https://en.wikipedia.org/wiki/Natural_number). We call these 364 | primitive types [natural types](#natural-expressions). 365 | 366 | ...well what exactly does this mean? Say you want to create a `size` 367 | type that has 3 possible states, `small`, `medium`, `large`. In ari, 368 | you can precisely type the number of states using the `3` type: 369 | 370 | ```lisp 371 | :size 3 372 | ``` 373 | 374 | The possible values of this type are `0`, `1`, `2`, which you can use 375 | to represent `small`, `medium`, `large`. This is a powerful concept, 376 | but this small example doesn't fit with the main goal of ari, to make 377 | things more accessible. 378 | 379 | ...this is exactly where [algebraic 380 | expressions](#algebraic-expressions) and [labels](#label-expressions) 381 | come in! You can break down and label the individual states of a `3` 382 | type with a [sum expression](#additive-expressions). For example, this 383 | sum expression produces a sum type that's equivalent to the `3` type: 384 | 385 | ```lisp 386 | :size (+ :small 1 :medium 1 :large 1) 387 | ``` 388 | 389 | and the labelled states in this example have a 1:1 correspondence with 390 | the `3` type: 391 | 392 | - `small` = `0` 393 | - `medium` = `1` 394 | - `large` = `2` 395 | 396 | The whole idea of ari is that binary data can be interpreted as one 397 | giant number, and we provide ways to break big numbers down into 398 | smaller numbers... and label them 🙂. 399 | 400 | > **NOTE:** Many other languages can partially model the idea of sum 401 | > types with "enums". The main issue though is enums are often 402 | > "rounded" to the best matching primitive type(s) (usually some kind 403 | > of int type). In ari every possible sum type has an equivalent 404 | > natural type, which allows for a level of precision not possible in 405 | > other type systems. 406 | 407 | ### Value bindings and dependent types 408 | 409 | In ari all types have an implicit binding with a corresponding runtime 410 | value. [Dereference expressions `@`](#dereference-expressions) can be 411 | used on a type to bring this value from "value-space" into 412 | "type-space". 413 | 414 | Here's an example where they're used to describe a 24-bit RGB colour 415 | image with a dynamically sized `width` & `height`: 416 | 417 | ```lisp 418 | :byte (^ :bit 2 :bit-length 8) 419 | :my-image-format 420 | (* 421 | :width byte 422 | :height byte 423 | :image 424 | (^ 425 | :pixel (* :r byte :g byte :b byte) 426 | @width 427 | @height 428 | ) 429 | ) 430 | ``` 431 | 432 | In this example the `@width` and `@height` types are evaluated from 433 | the runtime value of `width` & `height`. 434 | 435 | Expressions are normally evaluated at compile time, but this pushes 436 | the evaluation to runtime. Ari can use the same expressions between 437 | compile time & runtime because it's [purely 438 | functional](https://en.wikipedia.org/wiki/Functional_programming), 439 | meaning that expressions don't depend on any hidden state. 440 | 441 | ### Labels are optional, but you can also label anything 442 | 443 | Most languages force you to name things, even when the name is 444 | redundant or unnecessary. A lot of these languages have to come up 445 | with parallel constructs to match their named counterparts. 446 | eg. `functions ↔ lambdas`, `structs ↔ tuples`... Often there isn't an 447 | unnamed alternative. You'll be forced to decouple & name things even 448 | when an inlined alternative would be easier to understand. 449 | 450 | Ari takes a fundamentally different approach. Any expression can be 451 | inlined without labelling, but also, all expressions can be labelled. 452 | 453 | This gives developers flexibility to do whatever makes the most 454 | sense. Maybe something is only used once and it would be simpler to 455 | just inline it, maybe you don't even know how to name something yet, 456 | but you want to define its structure. Maybe you just want to refer to 457 | a type nested within another type without decoupling it from its 458 | parent. 459 | 460 | When you can label everything, anything can be a module. 461 | 462 | ## What ideas does ari steal? 463 | 464 | Ari steals a bunch of good ideas from various places: 465 | 466 | Academic Inspirations: 467 | 468 | - [Type theory](https://en.wikipedia.org/wiki/Type_theory) & 469 | [algebraic types](https://en.wikipedia.org/wiki/Algebraic_data_type) 470 | - [Group theory](https://en.wikipedia.org/wiki/Group_theory) 471 | - [Set theory](https://en.wikipedia.org/wiki/Set_theory) 472 | - [Curry-Howard 473 | correspondence](https://en.wikipedia.org/wiki/Curry%E2%80%93Howard_correspondence) 474 | - [Arithmetic coding](https://en.wikipedia.org/wiki/Arithmetic_coding) 475 | - [Purely functional 476 | programming](https://en.wikipedia.org/wiki/Purely_functional_programming) 477 | - [Lazy evaluation](https://en.wikipedia.org/wiki/Lazy_evaluation) 478 | - [Currying](https://en.wikipedia.org/wiki/Currying) 479 | - [Homoiconicity](https://en.wikipedia.org/wiki/Homoiconicity) 480 | 481 | Language Inspirations: 482 | 483 | - [Lisp]() 484 | ([s-expressions](https://en.wikipedia.org/wiki/S-expression) - ari 485 | is not a lisp, homoiconicity, functional-focused) 486 | - [Rust](https://www.rust-lang.org) (sum types & other algebraic 487 | types) 488 | - [Nix](https://nixos.org/manual/nix/stable/expressions/expression-language.html) 489 | (purely functional, lazily evaluated, currying) 490 | - [Haskell](https://www.haskell.org) (indirectly through Rust & Nix + 491 | monads) 492 | 493 | ## Language reference 494 | 495 | ### Atomic expressions 496 | 497 | These are the predefined base expressions of ari, they produce the 498 | "atoms" for [symbolic expressions](#symbolic-expressions). 499 | 500 | #### Natural expressions 501 | 502 | ```lisp 503 | 0 1 2 3 ... 504 | ``` 505 | 506 | Produce the [primitive 507 | types](https://en.wikipedia.org/wiki/Primitive_data_type) of the 508 | language, modelled after [natural 509 | numbers](https://en.wikipedia.org/wiki/Natural_number). Its "value" 510 | encodes the number of possible states that can exist in the type. 511 | 512 | ##### Bottom expression 513 | 514 | ```lisp 515 | 0 516 | ``` 517 | 518 | Produces the [bottom type 519 | `⊥`](https://en.wikipedia.org/wiki/Bottom_type), which has no possible 520 | states. You can think of this as the "error type". 521 | 522 | This is the [identity 523 | type](https://en.wikipedia.org/wiki/Identity_element) for [sum 524 | expressions](#add-and-sum-expressions): 525 | 526 | ```lisp 527 | (= 528 | (+ x 0) 529 | x 530 | ) 531 | ``` 532 | 533 | There are certain contexts that propagate the bottom type: 534 | 535 | - [Product expressions](#multiply-and-product-expressions) 536 | - The base of [map expressions](#exponentiate-and-map-expressions) 537 | 538 | This "error propagation" can be "caught" by other expressions. For 539 | example: 540 | 541 | ```lisp 542 | (+ 256 (* 256 0)) 543 | ``` 544 | 545 | `(* 256 0)` evaluates to `0`, the bottom type, but `(+ 256 0)` 546 | evaluates to `256`... which is not the bottom type. This [sum 547 | expression](#add-and-sum-expressions) catches the error! 548 | 549 | This doesn't _seem_ useful when only working with natural expressions, 550 | why not just remove expressions that propagate the bottom type? 551 | Well.... types can also be evaluated at runtime with [dereference 552 | expressions `@`](#dereference-expressions), and we use this same idea 553 | to catch runtime errors. 554 | 555 | ##### Unit expression 556 | 557 | ```lisp 558 | 1 559 | ``` 560 | 561 | Produces the [unit type](https://en.wikipedia.org/wiki/Unit_type), 562 | which has only one possible state. You can think of this as a type 563 | that doesn't actually store any information. 564 | 565 | This is the [identity 566 | type](https://en.wikipedia.org/wiki/Identity_element) for [product 567 | expressions](#add-and-sum-expressions): 568 | 569 | ```lisp 570 | (= 571 | (* x 1) 572 | x 573 | ) 574 | ``` 575 | 576 | #### Label expressions 577 | 578 | ```lisp 579 | :label 123 580 | ``` 581 | 582 | Define a name for the result of an expression in the current scope. 583 | 584 | #### Symbol expressions 585 | 586 | ```lisp 587 | symbol 588 | ``` 589 | 590 | Produce "symbol types", which are equivalent to whatever type is 591 | associated with `symbol` in the current scope. 592 | 593 | #### Value expressions 594 | 595 | In ari, all types are implicitly bound to a corresponding runtime 596 | value. Value expressions are used to refer to these runtime values. 597 | 598 | They can only be used in: 599 | 600 | - [Product expressions](#multiply-and-product-expressions) 601 | - The base of [map expressions](#exponentiate-and-map-expressions) 602 | 603 | > **NOTE:** These are the same contexts that propagate the [bottom 604 | > type `0`](#bottom-expression). 605 | 606 | ##### Reference expressions 607 | 608 | ```lisp 609 | $symbol 610 | ``` 611 | 612 | Produce "reference types", which are bound to the same runtime value 613 | of `symbol`, but are equivalent to [`1`](#unit-expression). 614 | 615 | ##### Dereference expressions 616 | 617 | ```lisp 618 | @symbol 619 | ``` 620 | 621 | When applied to symbol types, produce a type from the runtime value of 622 | the symbol type. 623 | 624 | ```lisp 625 | @123 626 | @(+ :small 1 :medium 1 :large) 627 | ``` 628 | 629 | When applied to non-symbol types, produce an "effective type" from the 630 | runtime value of the non-symbol type. 631 | 632 | "Effective types" don't have an associated runtime value. 633 | 634 | #### Path expressions 635 | 636 | ```lisp 637 | symbol:x:y:z 638 | (* :x (* :y (* :z 256))):x:y:z 639 | ``` 640 | 641 | Produce a nested type contained within another type. 642 | 643 | #### Extended symbol expressions 644 | 645 | ```ari 646 | '(symbol)' 647 | ``` 648 | 649 | Produce symbols that can include non-whitespace special characters. 650 | 651 | To encode quotes in this expression, double them up: 652 | 653 | ```ari 654 | '''quoted''' 655 | ``` 656 | 657 | > **NOTE:** To get a better understating of how this works, these 658 | > expressions only terminate after an odd sequence of quotes. Then all 659 | > terminating quotes (except for the last) are interpreted as part of 660 | > the symbol. 661 | 662 | Any characters following whitespace will be treated as documentation: 663 | 664 | ```lisp 665 | :'pixel A 24bit RGB pixel' 666 | (* :r 256 :g 256 :b 256) 667 | 668 | 'pixel Here we're referencing pixel' 669 | ``` 670 | 671 | #### Unicode text expressions 672 | 673 | ```ari 674 | "()" 675 | ``` 676 | 677 | A convenient notation for defining text-based grammars, which is 678 | actually just syntax sugar for runtime [assertion 679 | expressions](#assertion-expressions) that assert for 680 | [Unicode](https://en.wikipedia.org/wiki/Unicode) text. 681 | 682 | To encode quotes in this expression, double them up: 683 | 684 | ```ari 685 | "{ 686 | ""abc"": 123 687 | }" 688 | ``` 689 | 690 | > **NOTE** This follows the same behaviour as [extended symbol 691 | > expressions](#extended-symbol-expressions) 692 | 693 | Text not bound to any particular encoding context will be interpreted 694 | as utf-8, but this can be changed with text encoding macros: 695 | 696 | ```lisp 697 | (= 698 | (ascii-8 "text") 699 | (ascii "text") 700 | ) 701 | (ascii-7 "text") 702 | (utf-16 "text") 703 | (utf-32 "text") 704 | ``` 705 | 706 | ##### Codepoint symbol 707 | 708 | ```lisp 709 | codepoint 710 | ``` 711 | 712 | Represents a single Unicode [code 713 | point](https://en.wikipedia.org/wiki/Code_point) for text in the 714 | current text encoding context. This can be dynamically sized. 715 | 716 | ##### Grapheme symbol 717 | 718 | ```lisp 719 | grapheme 720 | ``` 721 | 722 | Represents a single Unicode 723 | [grapheme](https://en.wikipedia.org/wiki/Grapheme) for text in the 724 | current text encoding context. This can be dynamically sized. 725 | 726 | ### Symbolic expressions 727 | 728 | ```lisp 729 | (sexpr arg1 arg2 arg3) 730 | ``` 731 | 732 | Symbolic expressions are a list of [atomic 733 | expressions](#atomic-expressions), separated by whitespace & wrapped 734 | by parenthesis. 735 | 736 | The first element is treated as a function, and the remaining elements 737 | are passed as inputs to that function. 738 | 739 | These are considered "symbolic expressions" because their behaviour 740 | depends on the symbols defined in the current scope. 741 | 742 | These modelled after lisp 743 | [s-expressions](https://en.wikipedia.org/wiki/S-expression), but are 744 | different in a few ways: 745 | 746 | - Ari doesn't have [cons cells](https://en.wikipedia.org/wiki/Cons), 747 | so symbolic expressions aren't implemented with cons cells. The 748 | closest concept to cons cells are [product 749 | expressions](#multiply-and-product-expressions). 750 | 751 | - Symbolic expressions form a lexical scope from the [label 752 | expressions](#label-expressions) it contains. This means that "let" 753 | expressions are embedded in all symbolic expressions. 754 | 755 | #### Assertion expressions 756 | 757 | ```lisp 758 | :equal (= a b c) 759 | ``` 760 | 761 | [Asserts]() 762 | that all arguments have the same number of possible states. If they 763 | do, this evaluates to the last argument, otherwise it evaluates to 764 | [`0`](#bottom-expression). 765 | 766 | 767 | 768 | 769 | 770 | #### Algebraic expressions 771 | 772 | ##### Additive expressions 773 | 774 | ###### Add and sum expressions 775 | 776 | ```lisp 777 | :add (+ a b) 778 | ``` 779 | 780 | Given natural inputs, produces a [sum type 781 | `∑`](https://en.wikipedia.org/wiki/Tagged_union), which is either `a` 782 | or `b`. This adds together the number of possible states between the 783 | two types. 784 | 785 | We derive a nary form of add `+` by repeated application of 786 | associativity: 787 | 788 | ```lisp 789 | :additive-associativity 790 | (= 791 | (+ (+ a b) c) 792 | (+ a (+ b c) 793 | (+ a b c) 794 | ) 795 | ``` 796 | 797 | ###### Additive inverse expressions 798 | 799 | ```lisp 800 | :subtract (- a b) 801 | ``` 802 | 803 | Produces an [integer type `ℤ`](https://en.wikipedia.org/wiki/Integer) 804 | that subtracts the first few `b` states from `a`. 805 | 806 | Combined with the [additive identity `0`](#bottom-expression), we 807 | derive a unary form of subtract `-`: 808 | 809 | ```lisp 810 | :negative 811 | (= 812 | (- 0 x) 813 | (- x) 814 | ) 815 | ``` 816 | 817 | ###### Additive group theory 818 | 819 | Additive expressions form an [abelian 820 | group](https://en.wikipedia.org/wiki/Abelian_group) in type-space, and 821 | a [non-abelian](https://en.wikipedia.org/wiki/Non-abelian_group) group 822 | in value-space. 823 | 824 | ##### Multiplicative expressions 825 | 826 | ###### Multiply and product expressions 827 | 828 | ```lisp 829 | :multiply (* a b) 830 | ``` 831 | 832 | Given natural inputs, produces a [product type 833 | `Π`](https://en.wikipedia.org/wiki/Product_type), which has both `a` 834 | and `b`. This multiplies the number of possible states between the two 835 | types. 836 | 837 | We derive a nary form of multiply `*` by repeated application of 838 | associativity: 839 | 840 | ```lisp 841 | :multiplicative-associativity 842 | (= 843 | (* (* a b) c) 844 | (* a (* b c)) 845 | (* a b c) 846 | ) 847 | ``` 848 | 849 | ###### Multiplicative inverse expressions 850 | 851 | ```lisp 852 | :divide (/ a b) 853 | ``` 854 | 855 | Produces a [rational type 856 | `ℚ`](https://en.wikipedia.org/wiki/Rational_number) type that divides 857 | `b` states out of `a`. 858 | 859 | Combined with the [multiplicative identity `1`](#unit-expression), we 860 | derive a unary form of divide `/`: 861 | 862 | ```lisp 863 | :inverse 864 | (= 865 | (/ 1 x) 866 | (/ x) 867 | ) 868 | ``` 869 | 870 | ###### Multiplicative group theory 871 | 872 | Multiplicative expressions form an [abelian 873 | group](https://en.wikipedia.org/wiki/Abelian_group) in type-space, and 874 | a [non-abelian](https://en.wikipedia.org/wiki/Non-abelian_group) group 875 | in value-space. 876 | 877 | ##### Exponentiation expressions 878 | 879 | ###### Exponentiate and map expressions 880 | 881 | ```lisp 882 | :exponentiate (^ b e) 883 | ``` 884 | 885 | Given natural inputs, produces a [map type 886 | `→`](https://en.wikipedia.org/wiki/Associative_array), which maps the 887 | exponent `e` to the base `b`. This raises the number of possible 888 | states in `b` to the power of the number of possible states in `e`. 889 | 890 | Exponentiation is non-associative, but we derive a nary form of 891 | exponentiate `^` through 892 | [currying](https://en.wikipedia.org/wiki/Currying). Which is just 893 | repeated application of the [power of a power 894 | identity](https://en.wikipedia.org/wiki/Exponentiation#Identities_and_properties): 895 | 896 | ```lisp 897 | :power-of-a-power-identity 898 | (= 899 | (^ (^ a b) c) 900 | (^ a (* b c)) 901 | (^ a b c) 902 | ) 903 | ``` 904 | 905 | ###### Exponentiation left inverse expression 906 | 907 | ```lisp 908 | :logarithm (log b x) 909 | ``` 910 | 911 | Produces a [complex type 912 | ℂ](https://en.wikipedia.org/wiki/Complex_number), which treats `x` 913 | like a map type (even if it's not), and computes the exponent `e` 914 | given the base `b`. 915 | 916 | ###### Exponentiation right inverse expression 917 | 918 | ```lisp 919 | :root (root x e) 920 | ``` 921 | 922 | Produces a [complex type 923 | ℂ](https://en.wikipedia.org/wiki/Complex_number), which treats `x` 924 | like a map type (even if it's not), and computes the base `b` given 925 | the exponent `e`. 926 | 927 | `root` is actually just syntax sugar for exponentiation with a 928 | multiplicative inverse: 929 | 930 | ```lisp 931 | :root 932 | (= 933 | (^ x (/ e)) 934 | (root x e) 935 | ) 936 | ``` 937 | 938 | ###### Exponentiation group theory 939 | 940 | Exponentiation expressions form a 941 | [quasigroup](https://en.wikipedia.org/wiki/Quasigroup) in both 942 | type-space & value-space. 943 | 944 | #### Set expressions 945 | 946 | Sets let you interpret a single value as multiple different 947 | types. This is particularly useful when you don't actually know what 948 | the type is, but the type can be deduced by its contents. 949 | 950 | ##### Singletons 951 | 952 | All types are implicitly treated as 953 | [singletons](). These 954 | are sets with exactly one type. 955 | 956 | ##### Empty set expression 957 | 958 | ```lisp 959 | :empty-set () 960 | ``` 961 | 962 | Produces the [empty set](https://en.wikipedia.org/wiki/Empty_set). A 963 | set with no types. 964 | 965 | ##### Top expression 966 | 967 | ```lisp 968 | :top-type _ 969 | ``` 970 | 971 | Produces what is called a [top type 972 | `⊤`](https://en.wikipedia.org/wiki/Top_type), but it's not exactly a 973 | "type". It's a set containing every possible type. 974 | 975 | `_` is actually just syntax sugar for any type that directly 976 | references itself: 977 | 978 | ```lisp 979 | :_ _ 980 | ``` 981 | 982 | ##### Union expressions 983 | 984 | ```lisp 985 | :union (| a b) 986 | ``` 987 | 988 | Produces a set which takes the 989 | [union]() between `a` 990 | and `b`. 991 | 992 | We derive an nary form of union `|` by repeated application of 993 | associativity: 994 | 995 | ```lisp 996 | :union-associativity 997 | (= 998 | (| (| a b) c) 999 | (| a (| b c) 1000 | (| a b c) 1001 | ) 1002 | ``` 1003 | 1004 | ###### Zero or one expression 1005 | 1006 | ```lisp 1007 | ? 1008 | ``` 1009 | 1010 | Syntax sugar for the [union `|`](#union-expressions) between 1011 | [`0`](#bottom-expression) and [`1`](#unit-expression): 1012 | 1013 | ```lisp 1014 | :? (| 0 1) 1015 | ``` 1016 | 1017 | ##### Symmetric difference expression 1018 | 1019 | ```lisp 1020 | :symmetric-difference (~ a b) 1021 | ``` 1022 | 1023 | Produces a set which takes the [symmetric 1024 | difference](https://en.wikipedia.org/wiki/Symmetric_difference) 1025 | between `a` and `b`. 1026 | 1027 | symmetric-difference `~` is actually just syntax sugar for the union 1028 | `|` of both relative complements `!`: 1029 | 1030 | ```lisp 1031 | (= 1032 | (| (! a b) (! b a)) 1033 | (~ a b) 1034 | ) 1035 | ``` 1036 | 1037 | ##### Intersection expressions 1038 | 1039 | ```lisp 1040 | :intersection (& a b) 1041 | ``` 1042 | 1043 | Produces a set which takes the 1044 | [intersection]() 1045 | between `a` and `b`. 1046 | 1047 | We derive an nary form of intersection `&` by repeated application of 1048 | associativity: 1049 | 1050 | ```lisp 1051 | :intersection-associativity 1052 | (= 1053 | (& (& a b) c) 1054 | (& a (& b c) 1055 | (& a b c) 1056 | ) 1057 | ``` 1058 | 1059 | ##### Complement expressions 1060 | 1061 | ```lisp 1062 | :relative-complement (! a b) 1063 | ``` 1064 | 1065 | Produces a set which takes the [relative 1066 | complement]() 1067 | of `a` in `b`. 1068 | 1069 | Combined with the top type `_`, we derive a unary form of 1070 | relative-complement `!`: 1071 | 1072 | ```lisp 1073 | :complement 1074 | (= 1075 | (! x _) 1076 | (! x) 1077 | ) 1078 | ``` 1079 | 1080 | ###### One or more expression 1081 | 1082 | ```lisp 1083 | :one-or-more 1084 | (= 1085 | (! 0) 1086 | !) 1087 | ``` 1088 | 1089 | Syntax sugar for the [complement `!`](#complement-expressions) of 1090 | [`0`](#bottom-expression): 1091 | 1092 | ##### Interval expression 1093 | 1094 | ```lisp 1095 | :interval (.. a b) 1096 | ``` 1097 | 1098 | Produces a half-open 1099 | [interval]() 1100 | between `a` & `b`, where `b` is excluded. 1101 | 1102 | Combined with the empty set `()`, we derive a unary form of interval 1103 | `..`: 1104 | 1105 | ```lisp 1106 | (= 1107 | (.. () b) 1108 | (.. b) 1109 | ) 1110 | ``` 1111 | 1112 | 1113 | 1114 | 1115 | 1116 | 1120 | 1121 | ## License 1122 | 1123 | Copyright (C) 2023 Kira Bruneau 1124 | 1125 | This program is free software: you can redistribute it and/or modify 1126 | it under the terms of the GNU General Public License as published by 1127 | the Free Software Foundation, either version 3 of the License, or (at 1128 | your option) any later version. 1129 | 1130 | This program is distributed in the hope that it will be useful, but 1131 | WITHOUT ANY WARRANTY; without even the implied warranty of 1132 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 1133 | General Public License for more details. 1134 | 1135 | You should have received a copy of the GNU General Public License 1136 | along with this program. If not, see . 1137 | 1138 | ### Why is this licensed under the GPL instead of the LGPL? 1139 | 1140 | This was a difficult decision. By licensing this under the GPL, not 1141 | only are we preventing proprietary software from being combined with 1142 | ari, but also open source software using a license that's incompatible 1143 | with the GPL. 1144 | 1145 | This restriction may _seem_ to go against our goal of making binary 1146 | data more open & accessible, but it very much works in favour of it. 1147 | 1148 | Proprietary software is designed to restrict the freedoms of its users 1149 | for profit. By allowing ari to be used in proprietary software, we'd 1150 | be perpetuating the idea that software should be hard to access & 1151 | modify. This is exactly what we don't want. 1152 | 1153 | This doesn't mean that users are restricted from using ari along side 1154 | proprietary software. The GPL is designed in a way to take away 1155 | freedoms from developers, and give as many freedoms as possible back 1156 | to users. 1157 | 1158 | This license just requires that proprietary (or open source software 1159 | with a license allowing for integration with proprietary software) 1160 | can't be built on top of, or packaged together with ari. 1161 | 1162 | See [why you shouldn't use the Lesser GPL for your next 1163 | library](https://www.gnu.org/licenses/why-not-lgpl.html). 1164 | 1165 | 1166 | 1167 | 1168 | 1169 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------