1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
// Written in 2019 by Andrew Poelstra <apoelstra@wpsoftware.net>
// SPDX-License-Identifier: CC0-1.0
//! # Function-like Expression Language
//!
use core::str::FromStr;
use crate::prelude::*;
use crate::{errstr, Error, MAX_RECURSION_DEPTH};
#[derive(Debug)]
/// A token of the form `x(...)` or `x`
pub struct Tree<'a> {
/// The name `x`
pub name: &'a str,
/// The comma-separated contents of the `(...)`, if any
pub args: Vec<Tree<'a>>,
}
// or_b(pk(A),pk(B))
//
// A = musig(musig(B,C),D,E)
// or_b()
// pk(A), pk(B)
/// A trait for extracting a structure from a Tree representation in token form
pub trait FromTree: Sized {
/// Extract a structure from Tree representation
fn from_tree(top: &Tree) -> Result<Self, Error>;
}
enum Found {
Nothing,
LBracket(usize), // Either a left ( or {
Comma(usize),
RBracket(usize), // Either a right ) or }
}
fn next_expr(sl: &str, delim: char) -> Found {
let mut found = Found::Nothing;
if delim == '(' {
for (n, ch) in sl.char_indices() {
match ch {
'(' => {
found = Found::LBracket(n);
break;
}
',' => {
found = Found::Comma(n);
break;
}
')' => {
found = Found::RBracket(n);
break;
}
_ => {}
}
}
} else if delim == '{' {
let mut new_count = 0;
for (n, ch) in sl.char_indices() {
match ch {
'{' => {
found = Found::LBracket(n);
break;
}
'(' => {
new_count += 1;
}
',' => {
if new_count == 0 {
found = Found::Comma(n);
break;
}
}
')' => {
new_count -= 1;
}
'}' => {
found = Found::RBracket(n);
break;
}
_ => {}
}
}
} else {
unreachable!("{}", "Internal: delimiters in parsing must be '(' or '{'");
}
found
}
// Get the corresponding delim
fn closing_delim(delim: char) -> char {
match delim {
'(' => ')',
'{' => '}',
_ => unreachable!("Unknown delimiter"),
}
}
impl<'a> Tree<'a> {
/// Parse an expression with round brackets
pub fn from_slice(sl: &'a str) -> Result<(Tree<'a>, &'a str), Error> {
// Parsing TapTree or just miniscript
Self::from_slice_delim(sl, 0u32, '(')
}
pub(crate) fn from_slice_delim(
mut sl: &'a str,
depth: u32,
delim: char,
) -> Result<(Tree<'a>, &'a str), Error> {
if depth >= MAX_RECURSION_DEPTH {
return Err(Error::MaxRecursiveDepthExceeded);
}
match next_expr(sl, delim) {
// String-ending terminal
Found::Nothing => Ok((
Tree {
name: sl,
args: vec![],
},
"",
)),
// Terminal
Found::Comma(n) | Found::RBracket(n) => Ok((
Tree {
name: &sl[..n],
args: vec![],
},
&sl[n..],
)),
// Function call
Found::LBracket(n) => {
let mut ret = Tree {
name: &sl[..n],
args: vec![],
};
sl = &sl[n + 1..];
loop {
let (arg, new_sl) = Tree::from_slice_delim(sl, depth + 1, delim)?;
ret.args.push(arg);
if new_sl.is_empty() {
return Err(Error::ExpectedChar(closing_delim(delim)));
}
sl = &new_sl[1..];
match new_sl.as_bytes()[0] {
b',' => {}
last_byte => {
if last_byte == closing_delim(delim) as u8 {
break;
} else {
return Err(Error::ExpectedChar(closing_delim(delim)));
}
}
}
}
Ok((ret, sl))
}
}
}
/// Parses a tree from a string
#[allow(clippy::should_implement_trait)] // Cannot use std::str::FromStr because of lifetimes.
pub fn from_str(s: &'a str) -> Result<Tree<'a>, Error> {
// Filter out non-ASCII because we byte-index strings all over the
// place and Rust gets very upset when you splinch a string.
for ch in s.bytes() {
if !ch.is_ascii() {
return Err(Error::Unprintable(ch));
}
}
let (top, rem) = Tree::from_slice(s)?;
if rem.is_empty() {
Ok(top)
} else {
Err(errstr(rem))
}
}
}
/// Parse a string as a u32, for timelocks or thresholds
pub fn parse_num(s: &str) -> Result<u32, Error> {
if s.len() > 1 {
let ch = s.chars().next().unwrap();
if !('1'..='9').contains(&ch) {
return Err(Error::Unexpected(
"Number must start with a digit 1-9".to_string(),
));
}
}
u32::from_str(s).map_err(|_| errstr(s))
}
/// Attempts to parse a terminal expression
pub fn terminal<T, F, Err>(term: &Tree, convert: F) -> Result<T, Error>
where
F: FnOnce(&str) -> Result<T, Err>,
Err: ToString,
{
if term.args.is_empty() {
convert(term.name).map_err(|e| Error::Unexpected(e.to_string()))
} else {
Err(errstr(term.name))
}
}
/// Attempts to parse an expression with exactly one child
pub fn unary<L, T, F>(term: &Tree, convert: F) -> Result<T, Error>
where
L: FromTree,
F: FnOnce(L) -> T,
{
if term.args.len() == 1 {
let left = FromTree::from_tree(&term.args[0])?;
Ok(convert(left))
} else {
Err(errstr(term.name))
}
}
/// Attempts to parse an expression with exactly two children
pub fn binary<L, R, T, F>(term: &Tree, convert: F) -> Result<T, Error>
where
L: FromTree,
R: FromTree,
F: FnOnce(L, R) -> T,
{
if term.args.len() == 2 {
let left = FromTree::from_tree(&term.args[0])?;
let right = FromTree::from_tree(&term.args[1])?;
Ok(convert(left, right))
} else {
Err(errstr(term.name))
}
}
#[cfg(test)]
mod tests {
use super::parse_num;
#[test]
fn test_parse_num() {
assert!(parse_num("0").is_ok());
assert!(parse_num("00").is_err());
assert!(parse_num("0000").is_err());
assert!(parse_num("06").is_err());
assert!(parse_num("+6").is_err());
assert!(parse_num("-6").is_err());
}
}