Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,17 @@
|
||||
use std::alloc::{GlobalAlloc, Layout, System};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
struct Counting;
|
||||
static ALLOCATIONS: AtomicUsize = AtomicUsize::new(0);
|
||||
unsafe impl GlobalAlloc for Counting {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
ALLOCATIONS.fetch_add(1, Ordering::Relaxed);
|
||||
unsafe { System.alloc(layout) }
|
||||
}
|
||||
unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) { unsafe { System.dealloc(pointer, layout) } }
|
||||
unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, size: usize) -> *mut u8 {
|
||||
ALLOCATIONS.fetch_add(1, Ordering::Relaxed);
|
||||
unsafe { System.realloc(pointer, layout, size) }
|
||||
}
|
||||
}
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: Counting = Counting;
|
||||
@@ -0,0 +1,8 @@
|
||||
flow readArgs() (out: List<Text>)
|
||||
| step | kind | do |
|
||||
| out | flow | dever.process.arguments() |
|
||||
|
||||
flow throughTask() (out: List<Text>)
|
||||
| step | kind | do |
|
||||
| task | calc | run(readArgs()) |
|
||||
| out | calc | wait(task) |
|
||||
@@ -0,0 +1,18 @@
|
||||
use std::ffi::OsString;
|
||||
let expected = std::env::args_os().skip(1).map(OsString::into_string).collect::<Result<Vec<_>, _>>();
|
||||
if let Ok(expected) = expected {
|
||||
assert_eq!(@readArgs@().unwrap(), expected);
|
||||
assert_eq!(dever_runtime::task::run(true, 1, async |scope| @throughTask@(scope).await).unwrap().unwrap(), expected);
|
||||
@allocation_counter@
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let direct = std::env::args_os().skip(1).map(OsString::into_string).collect::<Result<Vec<_>, _>>().unwrap();
|
||||
let direct_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before;
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let generated = @readArgs@().unwrap();
|
||||
let generated_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before;
|
||||
assert_eq!(generated, direct);
|
||||
assert_eq!(generated_allocations, direct_allocations, "boundary must not copy argument strings");
|
||||
} else {
|
||||
let error = @readArgs@().unwrap_err();
|
||||
assert!(matches!(error, Failure::@ArgumentsResult@(@ArgumentsResult@::Failed(message)) if message == "process argument is not UTF-8"));
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
flow hash(password: Secret) (out: Text)
|
||||
| step | kind | do |
|
||||
| out | calc | blocking(dever.crypto.passwordHash(password)) |
|
||||
|
||||
flow verify(password: Secret, hash: Text) (out: Bool)
|
||||
| step | kind | do |
|
||||
| out | calc | blocking(dever.crypto.passwordVerify(password, hash)) |
|
||||
|
||||
flow spawned(password: Secret, hash: Text) (out: Bool)
|
||||
| step | kind | do |
|
||||
| t | calc | run(dever.crypto.passwordVerify(password, hash)) |
|
||||
| out | calc | wait(t) |
|
||||
|
||||
flow pair(password: Secret, hash: Text) (valid: Bool, size: Int)
|
||||
| step | kind | do |
|
||||
| valid | flow | dever.crypto.passwordVerify(password, hash) |
|
||||
| size | calc | length(hash) |
|
||||
|
||||
flow multiple(password: Secret, hash: Text) (out: Int)
|
||||
| step | kind | do |
|
||||
| checked | calc | blocking(pair(password, hash)) |
|
||||
| - | check | checked.valid else Invalid |
|
||||
| out | calc | checked.size |
|
||||
|
||||
flow apply(password: Secret, hash: Text, action: handler(password: Secret, hash: Text) (value: Bool)) (out: Bool)
|
||||
| step | kind | do |
|
||||
| out | calc | blocking(action(password, hash)) |
|
||||
|
||||
flow handled(password: Secret, hash: Text) (out: Bool)
|
||||
| step | kind | do |
|
||||
| out | flow | apply(password, hash, dever.crypto.passwordVerify) |
|
||||
|
||||
flow together(password: Secret, hash: Text) (out: Bool)
|
||||
| step | kind | parallel | do |
|
||||
| first | calc | verify | blocking(dever.crypto.passwordVerify(password, hash)) |
|
||||
| second | calc | verify | blocking(dever.crypto.passwordVerify(password, hash)) |
|
||||
| out | calc | - | first and second |
|
||||
|
||||
type Attempt { Done(value: Bool), error Failed(reason: dever.crypto.VerifyResult) }
|
||||
rule resolved(value: Attempt) (out: Bool) recover("report invalid password encodings as false")
|
||||
| value | out |
|
||||
| Done(valid) | valid |
|
||||
| Failed(reason) | false |
|
||||
|
||||
flow captured(password: Secret, hash: Text) (out: Bool)
|
||||
| step | kind | do |
|
||||
| received: Attempt | calc | result(blocking(dever.crypto.passwordVerify(password, hash))) |
|
||||
| out | rule | resolved(received) |
|
||||
|
||||
guard(value: Text) (out: Text) {
|
||||
check length(value) > 0 else Invalid
|
||||
out = value
|
||||
}
|
||||
flow argumentFailure(password: Secret, hash: Text) (out: Bool)
|
||||
| step | kind | do |
|
||||
| received: Attempt | calc | result(blocking(dever.crypto.passwordVerify(password, guard(hash)))) |
|
||||
| out | rule | resolved(received) |
|
||||
|
||||
flow member(password: Secret, hash: Text) ()
|
||||
| step | kind | do |
|
||||
| valid | flow | dever.crypto.passwordVerify(password, hash) |
|
||||
| - | check | valid else Invalid |
|
||||
|
||||
flow grouped(password: Secret, hash: Text) ()
|
||||
| step | kind | do |
|
||||
| tasks | calc | group(1) |
|
||||
| - | calc | run(tasks, member(password, hash)) |
|
||||
| - | calc | wait(tasks) |
|
||||
|
||||
flow failing(password: Secret, hash: Text, value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| valid | flow | dever.crypto.passwordVerify(password, hash) |
|
||||
| - | check | valid else Invalid |
|
||||
| out | calc | value + 1 |
|
||||
|
||||
flow overflow(password: Secret, hash: Text, value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | calc | blocking(failing(password, hash, value)) |
|
||||
|
||||
flow spawnedOverflow(password: Secret, hash: Text, value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(failing(password, hash, value)) |
|
||||
| out | calc | wait(task) |
|
||||
|
||||
setting password: Secret
|
||||
setting saved_hash: Text
|
||||
flow configuredTarget() (out: Bool)
|
||||
| step | kind | do |
|
||||
| out | flow | dever.crypto.passwordVerify(password, saved_hash) |
|
||||
flow configured() (out: Bool)
|
||||
| step | kind | do |
|
||||
| out | calc | blocking(configuredTarget()) |
|
||||
|
||||
cmd verify = verify
|
||||
@@ -0,0 +1,29 @@
|
||||
use dever_runtime::{task::{self, RunError}, value::secret::Secret};
|
||||
let password = Secret::from_input(b"test-only-password".to_vec());
|
||||
let hash = task::run(true, 1, async |scope| @hash@(scope, password.clone()).await).unwrap().unwrap();
|
||||
assert!(hash.starts_with("$argon2id$v=19$m=19456,t=2,p=1$"));
|
||||
assert!(task::run(true, 1, async |scope| @verify@(scope, password.clone(), hash.clone()).await).unwrap().unwrap());
|
||||
assert!(task::run(true, 1, async |scope| @spawned@(scope, password.clone(), hash.clone()).await).unwrap().unwrap());
|
||||
assert_eq!(task::run(true, 1, async |scope| @multiple@(scope, password.clone(), hash.clone()).await).unwrap().unwrap(), hash.len() as i64);
|
||||
assert!(task::run(true, 1, async |scope| @handled@(scope, password.clone(), hash.clone()).await).unwrap().unwrap());
|
||||
assert!(task::run(true, 1, async |scope| @together@(scope, password.clone(), hash.clone()).await).unwrap().unwrap());
|
||||
task::run(true, 1, async |scope| @grouped@(scope, password.clone(), hash.clone()).await).unwrap().unwrap();
|
||||
assert!(!task::run(true, 1, async |scope| Ok::<_, ()>(@captured@(scope, password.clone(), "invalid".into()).await)).unwrap().unwrap());
|
||||
assert!(matches!(task::run(true, 1, async |scope| @argumentFailure@(scope, password.clone(), String::new()).await).unwrap(), Err(RunError::Business { .. })));
|
||||
for spawned in [false, true] {
|
||||
match task::run(true, 1, async |scope| {
|
||||
if spawned { @spawnedOverflow@(scope, password.clone(), hash.clone(), i64::MAX).await }
|
||||
else { @overflow@(scope, password.clone(), hash.clone(), i64::MAX).await }
|
||||
}).unwrap() {
|
||||
Err(RunError::Fault { primary, additional }) => {
|
||||
assert_eq!(primary.downcast_ref::<&'static FaultInfo>().unwrap().source, @source_path@);
|
||||
assert!(additional.is_empty());
|
||||
}
|
||||
_ => panic!("expected original arithmetic fault"),
|
||||
}
|
||||
}
|
||||
let path = std::path::Path::new(@source_path@).with_extension("json");
|
||||
std::fs::write(&path, format!(r#"{{"module":{{"main":{{"main":{{"password":"test-only-password","saved_hash":"{hash}"}}}}}}}}"#)).unwrap();
|
||||
let settings = load_settings(&path).unwrap();
|
||||
assert!(task::run(true, 1, async |scope| @configured@(scope, &settings).await).unwrap().unwrap());
|
||||
assert_eq!(std::sync::Arc::strong_count(&settings), 1);
|
||||
@@ -0,0 +1,77 @@
|
||||
flow authorize(granted: Bool, level: Int) (out: Bool) {
|
||||
admin = level > 0
|
||||
out = rule (admin, granted) {
|
||||
(true, -) => true
|
||||
(false, true) => true
|
||||
(false, false) => requireGrant(granted)
|
||||
}
|
||||
}
|
||||
|
||||
flow display(value: Text?) (out: Text) {
|
||||
out = rule value {
|
||||
null => "guest"
|
||||
other => value
|
||||
}
|
||||
}
|
||||
|
||||
requireGrant(granted: Bool) (out: Bool) {
|
||||
check granted else Forbidden
|
||||
out = granted
|
||||
}
|
||||
|
||||
type Line {
|
||||
amount: Int
|
||||
discounted: Bool
|
||||
}
|
||||
|
||||
loop totals(lines: List<Line>) (amount: Int, discounted: Bool)
|
||||
line in lines {
|
||||
amount = sum line.amount
|
||||
discounted = any line.discounted
|
||||
}
|
||||
|
||||
flow checkout(level: Int, granted: Bool, lines: List<Line>) (amount: Int) {
|
||||
allowed = authorize(granted, level)
|
||||
check allowed else Forbidden
|
||||
result_row = totals(lines)
|
||||
amount = result_row.amount
|
||||
}
|
||||
|
||||
loop cartStats(lines: List<Line>) (discount: Int, units: Int)
|
||||
line in lines {
|
||||
discount = rule line.discounted {
|
||||
true => sum line.amount
|
||||
false => skip
|
||||
}
|
||||
units = count
|
||||
}
|
||||
|
||||
flow discountTotal(orders: List<List<Line>>) (out: Int) {
|
||||
out = loop order in orders {
|
||||
sum loop item in order {
|
||||
rule item.discounted {
|
||||
true => sum item.amount
|
||||
false => skip
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Refund { id: Int, limited: Bool }
|
||||
|
||||
refundOne(order: Refund) (acc: Int?, stop: Bool) {
|
||||
check order.id > 0 else Invalid
|
||||
acc = pendingRefund(order.limited, order.id)
|
||||
stop = order.limited
|
||||
}
|
||||
|
||||
rule pendingRefund(limited: Bool, id: Int) (out: Int?) limited {
|
||||
true => id
|
||||
false => null
|
||||
}
|
||||
|
||||
flow runRefunds(orders: List<Refund>) (pending: Int?) {
|
||||
pending = loop order in orders {
|
||||
foldUntil(previous = null, refundOne(order))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
encode(text: Text) (data: Bytes) {
|
||||
data = dever.bytes.fromText(text)
|
||||
}
|
||||
|
||||
decode(data: Bytes) (text: Text) {
|
||||
text = dever.bytes.toText(data)
|
||||
}
|
||||
|
||||
buffer(values: List<Int>) (data: Bytes) {
|
||||
data = dever.bytes.fromInts(values)
|
||||
}
|
||||
|
||||
cut(data: Bytes, start: Int, end: Int) (part: Bytes) {
|
||||
part = dever.bytes.slice(data, start, end)
|
||||
}
|
||||
|
||||
joinBytes(left: Bytes, right: Bytes) (data: Bytes) {
|
||||
data = dever.bytes.concat(left, right)
|
||||
}
|
||||
|
||||
byteAt(data: Bytes, index: Int) (value: Int?) {
|
||||
value = dever.bytes.at(data, index)
|
||||
}
|
||||
|
||||
byteSize(data: Bytes) (size: Int) {
|
||||
size = dever.bytes.length(data)
|
||||
}
|
||||
|
||||
loop byteStats(data: Bytes) (total: Int, values: List<Int>, count: Int)
|
||||
| each value in data | result |
|
||||
| total | sum value |
|
||||
| values | list value |
|
||||
| count | count |
|
||||
|
||||
loop byteSum(data: Bytes) (total: Int)
|
||||
| each value in data | result |
|
||||
| total | sum value |
|
||||
|
||||
loop byteFirst(data: Bytes) (out: Int?)
|
||||
| each value in data | result |
|
||||
| out | first value |
|
||||
|
||||
loop byteFiltered(data: Bytes) (values: List<Int>)
|
||||
| each value in data | value | result |
|
||||
| values | >= 128 | list value |
|
||||
|
||||
boundedByte(value: Int >= 0 and <= 255) (out: Int) {
|
||||
out = value
|
||||
}
|
||||
|
||||
loop validBytes(data: Bytes) (out: List<Int>)
|
||||
| each value in data | result |
|
||||
| out | list boundedByte(value) |
|
||||
|
||||
captureDecode(data: Bytes) (out: dever.bytes.DecodeResult) {
|
||||
out = result(dever.bytes.toText(data))
|
||||
}
|
||||
|
||||
captureBuffer(values: List<Int>) (out: dever.bytes.BufferResult) {
|
||||
out = result(dever.bytes.fromInts(values))
|
||||
}
|
||||
|
||||
captureCut(data: Bytes, start: Int, end: Int) (out: dever.bytes.BufferResult) {
|
||||
out = result(dever.bytes.slice(data, start, end))
|
||||
}
|
||||
|
||||
applyEncode(text: Text, encode: handler(text: Text) (bytes: Bytes)) (out: Bytes) {
|
||||
out = encode(text)
|
||||
}
|
||||
|
||||
throughHandler(text: Text) (out: Bytes) {
|
||||
out = applyEncode(text, dever.bytes.fromText)
|
||||
}
|
||||
|
||||
type Packet {
|
||||
data: Bytes
|
||||
name: Text
|
||||
}
|
||||
|
||||
keepPacket(packet: Packet) (part: Bytes, original: Packet) {
|
||||
part = dever.bytes.slice(packet.data, 1, 3)
|
||||
original = packet
|
||||
}
|
||||
|
||||
loop repeatedSlice(data: Bytes) (out: List<Bytes>)
|
||||
| each index in range(0, 3) | result |
|
||||
| out | list dever.bytes.slice(data, index, index + 1) |
|
||||
|
||||
appendChunk(chunk: Bytes, state: Bytes) (out: Bytes) {
|
||||
out = dever.bytes.concat(state, chunk)
|
||||
}
|
||||
|
||||
loop concatAll(chunks: List<Bytes>, seed: Bytes) (out: Bytes)
|
||||
| each chunk in chunks | result |
|
||||
| out | fold(acc = seed, appendChunk(chunk, acc)) |
|
||||
|
||||
loop encodeParts(chunks: List<Text>) (out: List<Bytes>)
|
||||
| each chunk in chunks | result |
|
||||
| out | list dever.bytes.fromText(chunk) |
|
||||
|
||||
loop joinParts(chunks: List<Bytes>) (out: Bytes)
|
||||
| each chunk in chunks | result |
|
||||
| out | fold(acc = dever.bytes.fromText(""), appendChunk(chunk, acc)) |
|
||||
|
||||
loop prefixParts(chunks: List<Bytes>) (out: Bytes)
|
||||
| each chunk in chunks | result |
|
||||
| out | fold(acc = dever.bytes.fromText("prefix:"), appendChunk(chunk, acc)) |
|
||||
|
||||
flow fusedBytes(text: Text) (out: Bytes)
|
||||
| step | kind | do |
|
||||
| parts | loop | encodeParts(text.split(text, "")) |
|
||||
| out | loop | joinParts(parts) |
|
||||
|
||||
flow prefixedBytes(text: Text) (out: Bytes)
|
||||
| step | kind | do |
|
||||
| parts | loop | encodeParts(text.split(text, "")) |
|
||||
| out | loop | prefixParts(parts) |
|
||||
|
||||
keepParts(text: Text) (out: Bytes, count: Int) {
|
||||
parts = encodeParts(text.split(text, ""))
|
||||
out = joinParts(parts)
|
||||
count = length(parts)
|
||||
}
|
||||
|
||||
joinSeparated(text: Text) (out: Bytes) {
|
||||
parts = encodeParts(text.split(text, "-"))
|
||||
out = joinParts(parts)
|
||||
}
|
||||
|
||||
markedPart(text: Text) (out: Bytes) { out = dever.bytes.fromText("x" + text) }
|
||||
|
||||
loop markedParts(chunks: List<Text>) (out: List<Bytes>)
|
||||
| each chunk in chunks | result |
|
||||
| out | list markedPart(chunk) |
|
||||
|
||||
joinMarked(text: Text) (out: Bytes) {
|
||||
parts = markedParts(text.split(text, ""))
|
||||
out = joinParts(parts)
|
||||
}
|
||||
|
||||
checkedPart(text: Text) (out: Bytes) {
|
||||
check text != "!" else Invalid
|
||||
out = dever.bytes.fromText(text)
|
||||
}
|
||||
|
||||
loop checkedParts(chunks: List<Text>) (out: List<Bytes>)
|
||||
| each chunk in chunks | result |
|
||||
| out | list checkedPart(chunk) |
|
||||
|
||||
joinChecked(text: Text) (out: Bytes) {
|
||||
parts = checkedParts(text.split(text, ""))
|
||||
out = joinParts(parts)
|
||||
}
|
||||
|
||||
type PartError { error WrongCount(count: Int) }
|
||||
|
||||
guardedJoin(text: Text, allowed: Bool) (out: Bytes) {
|
||||
parts = encodeParts(text.split(text, ""))
|
||||
check allowed else PartError.WrongCount(length(parts))
|
||||
out = joinParts(parts)
|
||||
}
|
||||
|
||||
moveJoinedSource(text: Text) (out: Bytes, original: Text) {
|
||||
alias = text
|
||||
parts = encodeParts(text.split(alias, ""))
|
||||
original = text
|
||||
out = joinParts(parts)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
use dever_runtime::Bytes;
|
||||
let text = String::from("中文 bytes");
|
||||
let pointer = text.as_ptr();
|
||||
let data = @encode@(text);
|
||||
assert_eq!(data.as_ptr(), pointer);
|
||||
assert_eq!(@decode@(&data).unwrap(), "中文 bytes");
|
||||
assert_eq!(@byteSize@(&data), 12);
|
||||
let part = @cut@(&data, 3, 6).unwrap();
|
||||
assert_eq!(part.as_ptr(), data[3..].as_ptr());
|
||||
assert_eq!(@decode@(&part).unwrap(), "文");
|
||||
for (start, end) in [(-1, 2), (0, -1), (3, 2), (0, 13), (i64::MAX, i64::MAX)] {
|
||||
assert!(matches!(@captureCut@(&data, start, end), @BufferResult@::Failed(_)));
|
||||
}
|
||||
assert!(@cut@(&data, 12, 12).unwrap().is_empty());
|
||||
assert_eq!(@byteAt@(&data, 0), Some(228));
|
||||
for index in [-1, 12, i64::MAX] { assert_eq!(@byteAt@(&data, index), None); }
|
||||
let invalid = @buffer@(&[255, 128, 0]).unwrap();
|
||||
assert!(matches!(@captureDecode@(&invalid), @DecodeResult@::Failed(_)));
|
||||
assert!(matches!(@captureDecode@(&data), @DecodeResult@::Decoded(_)));
|
||||
for values in [&[-1][..], &[256][..], &[0, i64::MAX][..]] {
|
||||
assert!(matches!(@captureBuffer@(values), @BufferResult@::Failed(_)));
|
||||
}
|
||||
assert!(@buffer@(&[]).unwrap().is_empty());
|
||||
let all = (0..=255).collect::<Vec<_>>();
|
||||
let bytes = @buffer@(&all).unwrap();
|
||||
let stats = @byteStats@(&bytes);
|
||||
assert_eq!((stats.f0, stats.f1, stats.f2), (32640, all.clone(), 256));
|
||||
assert_eq!(@validBytes@(&bytes), all);
|
||||
assert_eq!(@byteFiltered@(&bytes), (128..=255).collect::<Vec<_>>());
|
||||
assert_eq!(@byteFirst@(&bytes), Some(0));
|
||||
assert_eq!(@byteFirst@(&Bytes::new()), None);
|
||||
assert_eq!(@byteSum@(&Bytes::new()), 0);
|
||||
for length in [1, 4095, 4096, 4097, 65536] {
|
||||
let data = Bytes::from(vec![255; length]);
|
||||
assert_eq!(@byteSum@(&data), length as i64 * 255);
|
||||
}
|
||||
assert_eq!(@joinBytes@(part.clone(), &part).as_ref(), "文文".as_bytes());
|
||||
let text = String::from("handler 原内容移动");
|
||||
let pointer = text.as_ptr();
|
||||
assert_eq!(@throughHandler@(text).as_ptr(), pointer);
|
||||
let packet = @Packet@ { f0: data.clone(), f1: "原包".into() };
|
||||
let kept = @keepPacket@(packet).unwrap();
|
||||
assert_eq!(kept.f0.as_ptr(), data[1..].as_ptr());
|
||||
assert_eq!(kept.f1.f0.as_ptr(), data.as_ptr());
|
||||
let parts = @repeatedSlice@(&data).unwrap();
|
||||
for (index, part) in parts.iter().enumerate() { assert_eq!(part.as_ptr(), data[index..].as_ptr()); }
|
||||
|
||||
@allocation_counter@
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let sum = @byteSum@(std::hint::black_box(&bytes));
|
||||
let after = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!(sum, 32640);
|
||||
assert_eq!(after - before, 0);
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let part = @cut@(&data, 1, 4).unwrap();
|
||||
let after = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!(part.as_ptr(), data[1..].as_ptr());
|
||||
assert_eq!(after - before, 0);
|
||||
|
||||
let mut buffer = Vec::with_capacity(64);
|
||||
buffer.extend_from_slice(b"unique");
|
||||
let unique = Bytes::from(buffer);
|
||||
let pointer = unique.as_ptr();
|
||||
let suffix = Bytes::from_static(b" suffix");
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let joined = @joinBytes@(unique, &suffix);
|
||||
let after = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!(joined.as_ref(), b"unique suffix");
|
||||
assert_eq!(joined.as_ptr(), pointer);
|
||||
assert_eq!(after - before, 1, "bytes promotes Vec storage once; payload remains at the same address");
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let joined = @joinBytes@(joined, &Bytes::new());
|
||||
let after = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!(joined.as_ptr(), pointer);
|
||||
assert_eq!(after - before, 1, "bytes recreates its shared metadata while reusing the payload");
|
||||
let shared = joined.clone();
|
||||
let extended = @joinBytes@(joined, &suffix);
|
||||
assert_eq!(shared.as_ref(), b"unique suffix");
|
||||
assert_eq!(extended.as_ref(), b"unique suffix suffix");
|
||||
|
||||
let seed = Bytes::from_static(b"seed");
|
||||
let chunks = vec![Bytes::from_static(b"-a"), Bytes::new(), Bytes::from_static(b"-b")];
|
||||
assert_eq!(@concatAll@(&chunks, seed.clone()).as_ref(), b"seed-a-b");
|
||||
assert_eq!(seed.as_ref(), b"seed");
|
||||
assert_eq!(@concatAll@(&[], seed.clone()), seed);
|
||||
let mut reserved = Vec::with_capacity(64);
|
||||
reserved.extend_from_slice(b"seed");
|
||||
let reserved = Bytes::from(reserved);
|
||||
let pointer = reserved.as_ptr();
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let folded = @concatAll@(&chunks, reserved);
|
||||
let after = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!(folded.as_ref(), b"seed-a-b");
|
||||
assert_eq!(folded.as_ptr(), pointer);
|
||||
assert_eq!(after - before, 1, "freeze metadata is created once for the entire fold");
|
||||
for text in ["", "ASCII", "a好🙂"] {
|
||||
assert_eq!(@fusedBytes@(text).as_ref(), text.as_bytes());
|
||||
assert_eq!(@prefixedBytes@(text).as_ref(), format!("prefix:{text}").as_bytes());
|
||||
let kept = @keepParts@(text);
|
||||
assert_eq!(kept.f0.as_ref(), text.as_bytes());
|
||||
assert_eq!(kept.f1, text.chars().count() as i64);
|
||||
}
|
||||
assert_eq!(@joinSeparated@("a-好-🙂").as_ref(), "a好🙂".as_bytes());
|
||||
assert_eq!(@joinMarked@("a好").as_ref(), "xax好".as_bytes());
|
||||
assert!(@joinChecked@("a!好").is_err());
|
||||
assert_eq!(@joinChecked@("a好").unwrap().as_ref(), "a好".as_bytes());
|
||||
let long = "好🙂".repeat(4096);
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let fused = @fusedBytes@(&long);
|
||||
let after = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!(fused.as_ref(), long.as_bytes());
|
||||
assert!(after - before <= 2, "only the final payload and Bytes metadata may allocate");
|
||||
assert!(matches!(@guardedJoin@("好🙂", false), Err(Failure::@PartError@(@PartError@::WrongCount(2)))));
|
||||
let moved = @moveJoinedSource@(String::from("好🙂"));
|
||||
assert_eq!(moved.f0.as_ref(), "好🙂".as_bytes());
|
||||
assert_eq!(moved.f1, "好🙂");
|
||||
assert_eq!(@guardedJoin@("好🙂", true).unwrap().as_ref(), "好🙂".as_bytes());
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
readDatetime(text: Text) (out: DateTime) {
|
||||
out = dever.time.parseDatetime(text)
|
||||
}
|
||||
|
||||
writeDatetime(value: DateTime) (out: Text) {
|
||||
out = dever.time.formatDatetime(value)
|
||||
}
|
||||
|
||||
readDate(text: Text) (out: Date) {
|
||||
out = dever.time.parseDate(text)
|
||||
}
|
||||
|
||||
writeDate(value: Date) (out: Text) {
|
||||
out = dever.time.formatDate(value)
|
||||
}
|
||||
|
||||
readTime(text: Text) (out: Time) {
|
||||
out = dever.time.parseTime(text)
|
||||
}
|
||||
|
||||
writeTime(value: Time) (out: Text) {
|
||||
out = dever.time.formatTime(value)
|
||||
}
|
||||
|
||||
durationMillis(value: Int) (out: Duration) {
|
||||
out = dever.time.duration(value)
|
||||
}
|
||||
|
||||
addTime(value: DateTime, duration: Duration) (out: DateTime) {
|
||||
out = dever.time.add(value, duration)
|
||||
}
|
||||
|
||||
subtractTime(value: DateTime, duration: Duration) (out: DateTime) {
|
||||
out = dever.time.subtract(value, duration)
|
||||
}
|
||||
|
||||
timeDifference(later: DateTime, earlier: DateTime) (out: Duration) {
|
||||
out = dever.time.difference(later, earlier)
|
||||
}
|
||||
|
||||
loop orderDateTime(values: List<DateTime>) (oldest: DateTime?, newest: DateTime?, ordered: List<DateTime>)
|
||||
| each value in values | sort | result |
|
||||
| oldest | - | min value |
|
||||
| newest | - | max value |
|
||||
| ordered | [value.asc] | list value |
|
||||
|
||||
loop orderDate(values: List<Date>) (oldest: Date?, newest: Date?, ordered: List<Date>)
|
||||
| each value in values | sort | result |
|
||||
| oldest | - | min value |
|
||||
| newest | - | max value |
|
||||
| ordered | [value.asc] | list value |
|
||||
|
||||
loop orderTime(values: List<Time>) (oldest: Time?, newest: Time?, ordered: List<Time>)
|
||||
| each value in values | sort | result |
|
||||
| oldest | - | min value |
|
||||
| newest | - | max value |
|
||||
| ordered | [value.asc] | list value |
|
||||
|
||||
loop orderDuration(values: List<Duration>) (oldest: Duration?, newest: Duration?, ordered: List<Duration>)
|
||||
| each value in values | sort | result |
|
||||
| oldest | - | min value |
|
||||
| newest | - | max value |
|
||||
| ordered | [value.asc] | list value |
|
||||
|
||||
type Schedule {
|
||||
start: DateTime
|
||||
day: Date
|
||||
at: Time
|
||||
delay: Duration
|
||||
}
|
||||
|
||||
echo(value: Schedule) (out: Schedule) { out = value }
|
||||
json(value: Schedule) (out: Schedule) { out = dever.json.decode(dever.json.encode(value)) }
|
||||
captured(text: Text) (out: dever.time.DateTimeResult) { out = result(dever.time.parseDatetime(text)) }
|
||||
invalidOutput(millis: Int) (out: DateTime) {
|
||||
out = dever.time.add(dever.time.parseDatetime("1970-01-01T00:00:00Z"), dever.time.duration(millis))
|
||||
}
|
||||
cmd echo = app.echo
|
||||
cmd json = app.json
|
||||
cmd invalid = app.invalidOutput
|
||||
|
||||
isEarlier(first: DateTime, second: DateTime) (out: Bool) {
|
||||
out = first < second
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn calendar_executes_errors_arithmetic_and_ordered_loops() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"calendar",
|
||||
include_str!("calendar.dever"),
|
||||
Some(include_str!("calendar.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calendar_protocol_normalizes_once_and_reports_invalid_dates_and_outputs() {
|
||||
let binary = build(
|
||||
"calendar-command",
|
||||
include_str!("calendar.dever"),
|
||||
None,
|
||||
Profile::Dev,
|
||||
);
|
||||
let run = |name: &str, input: &str| Command::new(&binary).args([name, input]).output().unwrap();
|
||||
for name in ["main.main.echo", "main.main.json"] {
|
||||
let input = r#"{"value":{"start":"2024-02-29T12:34:56.12+08:00","day":"2024-02-29","at":"12:00:00.000","delay":-1}}"#;
|
||||
let output = run(name, input);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let result: dever_runtime::wire::serde_json::Value =
|
||||
dever_runtime::wire::serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!(
|
||||
result["data"],
|
||||
dever_runtime::wire::serde_json::json!({"start":"2024-02-29T04:34:56.120Z","day":"2024-02-29","at":"12:00:00","delay":-1})
|
||||
);
|
||||
for invalid in [
|
||||
input.replace("2024-02-29", "2023-02-29"),
|
||||
input.replace("12:00:00.000", "24:00:00"),
|
||||
input.replace(":-1", ":1.0"),
|
||||
input.replace(":-1", ":\"1\""),
|
||||
] {
|
||||
let output = run(name, &invalid);
|
||||
assert!(!output.status.success(), "{invalid}");
|
||||
assert!(output.stdout.is_empty());
|
||||
}
|
||||
}
|
||||
let output = run("main.main.invalid", r#"{"millis":9223372036854775807}"#);
|
||||
assert!(!output.status.success());
|
||||
assert!(output.stdout.is_empty());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("calendar range"));
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use dever_runtime::value::calendar::{DateTime, Date, Time, Duration};
|
||||
let instant = @readDatetime@("2024-02-29T12:34:56.12+08:00").unwrap();
|
||||
assert_eq!(@writeDatetime@(instant).unwrap(), "2024-02-29T04:34:56.120Z");
|
||||
assert_eq!(@writeDate@(@readDate@("2024-02-29").unwrap()), "2024-02-29");
|
||||
assert_eq!(@writeTime@(@readTime@("12:34:56.000").unwrap()), "12:34:56");
|
||||
assert!(@readDatetime@("2024-12-31T23:59:60Z").is_err());
|
||||
assert!(@readDate@("2023-02-29").is_err());
|
||||
assert!(@readTime@("24:00:00").is_err());
|
||||
let duration = @durationMillis@(-1);
|
||||
let earlier = @addTime@(instant, duration).unwrap();
|
||||
assert!(@isEarlier@(earlier, instant));
|
||||
assert!(!@isEarlier@(instant, instant));
|
||||
assert_eq!(@timeDifference@(earlier, instant).unwrap(), duration);
|
||||
assert_eq!(@subtractTime@(earlier, duration).unwrap(), instant);
|
||||
let dates = @orderDate@(&[@readDate@("2024-03-01").unwrap(), @readDate@("2024-02-29").unwrap()]);
|
||||
assert_eq!(dates.f0, dates.f2.first().copied());
|
||||
assert_eq!(dates.f1, dates.f2.last().copied());
|
||||
let times = @orderTime@(&[@readTime@("12:00:00").unwrap(), @readTime@("11:59:59.999").unwrap()]);
|
||||
assert_eq!(times.f0, times.f2.first().copied());
|
||||
assert_eq!(times.f1, times.f2.last().copied());
|
||||
let instants = @orderDateTime@(&[instant, earlier, instant]);
|
||||
assert_eq!(instants.f0, Some(earlier));
|
||||
assert_eq!(instants.f1, Some(instant));
|
||||
assert_eq!(instants.f2, [earlier, instant, instant]);
|
||||
let durations = @orderDuration@(&[Duration::from_millis(i64::MAX), duration, Duration::from_millis(i64::MIN)]);
|
||||
assert_eq!(durations.f0, Some(Duration::from_millis(i64::MIN)));
|
||||
assert_eq!(durations.f1, Some(Duration::from_millis(i64::MAX)));
|
||||
assert_eq!(@orderDateTime@(&[]).f0, None);
|
||||
assert!(@orderDateTime@(&[]).f2.is_empty());
|
||||
assert!(matches!(@captured@("bad"), @DateTimeResult@::Failed(message) if !message.is_empty()));
|
||||
assert!(matches!(@captured@("2024-02-29T12:34:56.12+08:00"), @DateTimeResult@::Read(value) if value == instant));
|
||||
let schedule = @Schedule@ { f0: instant, f1: Date::parse("2024-02-29").unwrap(), f2: Time::parse("12:00:00").unwrap(), f3: duration };
|
||||
assert_eq!(@json@(&schedule).unwrap(), schedule);
|
||||
let far = @invalidOutput@(i64::MAX).unwrap();
|
||||
assert!(@writeDatetime@(far).is_err());
|
||||
assert!(@addTime@(far, Duration::from_millis(1)).is_err());
|
||||
@allocation_counter@
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!(@addTime@(std::hint::black_box(instant), duration).unwrap(), earlier);
|
||||
assert_eq!(@timeDifference@(earlier, instant).unwrap(), duration);
|
||||
assert_eq!(@readDatetime@(std::hint::black_box("2024-02-29T12:34:56.12+08:00")).unwrap(), instant);
|
||||
assert_eq!(ALLOCATIONS.load(Ordering::Relaxed) - before, 0);
|
||||
@@ -0,0 +1,48 @@
|
||||
type Mailbox { values: Channel<Text> }
|
||||
|
||||
flow produce(channel: Channel<Text>, value: Text) ()
|
||||
| step | kind | do |
|
||||
| - | calc | send(channel, value) |
|
||||
| - | calc | close(channel) |
|
||||
|
||||
flow main(value: Text) (out: Text?)
|
||||
| step | kind | do |
|
||||
| channel | calc | channel<Text>(1) |
|
||||
| mailbox | calc | Mailbox { values = channel } |
|
||||
| task | calc | run(produce(mailbox.values, value)) |
|
||||
| out | calc | receive(channel) |
|
||||
| - | calc | wait(task) |
|
||||
|
||||
flow optional() (first: Int?, second: Int?, end: Int?)
|
||||
| step | kind | do |
|
||||
| channel | calc | channel<Int?>(2) |
|
||||
| - | calc | send(channel, null) |
|
||||
| - | calc | send(channel, 9) |
|
||||
| - | calc | close(channel) |
|
||||
| first | calc | receive(channel) |
|
||||
| second | calc | receive(channel) |
|
||||
| end | calc | receive(channel) |
|
||||
|
||||
flow sendClosed() ()
|
||||
| step | kind | do |
|
||||
| channel | calc | channel<Int>(1) |
|
||||
| - | calc | close(channel) |
|
||||
| - | calc | send(channel, 1) |
|
||||
|
||||
flow invalidCapacity(capacity: Int) ()
|
||||
| step | kind | do |
|
||||
| channel | calc | channel<Int>(capacity) |
|
||||
| - | calc | close(channel) |
|
||||
|
||||
flow cancelledSender(channel: Channel<Int>) ()
|
||||
| step | kind | do |
|
||||
| - | calc | send(channel, 2) |
|
||||
|
||||
flow cancel() (out: Int?)
|
||||
| step | kind | do |
|
||||
| channel | calc | channel<Int>(1) |
|
||||
| - | calc | send(channel, 1) |
|
||||
| task | calc | run(cancelledSender(channel)) |
|
||||
| - | calc | stop(task) |
|
||||
| - | calc | close(channel) |
|
||||
| out | calc | receive(channel) |
|
||||
@@ -0,0 +1,15 @@
|
||||
assert_eq!(dever_runtime::task::run(true, 4, async |scope| Ok::<_, ()>(@main@(scope, "雪".to_owned()).await)).unwrap().unwrap(), Some("雪".to_owned()));
|
||||
let output = dever_runtime::task::run(true, 1, async |_| Ok::<_, ()>(@optional@().await)).unwrap().unwrap();
|
||||
assert_eq!((output.f0, output.f1, output.f2), (None, Some(9), None));
|
||||
assert_eq!(dever_runtime::task::run(true, 1, async |scope| Ok::<_, ()>(@cancel@(scope).await)).unwrap().unwrap(), Some(1));
|
||||
let failure = dever_runtime::task::run(true, 1, async |_| { @sendClosed@().await; Ok::<_, ()>(()) }).unwrap().unwrap_err();
|
||||
let dever_runtime::task::RunError::Fault { primary, additional } = failure else { panic!("expected channel fault") };
|
||||
let info = primary.downcast_ref::<&'static FaultInfo>().unwrap();
|
||||
assert_eq!(info.message, "channel is closed");
|
||||
assert_eq!(info.source, @source_path@);
|
||||
assert!(additional.is_empty());
|
||||
for capacity in [0, -1, 65537] {
|
||||
let failure = dever_runtime::task::run(true, 1, async |_| { @invalidCapacity@(capacity); Ok::<_, ()>(()) }).unwrap().unwrap_err();
|
||||
let dever_runtime::task::RunError::Fault { primary, .. } = failure else { panic!("expected capacity fault") };
|
||||
assert_eq!(primary.downcast_ref::<&'static FaultInfo>().unwrap().message, "channel capacity must be within 1..65536");
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
identity(value: Int) (out: Int) {
|
||||
out = value
|
||||
}
|
||||
|
||||
fallback() (out: Int) {
|
||||
out = 42
|
||||
}
|
||||
|
||||
noop() () {
|
||||
|
||||
}
|
||||
|
||||
pair(value: Int) (left: Int, right: Int) {
|
||||
left = value
|
||||
right = value + 1
|
||||
}
|
||||
|
||||
otherPair() (left: Int, right: Int) {
|
||||
left = 20
|
||||
right = 22
|
||||
}
|
||||
|
||||
flow slow(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(60000) |
|
||||
| out | calc | value |
|
||||
|
||||
flow timed() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | calc | timeout(run(slow(0)), 1, fallback) |
|
||||
|
||||
flow fast() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | calc | timeout(run(identity(7)), 60000, fallback) |
|
||||
|
||||
flow racing() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | calc | race(run(slow(0)), run(identity(42))) |
|
||||
|
||||
flow ordered() (out: Int)
|
||||
| step | kind | do |
|
||||
| first | calc | run(identity(42)) |
|
||||
| second | calc | run(identity(0)) |
|
||||
| - | flow | dever.time.sleep(1) |
|
||||
| out | calc | race(first, second) |
|
||||
|
||||
flow multiple() (out: Int)
|
||||
| step | kind | do |
|
||||
| result | calc | race(run(pair(20)), run(otherPair())) |
|
||||
| out | calc | result.left + result.right |
|
||||
|
||||
flow multiTimeout() (out: Int)
|
||||
| step | kind | do |
|
||||
| result | calc | timeout(run(pair(20)), 60000, otherPair) |
|
||||
| out | calc | result.left + result.right |
|
||||
|
||||
flow grouped() ()
|
||||
| step | kind | do |
|
||||
| tasks | calc | group(1) |
|
||||
| - | calc | run(tasks, noop()) |
|
||||
| - | calc | run(tasks, dever.time.sleep(0)) |
|
||||
| - | calc | wait(tasks) |
|
||||
|
||||
flow stopped() ()
|
||||
| step | kind | do |
|
||||
| tasks | calc | group(2) |
|
||||
| - | calc | run(tasks, dever.time.sleep(60000)) |
|
||||
| - | calc | stop(tasks) |
|
||||
|
||||
type Outcome {
|
||||
Done(value: Int)
|
||||
error Failed(value: dever.time.SleepResult)
|
||||
}
|
||||
|
||||
rule resolve(value: Outcome) (out: Int) recover("report rejected sleep as -1")
|
||||
| value | out |
|
||||
| Done(number) | number |
|
||||
| Failed(error) | -1 |
|
||||
|
||||
flow failWork() (out: Int)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(-1) |
|
||||
| out | calc | 0 |
|
||||
|
||||
flow capturedRace() (out: Int)
|
||||
| step | kind | do |
|
||||
| result: Outcome | calc | result(race(run(failWork()), run(slow(0)))) |
|
||||
| out | rule | resolve(result) |
|
||||
|
||||
flow capturedTimeout() (out: Int)
|
||||
| step | kind | do |
|
||||
| result: Outcome | calc | result(timeout(run(failWork()), 60000, fallback)) |
|
||||
| out | rule | resolve(result) |
|
||||
|
||||
type Submitted {
|
||||
Done
|
||||
error Failed(value: dever.time.SleepResult)
|
||||
}
|
||||
|
||||
rule acknowledge(value: Submitted) () recover("caller explicitly acknowledges member failure")
|
||||
| value | do |
|
||||
| Done | noop() |
|
||||
| Failed(error) | noop() |
|
||||
|
||||
flow capturedGroup() ()
|
||||
| step | kind | do |
|
||||
| tasks | calc | group(1) |
|
||||
| - | calc | run(tasks, dever.time.sleep(-1)) |
|
||||
| submission: Submitted | calc | result(run(tasks, noop())) |
|
||||
| - | rule | acknowledge(submission) |
|
||||
| - | calc | stop(tasks) |
|
||||
|
||||
flow useFallback(action: handler() (out: Int)) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | calc | timeout(run(slow(0)), 1, action) |
|
||||
|
||||
flow boundFallback() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | flow | useFallback(fallback) |
|
||||
|
||||
flow parallelGroups() ()
|
||||
| step | kind | parallel | do |
|
||||
| first | calc | create | group(1) |
|
||||
| second | calc | create | group(1) |
|
||||
| - | calc | submit | run(first, noop()) |
|
||||
| - | calc | submit | run(second, noop()) |
|
||||
| - | calc | finish | wait(first) |
|
||||
| - | calc | finish | wait(second) |
|
||||
|
||||
flow failedFallback() (out: Int)
|
||||
| step | kind | do |
|
||||
| child | calc | run(identity(1)) |
|
||||
| - | flow | dever.time.sleep(-1) |
|
||||
| out | calc | wait(child) |
|
||||
|
||||
flow capturedFallback() (out: Int)
|
||||
| step | kind | do |
|
||||
| result: Outcome | calc | result(timeout(run(slow(0)), 1, failedFallback)) |
|
||||
| out | rule | resolve(result) |
|
||||
|
||||
type Broken {
|
||||
error Failed
|
||||
}
|
||||
|
||||
failZero() () {
|
||||
fail(Broken.Failed)
|
||||
}
|
||||
|
||||
flow neverGroup() ()
|
||||
| step | kind | do |
|
||||
| tasks | calc | group(1) |
|
||||
| - | calc | run(tasks, failZero()) |
|
||||
| - | calc | wait(tasks) |
|
||||
@@ -0,0 +1,25 @@
|
||||
use dever_runtime::task;
|
||||
task::run(true, 8, async |scope| {
|
||||
assert_eq!(@timed@(scope).await?, 42);
|
||||
assert_eq!(@fast@(scope).await, 7);
|
||||
assert_eq!(@racing@(scope).await?, 42);
|
||||
assert_eq!(@ordered@(scope).await?, 42);
|
||||
assert!([41, 42].contains(&@multiple@(scope).await));
|
||||
assert_eq!(@multiTimeout@(scope).await, 41);
|
||||
@grouped@(scope).await?;
|
||||
@stopped@(scope).await?;
|
||||
assert_eq!(@capturedRace@(scope).await, -1);
|
||||
assert_eq!(@capturedTimeout@(scope).await, -1);
|
||||
@capturedGroup@(scope).await?;
|
||||
assert_eq!(@boundFallback@(scope).await?, 42);
|
||||
@parallelGroups@(scope).await;
|
||||
Ok::<_, Failure>(())
|
||||
}).unwrap().unwrap();
|
||||
|
||||
task::run(true, 1, async |scope| {
|
||||
assert_eq!(@capturedFallback@(scope).await, -1);
|
||||
assert_eq!(@capturedFallback@(scope).await, -1);
|
||||
Ok::<_, ()>(())
|
||||
}).unwrap().unwrap();
|
||||
|
||||
assert!(matches!(task::run(true, 1, async |scope| @neverGroup@(scope).await).unwrap(), Err(task::RunError::Business { .. })));
|
||||
@@ -0,0 +1,12 @@
|
||||
type State { Active = "启用", Closed = "关闭" }
|
||||
type Item { name: Text, price: Decimal >= 0, quantity: Int >= 1, state: State, note: Text? }
|
||||
bill(input: Item) (total: Decimal, item: Item) { total = input.price * input.quantity
|
||||
item = input }
|
||||
guarded(value: Int) (out: Int) { check value > 0 else Invalid
|
||||
out = value }
|
||||
overflow(value: Int) (out: Int) { out = value + 1 }
|
||||
nonfinite(value: Float) (out: Float) { out = value / 0.0 }
|
||||
cmd bill = bill
|
||||
cmd guarded = guarded
|
||||
cmd overflow = overflow
|
||||
cmd nonfinite = nonfinite
|
||||
@@ -0,0 +1,120 @@
|
||||
flow delayed(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(4 - value) |
|
||||
| out | calc | value * 2 |
|
||||
|
||||
loop ordered(values: List<Int>, limit: Int >= 1 and <= 65536) (out: List<Int>, selected: List<Int>)
|
||||
| each value in values parallel limit | value | result |
|
||||
| out | - | list delayed(value) |
|
||||
| selected | >= 2 | list delayed(value) |
|
||||
|
||||
flow noop(value: Int) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(value) |
|
||||
|
||||
loop actions(values: List<Int>) (count: Int)
|
||||
| each value in values parallel 2 | value | result |
|
||||
| count | >= 0 | do noop(value) |
|
||||
|
||||
loop zero(values: List<Int>) ()
|
||||
| each value in values parallel 2 | result |
|
||||
| - | do noop(value) |
|
||||
|
||||
loop textLengths(values: List<Text>, suffix: Text) (out: List<Int>)
|
||||
| each value in values parallel 2 | result |
|
||||
| out | list length(value) + length(suffix) |
|
||||
|
||||
loop textCopies(values: List<Text>, suffix: Text) (out: List<Text>)
|
||||
| each value in values parallel 2 | result |
|
||||
| out | list value + suffix |
|
||||
|
||||
loop rangeValues(end: Int) (out: List<Int>)
|
||||
| each value in range(0, end) parallel 3 | result |
|
||||
| out | list value + 1 |
|
||||
|
||||
loop byteValues(values: Bytes) (out: List<Int>)
|
||||
| each value in values parallel 2 | result |
|
||||
| out | list value + 1 |
|
||||
|
||||
loop streamValues(values: AsyncStream<Int>) (out: List<Int>)
|
||||
| each value in values parallel 2 | result |
|
||||
| out | list delayed(value) |
|
||||
|
||||
rule next(state: Int) (out: Walk<Int, Int>)
|
||||
| state | out |
|
||||
| < 4 | Walk.Next(state, state + 1) |
|
||||
| >= 4 | Walk.Done |
|
||||
|
||||
loop walked(seed: Int) (out: List<Int>)
|
||||
| each value in walk(seed, next) parallel 2 | result |
|
||||
| out | list delayed(value) |
|
||||
|
||||
flow asyncNext(state: Int) (out: Walk<Int, Int>)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(1) |
|
||||
| out | rule | next(state) |
|
||||
|
||||
loop asyncWalked(seed: Int) (out: List<Int>)
|
||||
| each value in walk(seed, asyncNext) parallel 2 | result |
|
||||
| out | list delayed(value) |
|
||||
|
||||
type Trouble { error Broken }
|
||||
flow failed(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| - | check | value != 1 else Trouble.Broken |
|
||||
| - | flow | dever.time.sleep(60000) |
|
||||
| out | calc | value |
|
||||
|
||||
loop failFast(values: List<Int>) (out: List<Int>)
|
||||
| each value in values parallel 2 | result |
|
||||
| out | list failed(value) |
|
||||
|
||||
flow spawned(values: List<Int>) (out: List<Int>)
|
||||
| step | kind | do |
|
||||
| task | calc | run(rangeValues(length(values))) |
|
||||
| out | calc | wait(task) |
|
||||
|
||||
flow child(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(delayed(value)) |
|
||||
| out | calc | wait(task) |
|
||||
|
||||
loop children(values: List<Int>) (out: List<Int>)
|
||||
| each value in values parallel 2 | result |
|
||||
| out | list child(value) |
|
||||
|
||||
loop failedStream(values: AsyncStream<Int>) (out: List<Int>)
|
||||
| each value in values parallel 2 | result |
|
||||
| out | list failed(value) |
|
||||
|
||||
loop faulted(values: List<Int>, base: Int) (out: List<Int>)
|
||||
| each value in values parallel 2 | result |
|
||||
| out | list value + base |
|
||||
|
||||
loop decimals(values: List<Decimal>) (out: List<Decimal>)
|
||||
| each value in values parallel 2 | result |
|
||||
| out | list value / 3 |
|
||||
|
||||
loop capturedInput(values: List<Text>) (out: List<Text>)
|
||||
| each value in values parallel 2 | result |
|
||||
| out | list value + int.toText(length(values)) |
|
||||
|
||||
type Cursor { label: Text, remaining: Int }
|
||||
rule textStep(state: Cursor, remaining: Int) (out: Walk<Text, Cursor>)
|
||||
| state | remaining | out |
|
||||
| - | > 0 | Walk.Next(state.label, Cursor { label = state.label, remaining = remaining - 1 }) |
|
||||
| - | <= 0 | Walk.Done |
|
||||
|
||||
textNext(state: Cursor) (out: Walk<Text, Cursor>) { out = textStep(state, state.remaining) }
|
||||
flow asyncTextNext(state: Cursor) (out: Walk<Text, Cursor>)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(0) |
|
||||
| out | calc | textNext(state) |
|
||||
|
||||
loop textWalk(state: Cursor) (out: List<Text>)
|
||||
| each value in walk(state, textNext) parallel 2 | result |
|
||||
| out | list value |
|
||||
|
||||
loop asyncTextWalk(state: Cursor) (out: List<Text>)
|
||||
| each value in walk(state, asyncTextNext) parallel 2 | result |
|
||||
| out | list value |
|
||||
@@ -0,0 +1,42 @@
|
||||
use dever_runtime::{task, stream::AsyncStream, Bytes};
|
||||
task::execute(true, async {
|
||||
let result = @ordered@(&[0, 1, 2, 3], 3).await.unwrap();
|
||||
assert_eq!(result.f0, [0, 2, 4, 6]);
|
||||
assert_eq!(result.f1, [4, 6]);
|
||||
assert!(@ordered@(&[], 1).await.unwrap().f0.is_empty());
|
||||
assert_eq!(@ordered@(&[0, 1, 2, 3], 1).await.unwrap().f0, [0, 2, 4, 6]);
|
||||
assert_eq!(@actions@(&[0, 1, -1, 2]).await.unwrap(), 3);
|
||||
@zero@(&[0, 1, 2]).await.unwrap();
|
||||
let values = vec!["甲".to_owned(), "乙丙".to_owned()];
|
||||
assert_eq!(@textLengths@(&values, "suffix").await, [7, 8]);
|
||||
assert_eq!(@textCopies@(values, "尾").await, ["甲尾", "乙丙尾"]);
|
||||
assert_eq!(@rangeValues@(4).await, [1, 2, 3, 4]);
|
||||
assert_eq!(@byteValues@(&Bytes::from_static(&[0, 255])).await, [1, 256]);
|
||||
let stream = AsyncStream::values(vec![0, 1, 2, 3]);
|
||||
assert_eq!(@streamValues@(&stream).await.unwrap(), [0, 2, 4, 6]);
|
||||
assert!(stream.next().await.unwrap().is_none());
|
||||
assert_eq!(@walked@(0).await.unwrap(), [0, 2, 4, 6]);
|
||||
assert_eq!(@asyncWalked@(0).await.unwrap(), [0, 2, 4, 6]);
|
||||
let failed = @failFast@(&[0, 1, 2]).await;
|
||||
assert!(matches!(failed, Err(Failure::@Trouble@(@Trouble@::Broken))));
|
||||
let stream = AsyncStream::values(vec![0, 1, 2]);
|
||||
assert!(@failedStream@(&stream).await.is_err());
|
||||
assert!(stream.next().await.unwrap().is_none());
|
||||
assert_eq!(@capturedInput@(vec!["a".into(), "b".into()]).await, ["a2", "b2"]);
|
||||
assert_eq!(@decimals@(&[Decimal::from_int(3), Decimal::from_int(6)]).await, [Decimal::from_int(1), Decimal::from_int(2)]);
|
||||
let stream = AsyncStream::values(vec![0, 2]);
|
||||
{
|
||||
use std::{future::{Future, poll_fn}, task::Poll};
|
||||
let mut pending = Box::pin(@failedStream@(&stream));
|
||||
poll_fn(|cx| { assert!(pending.as_mut().poll(cx).is_pending()); Poll::Ready(()) }).await;
|
||||
}
|
||||
assert!(stream.next().await.unwrap().is_none());
|
||||
assert_eq!(@textWalk@(@Cursor@ { f0: "state".into(), f1: 3 }).await, ["state", "state", "state"]);
|
||||
assert_eq!(@asyncTextWalk@(@Cursor@ { f0: "state".into(), f1: 3 }).await.unwrap(), ["state", "state", "state"]);
|
||||
}).unwrap();
|
||||
assert_eq!(task::run(true, 2, async |scope| Ok::<_, ()>(@spawned@(scope, &[0, 1, 2]).await)).unwrap().unwrap(), [1, 2, 3]);
|
||||
assert_eq!(task::run(true, 2, async |scope| @children@(scope, &[0, 1, 2, 3]).await).unwrap().unwrap(), [0, 2, 4, 6]);
|
||||
let fault = task::run(true, 2, async |_scope| Ok::<_, ()>(@faulted@(&[1], i64::MAX).await)).unwrap().unwrap_err();
|
||||
let task::RunError::Fault { primary, additional } = fault else { panic!("original fault required") };
|
||||
assert!(additional.is_empty());
|
||||
assert_eq!(primary.downcast_ref::<&'static FaultInfo>().unwrap().source, @source_path@);
|
||||
@@ -0,0 +1,45 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn constants_execute_with_exact_decimal_and_optional_values() {
|
||||
let source = r#"
|
||||
type State { Ready, error Broken }
|
||||
const title = "中文😀"
|
||||
const alias = title
|
||||
const absent: Text? = null
|
||||
const present: Text? = alias
|
||||
const fraction = 0.1000000000000000000000000000000001
|
||||
const whole = 2
|
||||
const decimal_whole: Decimal = whole
|
||||
const minimum = -9223372036854775808
|
||||
const state: State = Ready
|
||||
const broken = State.Broken
|
||||
size() (out: Int) { out = length(alias) }
|
||||
text() (out: Text) { out = alias }
|
||||
missing() (out: Text?) { out = absent }
|
||||
available() (out: Text?) { out = present }
|
||||
amount() (out: Decimal) { out = fraction + decimal_whole }
|
||||
smallest() (out: Int) { out = minimum }
|
||||
ready() (out: State) { out = state }
|
||||
stop() () { fail(broken) }
|
||||
"#;
|
||||
let assertions = r#"
|
||||
assert_eq!(@size@(), 3);
|
||||
assert_eq!(@text@(), "中文😀");
|
||||
assert_eq!(@missing@(), None);
|
||||
assert_eq!(@available@(), Some(String::from("中文😀")));
|
||||
assert_eq!(@amount@().to_string(), "2.1");
|
||||
assert_eq!(@smallest@(), i64::MIN);
|
||||
assert_eq!(@ready@(), @State@::Ready);
|
||||
assert!(@stop@().is_err());
|
||||
"#;
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build("constants", source, Some(assertions), profile);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
type Credentials { key: Secret, count: Int }
|
||||
type Parsed { Ready(value: Credentials), error Failed(reason: dever.json.JsonResult) }
|
||||
hash(value: Bytes) (out: Bytes) { out = dever.crypto.sha256(value) }
|
||||
sign(key: Secret, value: Bytes) (out: Bytes) { out = dever.crypto.hmacSha256(key, value) }
|
||||
equal(left: Bytes, right: Bytes) (out: Bool) { out = dever.crypto.constantTimeEq(left, right) }
|
||||
present(value: Secret?) (out: Bool) { out = value != null }
|
||||
rule required(value: Secret?) (out: Secret)
|
||||
| value | out |
|
||||
| null | fail(Invalid) |
|
||||
| other | value |
|
||||
read(value: Json) (out: Parsed) { out = result(dever.json.decode(value)) }
|
||||
@@ -0,0 +1,19 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn secret_and_crypto_execute_known_vectors_and_never_echo_sensitive_errors() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"crypto",
|
||||
include_str!("crypto.dever"),
|
||||
Some(include_str!("crypto.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
use dever_runtime::{Bytes, value::secret::Secret, wire::json::Json};
|
||||
let decode = |text: &str| -> Bytes {
|
||||
(0..text.len()).step_by(2).map(|index| u8::from_str_radix(&text[index..index + 2], 16).unwrap()).collect::<Vec<_>>().into()
|
||||
};
|
||||
let abc = Bytes::from_static(b"abc");
|
||||
let digest = @hash@(&abc);
|
||||
assert_eq!(digest, decode("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"));
|
||||
let key = Secret::from_input(vec![0x0b; 20]);
|
||||
let signature = @sign@(&key, &Bytes::from_static(b"Hi There"));
|
||||
assert_eq!(signature, decode("b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"));
|
||||
assert!(@present@(Some(&key)));
|
||||
assert!(!@present@(None));
|
||||
assert!(@required@(None).is_err());
|
||||
let retained = @required@(Some(key.clone())).unwrap();
|
||||
assert_eq!(@sign@(&retained, &Bytes::from_static(b"Hi There")), signature);
|
||||
assert_eq!(format!("{key:?}"), "Secret([REDACTED])");
|
||||
let value = Json::from_text(r#"{"key":"test-marker","count":1}"#.into()).unwrap();
|
||||
assert!(matches!(@read@(&value), @Parsed@::Ready(_)));
|
||||
let value = Json::from_text(r#"{"key":"test-marker","count":"do-not-echo-this"}"#.into()).unwrap();
|
||||
let result = @read@(&value);
|
||||
let message = format!("{result:?}");
|
||||
assert!(message.contains("line") && message.contains("column"));
|
||||
assert!(!message.contains("test-marker") && !message.contains("do-not-echo-this"));
|
||||
@allocation_counter@
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert!(@equal@(&signature, std::hint::black_box(&signature)));
|
||||
assert!(!@equal@(&signature, &abc));
|
||||
assert!(@equal@(&Bytes::new(), &Bytes::new()));
|
||||
assert_eq!(ALLOCATIONS.load(Ordering::Relaxed) - before, 0);
|
||||
@@ -0,0 +1,67 @@
|
||||
missing(file: dever.system.File?) (out: Bool) { out = file == null }
|
||||
|
||||
flow createFile(path: Text) (out: dever.system.File)
|
||||
| step | kind | do |
|
||||
| out | flow | dever.io.create(path) |
|
||||
|
||||
flow openFile(path: Text) (out: dever.system.File)
|
||||
| step | kind | do |
|
||||
| out | flow | dever.io.open(path) |
|
||||
|
||||
flow readFile(file: dever.system.File, limit: Int) (out: dever.io.ReadState)
|
||||
| step | kind | do |
|
||||
| out | flow | dever.io.read(file, limit) |
|
||||
|
||||
flow writeFile(file: dever.system.File, bytes: Bytes) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.io.write(file, bytes) |
|
||||
|
||||
flow closeFile(file: dever.system.File) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.io.close(file) |
|
||||
|
||||
flow createAndWrite(path: Text, bytes: Bytes) ()
|
||||
| step | kind | do |
|
||||
| file | flow | createFile(path) |
|
||||
| alias | calc | file |
|
||||
| - | flow | writeFile(alias, bytes) |
|
||||
| - | flow | closeFile(file) |
|
||||
|
||||
flow readSome(path: Text, limit: Int) (out: dever.io.ReadState)
|
||||
| step | kind | do |
|
||||
| file | flow | openFile(path) |
|
||||
| out | flow | readFile(file, limit) |
|
||||
| - | flow | closeFile(file) |
|
||||
|
||||
flow offload(path: Text, limit: Int) (out: dever.io.ReadState)
|
||||
| step | kind | do |
|
||||
| out | calc | blocking(readSome(path, limit)) |
|
||||
|
||||
flow spawned(path: Text, limit: Int) (out: dever.io.ReadState)
|
||||
| step | kind | do |
|
||||
| task | calc | run(readSome(path, limit)) |
|
||||
| out | calc | wait(task) |
|
||||
|
||||
flow fault(path: Text, value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| file | flow | openFile(path) |
|
||||
| data | flow | readFile(file, 1) |
|
||||
| out | calc | value + 1 |
|
||||
|
||||
flow failAfterOpen(path: Text) ()
|
||||
| step | kind | do |
|
||||
| file | flow | openFile(path) |
|
||||
| - | flow | closeFile(file) |
|
||||
| - | flow | closeFile(file) |
|
||||
|
||||
type Attempt { Ready(value: dever.io.ReadState), error Failed(value: dever.io.ReadResult), error Missing(value: dever.io.OpenResult), error Closed(value: dever.io.CloseResult) }
|
||||
rule accepted(value: Attempt) (out: Bool) recover("report whether the requested file could be read")
|
||||
| value | out |
|
||||
| Ready(state) | true |
|
||||
| Failed(error) | false |
|
||||
| Missing(error) | false |
|
||||
| Closed(error) | false |
|
||||
flow captured(path: Text, limit: Int) (out: Bool)
|
||||
| step | kind | do |
|
||||
| attempt: Attempt | flow | result(readSome(path, limit)) |
|
||||
| out | rule | accepted(attempt) |
|
||||
@@ -0,0 +1,37 @@
|
||||
use dever_runtime::{Bytes, task};
|
||||
let root = std::env::temp_dir().join(format!("dever-native-file-{}", std::process::id()));
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let path = root.join("contents.bin");
|
||||
let name = path.to_str().unwrap();
|
||||
let bytes = Bytes::from_static(b"abc123");
|
||||
@createAndWrite@(name, &bytes).unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"abc123");
|
||||
assert!(@createFile@(name).is_err());
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"abc123", "create must not overwrite");
|
||||
let file = @openFile@(name).unwrap();
|
||||
let alias = file.clone();
|
||||
assert!(@missing@(None));
|
||||
assert!(!@missing@(Some(&file)));
|
||||
assert!(matches!(@readFile@(&file, 3).unwrap(), @ReadState@::Read(value) if value.as_ref() == b"abc"));
|
||||
assert!(matches!(@readFile@(&alias, 9).unwrap(), @ReadState@::Read(value) if value.as_ref() == b"123"));
|
||||
assert!(matches!(@readFile@(&file, 1).unwrap(), @ReadState@::End));
|
||||
assert!(@writeFile@(&file, &bytes).is_err(), "read-only files reject writing");
|
||||
@closeFile@(&alias).unwrap();
|
||||
assert!(@readFile@(&file, 1).is_err());
|
||||
assert!(@writeFile@(&file, &bytes).is_err());
|
||||
assert!(@closeFile@(&file).is_err());
|
||||
for limit in [0, -1, i64::MIN] {
|
||||
assert!(!@captured@(name, limit));
|
||||
}
|
||||
assert!(!@captured@(root.join("missing").to_str().unwrap(), 1));
|
||||
assert!(@captured@(name, 2));
|
||||
assert!(matches!(task::run(true, 1, async |scope| @offload@(scope, name.to_owned(), 6).await).unwrap().unwrap(), @ReadState@::Read(value) if value.as_ref() == b"abc123"));
|
||||
assert!(matches!(task::run(true, 1, async |scope| @spawned@(scope, name.to_owned(), 9).await).unwrap().unwrap(), @ReadState@::Read(value) if value.as_ref() == b"abc123"));
|
||||
let descriptors = || std::fs::read_dir("/proc/self/fd").unwrap().filter_map(|entry| std::fs::read_link(entry.unwrap().path()).ok()).filter(|target| *target == path).count();
|
||||
assert_eq!(descriptors(), 0);
|
||||
assert!(@failAfterOpen@(name).is_err());
|
||||
assert_eq!(descriptors(), 0);
|
||||
let fault = std::panic::catch_unwind(|| @fault@(name, i64::MAX)).unwrap_err();
|
||||
assert_eq!(fault.downcast_ref::<&'static FaultInfo>().unwrap().source, @source_path@);
|
||||
assert_eq!(descriptors(), 0, "unwinding releases files without business cleanup");
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
@@ -0,0 +1,24 @@
|
||||
request(body: Bytes) (out: dever.http.Request) {
|
||||
out = dever.http.Request { method = "POST", target = "/echo?q=1", headers = [dever.http.header("Host", "localhost")], body = body }
|
||||
}
|
||||
|
||||
records() (out: Bool) {
|
||||
original = request(dever.bytes.fromText("value"))
|
||||
changed = original
|
||||
changed.target = "/changed"
|
||||
header = dever.http.header("X-Name", "one")
|
||||
renamed = header
|
||||
renamed.name = "X-Other"
|
||||
found = dever.http.headerValue([header, dever.http.header("x-name", "two")], "X-NAME")
|
||||
missing = dever.http.headerValue([header], "absent")
|
||||
out = original.target == "/echo?q=1" and changed.target == "/changed" and original.body == changed.body and header.name == "X-Name" and renamed.name == "X-Other" and original != changed and found == dever.bytes.fromText("one") and missing == null
|
||||
}
|
||||
|
||||
flow fetch(address: Text, port: Int, body: Bytes) (response: dever.http.Response)
|
||||
| step | kind | do |
|
||||
| response | flow | dever.http.send(address, port, request(body), dever.http.defaultLimits()) |
|
||||
|
||||
flow scheduled(address: Text, port: Int, body: Bytes) (response: dever.http.Response)
|
||||
| step | kind | do |
|
||||
| pending | calc | run(fetch(address, port, body)) |
|
||||
| response | calc | wait(pending) |
|
||||
@@ -0,0 +1,31 @@
|
||||
use std::io::{Read, Write};
|
||||
use dever_runtime::{task, Bytes};
|
||||
assert!(@records@());
|
||||
for scheduled in [false, true] {
|
||||
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = i64::from(listener.local_addr().unwrap().port());
|
||||
let peer = std::thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
stream.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap();
|
||||
let mut request = Vec::new();
|
||||
while !request.ends_with(b"\r\n\r\nhello") {
|
||||
let mut bytes = [0; 4096];
|
||||
let size = stream.read(&mut bytes).unwrap();
|
||||
assert_ne!(size, 0);
|
||||
request.extend_from_slice(&bytes[..size]);
|
||||
}
|
||||
assert!(request.starts_with(b"POST /echo?q=1 HTTP/1.1\r\n"));
|
||||
stream.write_all(b"HTTP/1.1 202 Accepted\r\nX-Test: one\r\nX-Test: two\r\nContent-Length: 5\r\n\r\nworld").unwrap();
|
||||
});
|
||||
let body = Bytes::from_static(b"hello");
|
||||
let response = if scheduled {
|
||||
task::run(true, 8, async |scope| @scheduled@(scope, "127.0.0.1".into(), port, body).await).unwrap().unwrap()
|
||||
} else {
|
||||
task::execute(true, @fetch@("127.0.0.1", port, body)).unwrap().unwrap()
|
||||
};
|
||||
assert_eq!(response.status, 202);
|
||||
assert_eq!(response.body, Bytes::from_static(b"world"));
|
||||
assert_eq!(response.headers.iter().filter(|header| header.name == "x-test").count(), 2);
|
||||
peer.join().unwrap();
|
||||
}
|
||||
assert!(task::execute(true, @fetch@("localhost", 1, Bytes::new())).unwrap().is_err());
|
||||
@@ -0,0 +1,39 @@
|
||||
flow open(origin: Text, tls: dever.system.ClientTls) (client: dever.system.HttpClient)
|
||||
| step | kind | do |
|
||||
| client | flow | dever.http.client(origin, tls, dever.http.defaultLimits(), dever.http.defaultPoolLimits()) |
|
||||
|
||||
flow fetch(client: dever.system.HttpClient, body: Bytes) (response: dever.http.Response)
|
||||
| step | kind | do |
|
||||
| request | calc | dever.http.Request { method = "POST", target = "/pooled", headers = [], body = body } |
|
||||
| response | flow | dever.http.request(client, request) |
|
||||
|
||||
flow queued(client: dever.system.HttpClient, body: Bytes) (response: dever.http.Response)
|
||||
| step | kind | do |
|
||||
| pending | calc | run(fetch(client, body)) |
|
||||
| response | calc | wait(pending) |
|
||||
|
||||
flow close(client: dever.system.HttpClient) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.http.closeClient(client) |
|
||||
|
||||
rule chunkSize(event: dever.io.ReadEvent) (size: Int)
|
||||
| event | size |
|
||||
| Chunk(bytes) | length(bytes) |
|
||||
| Failed(message) | fail(dever.io.ReadEvent.Failed(message)) |
|
||||
|
||||
loop consumed(body: AsyncStream<dever.io.ReadEvent>) (size: Int)
|
||||
| each event in body | result |
|
||||
| size | sum chunkSize(event) |
|
||||
|
||||
flow download(client: dever.system.HttpClient, body: Bytes) (size: Int)
|
||||
| step | kind | do |
|
||||
| request | calc | dever.http.Request { method = "POST", target = "/pooled", headers = [], body = body } |
|
||||
| response | flow | dever.http.open(client, request) |
|
||||
| size | loop | consumed(response.body) |
|
||||
|
||||
flow upload(client: dever.system.HttpClient, bytes: Bytes) (size: Int)
|
||||
| step | kind | do |
|
||||
| body | calc | stream([dever.io.ReadEvent.Chunk(bytes)]) |
|
||||
| request | calc | dever.http.StreamRequest { method = "POST", target = "/pooled", headers = [], body = body } |
|
||||
| response | flow | dever.http.openStream(client, request) |
|
||||
| size | loop | consumed(response.body) |
|
||||
@@ -0,0 +1,25 @@
|
||||
use dever_runtime::{Bytes, http, net, task, tls};
|
||||
task::run(true, 32, async |scope| {
|
||||
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
|
||||
let origin = format!("http://localhost:{}", listener.port().unwrap());
|
||||
let active = listener.clone();
|
||||
let server = scope.spawn(move |child| async move {
|
||||
http::serve::<false, _, _>(&child, |request, _| async move {
|
||||
assert_eq!(request.target, "/pooled");
|
||||
Ok(http::Response { status: 201, headers: vec![], body: request.body })
|
||||
}, &active, &http::Limits { header_bytes: 8192, body_bytes: 1048576, timeout_ms: 1000, connections: 32, http2: None }, None).await
|
||||
}).unwrap();
|
||||
let client = @open@(scope, &origin, &tls::system()).await.unwrap();
|
||||
let response = @fetch@(&client, Bytes::from_static(b"one")).await.unwrap();
|
||||
assert_eq!(response.status, 201);
|
||||
assert_eq!(response.body, b"one"[..]);
|
||||
let response = @queued@(scope, client.clone(), Bytes::from_static(b"two")).await.unwrap();
|
||||
assert_eq!(response.body, b"two"[..]);
|
||||
assert_eq!(@download@(&client, Bytes::from_static(b"streamed")).await.unwrap(), 8);
|
||||
assert_eq!(@upload@(&client, Bytes::from_static(b"uploaded")).await.unwrap(), 8);
|
||||
@close@(&client).await.unwrap();
|
||||
assert!(@fetch@(&client, Bytes::new()).await.is_err());
|
||||
listener.close().unwrap();
|
||||
server.await.unwrap().unwrap();
|
||||
Ok::<_, ()>(())
|
||||
}).unwrap().unwrap();
|
||||
@@ -0,0 +1,90 @@
|
||||
setting prefix: Text
|
||||
|
||||
echo(request: dever.http.Request) (response: dever.http.Response) {
|
||||
response = dever.http.Response { status = 200, headers = [], body = request.body }
|
||||
}
|
||||
|
||||
flow routed(request: dever.http.Request) (response: dever.http.Response)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(1) |
|
||||
| response | calc | echo(request) |
|
||||
|
||||
flow scheduledRoute(request: dever.http.Request) (response: dever.http.Response)
|
||||
| step | kind | do |
|
||||
| child | calc | run(routed(request)) |
|
||||
| response | calc | wait(child) |
|
||||
|
||||
configured(request: dever.http.Request) (response: dever.http.Response) {
|
||||
response = dever.http.Response {
|
||||
status = 201
|
||||
headers = [dever.http.header("x-prefix", prefix), dever.http.header("x-method", request.method), dever.http.header("x-target", request.target)]
|
||||
body = request.body
|
||||
}
|
||||
}
|
||||
|
||||
failed(request: dever.http.Request) (response: dever.http.Response) {
|
||||
check request.target != "/fail" else Invalid
|
||||
response = echo(request)
|
||||
}
|
||||
|
||||
overflow(request: dever.http.Request) (response: dever.http.Response) {
|
||||
n = int.parse(dever.bytes.toText(request.body))
|
||||
check n != null else Invalid
|
||||
response = dever.http.Response { status = n + 1, headers = [], body = request.body }
|
||||
}
|
||||
|
||||
flow start(listener: dever.system.Listener, limits: dever.http.Limits) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.http.serve(echo, listener, limits) |
|
||||
|
||||
flow startAsync(listener: dever.system.Listener, limits: dever.http.Limits) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.http.serve(routed, listener, limits) |
|
||||
|
||||
flow startTasks(listener: dever.system.Listener, limits: dever.http.Limits) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.http.serve(scheduledRoute, listener, limits) |
|
||||
|
||||
flow startConfig(listener: dever.system.Listener, limits: dever.http.Limits) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.http.serve(configured, listener, limits) |
|
||||
|
||||
flow startFailure(listener: dever.system.Listener, limits: dever.http.Limits) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.http.serve(failed, listener, limits) |
|
||||
|
||||
flow startFault(listener: dever.system.Listener, limits: dever.http.Limits) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.http.serve(overflow, listener, limits) |
|
||||
|
||||
flow startTls(listener: dever.system.Listener, limits: dever.http.Limits, tls: dever.system.ServerTls) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.http.serveTls(echo, listener, limits, tls) |
|
||||
|
||||
flow liveRoute(request: dever.http.Request, reply: dever.system.HttpReply) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.http.start(reply, 200, []) |
|
||||
| - | flow | dever.http.write(reply, request.body) |
|
||||
| - | flow | dever.http.finish(reply) |
|
||||
|
||||
flow eventRoute(request: dever.http.Request, reply: dever.system.HttpReply) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.sse.start(reply, []) |
|
||||
| - | flow | dever.sse.send(reply, dever.sse.Event { event = "message", data = dever.bytes.toText(request.body), id = null, retry_ms = null }) |
|
||||
| - | flow | dever.http.finish(reply) |
|
||||
|
||||
flow completeRoute(request: dever.http.Request, reply: dever.system.HttpReply) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.http.respond(reply, echo(request)) |
|
||||
|
||||
flow startLive(listener: dever.system.Listener, limits: dever.http.Limits) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.http.serveLive(liveRoute, listener, limits, dever.http.defaultLiveLimits()) |
|
||||
|
||||
flow startEvents(listener: dever.system.Listener, limits: dever.http.Limits) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.http.serveLive(eventRoute, listener, limits, dever.http.defaultLiveLimits()) |
|
||||
|
||||
flow startComplete(listener: dever.system.Listener, limits: dever.http.Limits) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.http.serveLive(completeRoute, listener, limits, dever.http.defaultLiveLimits()) |
|
||||
@@ -0,0 +1,69 @@
|
||||
use dever_runtime::{Bytes, http, net, task};
|
||||
use std::sync::Arc;
|
||||
let settings = Arc::new(SettingValues { f0: "shared".into() });
|
||||
for http2 in [false, true] {
|
||||
for mode in 0..9 {
|
||||
let settings = settings.clone();
|
||||
task::run(true, 32, async |scope| {
|
||||
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
|
||||
let port = listener.port().unwrap();
|
||||
let active = listener.clone();
|
||||
let server = scope.spawn(move |child| async move {
|
||||
let mut limits = @defaultLimits@();
|
||||
if http2 { limits.f4 = Some(@defaultHttp2Limits@()); }
|
||||
match mode {
|
||||
0 => @start@(&child, &active, &limits).await,
|
||||
1 => @startAsync@(&child, &active, &limits).await,
|
||||
2 => @startTasks@(&child, &active, &limits).await,
|
||||
3 => @startConfig@(&child, &settings, &active, &limits).await,
|
||||
4 => @startFailure@(&child, &active, &limits).await,
|
||||
5 => @startFault@(&child, &active, &limits).await,
|
||||
6 => @startLive@(&child, &active, &limits).await,
|
||||
7 => @startEvents@(&child, &active, &limits).await,
|
||||
_ => @startComplete@(&child, &active, &limits).await,
|
||||
}
|
||||
}).unwrap();
|
||||
let limits = http::Limits { header_bytes: 8192, body_bytes: 1048576, timeout_ms: 1000, connections: 32, http2: http2.then_some(http::Http2Limits { streams: 16, stream_window_bytes: 65535, connection_window_bytes: 262144 }) };
|
||||
for target in ["/fail", "/echo?q=one%20two"] {
|
||||
let body = if mode == 5 { if target == "/fail" { b"9223372036854775807".as_slice() } else { b"199".as_slice() } } else { b"native".as_slice() };
|
||||
let response = http::send("127.0.0.1", port, http::Request { method: "POST".into(), target: target.into(), headers: vec![http::Header { name: "host".into(), value: Bytes::from_static(b"localhost") }], body: Bytes::from_static(body) }, &limits).await.unwrap();
|
||||
let status = if (mode == 4 || mode == 5) && target == "/fail" { 500 } else if mode == 3 { 201 } else { 200 };
|
||||
assert_eq!(response.status, status);
|
||||
assert_eq!(response.body.as_ref(), if status == 500 { b"".as_slice() } else if mode == 7 { b"event: message
|
||||
data: native
|
||||
|
||||
".as_slice() } else { body });
|
||||
if mode == 3 {
|
||||
for (name, value) in [("x-prefix", "shared"), ("x-method", "POST"), ("x-target", target)] {
|
||||
assert!(response.headers.iter().any(|h| h.name == name && h.value == value.as_bytes()));
|
||||
}
|
||||
}
|
||||
}
|
||||
listener.close().unwrap();
|
||||
server.await.unwrap().unwrap();
|
||||
Ok::<_, ()>(())
|
||||
}).unwrap().unwrap();
|
||||
}
|
||||
}
|
||||
task::run(true, 16, async |scope| {
|
||||
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
|
||||
let port = listener.port().unwrap();
|
||||
let active = listener.clone();
|
||||
let fixtures = std::path::Path::new(@tls_fixtures@);
|
||||
let tls = dever_runtime::tls::server(&std::fs::read(fixtures.join("server.pem")).unwrap(), &std::fs::read(fixtures.join("server-key.pem")).unwrap()).unwrap();
|
||||
let server = scope.spawn(move |child| async move { @startTls@(&child, &active, &@defaultLimits@(), &tls).await }).unwrap();
|
||||
let root = fixtures.join("root.pem");
|
||||
let response = scope.parallel(move || std::process::Command::new("python3").args(["-c", r#"
|
||||
import ssl, http.client, sys
|
||||
c = http.client.HTTPSConnection('localhost', int(sys.argv[1]), timeout=3, context=ssl.create_default_context(cafile=sys.argv[2]))
|
||||
c.request('POST', '/tls', b'certificate verified')
|
||||
r = c.getresponse()
|
||||
assert r.status == 200
|
||||
assert r.read() == b'certificate verified'
|
||||
c.close()
|
||||
"#, &port.to_string(), root.to_str().unwrap()]).output().unwrap()).await.unwrap();
|
||||
assert!(response.status.success(), "{}", String::from_utf8_lossy(&response.stderr));
|
||||
listener.close().unwrap();
|
||||
server.await.unwrap().unwrap();
|
||||
Ok::<_, ()>(())
|
||||
}).unwrap().unwrap();
|
||||
@@ -0,0 +1,515 @@
|
||||
putCount(value: Int, previous: Map<Int, Int>) (out: Map<Int, Int>) {
|
||||
key = length(previous)
|
||||
out = put(previous, key, value + key)
|
||||
}
|
||||
|
||||
loop growMap(values: List<Int>, seed: Map<Int, Int>) (out: Map<Int, Int>)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = seed, putCount(value, acc)) |
|
||||
|
||||
keepMap(values: List<Int>, seed: Map<Int, Int>) (updated: Map<Int, Int>, original: Map<Int, Int>) {
|
||||
updated = growMap(values, seed)
|
||||
original = seed
|
||||
}
|
||||
|
||||
putKey(previous: Map<Int, Int>, value: Int) (out: Map<Int, Int>) {
|
||||
out = put(previous, value % 2, value)
|
||||
}
|
||||
|
||||
loop replaceKeys(start: Int, end: Int) (out: Map<Int, Int>)
|
||||
| each value in range(start, end) | result |
|
||||
| out | fold(acc = {}, putKey(acc, value)) |
|
||||
|
||||
loop growBytes(values: Bytes) (out: List<Int>)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = [], addValue(value, acc)) |
|
||||
|
||||
mapKeyFault(value: Int, previous: Map<Int, Int>) (out: Map<Int, Int>) {
|
||||
key = value + 9_223_372_036_854_775_807
|
||||
out = put(previous, key, value)
|
||||
}
|
||||
|
||||
loop mapFault(values: List<Int>) (out: Map<Int, Int>)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = {}, mapKeyFault(value, acc)) |
|
||||
|
||||
accumulate(value: Int, previous: Int) (out: Int) { out = previous + value }
|
||||
|
||||
type Cursor { position: Int, end: Int }
|
||||
|
||||
rule cursorNext(more: Bool, cursor: Cursor) (out: Walk<Int, Cursor>)
|
||||
| more | cursor | out |
|
||||
| true | - | Next(cursor.position, Cursor { position = cursor.position + 1, end = cursor.end }) |
|
||||
| false | - | Done |
|
||||
|
||||
advance(cursor: Cursor) (out: Walk<Int, Cursor>) {
|
||||
out = cursorNext(cursor.position < cursor.end, cursor)
|
||||
}
|
||||
|
||||
advanceChecked(cursor: Cursor) (out: Walk<Int, Cursor>) {
|
||||
check cursor.position <= 1 else Invalid
|
||||
out = advance(cursor)
|
||||
}
|
||||
|
||||
loop walked(start: Int, end: Int) (items: List<Int>, total: Int)
|
||||
| each value in walk(Cursor { position = start, end = end }, advance) | result |
|
||||
| items | list value |
|
||||
| total | sum value |
|
||||
|
||||
loop walkFirst() (out: Int?)
|
||||
| each value in walk(Cursor { position = 0, end = 5 }, advanceChecked) | result |
|
||||
| out | first value |
|
||||
|
||||
loop walkMixed() (first: Int?, total: Int)
|
||||
| each value in walk(Cursor { position = 0, end = 5 }, advanceChecked) | result |
|
||||
| first | first value |
|
||||
| total | sum value |
|
||||
|
||||
loop walkNone() (out: List<Int>)
|
||||
| each value in walk(Cursor { position = 2, end = 5 }, advanceChecked) | take | result |
|
||||
| out | 0 | list value |
|
||||
|
||||
rule textNext(state: Text) (out: Walk<Text, Text>)
|
||||
| state | out |
|
||||
| "" | Walk.Done |
|
||||
| other | Walk.Next(state, "") |
|
||||
|
||||
loop walkText(seed: Text) (out: List<Text>)
|
||||
| each value in walk(seed, textNext) | result |
|
||||
| out | list value |
|
||||
|
||||
loop walkTextSize(seed: Text) (out: Int)
|
||||
| each value in walk(seed, textNext) | result |
|
||||
| out | sum length(value) |
|
||||
|
||||
decimalAdd(value: Decimal, previous: Decimal) (out: Decimal) { out = previous + value }
|
||||
floatAdd(value: Float, previous: Float) (out: Float) { out = previous + value }
|
||||
|
||||
loop decimalFold(values: List<Decimal>) (out: Decimal)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = 0, decimalAdd(value, acc)) |
|
||||
|
||||
loop floatFold(values: List<Float>) (out: Float)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = 0.0, floatAdd(value, acc)) |
|
||||
|
||||
type FoldState { title: Text, count: Int }
|
||||
|
||||
countNext(value: Int, previous: FoldState) (out: FoldState) {
|
||||
out = FoldState { title = previous.title, count = previous.count + value }
|
||||
}
|
||||
|
||||
loop countState(values: List<Int>, seed: FoldState) (out: FoldState)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = seed, countNext(value, acc)) |
|
||||
|
||||
sharedState(values: List<Int>, seed: FoldState) (out: FoldState, original: FoldState) {
|
||||
out = countState(values, seed)
|
||||
original = seed
|
||||
}
|
||||
|
||||
loop folded(values: List<Int>, seed: Int) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = seed, accumulate(value, acc)) |
|
||||
|
||||
accumulateUntil(value: Int, previous: Int, limit: Int) (acc: Int, stop: Bool) {
|
||||
acc = previous + value
|
||||
stop = acc >= limit
|
||||
}
|
||||
|
||||
loop bounded(values: List<Int>, limit: Int) (first: Int, total: Int)
|
||||
| each value in values | result |
|
||||
| first | foldUntil(acc = 0, accumulateUntil(value, acc, limit)) |
|
||||
| total | fold(acc = 0, accumulate(value, acc)) |
|
||||
|
||||
addValue(value: Int, previous: List<Int>) (out: List<Int>) { out = append(previous, value) }
|
||||
|
||||
loop foldList(values: List<Int>) (out: List<Int>)
|
||||
| each value in values | value | result |
|
||||
| out | > 0 | fold(acc = [], addValue(value, acc)) |
|
||||
|
||||
keepText(previous: Text) (out: Text) { out = previous }
|
||||
|
||||
loop keepSeed(values: List<Int>, seed: Text) (out: Text)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = seed, keepText(acc)) |
|
||||
|
||||
findValue(value: Int) (acc: Int?, stop: Bool) {
|
||||
acc = value
|
||||
stop = value > 0
|
||||
}
|
||||
|
||||
loop findFold(values: List<Int>) (out: Int?)
|
||||
| each value in values | result |
|
||||
| out | foldUntil(previous = null, findValue(value)) |
|
||||
|
||||
checkedAdd(value: Int, previous: Int) (out: Int) { out = previous + checked(value) }
|
||||
|
||||
loop checkedFold(values: List<Int>) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = 0, checkedAdd(value, acc)) |
|
||||
|
||||
badSource() (out: List<Int>) { fail(Invalid) }
|
||||
badSeed() (out: Int) { fail(Forbidden) }
|
||||
|
||||
badUpdate(previous: Int) (acc: Int, stop: Bool) { fail(Conflict) }
|
||||
|
||||
loop updateFailure(values: List<Int>) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | foldUntil(acc = 7, badUpdate(acc)) |
|
||||
|
||||
loop rangeFailure() (out: Int)
|
||||
| each value in range(badSeed(), 10) | result |
|
||||
| out | fold(acc = 0, accumulate(value, acc)) |
|
||||
|
||||
loop rangeEndFailure() (out: Int)
|
||||
| each value in range(0, badSeed()) | result |
|
||||
| out | fold(acc = 0, accumulate(value, acc)) |
|
||||
|
||||
loop sourceBeforeSeed() (out: Int)
|
||||
| each value in badSource() | result |
|
||||
| out | fold(acc = badSeed(), accumulate(value, acc)) |
|
||||
|
||||
loop seedBeforeConsume(values: List<Int>) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = badSeed(), accumulate(value, acc)) |
|
||||
|
||||
loop indexed(values: List<Int>) (out: Map<Int, Int>)
|
||||
| each value in values | result |
|
||||
| out | index value |
|
||||
|
||||
type IndexResult { Ready(value: Map<Int, Int>), error Duplicate(reason: dever.collection.Error) }
|
||||
|
||||
captureIndex(values: List<Int>) (out: IndexResult) { out = result(indexed(values)) }
|
||||
|
||||
loop indexNames(values: List<Text>) (out: Map<Int, Text>)
|
||||
| each value in values | result |
|
||||
| out | index length(value) |
|
||||
|
||||
loop indexFiltered(values: List<Int>) (out: Map<Int, Int>)
|
||||
| each value in values | value | result |
|
||||
| out | >= 0 | index checked(value) |
|
||||
|
||||
loop indexFailure(values: List<Int>) (out: Map<Int, Int>)
|
||||
| each value in values | result |
|
||||
| out | index checked(value) |
|
||||
|
||||
loop grouped(values: List<Int>) (out: Map<Int, List<Int>>)
|
||||
| each value in values | result |
|
||||
| out | group value % 2 |
|
||||
|
||||
loop groupNames(values: List<Text>) (out: Map<Int, List<Text>>)
|
||||
| each value in values | result |
|
||||
| out | group length(value) |
|
||||
|
||||
loop groupCopies(values: List<Text>) (copy: List<Text>, out: Map<Text, List<Text>>)
|
||||
| each value in values | result |
|
||||
| copy | list value |
|
||||
| out | group value |
|
||||
|
||||
loop groupFiltered(values: List<Int>) (out: Map<Int, List<Int>>)
|
||||
| each value in values | value | result |
|
||||
| out | >= 0 | group checked(value) |
|
||||
|
||||
loop groupFailure(values: List<Int>) (out: Map<Int, List<Int>>)
|
||||
| each value in values | result |
|
||||
| out | group checked(value) |
|
||||
|
||||
loop totals(values: List<Int>) (total: Int, items: List<Int>, count: Int >= 0, first: Int?, smallest: Int?, largest: Int?)
|
||||
| each value in values | result |
|
||||
| largest | max value |
|
||||
| count | count |
|
||||
| total | sum value |
|
||||
| items | list value |
|
||||
| first | first value |
|
||||
| smallest | min value |
|
||||
|
||||
loop ranged(start: Int, end: Int) (total: Int, count: Int)
|
||||
| each value in range(start, end) | result |
|
||||
| total | sum value |
|
||||
| count | count |
|
||||
|
||||
positive(value: Int) (out: Bool) {
|
||||
check value >= 0 else Invalid
|
||||
out = value > 0
|
||||
}
|
||||
|
||||
checked(value: Int) (out: Int) {
|
||||
check value >= 0 else Invalid
|
||||
out = value
|
||||
}
|
||||
|
||||
loop anyPositive(values: List<Int>) (out: Bool)
|
||||
| each value in values | result |
|
||||
| out | any positive(value) |
|
||||
|
||||
loop allPositive(values: List<Int>) (out: Bool)
|
||||
| each value in values | result |
|
||||
| out | all positive(value) |
|
||||
|
||||
loop firstPositive(values: List<Int>) (out: Int?)
|
||||
| each value in values | result |
|
||||
| out | first checked(value) |
|
||||
|
||||
loop mixed(values: List<Int>) (first: Int?, total: Int)
|
||||
| each value in values | result |
|
||||
| first | first checked(value) |
|
||||
| total | sum checked(value) |
|
||||
|
||||
loop names(values: List<Text>) (copied: List<Text>, first: Text?, smallest: Text?)
|
||||
| each value in values | result |
|
||||
| copied | list value |
|
||||
| first | first value |
|
||||
| smallest | min value |
|
||||
|
||||
loop repeated(values: List<Int>, label: Text) (out: List<Text>)
|
||||
| each value in values | result |
|
||||
| out | list label |
|
||||
|
||||
loop decimalTotal(values: List<Decimal>) (out: Decimal)
|
||||
| each value in values | result |
|
||||
| out | sum value |
|
||||
|
||||
loop floatTotal(values: List<Float>) (out: Float)
|
||||
| each value in values | result |
|
||||
| out | sum value |
|
||||
|
||||
loop action(values: List<Int>) ()
|
||||
| each value in values | result |
|
||||
| - | do checked(value) |
|
||||
|
||||
loop actionCount(values: List<Int>) (count: Int)
|
||||
| each value in values | result |
|
||||
| count | do checked(value) |
|
||||
|
||||
flow main() (out: Int)
|
||||
| step | kind | do |
|
||||
| result | loop | ranged(0, 5) |
|
||||
| out | calc | result.total |
|
||||
loop filtered(values: List<Int>) (positive: List<Int>, first: Int?, count: Int, total: Int)
|
||||
| each value in values | value | 12 / value | result |
|
||||
| positive | > 0 | - | list value |
|
||||
| first | > 0 | >= 2 | first value |
|
||||
| count | - | - | count |
|
||||
| total | < 0, > 0 | - | sum value |
|
||||
|
||||
loop optionalNames(values: List<Text?>) (missing: Int, selected: List<Text?>)
|
||||
| each value in values | value | result |
|
||||
| missing | null | count |
|
||||
| selected | "甲", "乙" | list value |
|
||||
|
||||
loop filteredFailure(values: List<Int>) (out: Int?)
|
||||
| each value in values | value | result |
|
||||
| out | >= 0 | first checked(value) |
|
||||
|
||||
loop filteredOwned(values: List<Text>) (copied: List<Text>, selected: Int)
|
||||
| each value in values | length(value + "!") | result |
|
||||
| copied | > 1 | list value |
|
||||
| selected | > 1 | count |
|
||||
|
||||
positiveOnly(value: Int >= 1) (out: Int) { out = value }
|
||||
|
||||
loop refined(values: List<Int?>) (out: List<Int>)
|
||||
| each value in values | value | result |
|
||||
| out | >= 1 | list positiveOnly(value) |
|
||||
|
||||
loop refinedNames(values: List<Text?>) (out: List<Text>, count: Int)
|
||||
| each value in values | value | result |
|
||||
| out | "甲", "乙" | list value |
|
||||
| count | - | count |
|
||||
|
||||
type Event { Named(label: Text), Tagged(label: Text), Empty }
|
||||
type Envelope { event: Event }
|
||||
type MaybeEnvelope { event: Event? }
|
||||
|
||||
loop payloads(values: List<Event>) (labels: List<Text>, size: Int)
|
||||
| each value in values | value | result |
|
||||
| labels | Named(label), Tagged(label) | list label |
|
||||
| size | Named(label), Tagged(label) | sum length(label) |
|
||||
|
||||
loop payloadFields(values: List<Envelope>) (labels: List<Text>, size: Int)
|
||||
| each value in values | value.event | result |
|
||||
| labels | Named(label), Tagged(label) | list label |
|
||||
| size | Named(label), Tagged(label) | sum length(label) |
|
||||
|
||||
loop optionalPayloads(values: List<MaybeEnvelope>) (labels: List<Text>)
|
||||
| each value in values | value.event | result |
|
||||
| labels | Named(label), Tagged(label) | list label |
|
||||
|
||||
wrap(value: Int) (out: Event?) { out = Event.Named("名") }
|
||||
|
||||
loop computedPayloads(values: List<Int>) (labels: List<Text>)
|
||||
| each value in values | wrap(value) | result |
|
||||
| labels | Named(label), Tagged(label) | list label |
|
||||
|
||||
loop movingPayloads(values: List<Event>) (labels: List<Text>)
|
||||
| each value in values | value | result |
|
||||
| labels | Named(label), Tagged(label) | list label |
|
||||
|
||||
type InputState { Ready, error Broken }
|
||||
|
||||
loop rejectBroken(values: List<InputState>) ()
|
||||
| each value in values | value | result |
|
||||
| - | Broken | do fail(value) |
|
||||
|
||||
loop limited(values: List<Int>, limit: Int >= 0) (out: List<Int>, count: Int)
|
||||
| each value in values | value | take | result |
|
||||
| out | >= 0 | limit | list checked(value) |
|
||||
| count | - | - | count |
|
||||
|
||||
loop takeOnly(values: List<Int>, limit: Int >= 0) (out: List<Int>)
|
||||
| each value in values | take | result |
|
||||
| out | limit | list checked(value) |
|
||||
|
||||
loop takeZero(values: List<Int>) (out: List<Int>)
|
||||
| each value in values | 1 / value | take | result |
|
||||
| out | > 0 | 0 | list checked(value) |
|
||||
|
||||
loop initializeLimit(values: List<Int>, size: Int >= 0) (out: List<Int>)
|
||||
| each value in values | take | result |
|
||||
| out | size + 1 | list value |
|
||||
|
||||
type Ranked { group: Int, score: Decimal, label: Text }
|
||||
|
||||
loop ranked(values: List<Ranked>, limit: Int >= 0) (out: List<Text>, count: Int)
|
||||
| each value in values | sort | take | result |
|
||||
| out | [value.group.asc, value.score.desc] | limit | list value.label |
|
||||
| count | - | - | count |
|
||||
|
||||
loop sortedTexts(values: List<Text>) (out: List<Text>)
|
||||
| each value in values | sort | result |
|
||||
| out | [length(value).asc] | list value |
|
||||
|
||||
loop sortedChecked(values: List<Int>, limit: Int >= 0) (out: List<Int>)
|
||||
| each value in values | sort | take | result |
|
||||
| out | [value.desc] | limit | list checked(value) |
|
||||
|
||||
loop sortBeforeResult(values: List<Int>, limit: Int >= 0) (out: List<Int>)
|
||||
| each value in values | sort | take | result |
|
||||
| out | [(1 / value).asc] | limit | list checked(-1) |
|
||||
|
||||
type ListState { items: List<Int>, left: Int, right: Int }
|
||||
|
||||
inlineNext(previous: ListState, value: Int) (out: ListState) {
|
||||
out = ListState { items = append(previous.items, value), left = previous.right, right = previous.left }
|
||||
}
|
||||
|
||||
loop inlineState(values: List<Int>, seed: ListState) (out: ListState)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = seed, inlineNext(acc, value)) |
|
||||
|
||||
keepListState(values: List<Int>, seed: ListState) (updated: ListState, original: ListState) {
|
||||
updated = inlineState(values, seed)
|
||||
original = seed
|
||||
}
|
||||
|
||||
prefixNext(value: Int, previous: ListState) (out: ListState) {
|
||||
count = length(previous.items)
|
||||
out = ListState { left = previous.right + count, items = append(previous.items, value + count), right = previous.left }
|
||||
}
|
||||
|
||||
loop prefixState(values: List<Int>, seed: ListState) (out: ListState)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = seed, prefixNext(value, acc)) |
|
||||
|
||||
aliasNext(value: Int, previous: ListState) (out: ListState) {
|
||||
items = append(previous.items, length(previous.items) + value)
|
||||
count = previous.left + 1
|
||||
out = ListState { right = previous.left, left = count, items = items }
|
||||
}
|
||||
|
||||
loop aliasState(values: List<Int>, seed: ListState) (out: ListState)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = seed, aliasNext(value, acc)) |
|
||||
|
||||
oldListNext(value: Int, previous: ListState) (out: ListState) {
|
||||
items = append(previous.items, value)
|
||||
count = length(previous.items)
|
||||
out = ListState { items = items, left = count, right = length(items) }
|
||||
}
|
||||
|
||||
loop oldListState(values: List<Int>, seed: ListState) (out: ListState)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = seed, oldListNext(value, acc)) |
|
||||
|
||||
stateCount(previous: ListState) (out: Int) { out = length(previous.items) }
|
||||
|
||||
wholeStateNext(value: Int, previous: ListState) (out: ListState) {
|
||||
out = ListState { items = append(previous.items, stateCount(previous) + value), left = previous.left, right = previous.right }
|
||||
}
|
||||
|
||||
loop wholeState(values: List<Int>, seed: ListState) (out: ListState)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = seed, wholeStateNext(value, acc)) |
|
||||
|
||||
recordFaultNext(previous: ListState, value: Int) (out: ListState) {
|
||||
out = ListState { left = previous.left + value, items = append(previous.items, 1 // value), right = previous.right }
|
||||
}
|
||||
|
||||
loop recordFault(values: List<Int>, seed: ListState) (out: ListState)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = seed, recordFaultNext(acc, value)) |
|
||||
|
||||
type ReadState { items: List<Int>, first: Int? }
|
||||
|
||||
readStateNext(previous: ReadState, value: Int) (out: ReadState) {
|
||||
first = get(previous.items, 0)
|
||||
out = ReadState { items = append(previous.items, value), first = first }
|
||||
}
|
||||
|
||||
loop readState(values: List<Int>, seed: ReadState) (out: ReadState)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = seed, readStateNext(acc, value)) |
|
||||
|
||||
type TextState { items: List<Text>, count: Int }
|
||||
|
||||
textStateNext(previous: TextState, value: Int) (out: TextState) {
|
||||
out = TextState { items = append(previous.items, "next"), count = previous.count + value }
|
||||
}
|
||||
|
||||
loop textState(values: List<Int>, seed: TextState) (out: TextState)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = seed, textStateNext(acc, value)) |
|
||||
|
||||
loop sumChecked(values: List<Int>) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | sum value |
|
||||
|
||||
loop sumBeforeFault(values: List<Int>) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | sum 9_223_372_036_854_775_807 // value |
|
||||
|
||||
appendTextPart(value: Text, previous: Text) (out: Text) { out = previous + value }
|
||||
|
||||
loop joinTextParts(values: List<Text>, seed: Text) (out: Text)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = seed, appendTextPart(value, acc)) |
|
||||
|
||||
keepTextParts(values: List<Text>, seed: Text) (out: Text, original: Text) {
|
||||
out = joinTextParts(values, seed)
|
||||
original = seed
|
||||
}
|
||||
|
||||
|
||||
loop projectedKeys(rows: List<MapEntry<Text, Int>>) (out: List<Text>)
|
||||
| each row in rows | result |
|
||||
| out | list row.key |
|
||||
|
||||
loop projectedValues(rows: List<MapEntry<Text, Int>>) (out: List<Int>)
|
||||
| each row in rows | result |
|
||||
| out | list row.value |
|
||||
|
||||
projectEntries(table: Map<Text, Int>) (keys: List<Text>, values: List<Int>, original: Map<Text, Int>) {
|
||||
keys = projectedKeys(entries(table))
|
||||
values = projectedValues(entries(table))
|
||||
original = table
|
||||
}
|
||||
|
||||
loop projectedLists(rows: List<MapEntry<Int, List<Text>>>) (out: List<List<Text>>)
|
||||
| each row in rows | result |
|
||||
| out | list row.value |
|
||||
|
||||
projectLists(table: Map<Int, List<Text>>) (values: List<List<Text>>, original: Map<Int, List<Text>>) {
|
||||
values = projectedLists(entries(table))
|
||||
original = table
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
let seed = Map::with_capacity(0);
|
||||
assert!(@growMap@(&[], seed.clone()).is_empty());
|
||||
let kept = @keepMap@(&[4, 5], seed);
|
||||
assert!(kept.f1.is_empty());
|
||||
assert_eq!(kept.f0.into_entries().iter().map(|row| (row.f0, row.f1)).collect::<Vec<_>>(), vec![(0, 4), (1, 6)]);
|
||||
let mut seed = Map::with_capacity(0);
|
||||
seed.put(10, 20);
|
||||
let kept = @keepMap@(&[4], seed);
|
||||
assert_eq!(kept.f1.into_entries().iter().map(|row| (row.f0, row.f1)).collect::<Vec<_>>(), vec![(10, 20)]);
|
||||
assert_eq!(kept.f0.into_entries().iter().map(|row| (row.f0, row.f1)).collect::<Vec<_>>(), vec![(10, 20), (1, 5)]);
|
||||
assert_eq!(@replaceKeys@(0, 4).into_entries().iter().map(|row| (row.f0, row.f1)).collect::<Vec<_>>(), vec![(0, 2), (1, 3)]);
|
||||
assert!(@replaceKeys@(4, 0).is_empty());
|
||||
assert_eq!(@growBytes@(&dever_runtime::Bytes::from_static(b"abc")), vec![97, 98, 99]);
|
||||
let fault = std::panic::catch_unwind(|| @mapFault@(&[1])).unwrap_err();
|
||||
let fault = fault.downcast_ref::<&'static FaultInfo>().unwrap();
|
||||
assert_eq!(fault.line, 28);
|
||||
assert_eq!(@folded@(&[], 7), 7);
|
||||
let walked = @walked@(2, 5);
|
||||
assert_eq!((walked.f0, walked.f1), (vec![2, 3, 4], 9));
|
||||
let empty_walk = @walked@(5, 2);
|
||||
assert_eq!((empty_walk.f0, empty_walk.f1), (vec![], 0));
|
||||
assert_eq!(@walkFirst@().unwrap(), Some(0));
|
||||
assert!(matches!(@walkMixed@(), Err(Failure::Api(ApiError::Invalid))));
|
||||
assert!(@walkNone@().unwrap().is_empty());
|
||||
let text = String::from("原状态移动到步进输出");
|
||||
let pointer = text.as_ptr();
|
||||
let walked_text = @walkText@(text);
|
||||
assert_eq!(walked_text.len(), 1);
|
||||
assert_eq!(walked_text[0].as_ptr(), pointer);
|
||||
assert_eq!(@walkTextSize@(String::from("中文")), 2);
|
||||
assert_eq!(@decimalFold@(&[Decimal::parse("0.1").unwrap(), Decimal::parse("0.2").unwrap()]).to_string(), "0.3");
|
||||
assert_eq!(@floatFold@(&[1e16, -1e16, 1.0]), 1.0);
|
||||
let title = String::from("记录状态移动");
|
||||
let pointer = title.as_ptr();
|
||||
let state = @countState@(&[2, 3], @FoldState@ { f0: title, f1: 1 });
|
||||
assert_eq!((state.f0.as_ptr(), state.f1), (pointer, 6));
|
||||
let shared = @sharedState@(&[2, 3], state);
|
||||
assert_eq!((shared.f0.f1, shared.f1.f1), (11, 6));
|
||||
assert_eq!(shared.f0.f0, shared.f1.f0);
|
||||
assert_eq!(@folded@(&[2, -3, 4], 7), 10);
|
||||
let bounded = @bounded@(&[2, 3, 10], 4);
|
||||
assert_eq!((bounded.f0, bounded.f1), (5, 15));
|
||||
assert_eq!(@foldList@(&[-1, 2, 0, 3]), vec![2, 3]);
|
||||
assert_eq!(@findFold@(&[]), None);
|
||||
assert_eq!(@findFold@(&[-1, 2, 3]), Some(2));
|
||||
assert_eq!(@checkedFold@(&[2, 3]).unwrap(), 5);
|
||||
assert!(matches!(@checkedFold@(&[2, -3]), Err(Failure::Api(ApiError::Invalid))));
|
||||
assert!(matches!(@sourceBeforeSeed@(), Err(Failure::Api(ApiError::Invalid))));
|
||||
assert!(matches!(@seedBeforeConsume@(&[]), Err(Failure::Api(ApiError::Forbidden))));
|
||||
assert_eq!(@updateFailure@(&[]).unwrap(), 7);
|
||||
assert!(matches!(@updateFailure@(&[1]), Err(Failure::Api(ApiError::Conflict))));
|
||||
assert!(matches!(@rangeFailure@(), Err(Failure::Api(ApiError::Forbidden))));
|
||||
assert!(matches!(@rangeEndFailure@(), Err(Failure::Api(ApiError::Forbidden))));
|
||||
let seed = String::from("累积状态直接移动");
|
||||
let pointer = seed.as_ptr();
|
||||
assert_eq!(@keepSeed@(&[1, 2, 3], seed).as_ptr(), pointer);
|
||||
assert!(std::panic::catch_unwind(|| @folded@(&[1], i64::MAX)).is_err());
|
||||
let indexed = @indexed@(&[3, 1, 2]).unwrap().into_entries();
|
||||
assert_eq!(indexed.iter().map(|entry| (entry.f0, entry.f1)).collect::<Vec<_>>(), vec![(3, 3), (1, 1), (2, 2)]);
|
||||
assert!(@indexed@(&[]).unwrap().is_empty());
|
||||
assert!(matches!(@indexed@(&[1, 1]), Err(Failure::@Error@(@Error@::DuplicateKey))));
|
||||
assert!(matches!(@captureIndex@(&[1, 1]), @IndexResult@::Duplicate(@Error@::DuplicateKey)));
|
||||
assert!(matches!(@captureIndex@(&[1]), @IndexResult@::Ready(_)));
|
||||
assert!(matches!(@indexFailure@(&[1, 1, -1]), Err(Failure::@Error@(@Error@::DuplicateKey))));
|
||||
assert!(matches!(@indexFailure@(&[1, -1, 1]), Err(Failure::Api(ApiError::Invalid))));
|
||||
assert_eq!(@indexFiltered@(&[-1, -1, 2]).unwrap().len(), 1);
|
||||
let name = String::from("移动到索引,不复制文本");
|
||||
let pointer = name.as_ptr();
|
||||
let indexed = @indexNames@(vec![name]).unwrap().into_entries();
|
||||
assert_eq!(indexed[0].f1.as_ptr(), pointer);
|
||||
let grouped = @grouped@(&[3, 2, 1, 4]).into_entries();
|
||||
assert_eq!(grouped.iter().map(|entry| entry.f0).collect::<Vec<_>>(), vec![1, 0]);
|
||||
assert_eq!((&grouped[0].f1, &grouped[1].f1), (&vec![3, 1], &vec![2, 4]));
|
||||
assert!(@grouped@(&[]).is_empty());
|
||||
let name = String::from("移动到分组,不复制文本");
|
||||
let pointer = name.as_ptr();
|
||||
let grouped = @groupNames@(vec![name]).into_entries();
|
||||
assert_eq!(grouped[0].f1[0].as_ptr(), pointer);
|
||||
let grouped = @groupCopies@(vec!["甲".into(), "乙".into(), "甲".into()]);
|
||||
assert_eq!(grouped.f0, vec!["甲", "乙", "甲"]);
|
||||
let entries = grouped.f1.into_entries();
|
||||
assert_eq!((&entries[0].f0, &entries[0].f1), (&String::from("甲"), &vec![String::from("甲"), String::from("甲")]));
|
||||
assert_eq!(@groupFiltered@(&[-1, 2]).unwrap().len(), 1);
|
||||
assert!(@groupFailure@(&[2, -1]).is_err());
|
||||
let empty = @totals@(&[]);
|
||||
assert_eq!((empty.f0, empty.f1, empty.f2, empty.f3, empty.f4, empty.f5), (0, vec![], 0, None, None, None));
|
||||
let values = @totals@(&[3, -1, 5]);
|
||||
assert_eq!((values.f0, values.f1, values.f2, values.f3, values.f4, values.f5), (7, vec![3, -1, 5], 3, Some(3), Some(-1), Some(5)));
|
||||
let range = @ranged@(-2, 3);
|
||||
assert_eq!((range.f0, range.f1), (0, 5));
|
||||
let empty = @ranged@(3, -2);
|
||||
assert_eq!((empty.f0, empty.f1), (0, 0));
|
||||
assert!(!@anyPositive@(&[]).unwrap());
|
||||
assert!(@allPositive@(&[]).unwrap());
|
||||
assert_eq!(@firstPositive@(&[]).unwrap(), None);
|
||||
assert!(@anyPositive@(&[1, -1]).unwrap());
|
||||
assert!(!@allPositive@(&[0, -1]).unwrap());
|
||||
assert_eq!(@firstPositive@(&[2, -1]).unwrap(), Some(2));
|
||||
assert!(@mixed@(&[2, -1]).is_err());
|
||||
assert!(@action@(&[]).is_ok());
|
||||
assert!(@action@(&[1, -1]).is_err());
|
||||
assert_eq!(@actionCount@(&[1, 2]).unwrap(), 2);
|
||||
let names = @names@(vec![String::from("乙"), String::from("甲")]);
|
||||
assert_eq!((names.f0, names.f1, names.f2), (vec![String::from("乙"), String::from("甲")], Some(String::from("乙")), Some(String::from("乙"))));
|
||||
assert_eq!(@repeated@(&[1, 2, 3], "中文"), vec!["中文", "中文", "中文"]);
|
||||
assert_eq!(@decimalTotal@(&[Decimal::parse("0.1").unwrap(), Decimal::parse("0.2").unwrap()]).to_string(), "0.3");
|
||||
assert_eq!(@floatTotal@(&[1e16, -1e16, 1.0]), 1.0);
|
||||
assert!(std::panic::catch_unwind(|| @totals@(&[i64::MAX, 1])).is_err());
|
||||
assert_eq!(@main@(), 10);
|
||||
let filtered = @filtered@(&[0, -2, 2, 9]);
|
||||
assert_eq!((filtered.f0, filtered.f1, filtered.f2, filtered.f3), (vec![2, 9], Some(2), 4, 9));
|
||||
let optional = @optionalNames@(vec![None, Some("甲".into()), Some("丙".into()), None]);
|
||||
assert_eq!((optional.f0, optional.f1), (2, vec![Some("甲".into())]));
|
||||
assert_eq!(@filteredFailure@(&[-1, 2, -3]).unwrap(), Some(2));
|
||||
let copied = @filteredOwned@(vec!["甲".into(), "乙".into()]);
|
||||
assert_eq!((copied.f0, copied.f1), (vec![String::from("甲"), String::from("乙")], 2));
|
||||
assert_eq!(@refined@(&[None, Some(-1), Some(3)]), vec![3]);
|
||||
let refined_names = @refinedNames@(vec![None, Some("甲".into()), Some("丙".into())]);
|
||||
assert_eq!((refined_names.f0, refined_names.f1), (vec![String::from("甲")], 3));
|
||||
let payloads = @payloads@(&[@Event@::Named("甲".into()), @Event@::Empty, @Event@::Tagged("你好".into())]);
|
||||
assert_eq!((payloads.f0, payloads.f1), (vec![String::from("甲"), String::from("你好")], 3));
|
||||
let fields = @payloadFields@(&[@Envelope@ { f0: @Event@::Named("甲".into()) }, @Envelope@ { f0: @Event@::Empty }]);
|
||||
assert_eq!((fields.f0, fields.f1), (vec![String::from("甲")], 1));
|
||||
assert_eq!(@optionalPayloads@(vec![@MaybeEnvelope@ { f0: Some(@Event@::Named("甲".into())) }, @MaybeEnvelope@ { f0: None }]), vec!["甲"]);
|
||||
assert_eq!(@computedPayloads@(&[1, 2]), vec!["名", "名"]);
|
||||
let label = String::from("移动原字符串,不复制内容");
|
||||
let original = label.as_ptr();
|
||||
let moved = @movingPayloads@(vec![@Event@::Named(label)]);
|
||||
assert_eq!(moved[0].as_ptr(), original);
|
||||
assert!(@rejectBroken@(&[]).is_ok());
|
||||
assert!(@rejectBroken@(&[@InputState@::Ready]).is_ok());
|
||||
assert!(@rejectBroken@(&[@InputState@::Ready, @InputState@::Broken]).is_err());
|
||||
let limited = @limited@(&[-1, 1, 2, -2], 1).unwrap();
|
||||
assert_eq!((limited.f0, limited.f1), (vec![1], 4));
|
||||
assert_eq!(@takeOnly@(&[1, -1], 1).unwrap(), vec![1]);
|
||||
assert!(@takeOnly@(&[-1], 0).unwrap().is_empty());
|
||||
assert!(@takeZero@(&[0]).unwrap().is_empty());
|
||||
assert!(std::panic::catch_unwind(|| @initializeLimit@(&[], i64::MAX)).is_err());
|
||||
let ranked = @ranked@(vec![
|
||||
@Ranked@ { f0: 2, f1: Decimal::parse("0.9").unwrap(), f2: "later".into() },
|
||||
@Ranked@ { f0: 1, f1: Decimal::parse("0.2").unwrap(), f2: "first tie".into() },
|
||||
@Ranked@ { f0: 1, f1: Decimal::parse("0.3").unwrap(), f2: "highest".into() },
|
||||
@Ranked@ { f0: 1, f1: Decimal::parse("0.2").unwrap(), f2: "second tie".into() },
|
||||
], 3);
|
||||
assert_eq!((ranked.f0, ranked.f1), (vec![String::from("highest"), String::from("first tie"), String::from("second tie")], 4));
|
||||
let texts = vec![String::from("你好"), String::from("甲")];
|
||||
let pointers = [texts[0].as_ptr(), texts[1].as_ptr()];
|
||||
let sorted = @sortedTexts@(texts);
|
||||
assert_eq!(sorted, vec!["甲", "你好"]);
|
||||
assert_eq!([sorted[0].as_ptr(), sorted[1].as_ptr()], [pointers[1], pointers[0]]);
|
||||
assert_eq!(@sortedChecked@(&[1, 5, 3], 1).unwrap(), vec![5]);
|
||||
assert!(@sortedChecked@(&[1, -1], 1).is_err());
|
||||
assert!(@sortedChecked@(&[-1], 0).unwrap().is_empty());
|
||||
assert!(std::panic::catch_unwind(|| @sortBeforeResult@(&[0], 1)).is_err());
|
||||
assert!(@sortBeforeResult@(&[0], 0).unwrap().is_empty());
|
||||
let seed = || @ListState@ { f0: vec![10], f1: 2, f2: 3 };
|
||||
let empty = @inlineState@(&[], seed());
|
||||
assert_eq!((empty.f0, empty.f1, empty.f2), (vec![10], 2, 3));
|
||||
let swapped = @inlineState@(&[4], seed());
|
||||
assert_eq!((swapped.f0, swapped.f1, swapped.f2), (vec![10, 4], 3, 2));
|
||||
let twice = @inlineState@(&[4, 5], seed());
|
||||
assert_eq!((twice.f0, twice.f1, twice.f2), (vec![10, 4, 5], 2, 3));
|
||||
let kept = @keepListState@(&[4], seed());
|
||||
assert_eq!((kept.f0.f0, kept.f1.f0), (vec![10, 4], vec![10]));
|
||||
let before = @prefixState@(&[4, 5], seed());
|
||||
assert_eq!((before.f0, before.f1, before.f2), (vec![10, 5, 7], 4, 4));
|
||||
let aliased = @aliasState@(&[4, 5], seed());
|
||||
assert_eq!((aliased.f0, aliased.f1, aliased.f2), (vec![10, 5, 7], 4, 3));
|
||||
let old = @oldListState@(&[4, 5], seed());
|
||||
assert_eq!((old.f0, old.f1, old.f2), (vec![10, 4, 5], 2, 3));
|
||||
let whole = @wholeState@(&[4, 5], seed());
|
||||
assert_eq!((whole.f0, whole.f1, whole.f2), (vec![10, 5, 7], 2, 3));
|
||||
let fault = std::panic::catch_unwind(|| @recordFault@(&[0], seed())).unwrap_err();
|
||||
let fault = fault.downcast_ref::<&'static FaultInfo>().unwrap();
|
||||
assert_eq!((fault.line, fault.column, fault.message), (446, 82, "arithmetic fault"));
|
||||
let fault = std::panic::catch_unwind(|| @recordFault@(&[1], @ListState@ { f0: vec![], f1: i64::MAX, f2: 0 })).unwrap_err();
|
||||
let fault = fault.downcast_ref::<&'static FaultInfo>().unwrap();
|
||||
assert_eq!((fault.line, fault.column, fault.message), (446, 28, "arithmetic fault"));
|
||||
let empty_seed = @prefixState@(&[4, 5], @ListState@ { f0: vec![], f1: 2, f2: 3 });
|
||||
assert_eq!((empty_seed.f0, empty_seed.f1, empty_seed.f2), (vec![4, 6], 3, 3));
|
||||
let read = @readState@(&[4, 5], @ReadState@ { f0: vec![], f1: None });
|
||||
assert_eq!((read.f0, read.f1), (vec![4, 5], Some(4)));
|
||||
let read = @readState@(&[4, 5], @ReadState@ { f0: vec![10], f1: None });
|
||||
assert_eq!((read.f0, read.f1), (vec![10, 4, 5], Some(10)));
|
||||
let text = @textState@(&[4, 5], @TextState@ { f0: vec!["seed".into()], f1: 2 });
|
||||
assert_eq!((text.f0, text.f1), (vec![String::from("seed"), String::from("next"), String::from("next")], 11));
|
||||
assert_eq!(@sumChecked@(&[]), 0);
|
||||
assert_eq!(@sumChecked@(&[i64::MAX, -i64::MAX, -1]), -1);
|
||||
let fault = std::panic::catch_unwind(|| @sumBeforeFault@(&[1, 1, 0])).unwrap_err();
|
||||
let fault = fault.downcast_ref::<&'static FaultInfo>().unwrap();
|
||||
assert_eq!(fault.message, "loop aggregate overflow");
|
||||
assert_eq!(@joinTextParts@(&[], "seed".into()), "seed");
|
||||
let text = @keepTextParts@(&["好".into(), "🙂".into()], "seed:".into());
|
||||
assert_eq!((text.f0, text.f1), (String::from("seed:好🙂"), String::from("seed:")));
|
||||
let mut table = Map::with_capacity(0);
|
||||
table.put(String::from("雪😀"), 7);
|
||||
table.put(String::from(""), -3);
|
||||
let projected = @projectEntries@(table.clone());
|
||||
assert_eq!(projected.f0, vec!["雪😀", ""]);
|
||||
assert_eq!(projected.f1, vec![7, -3]);
|
||||
assert_eq!(projected.f2, table);
|
||||
let empty = @projectEntries@(Map::with_capacity(0));
|
||||
assert!(empty.f0.is_empty() && empty.f1.is_empty() && empty.f2.is_empty());
|
||||
let name = String::from("列表值保留原数据");
|
||||
let pointer = name.as_ptr();
|
||||
let mut table = Map::with_capacity(0);
|
||||
table.put(4, vec![name]);
|
||||
let mut projected = @projectLists@(table);
|
||||
assert_eq!(projected.f1.get(&4).unwrap()[0].as_ptr(), pointer);
|
||||
assert_ne!(projected.f0[0][0].as_ptr(), pointer);
|
||||
projected.f0[0][0].push('!');
|
||||
assert_eq!(projected.f1.get(&4).unwrap(), &vec!["列表值保留原数据"]);
|
||||
@@ -0,0 +1,156 @@
|
||||
readJson(text: Text) (value: Json) {
|
||||
value = dever.json.fromText(text)
|
||||
}
|
||||
|
||||
writeJson(value: Json) (text: Text) {
|
||||
text = dever.json.toText(value)
|
||||
}
|
||||
|
||||
readDocument(text: Text) (document: dever.json.value.Document) {
|
||||
document = dever.json.parse(text)
|
||||
}
|
||||
|
||||
writeDocument(document: dever.json.value.Document) (text: Text) {
|
||||
text = dever.json.stringify(document)
|
||||
}
|
||||
|
||||
captureJson(text: Text) (value: dever.json.JsonResult) {
|
||||
value = result(dever.json.fromText(text))
|
||||
}
|
||||
|
||||
captureDocument(text: Text) (value: dever.json.value.ParseResult) {
|
||||
value = result(dever.json.parse(text))
|
||||
}
|
||||
|
||||
captureWrite(document: dever.json.value.Document) (value: dever.json.value.WriteResult) {
|
||||
value = result(dever.json.stringify(document))
|
||||
}
|
||||
|
||||
fieldJson(value: Json, name: Text) (child: Json?) {
|
||||
child = dever.json.propertyValue(value, name)
|
||||
}
|
||||
|
||||
kindJson(value: Json) (kind: dever.json.Kind) {
|
||||
kind = dever.json.kind(value)
|
||||
}
|
||||
|
||||
elementJson(value: Json, index: Int) (child: Json?) {
|
||||
child = dever.json.elementValue(value, index)
|
||||
}
|
||||
|
||||
changeJson(value: Json, name: Text, child: Json) (out: Json) {
|
||||
out = dever.json.setProperty(value, name, child)
|
||||
}
|
||||
|
||||
buildJson(name: Text, number: Int) (out: Json) {
|
||||
out = dever.json.object({
|
||||
"name" = dever.json.string(name)
|
||||
"values" = dever.json.array([dever.json.integer(number), dever.json.boolean(true), dever.json.nullValue()])
|
||||
})
|
||||
}
|
||||
|
||||
textJson(value: Json) (text: Text) {
|
||||
text = dever.json.asText(value)
|
||||
}
|
||||
|
||||
intJson(value: Json) (number: Int) {
|
||||
number = dever.json.asInteger(value)
|
||||
}
|
||||
|
||||
documentProperty(document: dever.json.value.Document, id: Int, name: Text) (child: Int?) {
|
||||
child = dever.json.property(document, id, name)
|
||||
}
|
||||
|
||||
documentElement(document: dever.json.value.Document, id: Int, index: Int) (child: Int?) {
|
||||
child = dever.json.element(document, id, index)
|
||||
}
|
||||
|
||||
documentNode(document: dever.json.value.Document, id: Int) (child: dever.json.value.Value?) {
|
||||
child = dever.json.node(document, id)
|
||||
}
|
||||
|
||||
makeDocument() (document: dever.json.value.Document) {
|
||||
document = dever.json.value.Document {
|
||||
root = 1
|
||||
nodes = [dever.json.value.Value.Number("1e+9999"), dever.json.value.Value.Array([0])]
|
||||
}
|
||||
}
|
||||
|
||||
type Payload {
|
||||
label: Text
|
||||
values: List<Int>
|
||||
price: Decimal >= 0
|
||||
note: Text?
|
||||
}
|
||||
|
||||
encodePayload(payload: Payload) (text: Text) {
|
||||
text = dever.json.toText(dever.json.encode(payload))
|
||||
}
|
||||
|
||||
encodeFloating(values: List<Float?>) (out: dever.json.JsonResult) {
|
||||
out = result(dever.json.encode(values))
|
||||
}
|
||||
|
||||
encodeOptional(value: Text?) (out: Text) {
|
||||
out = dever.json.toText(dever.json.encode(value))
|
||||
}
|
||||
|
||||
decodePayload(value: Json) (payload: Payload) {
|
||||
payload = dever.json.decode(value)
|
||||
}
|
||||
|
||||
type PayloadResult {
|
||||
Read(payload: Payload)
|
||||
error Failed(reason: dever.json.JsonResult)
|
||||
}
|
||||
|
||||
capturePayload(value: Json) (out: PayloadResult) {
|
||||
out = result(dever.json.decode(value))
|
||||
}
|
||||
|
||||
capturePayloadText(text: Text) (out: PayloadResult) {
|
||||
out = result(dever.json.decode(dever.json.fromText(text)))
|
||||
}
|
||||
|
||||
decodeOptional(value: Json) (text: Text?) {
|
||||
text = dever.json.decode(value)
|
||||
}
|
||||
|
||||
type State { Draft, Published }
|
||||
decodeState(value: Json) (state: State) {
|
||||
state = dever.json.decode(value)
|
||||
}
|
||||
|
||||
flow decodeInFlow(value: Json) (payload: Payload)
|
||||
| step | kind | do |
|
||||
| payload | calc | dever.json.decode(value) |
|
||||
|
||||
type Fragment {
|
||||
label: Text
|
||||
value: Json
|
||||
optional: List<Json?>
|
||||
}
|
||||
|
||||
encodeFragment(value: Fragment) (out: Text) {
|
||||
out = dever.json.toText(dever.json.encode(value))
|
||||
}
|
||||
|
||||
decodeFragment(value: Json) (out: Fragment) {
|
||||
out = dever.json.decode(value)
|
||||
}
|
||||
|
||||
encodeFragments(values: List<Fragment?>) (out: dever.json.JsonResult) {
|
||||
out = result(dever.json.encode(values))
|
||||
}
|
||||
|
||||
encodeNumbers(values: List<Int>) (out: dever.json.JsonResult) {
|
||||
out = result(dever.json.encode(values))
|
||||
}
|
||||
|
||||
wireFragment(value: Fragment) (out: Fragment) { out = value }
|
||||
wireJson(value: Json) (out: Json) { out = value }
|
||||
wireBundle(value: Fragment) (status: Int, out: Fragment) { status = 1
|
||||
out = value }
|
||||
cmd fragment = app.wireFragment
|
||||
cmd raw = app.wireJson
|
||||
cmd bundle = app.wireBundle
|
||||
@@ -0,0 +1,97 @@
|
||||
let raw = String::from(" {\"z\":1e9999,\"雪\":[null,true,\"白\",1e+03]} ");
|
||||
let pointer = raw.as_ptr();
|
||||
let value = @readJson@(raw).unwrap();
|
||||
assert_eq!(value.as_str().as_ptr(), pointer);
|
||||
let child = @fieldJson@(&value, "z").unwrap().unwrap();
|
||||
assert_eq!(child.as_str(), "1e9999");
|
||||
assert!(@fieldJson@(&value, "missing").unwrap().is_none());
|
||||
assert!(@intJson@(&child).is_err());
|
||||
for (raw, expected) in [(" \nnull", @Kind@::Null), ("false", @Kind@::Boolean), (" true ", @Kind@::Boolean), ("1e9999", @Kind@::Number), ("\t\"雪\"", @Kind@::String), ("[]", @Kind@::Array), (" {}", @Kind@::Object)] {
|
||||
assert_eq!(@kindJson@(&@readJson@(raw.into()).unwrap()), expected);
|
||||
}
|
||||
let array = @readJson@(r#" [ null, { "雪": -0 }, 1e9999, "a\nb" ] "#.into()).unwrap();
|
||||
for (index, raw) in [(0,"null"), (1,r#"{ "雪": -0 }"#), (2,"1e9999"), (3,r#""a\nb""#)] {
|
||||
assert_eq!(@elementJson@(&array, index).unwrap().as_str(), raw);
|
||||
}
|
||||
for index in [-1, 4, i64::MAX] { assert!(@elementJson@(&array, index).is_none()); }
|
||||
assert!(@elementJson@(&value, 0).is_none());
|
||||
assert!(@elementJson@(&@readJson@("[]".into()).unwrap(), 0).is_none());
|
||||
let text = @writeJson@(value);
|
||||
assert_eq!(text.as_ptr(), pointer);
|
||||
let document = @readDocument@(&text).unwrap();
|
||||
assert_eq!(document.f0, 6);
|
||||
assert_eq!(@documentProperty@(&document, 6, "z"), Some(0));
|
||||
assert_eq!(@documentProperty@(&document, 6, "雪"), Some(5));
|
||||
assert_eq!(@documentElement@(&document, 5, 2), Some(3));
|
||||
assert_eq!(@documentNode@(&document, 3), Some(@Value@::String("白".into())));
|
||||
for id in [-1, 7, i64::MAX] {
|
||||
assert_eq!(@documentProperty@(&document, id, "z"), None);
|
||||
assert_eq!(@documentElement@(&document, id, 0), None);
|
||||
assert_eq!(@documentNode@(&document, id), None);
|
||||
}
|
||||
assert_eq!(@documentElement@(&document, 5, -1), None);
|
||||
assert_eq!(@writeDocument@(&document).unwrap(), "{\"z\":1e9999,\"雪\":[null,true,\"白\",1e+03]}");
|
||||
assert_eq!(@writeDocument@(&@makeDocument@()).unwrap(), "[1e+9999]");
|
||||
let built = @buildJson@("中文", 7).unwrap();
|
||||
assert_eq!(built.as_str(), "{\"name\":\"中文\",\"values\":[7,true,null]}");
|
||||
assert_eq!(@textJson@(&@fieldJson@(&built, "name").unwrap().unwrap()).unwrap(), "中文");
|
||||
let number = @readJson@("42".into()).unwrap();
|
||||
let updated = @changeJson@(&built, "name", &number).unwrap();
|
||||
assert_eq!(@intJson@(&@fieldJson@(&updated, "name").unwrap().unwrap()).unwrap(), 42);
|
||||
for raw in ["[1,]", "{\"雪\":0,\"\\u96ea\":1}", ""] {
|
||||
assert!(matches!(@captureJson@(raw.into()), @JsonResult@::Failed(_)));
|
||||
assert!(matches!(@captureDocument@(raw), @ParseResult@::Failed(_, _)));
|
||||
}
|
||||
let invalid = @Document@ { f0: 0, f1: vec![@Value@::Array(vec![0])] };
|
||||
assert!(matches!(@captureWrite@(&invalid), @WriteResult@::Failed(0, _)));
|
||||
|
||||
@allocation_counter@
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let property = @documentProperty@(std::hint::black_box(&document), 6, "雪");
|
||||
let element = @documentElement@(std::hint::black_box(&document), 5, 2);
|
||||
let after = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!((property, element), (Some(5), Some(3)));
|
||||
assert_eq!(after - before, 0);
|
||||
let payload = @Payload@ { f0: "中文".into(), f1: vec![1, 2, 3], f2: Decimal::parse("0.1").unwrap(), f3: None };
|
||||
assert_eq!(@encodePayload@(&payload).unwrap(), r#"{"label":"中文","values":[1,2,3],"price":"0.1","note":null}"#);
|
||||
for number in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
assert!(matches!(@encodeFloating@(&[Some(number)]), @JsonResult@::Failed(message) if message == "non-finite Float cannot be encoded"));
|
||||
}
|
||||
assert_eq!(@encodeOptional@(Some("雪")).unwrap(), "\"雪\"");
|
||||
assert_eq!(@encodeOptional@(None).unwrap(), "null");
|
||||
let encoded = @readJson@(@encodePayload@(&payload).unwrap()).unwrap();
|
||||
assert_eq!(@decodePayload@(&encoded).unwrap(), payload);
|
||||
assert_eq!(@decodeInFlow@(&encoded).unwrap(), payload);
|
||||
assert!(matches!(@capturePayload@(&encoded), @PayloadResult@::Read(_)));
|
||||
assert!(@capturePayloadText@(String::from("[1,")).is_err());
|
||||
assert!(matches!(@capturePayloadText@(String::from("[]")).unwrap(), @PayloadResult@::Failed(_)));
|
||||
for source in [
|
||||
r#"{"label":"x","values":[],"price":"-0.1"}"#,
|
||||
r#"{"label":"x","values":[],"price":0.1}"#,
|
||||
r#"{"label":"x","values":[],"price":"0","extra":0}"#,
|
||||
r#"{"values":[],"price":"0"}"#,
|
||||
r#"{"label":"x","values":[1.2],"price":"0"}"#,
|
||||
r#"["x",[],"0",null]"#,
|
||||
] {
|
||||
let value = @readJson@(source.into()).unwrap();
|
||||
assert!(@decodePayload@(&value).is_err());
|
||||
assert!(matches!(@capturePayload@(&value), @PayloadResult@::Failed(@JsonResult@::Failed(message)) if !message.is_empty()));
|
||||
}
|
||||
assert_eq!(@decodeOptional@(&@readJson@("null".into()).unwrap()).unwrap(), None);
|
||||
assert_eq!(@decodeOptional@(&@readJson@("\"雪\"".into()).unwrap()).unwrap(), Some("雪".into()));
|
||||
assert_eq!(@decodeState@(&@readJson@("\"Draft\"".into()).unwrap()).unwrap(), @State@::Draft);
|
||||
assert!(@decodeState@(&@readJson@("\"unknown\"".into()).unwrap()).is_err());
|
||||
let raw = @readJson@(" \n{\"a\":[1e9999,-0]}\t ".into()).unwrap();
|
||||
let fragment = @Fragment@ { f0: "雪\"".into(), f1: raw.clone(), f2: vec![None, Some(raw.clone())] };
|
||||
let expected = r#"{"label":"雪\"","value":{"a":[1e9999,-0]},"optional":[null,{"a":[1e9999,-0]}]}"#;
|
||||
assert_eq!(@encodeFragment@(&fragment).unwrap(), expected);
|
||||
assert_eq!(fragment.f1.as_str(), raw.as_str());
|
||||
let decoded = @decodeFragment@(&@readJson@(expected.into()).unwrap()).unwrap();
|
||||
assert_eq!(decoded.f1.as_str(), r#"{"a":[1e9999,-0]}"#);
|
||||
assert_eq!(@encodeFragment@(&decoded).unwrap(), expected);
|
||||
assert!(matches!(@encodeFragments@(&[Some(fragment.clone()), None]), @JsonResult@::Parsed(value) if value.as_str() == format!("[{expected},null]")));
|
||||
let deep = @readJson@(format!("{}0{}", "[".repeat(64), "]".repeat(64))).unwrap();
|
||||
let fragment = @Fragment@ { f0: "deep".into(), f1: deep, f2: vec![] };
|
||||
assert!(matches!(@encodeFragments@(&[Some(fragment)]), @JsonResult@::Failed(message) if message.contains("nesting")));
|
||||
assert!(matches!(@encodeNumbers@(&vec![0; 65535]), @JsonResult@::Parsed(_)));
|
||||
assert!(matches!(@encodeNumbers@(&vec![0; 65536]), @JsonResult@::Failed(message) if message.contains("value limit")));
|
||||
@@ -0,0 +1,46 @@
|
||||
rule chunkSize(event: dever.io.ReadEvent) (out: Int)
|
||||
| event | out |
|
||||
| Chunk(bytes) | length(bytes) |
|
||||
| Failed(message) | fail(dever.io.ReadEvent.Failed(message)) |
|
||||
|
||||
loop consumed(stream: AsyncStream<dever.io.ReadEvent>) (out: Int)
|
||||
| each event in stream | result |
|
||||
| out | sum chunkSize(event) |
|
||||
|
||||
flow send(socket: dever.system.Socket, payload: Bytes) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.net.write(socket, payload) |
|
||||
| - | flow | dever.net.close(socket) |
|
||||
|
||||
flow roundTrip(host: Text, payload: Bytes) (out: Int)
|
||||
| step | kind | do |
|
||||
| listener | flow | dever.net.listen(host, 0) |
|
||||
| port | flow | dever.net.port(listener) |
|
||||
| client | flow | dever.net.connect(host, port) |
|
||||
| server | flow | dever.net.accept(listener) |
|
||||
| sender | calc | run(send(client, payload)) |
|
||||
| stream | flow | dever.net.chunks(server, 4096) |
|
||||
| out | loop | consumed(stream) |
|
||||
| - | calc | wait(sender) |
|
||||
| - | flow | dever.net.close(server) |
|
||||
| - | flow | dever.net.closeListener(listener) |
|
||||
|
||||
flow dialTimed(address: Text, port: Int, milliseconds: Int) (out: dever.system.Socket)
|
||||
| step | kind | do |
|
||||
| out | flow | dever.net.connectTimeout(address, port, milliseconds) |
|
||||
|
||||
flow readSome(socket: dever.system.Socket, limit: Int) (out: dever.io.ReadState)
|
||||
| step | kind | do |
|
||||
| out | flow | dever.net.read(socket, limit) |
|
||||
|
||||
flow setTimeout(socket: dever.system.Socket, milliseconds: Int) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.net.timeout(socket, milliseconds) |
|
||||
|
||||
loop allSockets(stream: AsyncStream<dever.net.ConnectResult>) (out: List<dever.system.Socket>)
|
||||
| each event in stream | result |
|
||||
| out | list dever.net.connected(event) |
|
||||
|
||||
flow incoming(listener: dever.system.Listener) (out: AsyncStream<dever.net.ConnectResult>)
|
||||
| step | kind | do |
|
||||
| out | flow | dever.net.connections(listener) |
|
||||
@@ -0,0 +1,31 @@
|
||||
use dever_runtime::{net, task, Bytes};
|
||||
task::run(true, 8, async |scope| {
|
||||
for host in ["127.0.0.1", "localhost"] {
|
||||
for size in [0, 1, 100_000] {
|
||||
let payload = Bytes::from(vec![42; size]);
|
||||
assert_eq!(@roundTrip@(scope, host, payload).await.unwrap(), size as i64);
|
||||
}
|
||||
}
|
||||
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
|
||||
let client = @dialTimed@("127.0.0.1", listener.port().unwrap(), 1000).await.unwrap();
|
||||
let incoming = @incoming@(&listener);
|
||||
let server = match incoming.next().await.unwrap().unwrap() {
|
||||
@ConnectResult@::Connected(socket) => socket,
|
||||
other => panic!("expected real connection: {other:?}"),
|
||||
};
|
||||
incoming.close();
|
||||
@setTimeout@(&server, 10).unwrap();
|
||||
assert!(@readSome@(&server, 1).await.is_err());
|
||||
client.write(b"x").await.unwrap();
|
||||
assert!(matches!(@readSome@(&server, 1).await.unwrap(), @ReadState@::Read(bytes) if bytes.as_ref() == b"x"));
|
||||
client.close().unwrap();
|
||||
assert!(matches!(@readSome@(&server, 1).await.unwrap(), @ReadState@::End));
|
||||
server.close().unwrap();
|
||||
assert!(@readSome@(&server, 1).await.is_err());
|
||||
assert!(listener.port().is_ok(), "short-circuit stream retains the external listener");
|
||||
listener.close().unwrap();
|
||||
assert!(@allSockets@(&@incoming@(&listener)).await.is_err());
|
||||
assert!(@dialTimed@("localhost", 1, 10).await.is_err());
|
||||
assert!(@dialTimed@("127.0.0.1", -1, 10).await.is_err());
|
||||
Ok::<_, ()>(())
|
||||
}).unwrap().unwrap();
|
||||
@@ -0,0 +1,179 @@
|
||||
type Trouble { error Left, error Right }
|
||||
type Pair { left: Text, right: Text }
|
||||
|
||||
flow delayed(value: Int, millis: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(millis) |
|
||||
| out | calc | value |
|
||||
|
||||
flow together() (left: Int, right: Int)
|
||||
| step | kind | parallel | do |
|
||||
| left | flow | read | delayed(11, 5) |
|
||||
| right | flow | read | delayed(22, 10) |
|
||||
|
||||
flow readText(text: Text) (out: Int)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(1) |
|
||||
| out | calc | length(text) |
|
||||
|
||||
flow takeText(text: Text) (out: Text)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(1) |
|
||||
| out | calc | text |
|
||||
|
||||
flow shared(text: Text) (left: Int, right: Int)
|
||||
| step | kind | parallel | do |
|
||||
| left | flow | read | readText(text) |
|
||||
| right | flow | read | readText(text) |
|
||||
|
||||
flow mixed(text: Text) (size: Int, saved: Text)
|
||||
| step | kind | parallel | do |
|
||||
| size | flow | read | readText(text) |
|
||||
| saved | flow | read | takeText(text) |
|
||||
|
||||
flow fields(value: Pair) (size: Int, saved: Text)
|
||||
| step | kind | parallel | do |
|
||||
| size | flow | read | readText(value.left) |
|
||||
| saved | flow | read | takeText(value.right) |
|
||||
|
||||
flow sameField(value: Pair) (size: Int, saved: Text)
|
||||
| step | kind | parallel | do |
|
||||
| size | flow | read | readText(value.left) |
|
||||
| saved | flow | read | takeText(value.left) |
|
||||
|
||||
flow alias(value: Pair) (size: Int, saved: Text)
|
||||
| step | kind | parallel | do |
|
||||
| text | calc | - | value.left |
|
||||
| size | flow | read | readText(text) |
|
||||
| saved | flow | read | takeText(value.left) |
|
||||
|
||||
leftFail(value: Int) (out: Int) { check value != 0 else Trouble.Left
|
||||
out = value }
|
||||
rightFail(value: Int) (out: Int) { check value != 0 else Trouble.Right
|
||||
out = value }
|
||||
|
||||
flow lateLeft(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(5) |
|
||||
| out | calc | leftFail(value) |
|
||||
|
||||
flow lateRight(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(5) |
|
||||
| out | calc | rightFail(value) |
|
||||
|
||||
flow tiedErrors(value: Int) (left: Int, right: Int)
|
||||
| step | kind | parallel | do |
|
||||
| left | flow | both | lateLeft(value) |
|
||||
| right | flow | both | lateRight(value) |
|
||||
|
||||
flow firstObserved(value: Int) (left: Int, right: Int)
|
||||
| step | kind | parallel | do |
|
||||
| left | flow | both | delayed(value, 60000) |
|
||||
| right | calc | both | rightFail(value) |
|
||||
|
||||
flow argumentsFirst(value: Int) (left: Int, right: Int)
|
||||
| step | kind | parallel | do |
|
||||
| left | calc | both | rightFail(value) |
|
||||
| right | flow | both | delayed(leftFail(value), 60000) |
|
||||
|
||||
flow syncArgumentsFirst(value: Int) (left: Int, right: Int)
|
||||
| step | kind | parallel | do |
|
||||
| left | calc | both | rightFail(value) |
|
||||
| right | calc | both | rightFail(leftFail(value)) |
|
||||
|
||||
flow cancelledBuffer(text: Text, value: Int) (saved: Text, right: Int)
|
||||
| step | kind | parallel | do |
|
||||
| saved | flow | both | takeText(text) |
|
||||
| right | calc | both | rightFail(value) |
|
||||
|
||||
flow pendingBuffer(text: Text) (saved: Text, right: Int)
|
||||
| step | kind | parallel | do |
|
||||
| saved | flow | both | takeText(text) |
|
||||
| right | flow | both | delayed(1, 60000) |
|
||||
|
||||
type Attempt { Done(value: Int), error Failed(value: Trouble) }
|
||||
rule resolve(value: Attempt) (out: Int) recover("report a rejected number as -1")
|
||||
| value | out |
|
||||
| Done(item) | item |
|
||||
| Failed(error) | -1 |
|
||||
|
||||
flow captured(value: Int) (left: Int, right: Int)
|
||||
| step | kind | parallel | do |
|
||||
| attempt: Attempt | calc | both | result(rightFail(value)) |
|
||||
| right | flow | both | delayed(17, 1) |
|
||||
| left | rule | - | resolve(attempt) |
|
||||
|
||||
flow apply(value: Int, work: handler(value: Int) (out: Int)) (left: Int, right: Int)
|
||||
| step | kind | parallel | do |
|
||||
| left | calc | both | work(value) |
|
||||
| right | calc | both | work(value + 1) |
|
||||
|
||||
flow handlerStart(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| values | flow | apply(value, lateLeft) |
|
||||
| out | calc | values.left + values.right |
|
||||
|
||||
flow decimals(value: Decimal) (left: Decimal, second: Decimal, right: Int)
|
||||
| step | kind | parallel | do |
|
||||
| left | calc | both | value + 0.1 |
|
||||
| second | calc | both | value * 2 |
|
||||
| right | flow | both | delayed(5, 1) |
|
||||
|
||||
fresh(text: Text) (out: Text?) { out = text }
|
||||
makePair(text: Text) (out: Pair) { out = Pair { left = text, right = "other" } }
|
||||
rule optionalLength(text: Text?) (out: Int)
|
||||
| text | out |
|
||||
| null | 0 |
|
||||
| other | length(text) |
|
||||
|
||||
flow temporaryValues(text: Text) (first: Int, second: Int, third: Int, json: Json, last: Int)
|
||||
| step | kind | parallel | do |
|
||||
| first | rule | all | optionalLength(fresh(text)) |
|
||||
| second | calc | all | length(makePair(text).left) |
|
||||
| third | flow | all | readText(text + "!") |
|
||||
| json | calc | all | dever.json.encode(makePair(text)) |
|
||||
| last | flow | all | delayed(1, 1) |
|
||||
|
||||
flow pureGroup(value: Int) (left: Int, right: Int)
|
||||
| step | kind | parallel | do |
|
||||
| left | calc | both | value + 1 |
|
||||
| right | calc | both | value + 2 |
|
||||
|
||||
flow twoGroups(value: Int) (out: Int)
|
||||
| step | kind | parallel | do |
|
||||
| left | flow | first | delayed(value, 1) |
|
||||
| right | flow | first | delayed(value + 1, 1) |
|
||||
| sum | calc | - | left + right |
|
||||
| a | flow | second | delayed(sum, 1) |
|
||||
| b | flow | second | delayed(sum + 1, 1) |
|
||||
| out | calc | - | a + b |
|
||||
|
||||
flow doTogether() ()
|
||||
| step | kind | parallel | do |
|
||||
| - | flow | all | dever.time.sleep(1) |
|
||||
| - | flow | all | dever.time.sleep(2) |
|
||||
|
||||
alwaysFail() (out: Int) { out = fail(Trouble.Left) }
|
||||
flow neverGroup() ()
|
||||
| step | kind | parallel | do |
|
||||
| - | calc | all | alwaysFail() |
|
||||
| - | flow | all | dever.time.sleep(60000) |
|
||||
|
||||
cmd together = app.together
|
||||
|
||||
flow expressionCapture(text: Text) (first: Text, second: Text, size: Int)
|
||||
| step | kind | parallel | do |
|
||||
| first | calc | all | makePair(text).left |
|
||||
| second | flow | all | takeText(text) |
|
||||
| size | flow | all | delayed(1, 1) |
|
||||
|
||||
flow valueCapture(text: Text) (first: Text, second: Text)
|
||||
| step | kind | parallel | do |
|
||||
| first | calc | all | text |
|
||||
| second | flow | all | takeText(text) |
|
||||
|
||||
flow faultGroup(text: Text, value: Int) ()
|
||||
| step | kind | parallel | do |
|
||||
| held | flow | all | takeText(text) |
|
||||
| out | calc | all | value + 1 |
|
||||
@@ -0,0 +1,40 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parallel_executes_concurrent_polling_error_order_borrows_moves_and_cancellation() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"parallel",
|
||||
include_str!("parallel.dever"),
|
||||
Some(include_str!("parallel.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parallel_cmd_executes_the_checked_group() {
|
||||
let binary = build(
|
||||
"parallel-command",
|
||||
include_str!("parallel.dever"),
|
||||
None,
|
||||
Profile::Dev,
|
||||
);
|
||||
let output = Command::new(binary)
|
||||
.args(["main.main.together", "{}"])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!(value["data"], serde_json::json!({"left":11,"right":22}));
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
use std::{alloc::{GlobalAlloc, Layout, System}, future::{Future, poll_fn}, task::Poll, sync::atomic::{AtomicBool, AtomicUsize, Ordering}};
|
||||
struct Counting;
|
||||
static ALLOCATIONS: AtomicUsize = AtomicUsize::new(0);
|
||||
static WATCH: AtomicUsize = AtomicUsize::new(0);
|
||||
static FREED: AtomicBool = AtomicBool::new(false);
|
||||
unsafe impl GlobalAlloc for Counting {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
ALLOCATIONS.fetch_add(1, Ordering::Relaxed);
|
||||
unsafe { System.alloc(layout) }
|
||||
}
|
||||
unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, size: usize) -> *mut u8 {
|
||||
ALLOCATIONS.fetch_add(1, Ordering::Relaxed);
|
||||
unsafe { System.realloc(pointer, layout, size) }
|
||||
}
|
||||
unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
|
||||
if pointer as usize == WATCH.load(Ordering::Relaxed) { FREED.store(true, Ordering::Relaxed); }
|
||||
unsafe { System.dealloc(pointer, layout) }
|
||||
}
|
||||
}
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: Counting = Counting;
|
||||
|
||||
dever_runtime::task::execute(true, async {
|
||||
// 只轮询两次,中间不轮询被测 future;第二次已全部就绪才能证明首轮启动了两步。
|
||||
let mut pending = Box::pin(@together@());
|
||||
poll_fn(|context| { assert!(pending.as_mut().poll(context).is_pending()); Poll::Ready(()) }).await;
|
||||
dever_runtime::task::sleep(25).await.unwrap();
|
||||
let result = poll_fn(|context| match pending.as_mut().poll(context) {
|
||||
Poll::Ready(result) => Poll::Ready(result.unwrap()),
|
||||
Poll::Pending => panic!("parallel steps did not start in the same poll"),
|
||||
}).await;
|
||||
assert_eq!((result.f0, result.f1), (11, 22));
|
||||
|
||||
let mut pending = Box::pin(@tiedErrors@(0));
|
||||
poll_fn(|context| { assert!(pending.as_mut().poll(context).is_pending()); Poll::Ready(()) }).await;
|
||||
dever_runtime::task::sleep(25).await.unwrap();
|
||||
assert!(matches!(pending.await, Err(Failure::@Trouble@(@Trouble@::Left))));
|
||||
assert!(matches!(@firstObserved@(0).await, Err(Failure::@Trouble@(@Trouble@::Right))));
|
||||
assert!(matches!(@argumentsFirst@(0).await, Err(Failure::@Trouble@(@Trouble@::Left))));
|
||||
assert!(matches!(@syncArgumentsFirst@(0), Err(Failure::@Trouble@(@Trouble@::Left))));
|
||||
assert!(matches!(@neverGroup@().await, Err(Failure::@Trouble@(@Trouble@::Left))));
|
||||
|
||||
let text = "shared 文本".repeat(1000);
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let result = @shared@(&text).await.unwrap();
|
||||
assert_eq!(ALLOCATIONS.load(Ordering::Relaxed), before);
|
||||
assert_eq!((result.f0, result.f1), (text.chars().count() as i64, text.chars().count() as i64));
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let result = @mixed@(text).await.unwrap();
|
||||
assert_eq!(ALLOCATIONS.load(Ordering::Relaxed) - before, 1);
|
||||
assert_eq!(result.f0, result.f1.chars().count() as i64);
|
||||
|
||||
let pair = @Pair@ { f0: "left".repeat(1000), f1: "right".repeat(1000) };
|
||||
let pointer = pair.f1.as_ptr();
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let result = @fields@(pair).await.unwrap();
|
||||
assert_eq!(ALLOCATIONS.load(Ordering::Relaxed), before);
|
||||
assert_eq!(result.f1.as_ptr(), pointer);
|
||||
let pair = @Pair@ { f0: "left".repeat(1000), f1: "right".repeat(1000) };
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let result = @sameField@(&pair).await.unwrap();
|
||||
assert_eq!(ALLOCATIONS.load(Ordering::Relaxed) - before, 1);
|
||||
assert_eq!(result.f0, 4000);
|
||||
assert_eq!(result.f1.len(), 4000);
|
||||
let pair = @Pair@ { f0: "alias".repeat(1000), f1: String::new() };
|
||||
let result = @alias@(&pair).await.unwrap();
|
||||
assert_eq!(result.f0, result.f1.len() as i64);
|
||||
|
||||
let text = "cancelled".repeat(1000);
|
||||
WATCH.store(text.as_ptr() as usize, Ordering::Relaxed);
|
||||
FREED.store(false, Ordering::Relaxed);
|
||||
assert!(@cancelledBuffer@(text, 0).await.is_err());
|
||||
assert!(FREED.load(Ordering::Relaxed), "failure must release pending owned input before returning");
|
||||
WATCH.store(0, Ordering::Relaxed);
|
||||
let text = "pending".repeat(1000);
|
||||
WATCH.store(text.as_ptr() as usize, Ordering::Relaxed);
|
||||
FREED.store(false, Ordering::Relaxed);
|
||||
let mut pending = Box::pin(@pendingBuffer@(text));
|
||||
poll_fn(|context| { assert!(pending.as_mut().poll(context).is_pending()); Poll::Ready(()) }).await;
|
||||
assert!(!FREED.load(Ordering::Relaxed));
|
||||
drop(pending);
|
||||
assert!(FREED.load(Ordering::Relaxed), "caller cancellation must drop the entire group");
|
||||
WATCH.store(0, Ordering::Relaxed);
|
||||
|
||||
let result = @captured@(0).await.unwrap();
|
||||
assert_eq!((result.f0, result.f1), (-1, 17));
|
||||
assert_eq!(@handlerStart@(2).await.unwrap(), 5);
|
||||
let result = @decimals@(Decimal::parse("0.2").unwrap()).await.unwrap();
|
||||
assert_eq!(result.f0, Decimal::parse("0.3").unwrap());
|
||||
assert_eq!(result.f1, Decimal::parse("0.4").unwrap());
|
||||
let result = @temporaryValues@(String::from("abcdef")).await.unwrap();
|
||||
assert_eq!((result.f0, result.f1, result.f2, result.f4), (6, 6, 7, 1));
|
||||
let text = String::from("captured input");
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let result = @valueCapture@(text).await.unwrap();
|
||||
assert_eq!(ALLOCATIONS.load(Ordering::Relaxed) - before, 1);
|
||||
assert_eq!(result.f0, result.f1);
|
||||
let result = @expressionCapture@(String::from("nested expression")).await.unwrap();
|
||||
assert_eq!(result.f0, result.f1);
|
||||
let result = @pureGroup@(10);
|
||||
assert_eq!((result.f0, result.f1), (11, 12));
|
||||
assert_eq!(@twoGroups@(2).await.unwrap(), 11);
|
||||
@doTogether@().await.unwrap();
|
||||
}).unwrap();
|
||||
|
||||
let text = "fault-owned-input".repeat(1000);
|
||||
WATCH.store(text.as_ptr() as usize, Ordering::Relaxed);
|
||||
FREED.store(false, Ordering::Relaxed);
|
||||
let error = std::panic::catch_unwind(|| dever_runtime::task::execute(true, @faultGroup@(text, i64::MAX))).unwrap_err();
|
||||
assert!(error.downcast_ref::<&'static dever_runtime::value::FaultInfo>().is_some());
|
||||
assert!(FREED.load(Ordering::Relaxed));
|
||||
WATCH.store(0, Ordering::Relaxed);
|
||||
@@ -0,0 +1,380 @@
|
||||
type Item { name: Text, count: Int }
|
||||
type Pair { Both(first: Text, second: Text) }
|
||||
type Choice { Small(x: Int), Large(x: Int) }
|
||||
type Problem { error Missing(message: Text) }
|
||||
type Reply { Ready(value: Int), error Failed(problem: Problem) }
|
||||
|
||||
flow flowText(value: Text?) (out: Text)
|
||||
| step | kind | do |
|
||||
| - | check | value != null else Invalid |
|
||||
| out | calc | join(value, "!") |
|
||||
|
||||
flow flowChecked(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| - | calc | maybe(value) |
|
||||
| out | calc | value + 1 |
|
||||
|
||||
flow flowNested(value: Text?) (out: Text)
|
||||
| step | kind | do |
|
||||
| out | flow | flowText(value) |
|
||||
|
||||
flow flowMeasured(value: Text) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | calc | length(value) |
|
||||
|
||||
size(value: Text) (n: Int) { alias = value
|
||||
n = length(alias) }
|
||||
identity(value: Text) (out: Text) { out = value }
|
||||
twice(value: Text) (first: Text, second: Text) { first = identity(value)
|
||||
second = value }
|
||||
increment(item: Item) (out: Item) { out = item
|
||||
out.count = out.count + 1 }
|
||||
unchanged(item: Item) (next: Item, old: Item) { next = increment(item)
|
||||
old = item }
|
||||
name(item: Item) (text: Text) { text = item.name }
|
||||
nameSize(item: Item) (n: Int) { n = length(item.name) }
|
||||
count(item: Item) (n: Int) { n = item.count }
|
||||
requireText(value: Text?) (out: Text) { check value != null else Invalid
|
||||
out = value }
|
||||
nullEquality() (same: Bool, different: Bool) { same = null == null
|
||||
different = null != null }
|
||||
nullableSize(value: Text?) (n: Int) { check value != null else Invalid
|
||||
n = length(value) }
|
||||
make() (value: Text?) { value = "你好" }
|
||||
freshSize() (n: Int) { value = make()
|
||||
check value != null else Invalid
|
||||
n = length(value) }
|
||||
add(x: Int, y: Int) (out: Int) { out = x + y }
|
||||
subtract(x: Int, y: Int) (out: Int) { out = x - y }
|
||||
multiply(x: Int, y: Int) (out: Int) { out = x * y }
|
||||
quotient(x: Int, y: Int) (out: Int) { out = x // y }
|
||||
remainder(x: Int, y: Int) (out: Int) { out = x % y }
|
||||
negate(x: Int) (out: Int) { out = -x }
|
||||
divide(x: Decimal, y: Decimal) (out: Decimal) { out = x / y }
|
||||
fraction() (out: Decimal) { out = 1 / 3 }
|
||||
join(a: Text, b: Text) (out: Text) { out = a + b }
|
||||
addItem(values: List<Text>, item: Text) (out: List<Text>) { out = append(values, item) }
|
||||
getItem(values: List<Text>, index: Int) (out: Text?) { out = get(values, index) }
|
||||
lookup(values: Map<Text, Int>, key: Text) (out: Int?) { out = get(values, key) }
|
||||
map() (out: Map<Text, Int>) { out = { "first" = 1, "second" = 2 } }
|
||||
maybe(value: Int) (next: Int) { check value >= 1 else Problem.Missing("small")
|
||||
next = value }
|
||||
capture(value: Int) (out: Reply) { out = result(maybe(value)) }
|
||||
raise() (value: Int) { fail(Problem.Missing("missing")) }
|
||||
parameterFailure() (out: Reply) { out = result(maybe(raise())) }
|
||||
rule choose(flag: Bool, value: Text) (out: Text)
|
||||
| flag | value | out |
|
||||
| true | - | value |
|
||||
| false | - | value |
|
||||
rule split(pair: Pair) (first: Text, second: Text)
|
||||
| pair | first | second |
|
||||
| Both(a, b) | a | b |
|
||||
rule keep(pair: Pair) (first: Text, whole: Pair)
|
||||
| pair | first | whole |
|
||||
| Both(a, b) | a | pair |
|
||||
rule mixed(pair: Pair) (first: Text, n: Int)
|
||||
| pair | first | n |
|
||||
| Both(a, b) | a | length(b) |
|
||||
rule payload(value: Choice) (n: Int)
|
||||
| value | n |
|
||||
| Small(number), Large(number) | number |
|
||||
rule absolute(value: Int) (out: Int >= 0)
|
||||
| value | out |
|
||||
| < 0 | -value |
|
||||
| other | value |
|
||||
rule nullable(value: Text?) (out: Text)
|
||||
| value | out |
|
||||
| null | "absent" |
|
||||
| other | value |
|
||||
rule nullablePayload(value: Pair?) (out: Text)
|
||||
| value | out |
|
||||
| null | "absent" |
|
||||
| Both(a, b) | a |
|
||||
rule read(value: Reply?) (out: Int)
|
||||
| value | out |
|
||||
| null | 0 |
|
||||
| Ready(number) | number |
|
||||
| Failed(problem) | fail(value) |
|
||||
|
||||
requireOnly(value: Text?) () { check value != null else Invalid }
|
||||
getNullable(values: List<Text?>, index: Int) (out: Text?) { out = get(values, index) }
|
||||
getNullableInt(values: List<Int?>, index: Int) (out: Int?) { out = get(values, index) }
|
||||
lookupNullable(values: Map<Text, Text?>, key: Text) (out: Text?) { out = get(values, key) }
|
||||
temporaryGet() (out: Int) { out = nullableSize(get(["temporary"], 0)) }
|
||||
borrowNullable(values: List<Text?>) (out: Int) { out = nullableSize(get(values, 0)) }
|
||||
rule borrowPayload(value: Pair?) (out: Int)
|
||||
| value | out |
|
||||
| null | 0 |
|
||||
| Both(a, b) | length(a) |
|
||||
|
||||
dynamicMap(first: Text, second: Text) (out: Map<Text, Int>) { out = { first = 1, second = 2 } }
|
||||
|
||||
aliasAfterMove(value: Text) (out: Text, n: Int) { alias = value
|
||||
out = value
|
||||
n = length(alias) }
|
||||
rule payloadAfterMove(pair: Pair) (whole: Pair, n: Int)
|
||||
| pair | whole | n |
|
||||
| Both(a, b) | pair | length(a) |
|
||||
fieldAliasAfterMove(value: Item) (out: Item, n: Int) { first = value.name
|
||||
alias = first
|
||||
out = value
|
||||
n = length(alias) }
|
||||
nonnullAliasAfterMove(value: Text?) (out: Text?, n: Int) { alias = value
|
||||
check alias != null else Invalid
|
||||
out = value
|
||||
n = length(alias) }
|
||||
aliasBeforeMove(value: Text) (out: Text, n: Int) { alias = value
|
||||
n = length(alias)
|
||||
out = value }
|
||||
|
||||
containsText(values: List<Text>, target: Text) (found: Bool) {
|
||||
found = contains(values, target)
|
||||
}
|
||||
|
||||
containsNullable(values: List<Text?>, target: Text?) (found: Bool) {
|
||||
found = contains(values, target)
|
||||
}
|
||||
|
||||
containsRecord(values: List<Item>, target: Item) (found: Bool) {
|
||||
found = contains(values, target)
|
||||
}
|
||||
|
||||
containsNested(values: List<List<Int>>, target: List<Int>) (found: Bool) {
|
||||
found = contains(values, target)
|
||||
}
|
||||
|
||||
lookupSize(values: List<Text>, index: Int) (n: Int) { value = get(values, index)
|
||||
check value != null else NotFound
|
||||
n = length(value) }
|
||||
lookupBeforeMove(values: List<Text>) (out: List<Text>, n: Int) { value = get(values, 0)
|
||||
check value != null else NotFound
|
||||
n = length(value)
|
||||
out = append(values, "tail") }
|
||||
lookupAfterMove(values: List<Text>) (out: List<Text>, n: Int) { value = get(values, 0)
|
||||
check value != null else NotFound
|
||||
out = append(values, "tail")
|
||||
n = length(value) }
|
||||
lookupMapSize(values: Map<Text, Text?>, key: Text) (n: Int) { value = get(values, key)
|
||||
check value != null else NotFound
|
||||
n = length(value) }
|
||||
|
||||
putMap(values: Map<Text, Text>, key: Text, value: Text) (out: Map<Text, Text>) {
|
||||
out = put(values, key, value)
|
||||
}
|
||||
removeMap(values: Map<Text, Text>, key: Text) (out: Map<Text, Text>) {
|
||||
out = remove(values, key)
|
||||
}
|
||||
keepMap(values: Map<Text, Text>) (out: Map<Text, Text>, original: Map<Text, Text>) {
|
||||
out = put(values, "first", "changed")
|
||||
original = values
|
||||
}
|
||||
removeIntKey(values: Map<Int, Text>, key: Int) (out: Map<Int, Text>) {
|
||||
out = remove(values, key)
|
||||
}
|
||||
|
||||
mapEntries(values: Map<Text, Text>) (out: List<MapEntry<Text, Text>>) {
|
||||
out = entries(values)
|
||||
}
|
||||
entryValueSize(entry: MapEntry<Text, Text>) (n: Int) {
|
||||
n = length(entry.value)
|
||||
}
|
||||
renamedEntry(entry: MapEntry<Text, Text>) (out: MapEntry<Text, Text>) {
|
||||
out = entry
|
||||
out.key = "renamed"
|
||||
}
|
||||
entryIntValue(entry: MapEntry<Int, Int>) (out: Int) {
|
||||
out = entry.value
|
||||
}
|
||||
|
||||
handlerIdentity(value: Text) (out: Text) { out = value }
|
||||
handlerSuffix(value: Text) (out: Text) { out = value + "!" }
|
||||
handlerApply(value: Text, transform: handler(value: Text) (out: Text)) (out: Text) {
|
||||
out = transform(value)
|
||||
}
|
||||
handlerForward(value: Text, transform: handler(value: Text) (out: Text)) (out: Text) {
|
||||
out = handlerApply(value, transform)
|
||||
}
|
||||
handlerNative(value: Text) (first: Text, second: Text) {
|
||||
first = handlerForward(value, handlerIdentity)
|
||||
second = handlerApply(value, handlerSuffix)
|
||||
}
|
||||
type HandlerResult { Done(value: Int), error Rejected(message: Text) }
|
||||
handlerPositive(value: Int) (out: Int) {
|
||||
check value > 0 else HandlerResult.Rejected("positive required")
|
||||
out = value
|
||||
}
|
||||
handlerCapture(value: Int, operation: handler(value: Int) (out: Int)) (out: HandlerResult) {
|
||||
out = result(operation(value))
|
||||
}
|
||||
handlerCaptured(value: Int) (out: HandlerResult) {
|
||||
out = handlerCapture(value, handlerPositive)
|
||||
}
|
||||
rule handlerRule(value: Text, transform: handler(value: Text) (out: Text)) (out: Text)
|
||||
| value | transform | out |
|
||||
| - | - | transform(value) |
|
||||
handlerRuled(value: Text) (out: Text) { out = handlerRule(value, handlerSuffix) }
|
||||
handlerTextLength(value: Text) (out: Int) { out = length(value) }
|
||||
handlerMeasure(value: Text, operation: handler(value: Text) (out: Int)) (out: Int) { out = operation(value) }
|
||||
handlerMeasured(value: Text) (out: Int) { out = handlerMeasure(value, handlerTextLength) }
|
||||
handlerPair(value: Int) (first: Int, second: Int) { first = value
|
||||
second = value + 1 }
|
||||
handlerPairApply(value: Int, operation: handler(value: Int) (first: Int, second: Int)) (out: Int) {
|
||||
pair = operation(value)
|
||||
out = pair.first + pair.second
|
||||
}
|
||||
handlerPaired(value: Int) (out: Int) { out = handlerPairApply(value, handlerPair) }
|
||||
handlerPositiveRange(value: Int) (out: Int >= 1) { check value >= 1 else Invalid
|
||||
out = value }
|
||||
handlerGuarded(value: Int, operation: handler(value: Int) (out: Int)) (out: Int) {
|
||||
check operation(value) >= 1 else Conflict
|
||||
out = 1
|
||||
}
|
||||
handlerGuardedNative(value: Int) (out: Int) { out = handlerGuarded(value, handlerPositiveRange) }
|
||||
const heading = "中文😀"
|
||||
|
||||
constantSize() (out: Int) {
|
||||
out = length(heading)
|
||||
}
|
||||
|
||||
loop loopMeasured(values: List<Text>) (total: Int)
|
||||
| each value in values | result |
|
||||
| total | sum length(value) |
|
||||
|
||||
loop rangeMeasured(start: Int, end: Int) (total: Int)
|
||||
| each value in range(start, end) | result |
|
||||
| total | sum value |
|
||||
|
||||
loop filterMeasured(values: List<Text>) (total: Int)
|
||||
| each value in values | length(value) | result |
|
||||
| total | > 1 | sum length(value) |
|
||||
|
||||
type Message { Named(label: Text), Empty }
|
||||
|
||||
loop payloadMeasured(values: List<Message>) (total: Int)
|
||||
| each value in values | value | result |
|
||||
| total | Named(label) | sum length(label) |
|
||||
|
||||
loop takeNone(values: List<Text>) (out: List<Text>)
|
||||
| each value in values | take | result |
|
||||
| out | 0 | list value |
|
||||
|
||||
emptyKeep(values: List<Text>) (out: List<Text>, size: Int) {
|
||||
out = takeNone(values)
|
||||
size = length(values)
|
||||
}
|
||||
|
||||
loop sortedMeasured(values: List<Text>) (out: List<Text>)
|
||||
| each value in values | sort | result |
|
||||
| out | [length(value).asc] | list value |
|
||||
|
||||
foldSize(value: Text, previous: Int) (out: Int) { out = previous + length(value) }
|
||||
|
||||
loop foldMeasured(values: List<Text>) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = 0, foldSize(value, acc)) |
|
||||
|
||||
keepState(previous: Text) (out: Text) { out = previous }
|
||||
|
||||
loop foldMove(values: List<Int>, seed: Text) (out: Text)
|
||||
| each value in values | result |
|
||||
| out | fold(acc = seed, keepState(acc)) |
|
||||
|
||||
rule measuredNext(state: Int) (out: Walk<Int, Int>)
|
||||
| state | out |
|
||||
| > 0 | Next(state, state - 1) |
|
||||
| <= 0 | Done |
|
||||
|
||||
loop walkMeasured(seed: Int) (out: Int)
|
||||
| each value in walk(seed, measuredNext) | result |
|
||||
| out | sum value |
|
||||
|
||||
type FieldPair { left: Text, right: Text, count: Int }
|
||||
|
||||
swapFields(value: FieldPair) (out: FieldPair) {
|
||||
out = FieldPair { left = value.right, right = value.left, count = value.count }
|
||||
}
|
||||
|
||||
copyField(value: FieldPair) (out: FieldPair) {
|
||||
out = FieldPair { left = value.left, right = value.left, count = value.count }
|
||||
}
|
||||
|
||||
keepFields(value: FieldPair) (out: FieldPair, original: FieldPair) {
|
||||
out = swapFields(value)
|
||||
original = value
|
||||
}
|
||||
|
||||
|
||||
putAtLength(values: Map<Int, Int>) (out: Map<Int, Int>) {
|
||||
out = put(values, length(values), 17)
|
||||
}
|
||||
|
||||
appendOwnLength(values: List<Int>) (out: List<Int>) {
|
||||
out = append(values, length(values))
|
||||
}
|
||||
|
||||
type CollectionRecord { values: List<Int>, lookup: Map<Int, Int> }
|
||||
|
||||
appendFieldLength(state: CollectionRecord) (out: List<Int>, lookup: Map<Int, Int>) {
|
||||
out = append(state.values, length(state.values))
|
||||
lookup = state.lookup
|
||||
}
|
||||
|
||||
putFieldLength(state: CollectionRecord) (out: Map<Int, Int>, values: List<Int>) {
|
||||
out = put(state.lookup, length(state.lookup), length(state.values))
|
||||
values = state.values
|
||||
}
|
||||
|
||||
appendFieldKeepOriginal(state: CollectionRecord) (out: List<Int>, original: CollectionRecord) {
|
||||
out = append(state.values, length(state.values))
|
||||
original = state
|
||||
}
|
||||
|
||||
checkedCollection(value: Int) (out: CollectionRecord) {
|
||||
check value >= 0 else Forbidden
|
||||
out = CollectionRecord { values = [], lookup = {} }
|
||||
}
|
||||
|
||||
appendEvaluatedField() (out: List<Int>) {
|
||||
out = append(checkedCollection(-1).values, maybe(-1))
|
||||
}
|
||||
|
||||
loop sumMap(values: Map<Int, Int>) (out: Int)
|
||||
| each entry in entries(values) | result |
|
||||
| out | sum entry.value |
|
||||
|
||||
loop firstMapKey(values: Map<Int, Int>) (out: Int?)
|
||||
| each entry in entries(values) | result |
|
||||
| out | first entry.key |
|
||||
|
||||
sumTemporaryMap() (out: Int) { out = sumMap({ 3 = 11, 1 = 17 }) }
|
||||
|
||||
loop copyMapEntries(values: Map<Int, Int>) (out: List<MapEntry<Int, Int>>)
|
||||
| each entry in entries(values) | result |
|
||||
| out | list entry |
|
||||
|
||||
type FoldRecord { values: List<Int>, left: Int, right: Int }
|
||||
|
||||
appendRecordFields(state: FoldRecord, item: Int) (out: FoldRecord) {
|
||||
size = length(state.values)
|
||||
out = FoldRecord { values = append(state.values, item + size), left = state.right, right = state.left }
|
||||
}
|
||||
|
||||
loop recordFields(values: List<Int>, initial: FoldRecord) (out: FoldRecord)
|
||||
| each item in values | result |
|
||||
| out | fold(state = initial, appendRecordFields(state, item)) |
|
||||
|
||||
appendKeepOldSize(item: Int, state: FoldRecord) (out: FoldRecord) {
|
||||
out = FoldRecord { values = append(state.values, item), left = length(state.values), right = state.right }
|
||||
}
|
||||
|
||||
loop recordOldSize(values: List<Int>) (out: FoldRecord)
|
||||
| each item in values | result |
|
||||
| out | fold(state = FoldRecord { values = [], left = 0, right = 0 }, appendKeepOldSize(item, state)) |
|
||||
|
||||
recordFault(item: Int, state: FoldRecord) (out: FoldRecord) {
|
||||
out = FoldRecord { left = state.left + 1, values = append(state.values, item + 1), right = state.right }
|
||||
}
|
||||
|
||||
loop foldedFault(values: List<Int>, initial: FoldRecord) (out: FoldRecord)
|
||||
| each item in values | result |
|
||||
| out | fold(state = initial, recordFault(item, state)) |
|
||||
@@ -0,0 +1,366 @@
|
||||
use std::alloc::{GlobalAlloc, Layout, System};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
static ALLOCATIONS: AtomicUsize = AtomicUsize::new(0);
|
||||
struct CountAllocations;
|
||||
unsafe impl GlobalAlloc for CountAllocations {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
ALLOCATIONS.fetch_add(1, Ordering::Relaxed);
|
||||
unsafe { System.alloc(layout) }
|
||||
}
|
||||
unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
|
||||
unsafe { System.dealloc(pointer, layout) }
|
||||
}
|
||||
unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, size: usize) -> *mut u8 {
|
||||
ALLOCATIONS.fetch_add(1, Ordering::Relaxed);
|
||||
unsafe { System.realloc(pointer, layout, size) }
|
||||
}
|
||||
}
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: CountAllocations = CountAllocations;
|
||||
|
||||
let before_constant = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!(std::hint::black_box(@constantSize@()), 3);
|
||||
assert_eq!(ALLOCATIONS.load(Ordering::Relaxed) - before_constant, 0);
|
||||
|
||||
assert_eq!(@size@("你好🌍"), 3);
|
||||
assert_eq!(@flowNested@(Some("你好".to_owned())).unwrap(), "你好!");
|
||||
assert!(matches!(@flowNested@(None), Err(Failure::Api(ApiError::Invalid))));
|
||||
assert_eq!(@flowChecked@(2).unwrap(), 3);
|
||||
assert!(matches!(@flowChecked@(0), Err(Failure::@Problem@(_))));
|
||||
let doubled = @twice@(String::from("two"));
|
||||
assert_eq!((doubled.f0, doubled.f1), ("two".into(), "two".into()));
|
||||
let item = @Item@ { f0: "item".into(), f1: 2 };
|
||||
assert_eq!(@count@(&item), 2);
|
||||
assert_eq!(@nameSize@(&item), 4);
|
||||
let pair = @unchanged@(item);
|
||||
assert_eq!(pair.f0.f1, 3);
|
||||
assert_eq!(pair.f1.f1, 2);
|
||||
assert_eq!(@name@(pair.f1), "item");
|
||||
assert_eq!(@requireText@(Some("ok".into())).unwrap(), "ok");
|
||||
assert!(matches!(@requireText@(None), Err(Failure::Api(ApiError::Invalid))));
|
||||
assert_eq!(@nullableSize@(Some("你好")).unwrap(), 2);
|
||||
assert_eq!(@freshSize@().unwrap(), 2);
|
||||
assert_eq!(@add@(3, 4), 7);
|
||||
assert_eq!(@divide@(Decimal::from_int(1), Decimal::from_int(4)).to_string(), "0.25");
|
||||
assert_eq!(@fraction@().to_string(), "0.3333333333333333333333333333333333");
|
||||
assert_eq!(@join@("first".into(), "second"), "firstsecond");
|
||||
let values = @addItem@(vec!["a".into()], "b".into());
|
||||
assert_eq!(@getItem@(&values, 1), Some("b".into()));
|
||||
assert_eq!(@getItem@(&values, -1), None);
|
||||
assert_eq!(@lookup@(&@map@(), "second"), Some(2));
|
||||
assert_eq!(@capture@(2), @Reply@::Ready(2));
|
||||
assert_eq!(@capture@(0), @Reply@::Failed(@Problem@::Missing("small".into())));
|
||||
assert!(matches!(@parameterFailure@(), Err(Failure::@Problem@(@Problem@::Missing(message))) if message == "missing"));
|
||||
assert_eq!(@choose@(true, "chosen".into()), "chosen");
|
||||
assert_eq!(@choose@(false, "other".into()), "other");
|
||||
let split = @split@(@Pair@::Both("a".into(), "b".into()));
|
||||
assert_eq!((split.f0, split.f1), ("a".into(), "b".into()));
|
||||
let kept = @keep@(@Pair@::Both("a".into(), "b".into()));
|
||||
assert_eq!(kept.f0, "a");
|
||||
assert_eq!(kept.f1, @Pair@::Both("a".into(), "b".into()));
|
||||
let mixed = @mixed@(@Pair@::Both("a".into(), "你好".into()));
|
||||
assert_eq!((mixed.f0, mixed.f1), ("a".into(), 2));
|
||||
assert_eq!(@payload@(&@Choice@::Small(2)), 2);
|
||||
assert_eq!(@payload@(&@Choice@::Large(5)), 5);
|
||||
assert_eq!(@absolute@(-2), 2);
|
||||
assert_eq!(@absolute@(0), 0);
|
||||
assert_eq!(@nullable@(None), "absent");
|
||||
assert_eq!(@nullable@(Some("text".into())), "text");
|
||||
assert_eq!(@nullablePayload@(Some(@Pair@::Both("a".into(), "b".into()))), "a");
|
||||
assert_eq!(@read@(Some(@Reply@::Ready(8))).unwrap(), 8);
|
||||
assert_eq!(@read@(None).unwrap(), 0);
|
||||
assert!(matches!(@read@(Some(@Reply@::Failed(@Problem@::Missing("bad".into())))), Err(Failure::@Reply@(_))));
|
||||
let fault = std::panic::catch_unwind(|| @add@(i64::MAX, 1)).unwrap_err();
|
||||
let info = fault.downcast_ref::<&'static FaultInfo>().unwrap();
|
||||
assert_eq!(info.source, @source_path@);
|
||||
assert!(info.line > 0 && info.column > 0);
|
||||
assert_eq!(@add@(1, 2), 3);
|
||||
for (operation, left, right) in [
|
||||
(@subtract@ as fn(i64, i64) -> i64, i64::MIN, 1),
|
||||
(@multiply@, i64::MAX, 2),
|
||||
(@quotient@, 1, 0),
|
||||
(@quotient@, i64::MIN, -1),
|
||||
(@remainder@, 1, 0),
|
||||
(@remainder@, i64::MIN, -1),
|
||||
] {
|
||||
let error = std::panic::catch_unwind(|| operation(left, right)).unwrap_err();
|
||||
let info = error.downcast_ref::<&'static FaultInfo>().unwrap();
|
||||
assert_eq!(info.source, @source_path@);
|
||||
assert_eq!(info.message, "arithmetic fault");
|
||||
assert!(info.line > 0 && info.column > 0);
|
||||
}
|
||||
let error = std::panic::catch_unwind(|| @negate@(i64::MIN)).unwrap_err();
|
||||
assert_eq!(error.downcast_ref::<&'static FaultInfo>().unwrap().message, "integer overflow");
|
||||
let error = std::panic::catch_unwind(|| @divide@(Decimal::from_int(1), Decimal::ZERO)).unwrap_err();
|
||||
assert_eq!(error.downcast_ref::<&'static FaultInfo>().unwrap().message, "arithmetic fault");
|
||||
assert_eq!(@subtract@(9, 2), 7);
|
||||
assert_eq!(@multiply@(3, 4), 12);
|
||||
assert_eq!(@quotient@(-9, 2), -4);
|
||||
assert_eq!(@remainder@(-9, 2), -1);
|
||||
assert_eq!(@negate@(2), -2);
|
||||
assert!(@requireOnly@(Some("ok")).is_ok());
|
||||
assert!(@requireOnly@(None).is_err());
|
||||
let nullable = vec![Some("first".into()), None];
|
||||
assert_eq!(@getNullable@(&nullable, 0), Some("first".into()));
|
||||
assert_eq!(@getNullable@(&nullable, 1), None);
|
||||
assert_eq!(@getNullable@(&nullable, 2), None);
|
||||
assert_eq!(@getNullableInt@(&[None, Some(4)], 1), Some(4));
|
||||
assert_eq!(@getNullableInt@(&[None, Some(4)], 0), None);
|
||||
let mut map = Map::with_capacity(2);
|
||||
assert!(map.insert_unique("first".into(), Some("one".into())));
|
||||
assert!(map.insert_unique("second".into(), None));
|
||||
assert_eq!(@lookupNullable@(&map, "first"), Some("one".into()));
|
||||
assert_eq!(@lookupNullable@(&map, "second"), None);
|
||||
assert_eq!(@lookupNullable@(&map, "absent"), None);
|
||||
assert_eq!(@temporaryGet@().unwrap(), 9);
|
||||
assert_eq!(@borrowNullable@(&nullable).unwrap(), 5);
|
||||
assert_eq!(@borrowPayload@(Some(&@Pair@::Both("你好".into(), "b".into()))), 2);
|
||||
assert_eq!(@dynamicMap@("a".into(), "b".into()).len(), 2);
|
||||
let duplicate = std::panic::catch_unwind(|| @dynamicMap@("a".into(), "a".into())).unwrap_err();
|
||||
assert_eq!(duplicate.downcast_ref::<&'static FaultInfo>().unwrap().message, "duplicate Map key");
|
||||
let alias = @aliasAfterMove@("你好".into());
|
||||
assert_eq!((alias.f0, alias.f1), ("你好".into(), 2));
|
||||
let whole = @payloadAfterMove@(@Pair@::Both("你好".into(), "b".into()));
|
||||
assert_eq!(whole.f0, @Pair@::Both("你好".into(), "b".into()));
|
||||
assert_eq!(whole.f1, 2);
|
||||
let field = @fieldAliasAfterMove@(@Item@ { f0: "你好".into(), f1: 9 });
|
||||
assert_eq!((field.f0.f0, field.f1), ("你好".into(), 2));
|
||||
let nullable = @nonnullAliasAfterMove@(Some("你好".into())).unwrap();
|
||||
assert_eq!((nullable.f0, nullable.f1), (Some("你好".into()), 2));
|
||||
assert!(@nonnullAliasAfterMove@(None).is_err());
|
||||
let before = @aliasBeforeMove@("你好".into());
|
||||
assert_eq!((before.f0, before.f1), ("你好".into(), 2));
|
||||
let empty = @nullEquality@();
|
||||
assert!(empty.f0);
|
||||
assert!(!empty.f1);
|
||||
assert!(@containsText@(&["你好".into(), "world".into()], "你好"));
|
||||
assert!(!@containsText@(&[], "你好"));
|
||||
assert!(!@containsText@(&["你好".into()], "你"));
|
||||
assert!(@containsNullable@(&[None, Some("你好".into())], None));
|
||||
assert!(@containsNullable@(&[None, Some("你好".into())], Some("你好")));
|
||||
assert!(@containsRecord@(&[@Item@ { f0: "你好".into(), f1: 1 }], &@Item@ { f0: "你好".into(), f1: 1 }));
|
||||
assert!(@containsNested@(&[vec![1, 2], vec![3]], &[1, 2]));
|
||||
assert_eq!(@lookupSize@(&["你好".into()], 0).unwrap(), 2);
|
||||
assert!(@lookupSize@(&[], 0).is_err());
|
||||
assert!(@lookupSize@(&["name".into()], -1).is_err());
|
||||
let before = @lookupBeforeMove@(vec!["你好".into()]).unwrap();
|
||||
let after = @lookupAfterMove@(vec!["你好".into()]).unwrap();
|
||||
assert_eq!(before.f0, vec!["你好", "tail"]);
|
||||
assert_eq!(after.f0, before.f0);
|
||||
assert_eq!(after.f1, 2);
|
||||
let mut values = Map::with_capacity(2);
|
||||
values.put("present".to_owned(), Some("你好".to_owned()));
|
||||
values.put("empty".to_owned(), None);
|
||||
assert_eq!(@lookupMapSize@(&values, "present").unwrap(), 2);
|
||||
assert!(@lookupMapSize@(&values, "empty").is_err());
|
||||
assert!(@lookupMapSize@(&values, "missing").is_err());
|
||||
let mut map = Map::with_capacity(3);
|
||||
map.put("first".to_owned(), "one".to_owned());
|
||||
map.put("middle".to_owned(), "two".to_owned());
|
||||
map.put("last".to_owned(), "three".to_owned());
|
||||
let kept = @keepMap@(map.clone());
|
||||
assert_eq!(kept.f1, map);
|
||||
let mut expected = map.clone();
|
||||
expected.put("first".to_owned(), "changed".to_owned());
|
||||
assert_eq!(kept.f0, expected);
|
||||
assert_eq!(@putMap@(map.clone(), "first".into(), "changed".into()), expected);
|
||||
let mut deleted = Map::with_capacity(2);
|
||||
deleted.put("first".to_owned(), "one".to_owned());
|
||||
deleted.put("last".to_owned(), "three".to_owned());
|
||||
assert_eq!(@removeMap@(map.clone(), "middle"), deleted);
|
||||
assert_eq!(@removeMap@(map.clone(), "absent"), map);
|
||||
let mut numeric = Map::with_capacity(1);
|
||||
numeric.put(3i64, "three".to_owned());
|
||||
assert!(@removeIntKey@(numeric, 3).is_empty());
|
||||
|
||||
// 实际生成程序和直接 Rust 都只读借用;统计只覆盖操作,不包含输入准备。
|
||||
let probe = vec!["你好🌍".repeat(1024), "other".to_owned()];
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let size = @lookupSize@(&probe, 0).unwrap();
|
||||
let found = @containsText@(&probe, &probe[0]);
|
||||
let generated_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before;
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let reference_size = probe.first().unwrap().chars().count() as i64;
|
||||
let reference_found = probe.iter().any(|value| value == &probe[0]);
|
||||
let reference_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before;
|
||||
assert_eq!((size, found), (reference_size, reference_found));
|
||||
assert_eq!(generated_allocations, 0);
|
||||
assert_eq!(reference_allocations, 0);
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let loop_size = @loopMeasured@(&probe);
|
||||
let filter_size = @filterMeasured@(&probe);
|
||||
let range_total = @rangeMeasured@(0, 1024);
|
||||
let loop_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before;
|
||||
assert_eq!(loop_size, probe.iter().map(|v| v.chars().count() as i64).sum::<i64>());
|
||||
assert_eq!(range_total, (0..1024).sum::<i64>());
|
||||
assert_eq!(filter_size, loop_size);
|
||||
assert_eq!(loop_allocations, 0, "borrowed loop and lazy range need no intermediate allocation");
|
||||
let messages = [@Message@::Named(probe[0].clone()), @Message@::Empty];
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let message_size = @payloadMeasured@(&messages);
|
||||
let message_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before;
|
||||
assert_eq!(message_size, reference_size);
|
||||
assert_eq!(message_allocations, 0, "choice filter borrows payloads instead of copying messages");
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let empty_kept = @emptyKeep@(&probe);
|
||||
let empty_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before;
|
||||
assert!(empty_kept.f0.is_empty());
|
||||
assert_eq!(empty_kept.f1, 2);
|
||||
assert_eq!(empty_allocations, 0, "constant take zero does not clone a retained source");
|
||||
let source = (0..4096).map(|index| "中文".repeat(index * 19 % 97)).collect::<Vec<_>>();
|
||||
let reference = source.clone();
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let sorted = @sortedMeasured@(source);
|
||||
let sorted_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before;
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let mut keyed = reference.into_iter().map(|text| ((text.chars().count() as i64,), text)).collect::<Vec<_>>();
|
||||
keyed.sort_by(|left, right| left.0.cmp(&right.0));
|
||||
let reference = keyed.into_iter().map(|(_, text)| text).collect::<Vec<_>>();
|
||||
let reference_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before;
|
||||
assert_eq!(sorted, reference);
|
||||
assert_eq!(sorted_allocations, reference_allocations, "stable cached-key sorting has no extra allocation over direct Rust");
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let entries = @mapEntries@(map);
|
||||
let allocations = ALLOCATIONS.load(Ordering::Relaxed) - before;
|
||||
assert_eq!(allocations, 1, "collect entries once, move keys and values without cloning");
|
||||
assert_eq!(entries.iter().map(|e| e.f0.as_str()).collect::<Vec<_>>(), vec!["first", "middle", "last"]);
|
||||
assert_eq!(@entryValueSize@(&entries[0]), 3);
|
||||
let renamed = @renamedEntry@(entries.into_iter().next().unwrap());
|
||||
assert_eq!(renamed.f0, "renamed");
|
||||
assert_eq!(renamed.f1, "one");
|
||||
assert_eq!(@entryIntValue@(dever_runtime::collection::MapEntry { f0: 1, f1: 2 }), 2);
|
||||
let result = @handlerNative@("hello".to_owned());
|
||||
assert_eq!(result.f0, "hello");
|
||||
assert_eq!(result.f1, "hello!");
|
||||
assert_eq!(@handlerRuled@("table".to_owned()), "table!");
|
||||
assert!(matches!(@handlerCaptured@(3), @HandlerResult@::Done(3)));
|
||||
assert!(matches!(@handlerCaptured@(0), @HandlerResult@::Rejected(f0) if f0 == "positive required"));
|
||||
assert_eq!(@handlerPaired@(4), 9);
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let actual = @handlerMeasured@(&probe[0]);
|
||||
let handler_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before;
|
||||
assert_eq!(actual, probe[0].chars().count() as i64);
|
||||
assert_eq!(handler_allocations, 0, "static callbacks borrow without heap allocation");
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let flow_size = @flowMeasured@(&probe[0]);
|
||||
let flow_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before;
|
||||
assert_eq!(flow_size, actual);
|
||||
assert_eq!(flow_allocations, 0, "sequential flow borrows without a runtime workflow object");
|
||||
assert_eq!(@handlerGuardedNative@(2).unwrap(), 1);
|
||||
assert!(matches!(@handlerGuardedNative@(0), Err(Failure::Api(ApiError::Invalid))));
|
||||
let state = String::from("累积状态不在每轮复制");
|
||||
let pointer = state.as_ptr();
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let size = @foldMeasured@(&probe);
|
||||
let kept = @foldMove@(&[1, 2, 3], state);
|
||||
let allocations = ALLOCATIONS.load(Ordering::Relaxed) - before;
|
||||
assert_eq!(size, probe.iter().map(|s| s.chars().count() as i64).sum::<i64>());
|
||||
assert_eq!(kept.as_ptr(), pointer);
|
||||
assert_eq!(allocations, 0, "fold borrows source values and moves state without allocating");
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let walked = @walkMeasured@(std::hint::black_box(100));
|
||||
let allocations = ALLOCATIONS.load(Ordering::Relaxed) - before;
|
||||
assert_eq!(walked, 5050);
|
||||
assert_eq!(allocations, 0, "walk directly advances state without a queue or boxed iterator");
|
||||
let pair = @FieldPair@ { f0: "左字段".into(), f1: "右字段".into(), f2: 3 };
|
||||
let pointers = [pair.f0.as_ptr(), pair.f1.as_ptr()];
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let swapped = @swapFields@(pair);
|
||||
let allocations = ALLOCATIONS.load(Ordering::Relaxed) - before;
|
||||
assert_eq!([swapped.f0.as_ptr(), swapped.f1.as_ptr()], [pointers[1], pointers[0]]);
|
||||
assert_eq!(swapped.f2, 3);
|
||||
assert_eq!(allocations, 0, "disjoint record fields move independently");
|
||||
let kept = @keepFields@(swapped);
|
||||
assert_eq!((&kept.f0.f0, &kept.f1.f0), (&String::from("左字段"), &String::from("右字段")));
|
||||
let original = kept.f1.f0.as_ptr();
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let copied = @copyField@(kept.f1);
|
||||
let allocations = ALLOCATIONS.load(Ordering::Relaxed) - before;
|
||||
assert_eq!(copied.f0, copied.f1);
|
||||
assert_eq!(copied.f1.as_ptr(), original);
|
||||
assert_eq!(allocations, 1, "reusing the same field copies it exactly once");
|
||||
|
||||
let mut capacity_map = Map::with_capacity(8);
|
||||
capacity_map.put(0, 5);
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let capacity_map = @putAtLength@(capacity_map);
|
||||
let after = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!(capacity_map.get(&1), Some(&17));
|
||||
assert_eq!(after - before, 0, "updating from the same map must reuse its storage");
|
||||
let mut capacity_list = Vec::with_capacity(8);
|
||||
capacity_list.push(5);
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let capacity_list = @appendOwnLength@(capacity_list);
|
||||
let after = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!(capacity_list, [5, 1]);
|
||||
assert_eq!(after - before, 0, "reading length must not clone the list");
|
||||
|
||||
{
|
||||
let mut values = Vec::with_capacity(8);
|
||||
values.push(5);
|
||||
let pointer = values.as_ptr();
|
||||
let state = @CollectionRecord@ { f0: values, f1: Map::with_capacity(0) };
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let values = @appendFieldLength@(state).f0;
|
||||
let after = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!(values, [5, 1]);
|
||||
assert_eq!(values.as_ptr(), pointer, "local field updates reuse the owned buffer");
|
||||
assert_eq!(after - before, 0, "reading a local field must not clone its list");
|
||||
}
|
||||
let mut lookup = Map::with_capacity(8);
|
||||
lookup.put(0, 5);
|
||||
let state = @CollectionRecord@ { f0: vec![5, 6], f1: lookup };
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let lookup = @putFieldLength@(state).f0;
|
||||
let after = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!(lookup.get(&1), Some(&2));
|
||||
assert_eq!(after - before, 0, "local field updates reuse the owned map");
|
||||
let state = @CollectionRecord@ { f0: vec![5], f1: Map::with_capacity(0) };
|
||||
let pointer = state.f0.as_ptr();
|
||||
let preserved = @appendFieldKeepOriginal@(state);
|
||||
assert_eq!(preserved.f0, [5, 1]);
|
||||
assert_eq!(preserved.f1.f0, [5]);
|
||||
assert_eq!(preserved.f1.f0.as_ptr(), pointer);
|
||||
assert_ne!(preserved.f0.as_ptr(), pointer);
|
||||
assert!(matches!(@appendEvaluatedField@(), Err(Failure::Api(ApiError::Forbidden))),
|
||||
"a computed receiver still fails before its item expression");
|
||||
|
||||
let mut entries = Map::with_capacity(2);
|
||||
entries.put(3, 11);
|
||||
entries.put(1, 17);
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let total = @sumMap@(&entries);
|
||||
let first = @firstMapKey@(&entries);
|
||||
let after = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!((total, first), (28, Some(3)));
|
||||
assert_eq!(after - before, 0, "direct traversal must not materialize or clone entries");
|
||||
assert_eq!(entries.get(&1), Some(&17));
|
||||
assert_eq!(@sumTemporaryMap@(), 28);
|
||||
assert_eq!(@sumMap@(&Map::with_capacity(0)), 0);
|
||||
assert_eq!(@firstMapKey@(&Map::with_capacity(0)), None);
|
||||
let copied = @copyMapEntries@(&entries);
|
||||
assert_eq!(copied.iter().map(|entry| (entry.f0, entry.f1)).collect::<Vec<_>>(), [(3,11), (1,17)]);
|
||||
|
||||
let mut buffer = Vec::with_capacity(8);
|
||||
buffer.push(4);
|
||||
let pointer = buffer.as_ptr();
|
||||
let initial = @FoldRecord@ { f0: buffer, f1: 11, f2: 23 };
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let result = @recordFields@(&[7, 8, 9], initial);
|
||||
let after = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!(result.f0, [4, 8, 10, 12]);
|
||||
assert_eq!((result.f1, result.f2), (23, 11), "field swaps read the previous state");
|
||||
assert_eq!(result.f0.as_ptr(), pointer);
|
||||
assert_eq!(after - before, 0, "record fold retains its existing buffer");
|
||||
let empty = @recordFields@(&[], result);
|
||||
assert_eq!(empty.f0.as_ptr(), pointer);
|
||||
assert_eq!((empty.f1, empty.f2), (23, 11));
|
||||
let preserved = @recordOldSize@(&[7, 8, 9]);
|
||||
assert_eq!(preserved.f0, [7, 8, 9]);
|
||||
assert_eq!(preserved.f1, 2, "reading an old buffer after append must preserve value semantics");
|
||||
let state = || @FoldRecord@ { f0: Vec::new(), f1: i64::MAX, f2: 0 };
|
||||
let direct = std::panic::catch_unwind(|| @recordFault@(i64::MAX, state())).err().expect("direct overflow");
|
||||
let folded = std::panic::catch_unwind(|| @foldedFault@(&[i64::MAX], state())).err().expect("folded overflow");
|
||||
let direct = direct.downcast_ref::<&'static FaultInfo>().unwrap();
|
||||
let folded = folded.downcast_ref::<&'static FaultInfo>().unwrap();
|
||||
assert_eq!((direct.source, direct.line, direct.column), (folded.source, folded.line, folded.column), "fold retains field evaluation and first fault location");
|
||||
@@ -0,0 +1,38 @@
|
||||
type Banner { title: Text, details: List<Text>, count: Int >= 1 }
|
||||
type State { Active, Paused }
|
||||
setting banner: Banner
|
||||
setting names: List<Text>
|
||||
setting optional: Text?
|
||||
setting state: State
|
||||
readSize() (out: Int) { out = length(banner.title) + length(names) }
|
||||
copyTitle() (out: Text) { out = banner.title }
|
||||
copyBanner() (out: Banner) { out = banner }
|
||||
copyNames() (out: List<Text>) { out = names }
|
||||
nullable() (out: Text?) { out = optional }
|
||||
mode() (out: State) { out = state }
|
||||
measure() (out: Int >= 1) { out = banner.count }
|
||||
select(value: Int) (out: Int) { out = value + readSize() }
|
||||
apply(value: Int, action: handler(value: Int) (out: Int)) (out: Int) { out = action(value) }
|
||||
viaHandler(value: Int) (out: Int) { out = apply(value, select) }
|
||||
flow start() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | calc | readSize() |
|
||||
loop sizes(n: Int) (out: Int)
|
||||
| each value in range(0, n) | result |
|
||||
| out | sum select(value) |
|
||||
plain(value: Int) (out: Int) { out = value }
|
||||
|
||||
aliasTitle() (out: Text) {
|
||||
first = banner
|
||||
second = first
|
||||
out = second.title
|
||||
}
|
||||
changed() (out: Banner) {
|
||||
out = banner
|
||||
out.title = "new"
|
||||
}
|
||||
present() (out: Text) {
|
||||
value = optional
|
||||
check value != null else Invalid
|
||||
out = value
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn settings_borrow_without_allocations_and_propagate_through_flow_loop_and_handler() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"settings",
|
||||
include_str!("settings.dever"),
|
||||
Some(include_str!("settings.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
let input = r#"{"module":{"main":{"main":{"banner":{"title":"雪😀","details":["large","unused"],"count":3},"names":["one","two"],"optional":null,"state":"Active"}}}}"#;
|
||||
let path = std::path::Path::new(@source_path@).with_extension("json");
|
||||
std::fs::write(&path, input).unwrap();
|
||||
let settings = load_settings(&path).unwrap();
|
||||
assert_eq!(@copyTitle@(&settings), "雪😀");
|
||||
assert_eq!(@copyNames@(&settings), ["one", "two"]);
|
||||
assert_eq!(@copyBanner@(&settings).f1, ["large", "unused"]);
|
||||
assert_eq!(@nullable@(&settings), None);
|
||||
assert_eq!(@mode@(&settings), @State@::Active);
|
||||
assert_eq!(@plain@(8), 8);
|
||||
@allocation_counter@
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!(@readSize@(std::hint::black_box(&settings)), 4);
|
||||
assert_eq!(@start@(&settings), 4);
|
||||
assert_eq!(@viaHandler@(&settings, 3), 7);
|
||||
assert_eq!(@sizes@(&settings, 4), 22);
|
||||
assert_eq!(@measure@(&settings), 3);
|
||||
assert_eq!(ALLOCATIONS.load(Ordering::Relaxed) - before, 0);
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let title = @copyTitle@(std::hint::black_box(&settings));
|
||||
assert_eq!(ALLOCATIONS.load(Ordering::Relaxed) - before, 1);
|
||||
assert_eq!(title, "雪😀");
|
||||
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
let title = @aliasTitle@(std::hint::black_box(&settings));
|
||||
assert_eq!(ALLOCATIONS.load(Ordering::Relaxed) - before, 1);
|
||||
assert_eq!(title, "雪😀");
|
||||
assert_eq!(@changed@(&settings).f0, "new");
|
||||
assert_eq!(@copyTitle@(&settings), "雪😀");
|
||||
assert!(@present@(&settings).is_err());
|
||||
@@ -0,0 +1,149 @@
|
||||
identity(value: Text) (out: Text) { out = value }
|
||||
size(value: Text) (out: Int) { out = length(value) }
|
||||
pair(value: Int) (left: Int, right: Int) {
|
||||
left = value
|
||||
right = value + 1
|
||||
}
|
||||
|
||||
flow work(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(0) |
|
||||
| out | calc | value |
|
||||
|
||||
flow child(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(work(value)) |
|
||||
| out | calc | wait(task) |
|
||||
|
||||
flow main() (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(child(42)) |
|
||||
| out | calc | wait(task) |
|
||||
|
||||
flow text(value: Text) (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(identity(value)) |
|
||||
| kept | calc | length(value) |
|
||||
| received | calc | wait(task) |
|
||||
| out | calc | kept + length(received) |
|
||||
|
||||
flow borrowed(value: Text) (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(size(value)) |
|
||||
| out | calc | wait(task) |
|
||||
|
||||
flow multiple(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(pair(value)) |
|
||||
| received | calc | wait(task) |
|
||||
| out | calc | received.left + received.right |
|
||||
|
||||
flow cancel() ()
|
||||
| step | kind | do |
|
||||
| task | calc | run(dever.time.sleep(60000)) |
|
||||
| - | calc | stop(task) |
|
||||
|
||||
type Attempt { Done(value: Int), error Failed(value: dever.time.SleepResult) }
|
||||
rule resolve(value: Attempt) (out: Int) recover("report rejected delay as -1")
|
||||
| value | out |
|
||||
| Done(number) | number |
|
||||
| Failed(error) | -1 |
|
||||
|
||||
flow failing(millis: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(millis) |
|
||||
| out | calc | 10 |
|
||||
|
||||
flow captured(millis: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(failing(millis)) |
|
||||
| attempt: Attempt | calc | result(wait(task)) |
|
||||
| out | rule | resolve(attempt) |
|
||||
|
||||
flow unfinished(millis: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(work(9)) |
|
||||
| - | flow | dever.time.sleep(millis) |
|
||||
| out | calc | wait(task) |
|
||||
|
||||
flow recovered(millis: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| attempt: Attempt | flow | result(unfinished(millis)) |
|
||||
| out | rule | resolve(attempt) |
|
||||
|
||||
flow together() (out: Int)
|
||||
| step | kind | parallel | do |
|
||||
| a | calc | start | run(work(11)) |
|
||||
| b | calc | start | run(work(31)) |
|
||||
| left | calc | join | wait(a) |
|
||||
| right | calc | join | wait(b) |
|
||||
| out | calc | - | left + right |
|
||||
|
||||
flow failStop(millis: Int) ()
|
||||
| step | kind | do |
|
||||
| task | calc | run(dever.time.sleep(millis)) |
|
||||
| - | flow | dever.time.sleep(1) |
|
||||
| - | calc | stop(task) |
|
||||
|
||||
flow overflow(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(pair(value)) |
|
||||
| received | calc | wait(task) |
|
||||
| out | calc | received.right |
|
||||
|
||||
cmd main = main
|
||||
cmd captured = captured
|
||||
cmd cancel = cancel
|
||||
cmd overflow = overflow
|
||||
|
||||
flow spawnedRecovery() (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(recovered(-1)) |
|
||||
| out | calc | wait(task) |
|
||||
|
||||
flow apply(value: Int, action: handler(value: Int) (out: Int)) (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(action(value)) |
|
||||
| out | calc | wait(task) |
|
||||
|
||||
flow handled() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | flow | apply(42, child) |
|
||||
|
||||
type Problem { error Invalid }
|
||||
guard(value: Int) (out: Int) {
|
||||
check value > 0 else Problem.Invalid
|
||||
out = value
|
||||
}
|
||||
alwaysFail() (out: Int) { out = fail(Problem.Invalid) }
|
||||
flow neverReturns() (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(alwaysFail()) |
|
||||
| out | calc | wait(task) |
|
||||
|
||||
flow argumentFailure(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| attempt: Attempt | flow | result(unfinished(guard(value))) |
|
||||
| out | rule | resolve(attempt) |
|
||||
|
||||
flow slow() (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(failing(60000)) |
|
||||
| out | calc | wait(task) |
|
||||
|
||||
flow failedGroup(millis: Int) (out: Int)
|
||||
| step | kind | parallel | do |
|
||||
| left | flow | tasks | slow() |
|
||||
| right | flow | tasks | failing(millis) |
|
||||
| out | calc | - | left + right |
|
||||
|
||||
flow recoveredGroup(millis: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| attempt: Attempt | flow | result(failedGroup(millis)) |
|
||||
| out | rule | resolve(attempt) |
|
||||
|
||||
flow abandonedFault(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(pair(value)) |
|
||||
| - | flow | dever.time.sleep(1) |
|
||||
| out | calc | fail(Problem.Invalid) |
|
||||
@@ -0,0 +1,44 @@
|
||||
@allocation_counter@
|
||||
use dever_runtime::task::{self, RunError};
|
||||
assert_eq!(task::run(true, 8, async |scope| @main@(scope).await).unwrap().unwrap(), 42);
|
||||
assert_eq!(task::run(true, 8, async |scope| @together@(scope).await).unwrap().unwrap(), 42);
|
||||
assert_eq!(task::run(true, 8, async |scope| Ok::<_, ()>(@text@(scope, "hello".into()).await)).unwrap().unwrap(), 10);
|
||||
assert_eq!(task::run(true, 8, async |scope| Ok::<_, ()>(@borrowed@(scope, "hello".into()).await)).unwrap().unwrap(), 5);
|
||||
assert_eq!(task::run(true, 8, async |scope| Ok::<_, ()>(@multiple@(scope, 20).await)).unwrap().unwrap(), 41);
|
||||
task::run(true, 8, async |scope| @cancel@(scope).await).unwrap().unwrap();
|
||||
assert_eq!(task::run(true, 8, async |scope| Ok::<_, ()>(@captured@(scope, -1).await)).unwrap().unwrap(), -1);
|
||||
assert_eq!(task::run(true, 8, async |scope| Ok::<_, ()>(@captured@(scope, 0).await)).unwrap().unwrap(), 10);
|
||||
// 容量为 1,恢复后能再次派生,证明捕获边界已归还前一次任务的许可。
|
||||
task::run(true, 1, async |scope| {
|
||||
assert_eq!(@recovered@(scope, -1).await, -1);
|
||||
assert_eq!(@recovered@(scope, -1).await, -1);
|
||||
Ok::<_, ()>(())
|
||||
}).unwrap().unwrap();
|
||||
assert!(matches!(task::run(true, 8, async |scope| @failStop@(scope, -1).await).unwrap(), Err(RunError::Business { .. })));
|
||||
match task::run(true, 8, async |scope| Ok::<_, ()>(@overflow@(scope, i64::MAX).await)).unwrap() {
|
||||
Err(RunError::Fault { primary, additional }) => {
|
||||
let info = primary.downcast_ref::<&'static FaultInfo>().unwrap();
|
||||
assert_eq!(info.source, @source_path@);
|
||||
assert!(additional.is_empty());
|
||||
}
|
||||
_ => panic!("expected original arithmetic fault"),
|
||||
}
|
||||
|
||||
assert_eq!(task::run(true, 8, async |scope| Ok::<_, ()>(@spawnedRecovery@(scope).await)).unwrap().unwrap(), -1);
|
||||
assert_eq!(task::run(true, 8, async |scope| @handled@(scope).await).unwrap().unwrap(), 42);
|
||||
|
||||
assert!(matches!(task::run(true, 8, async |scope| @neverReturns@(scope).await).unwrap(), Err(RunError::Business { .. })));
|
||||
assert!(matches!(task::run(true, 8, async |scope| @argumentFailure@(scope, 0).await).unwrap(), Err(RunError::Business { .. })));
|
||||
task::run(true, 1, async |scope| {
|
||||
assert_eq!(@recoveredGroup@(scope, -1).await, -1);
|
||||
assert_eq!(@recoveredGroup@(scope, -1).await, -1);
|
||||
Ok::<_, ()>(())
|
||||
}).unwrap().unwrap();
|
||||
|
||||
match task::run(true, 8, async |scope| @abandonedFault@(scope, i64::MAX).await).unwrap() {
|
||||
Err(RunError::Business { additional, .. }) => {
|
||||
assert_eq!(additional.len(), 1, "unconsumed Task must stay alive until failure exit");
|
||||
assert_eq!(additional[0].downcast_ref::<&'static FaultInfo>().unwrap().source, @source_path@);
|
||||
}
|
||||
_ => panic!("primary business error must be retained"),
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
textTrim(value: Text) (result: Text) {
|
||||
result = text.trim(value)
|
||||
}
|
||||
|
||||
textLower(value: Text) (result: Text) {
|
||||
result = text.lower(value)
|
||||
}
|
||||
|
||||
textUpper(value: Text) (result: Text) {
|
||||
result = text.upper(value)
|
||||
}
|
||||
|
||||
textCodepoint(value: Text) (result: Int?) {
|
||||
result = text.codepoint(value)
|
||||
}
|
||||
|
||||
textFromCodepoint(value: Int) (result: Text?) {
|
||||
result = text.fromCodepoint(value)
|
||||
}
|
||||
|
||||
textAt(value: Text, index: Int) (result: Text?) {
|
||||
result = text.at(value, index)
|
||||
}
|
||||
|
||||
textSlice(value: Text, start: Int, end: Int) (result: Text?) {
|
||||
result = text.slice(value, start, end)
|
||||
}
|
||||
|
||||
textIndexOf(value: Text, pattern: Text) (result: Int?) {
|
||||
result = text.indexOf(value, pattern)
|
||||
}
|
||||
|
||||
textContains(value: Text, pattern: Text) (result: Bool) {
|
||||
result = text.contains(value, pattern)
|
||||
}
|
||||
|
||||
textStartsWith(value: Text, prefix: Text) (result: Bool) {
|
||||
result = text.startsWith(value, prefix)
|
||||
}
|
||||
|
||||
textEndsWith(value: Text, suffix: Text) (result: Bool) {
|
||||
result = text.endsWith(value, suffix)
|
||||
}
|
||||
|
||||
textSplit(value: Text, separator: Text) (result: List<Text>) {
|
||||
result = text.split(value, separator)
|
||||
}
|
||||
|
||||
textReplace(value: Text, pattern: Text, replacement: Text) (result: Text) {
|
||||
result = text.replace(value, pattern, replacement)
|
||||
}
|
||||
|
||||
textIsEmpty(value: Text) (result: Bool) {
|
||||
result = text.isEmpty(value)
|
||||
}
|
||||
|
||||
textJoin(values: List<Text>, separator: Text) (result: Text) {
|
||||
result = text.join(values, separator)
|
||||
}
|
||||
|
||||
intParse(value: Text) (result: Int?) {
|
||||
result = int.parse(value)
|
||||
}
|
||||
|
||||
intToText(value: Int) (result: Text) {
|
||||
result = int.toText(value)
|
||||
}
|
||||
|
||||
floatFromInt(value: Int) (result: Float) {
|
||||
result = float.fromInt(value)
|
||||
}
|
||||
|
||||
floatParse(value: Text) (result: Float?) {
|
||||
result = float.parse(value)
|
||||
}
|
||||
|
||||
floatToText(value: Float) (result: Text) {
|
||||
result = float.toText(value)
|
||||
}
|
||||
|
||||
decimalRound(value: Decimal, places: Int) (result: Decimal) {
|
||||
result = decimal.round(value, places)
|
||||
}
|
||||
|
||||
decimalParse(value: Text) (result: Decimal?) {
|
||||
result = decimal.parse(value)
|
||||
}
|
||||
|
||||
decimalToText(value: Decimal) (result: Text) {
|
||||
result = decimal.toText(value)
|
||||
}
|
||||
|
||||
decimalFromInt(value: Int) (result: Decimal) {
|
||||
result = decimal.fromInt(value)
|
||||
}
|
||||
|
||||
mathSqrt(value: Float) (result: Float) {
|
||||
result = math.sqrt(value)
|
||||
}
|
||||
|
||||
mathSin(value: Float) (result: Float) {
|
||||
result = math.sin(value)
|
||||
}
|
||||
|
||||
mathCos(value: Float) (result: Float) {
|
||||
result = math.cos(value)
|
||||
}
|
||||
|
||||
mathLog(value: Float) (result: Float) {
|
||||
result = math.log(value)
|
||||
}
|
||||
|
||||
mathPow(value: Float, exponent: Float) (result: Float) {
|
||||
result = math.pow(value, exponent)
|
||||
}
|
||||
|
||||
mathIsNan(value: Float) (result: Bool) {
|
||||
result = math.isNan(value)
|
||||
}
|
||||
|
||||
mathIsFinite(value: Float) (result: Bool) {
|
||||
result = math.isFinite(value)
|
||||
}
|
||||
|
||||
mathIsInfinite(value: Float) (result: Bool) {
|
||||
result = math.isInfinite(value)
|
||||
}
|
||||
|
||||
rule requiredFloat(value: Float?) (out: Float)
|
||||
| value | out |
|
||||
| null | fail(Invalid) |
|
||||
| other | value |
|
||||
|
||||
rule requiredDecimal(value: Decimal?) (out: Decimal)
|
||||
| value | out |
|
||||
| null | fail(Invalid) |
|
||||
| other | value |
|
||||
|
||||
readFloat(value: Text) (out: Float) {
|
||||
out = requiredFloat(float.parse(value))
|
||||
}
|
||||
|
||||
readDecimal(value: Text) (out: Decimal) {
|
||||
out = requiredDecimal(decimal.parse(value))
|
||||
}
|
||||
|
||||
appendChunk(chunk: Text, whole: Text) (out: Text) { out = whole + chunk }
|
||||
|
||||
loop joinChunks(parts: List<Text>) (out: Text)
|
||||
| each chunk in parts | result |
|
||||
| out | fold(whole = "", appendChunk(chunk, whole)) |
|
||||
|
||||
loop prefixChunks(parts: List<Text>) (out: Text)
|
||||
| each chunk in parts | result |
|
||||
| out | fold(whole = "前缀:", appendChunk(chunk, whole)) |
|
||||
@@ -0,0 +1,96 @@
|
||||
assert_eq!(@textTrim@(" 雪 \n"), "雪");
|
||||
assert_eq!(@textLower@("İABC雪"), "i\u{307}abc雪");
|
||||
assert_eq!(@textUpper@("straße雪"), "STRASSE雪");
|
||||
for value in ["", "ab", "e\u{301}"] { assert_eq!(@textCodepoint@(value), None); }
|
||||
for point in [0, 0x7f, 0x80, 0x7ff, 0x800, 0xd7ff, 0xe000, 0xffff, 0x10000, 0x10ffff] {
|
||||
let text = char::from_u32(point).unwrap().to_string();
|
||||
assert_eq!(@textCodepoint@(&text), Some(i64::from(point)));
|
||||
assert_eq!(@textFromCodepoint@(i64::from(point)), Some(text));
|
||||
}
|
||||
for point in [-1, 0xd800, 0xdfff, 0x110000, i64::MAX] {
|
||||
assert_eq!(@textFromCodepoint@(point), None);
|
||||
}
|
||||
let text = "a雪😀e\u{301}";
|
||||
assert_eq!(@textAt@(text, 2), Some("😀".into()));
|
||||
for index in [-1, 5, i64::MAX] { assert_eq!(@textAt@(text, index), None); }
|
||||
assert_eq!(@textSlice@(text, 1, 3), Some("雪😀".into()));
|
||||
assert_eq!(@textSlice@(text, 5, 5), Some(String::new()));
|
||||
assert_eq!(@textSlice@("", 0, 0), Some(String::new()));
|
||||
for (start, end) in [(-1, 2), (0, -1), (3, 2), (0, 6), (6, 6), (i64::MAX, i64::MAX)] {
|
||||
assert_eq!(@textSlice@(text, start, end), None);
|
||||
}
|
||||
assert_eq!(@textIndexOf@(text, "😀"), Some(2));
|
||||
assert_eq!(@textIndexOf@(text, "missing"), None);
|
||||
assert_eq!(@textIndexOf@(text, ""), Some(0));
|
||||
assert!(@textContains@(text, "雪😀"));
|
||||
assert!(@textStartsWith@(text, "a雪"));
|
||||
assert!(@textEndsWith@(text, "e\u{301}"));
|
||||
assert!(!@textIsEmpty@(text));
|
||||
assert!(@textIsEmpty@(""));
|
||||
assert_eq!(@textSplit@("雪😀", ""), ["雪", "😀"]);
|
||||
assert!(@textSplit@("", "").is_empty());
|
||||
assert_eq!(@textSplit@(",a,,", ","), ["", "a", "", ""]);
|
||||
assert_eq!(@textReplace@("雪雪", "雪", "😀"), "😀😀");
|
||||
assert_eq!(@textJoin@(&["雪".into(), "😀".into()], ","), "雪,😀");
|
||||
for value in [i64::MIN, -1, 0, 1, i64::MAX] {
|
||||
assert_eq!(@intParse@(&@intToText@(value)), Some(value));
|
||||
assert_eq!(@decimalFromInt@(value), Decimal::from_int(value));
|
||||
assert_eq!(@floatFromInt@(value), value as f64);
|
||||
}
|
||||
for value in ["", " 1", "1 ", "1.0", "9223372036854775808"] { assert_eq!(@intParse@(value), None); }
|
||||
for value in ["", "nan", "NAN", "+inf", "Infinity", " 1", "1 ", "1_0", "1e", "--1"] {
|
||||
assert_eq!(@floatParse@(value), None);
|
||||
}
|
||||
for value in [0.0, -0.0, 0.1, f64::MIN_POSITIVE, f64::MAX, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
assert_eq!(@floatParse@(&@floatToText@(value)).unwrap().to_bits(), value.to_bits());
|
||||
}
|
||||
assert!(@floatParse@("NaN").unwrap().is_nan());
|
||||
assert_eq!(@floatParse@("1e9999"), Some(f64::INFINITY));
|
||||
for value in ["", "NaN", "inf", " 1", "1 ", "1_0", "1e", "1e6145", "1e-6177", "1.0000000000000000000000000000000001"] {
|
||||
assert_eq!(@decimalParse@(value), None, "{value}");
|
||||
}
|
||||
for value in ["0", "0.1", "1e6144", "1e-6176"] {
|
||||
let parsed = @decimalParse@(value).unwrap();
|
||||
assert_eq!(@decimalParse@(&@decimalToText@(parsed)), Some(parsed));
|
||||
}
|
||||
for (value, places, expected) in [("1.25", 1, "1.2"), ("1.35", 1, "1.4"), ("250", -2, "200"), ("-1.25", 1, "-1.2")] {
|
||||
assert_eq!(@decimalRound@(Decimal::parse(value).unwrap(), places), Decimal::parse(expected).unwrap());
|
||||
}
|
||||
for places in [i64::MIN, -6112, 6177, i64::MAX] {
|
||||
let failure = std::panic::catch_unwind(|| @decimalRound@(Decimal::from_int(1), places)).unwrap_err();
|
||||
let info = failure.downcast_ref::<&'static dever_runtime::value::FaultInfo>().unwrap();
|
||||
assert!(info.source.ends_with("lib/decimal.dv"));
|
||||
assert_eq!(info.line, 2);
|
||||
assert!(info.column > 0);
|
||||
assert_eq!(info.message, "decimal rounding fault");
|
||||
}
|
||||
assert_eq!(@mathSqrt@(4.0), 2.0);
|
||||
assert_eq!(@mathSin@(0.0), 0.0);
|
||||
assert_eq!(@mathCos@(0.0), 1.0);
|
||||
assert_eq!(@mathLog@(1.0), 0.0);
|
||||
assert_eq!(@mathPow@(2.0, 3.0), 8.0);
|
||||
assert!(@mathIsNan@(@mathSqrt@(-1.0)));
|
||||
assert!(@mathIsFinite@(1.0));
|
||||
assert!(!@mathIsFinite@(f64::INFINITY));
|
||||
assert!(@mathIsInfinite@(f64::INFINITY));
|
||||
|
||||
@allocation_counter@
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!(@textIndexOf@(std::hint::black_box(text), "😀"), Some(2));
|
||||
assert!(@textContains@(std::hint::black_box(text), "雪"));
|
||||
assert_eq!(@intParse@(std::hint::black_box("123")), Some(123));
|
||||
assert_eq!(@floatParse@(std::hint::black_box("0.125")), Some(0.125));
|
||||
assert_eq!(ALLOCATIONS.load(Ordering::Relaxed) - before, 0);
|
||||
assert_eq!(@readFloat@("0.125").unwrap(), 0.125);
|
||||
assert!(@readFloat@("NaN").unwrap().is_nan());
|
||||
assert!(@readFloat@("bad").is_err());
|
||||
assert_eq!(@readDecimal@("0.125").unwrap(), Decimal::parse("0.125").unwrap());
|
||||
assert!(@readDecimal@("bad").is_err());
|
||||
|
||||
for parts in [vec![], vec![""], vec!["", "a", "", "雪🙂", ""], vec!["ab", "好🙂", "cd"]] {
|
||||
let parts = parts.into_iter().map(str::to_owned).collect::<Vec<_>>();
|
||||
let original = parts.clone();
|
||||
assert_eq!(@joinChunks@(&parts), parts.concat());
|
||||
assert_eq!(@prefixChunks@(&parts), "前缀:".to_owned() + &parts.concat());
|
||||
assert_eq!(parts, original, "joining borrows and preserves its input");
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
flow printLine(text: Text) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.io.println(text) |
|
||||
|
||||
flow offload(text: Text) ()
|
||||
| step | kind | do |
|
||||
| - | calc | blocking(printLine(text)) |
|
||||
|
||||
flow spawned(text: Text) ()
|
||||
| step | kind | do |
|
||||
| task | calc | run(printLine(text)) |
|
||||
| - | calc | wait(task) |
|
||||
|
||||
cmd line = printLine
|
||||
@@ -0,0 +1,18 @@
|
||||
if std::env::args().any(|value| value == "fail") {
|
||||
let error = @printLine@("private output text").unwrap_err();
|
||||
let Failure::@WriteResult@(@WriteResult@::Failed(message)) = error else {
|
||||
panic!("original write error required");
|
||||
};
|
||||
assert!(!message.is_empty());
|
||||
assert!(!message.contains("private output text"));
|
||||
let failure = dever_runtime::task::run(true, 1, async |scope| @offload@(scope, "worker failure".to_owned()).await).unwrap().unwrap_err();
|
||||
assert!(matches!(failure, dever_runtime::task::RunError::Business {
|
||||
error: Failure::@WriteResult@(@WriteResult@::Failed(_)), ..
|
||||
}));
|
||||
return;
|
||||
}
|
||||
@printLine@("雪😀").unwrap();
|
||||
@printLine@("").unwrap();
|
||||
@printLine@("first\nsecond").unwrap();
|
||||
dever_runtime::task::run(true, 1, async |scope| @offload@(scope, "blocking".to_owned()).await).unwrap().unwrap();
|
||||
dever_runtime::task::run(true, 1, async |scope| @spawned@(scope, "task".to_owned()).await).unwrap().unwrap();
|
||||
@@ -0,0 +1,73 @@
|
||||
type Item { text: Text }
|
||||
|
||||
loop first(values: AsyncStream<Int>) (out: Int?)
|
||||
| each value in values | result |
|
||||
| out | first value |
|
||||
|
||||
loop summary(values: AsyncStream<Int>) (first: Int?, count: Int, sum: Int)
|
||||
| each value in values | result |
|
||||
| first | first value |
|
||||
| count | count |
|
||||
| sum | sum value |
|
||||
|
||||
loop records(values: AsyncStream<Item>) (out: List<Item>)
|
||||
| each value in values | result |
|
||||
| out | list value |
|
||||
|
||||
loop nulls(values: AsyncStream<Int?>) (out: List<Int?>)
|
||||
| each value in values | result |
|
||||
| out | list value |
|
||||
|
||||
guard(value: Int) (out: Int) { check value > 0 else Invalid
|
||||
out = value }
|
||||
loop checked(values: AsyncStream<Int>) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | sum guard(value) |
|
||||
|
||||
flow main() (out: Int)
|
||||
| step | kind | do |
|
||||
| values | calc | stream([1, 2, 3]) |
|
||||
| result | loop | summary(values) |
|
||||
| out | calc | result.sum |
|
||||
|
||||
flow bytes() (out: Int)
|
||||
| step | kind | do |
|
||||
| values | calc | stream(dever.bytes.fromText("ABC")) |
|
||||
| result | loop | summary(values) |
|
||||
| out | calc | result.sum |
|
||||
|
||||
flow channel() (first: Int?, next: Int?)
|
||||
| step | kind | do |
|
||||
| queue | calc | channel<Int>(2) |
|
||||
| - | calc | send(queue, 1) |
|
||||
| - | calc | send(queue, 2) |
|
||||
| values | calc | stream(queue) |
|
||||
| first | loop | first(values) |
|
||||
| next | calc | receive(queue) |
|
||||
| - | calc | close(queue) |
|
||||
|
||||
flow ticking(period: Int) (out: Int?)
|
||||
| step | kind | do |
|
||||
| values | flow | dever.task.ticks(period) |
|
||||
| out | loop | first(values) |
|
||||
|
||||
flow empty() (out: List<Int?>)
|
||||
| step | kind | do |
|
||||
| values: AsyncStream<Int?> | calc | stream([]) |
|
||||
| out | loop | nulls(values) |
|
||||
|
||||
flow closeAlias() (out: Int?)
|
||||
| step | kind | do |
|
||||
| values | calc | stream([1, 2]) |
|
||||
| alias | calc | values |
|
||||
| - | calc | close(alias) |
|
||||
| out | loop | first(values) |
|
||||
|
||||
ignore(value: Int) () {}
|
||||
loop drain(values: AsyncStream<Int>) ()
|
||||
| each value in values | result |
|
||||
| - | do ignore(value) |
|
||||
|
||||
loop noPull(values: AsyncStream<Int>) (out: List<Int>)
|
||||
| each value in values | take | result |
|
||||
| out | 0 | list value |
|
||||
@@ -0,0 +1,41 @@
|
||||
use dever_runtime::{stream::AsyncStream, task};
|
||||
let values = AsyncStream::values(vec![1, 2, 3]);
|
||||
let alias = values.clone();
|
||||
assert_eq!(task::run(true, 1, async |_| Ok::<_, ()>(@first@(&values).await)).unwrap().unwrap(), Some(1));
|
||||
assert_eq!(task::run(true, 1, async |_| Ok::<_, ()>(alias.next().await.unwrap())).unwrap().unwrap(), None);
|
||||
assert_eq!(task::run(true, 1, async |_| Ok::<_, ()>(@main@().await)).unwrap().unwrap(), 6);
|
||||
assert_eq!(task::run(true, 1, async |_| Ok::<_, ()>(@bytes@().await)).unwrap().unwrap(), 198);
|
||||
let values = AsyncStream::values(vec![None, Some(2)]);
|
||||
assert_eq!(task::run(true, 1, async |_| Ok::<_, ()>(@nulls@(&values).await)).unwrap().unwrap(), vec![None, Some(2)]);
|
||||
let values = AsyncStream::values(vec![@Item@ { f0: "moved".to_owned() }]);
|
||||
let output = task::run(true, 1, async |_| Ok::<_, ()>(@records@(&values).await)).unwrap().unwrap();
|
||||
assert_eq!(output[0].f0, "moved");
|
||||
let output = task::run(true, 1, async |_| Ok::<_, ()>(@channel@().await)).unwrap().unwrap();
|
||||
assert_eq!((output.f0, output.f1), (Some(1), Some(2)));
|
||||
assert_eq!(task::run(true, 1, async |_| Ok::<_, ()>(@ticking@(1).await)).unwrap().unwrap(), Some(1));
|
||||
assert!(task::run(true, 1, async |_| Ok::<_, ()>(@empty@().await)).unwrap().unwrap().is_empty());
|
||||
assert_eq!(task::run(true, 1, async |_| Ok::<_, ()>(@closeAlias@().await)).unwrap().unwrap(), None);
|
||||
let values = AsyncStream::values(vec![0, 2]);
|
||||
assert!(task::run(true, 1, async |_| @checked@(&values).await).unwrap().is_err());
|
||||
assert_eq!(task::run(true, 1, async |_| Ok::<_, ()>(values.next().await.unwrap())).unwrap().unwrap(), None);
|
||||
let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let observed = calls.clone();
|
||||
let values = AsyncStream::values((0..3).inspect(move |_| { observed.fetch_add(1, std::sync::atomic::Ordering::SeqCst); }));
|
||||
assert!(task::run(true, 1, async |_| Ok::<_, ()>(@noPull@(&values).await)).unwrap().unwrap().is_empty());
|
||||
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0);
|
||||
let values = AsyncStream::ticks(60000).unwrap();
|
||||
let alias = values.clone();
|
||||
task::run(true, 1, async |scope| {
|
||||
let started = dever_runtime::channel::Channel::new(1).unwrap();
|
||||
let ready = started.clone();
|
||||
let task = scope.spawn_leaf(async move {
|
||||
let mut drain = std::pin::pin!(@drain@(&values));
|
||||
assert!(std::future::Future::poll(drain.as_mut(), &mut std::task::Context::from_waker(std::task::Waker::noop())).is_pending());
|
||||
ready.send(()).await.unwrap();
|
||||
drain.await
|
||||
}).unwrap();
|
||||
started.receive().await.unwrap();
|
||||
task.stop().await.unwrap();
|
||||
assert_eq!(alias.next().await.unwrap(), None);
|
||||
Ok::<_, ()>(())
|
||||
}).unwrap().unwrap();
|
||||
@@ -0,0 +1,48 @@
|
||||
rule bytes(event: dever.io.ReadEvent) (out: Bytes)
|
||||
| event | out |
|
||||
| Chunk(value) | value |
|
||||
| Failed(message) | fail(dever.io.ReadEvent.Failed(message)) |
|
||||
|
||||
loop first(values: Stream<dever.io.ReadEvent>) (out: Bytes?)
|
||||
| each value in values | result |
|
||||
| out | first bytes(value) |
|
||||
|
||||
loop all(values: Stream<dever.io.ReadEvent>) (out: List<Bytes>)
|
||||
| each value in values | result |
|
||||
| out | list bytes(value) |
|
||||
|
||||
loop overflow(values: Stream<dever.io.ReadEvent>, base: Int) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | sum length(bytes(value)) + base |
|
||||
|
||||
loop summary(values: Stream<dever.io.ReadEvent>) (first: Bytes?, rest: List<Bytes>)
|
||||
| each value in values | result |
|
||||
| first | first bytes(value) |
|
||||
| rest | list bytes(value) |
|
||||
|
||||
loop zero(values: Stream<dever.io.ReadEvent>) (out: List<dever.io.ReadEvent>)
|
||||
| each value in values | take | result |
|
||||
| out | 0 | list value |
|
||||
|
||||
flow closeOnly(values: Stream<dever.io.ReadEvent>) ()
|
||||
| step | kind | do |
|
||||
| - | calc | close(values) |
|
||||
|
||||
flow chunks(file: dever.system.File, size: Int) (out: Stream<dever.io.ReadEvent>)
|
||||
| step | kind | do |
|
||||
| out | flow | dever.io.chunks(file, size) |
|
||||
|
||||
flow collect(path: Text, size: Int) (out: List<Bytes>)
|
||||
| step | kind | do |
|
||||
| file | flow | dever.io.open(path) |
|
||||
| stream | flow | chunks(file, size) |
|
||||
| out | loop | all(stream) |
|
||||
|
||||
flow offload(path: Text, size: Int) (out: List<Bytes>)
|
||||
| step | kind | do |
|
||||
| out | calc | blocking(collect(path, size)) |
|
||||
|
||||
flow spawned(path: Text, size: Int) (out: List<Bytes>)
|
||||
| step | kind | do |
|
||||
| task | calc | run(collect(path, size)) |
|
||||
| out | calc | wait(task) |
|
||||
@@ -0,0 +1,46 @@
|
||||
use dever_runtime::{io::File, task};
|
||||
let path = std::env::temp_dir().join(format!("dever-native-sync-stream-{}", std::process::id()));
|
||||
let mut created = std::fs::OpenOptions::new().create_new(true).write(true).open(&path).unwrap();
|
||||
std::io::Write::write_all(&mut created, b"abc123").unwrap();
|
||||
drop(created);
|
||||
let name = path.to_str().unwrap();
|
||||
let file = File::open(name).unwrap();
|
||||
let stream = @chunks@(&file, 3).unwrap();
|
||||
let alias = stream.clone();
|
||||
assert_eq!(@first@(&stream).unwrap().unwrap().as_ref(), b"abc");
|
||||
assert!(alias.next().is_none());
|
||||
assert_eq!(file.read(3).unwrap().unwrap().as_ref(), b"123");
|
||||
assert!(@all@(&stream).unwrap().is_empty());
|
||||
file.close().unwrap();
|
||||
let file = File::open(name).unwrap();
|
||||
let stream = @chunks@(&file, 3).unwrap();
|
||||
assert!(@zero@(&stream).is_empty());
|
||||
assert!(stream.next().is_none());
|
||||
assert_eq!(file.read(6).unwrap().unwrap().as_ref(), b"abc123");
|
||||
let stream = @chunks@(&file, 3).unwrap();
|
||||
@closeOnly@(&stream);
|
||||
assert!(stream.next().is_none());
|
||||
file.close().unwrap();
|
||||
let file = File::open(name).unwrap();
|
||||
let stream = @chunks@(&file, 3).unwrap();
|
||||
let result = @summary@(&stream).unwrap();
|
||||
assert_eq!(result.f0.unwrap().as_ref(), b"abc");
|
||||
assert_eq!(result.f1.iter().map(|bytes| bytes.as_ref()).collect::<Vec<_>>(), vec![b"abc", b"123"]);
|
||||
file.close().unwrap();
|
||||
let file = File::open(name).unwrap();
|
||||
let stream = @chunks@(&file, 3).unwrap();
|
||||
file.close().unwrap();
|
||||
assert!(@all@(&stream).is_err());
|
||||
assert!(stream.next().is_none());
|
||||
let expected = vec![b"abc".as_slice(), b"123".as_slice()];
|
||||
let file = File::open(name).unwrap();
|
||||
let stream = @chunks@(&file, 3).unwrap();
|
||||
let fault = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| @overflow@(&stream, i64::MAX))).unwrap_err();
|
||||
assert_eq!(fault.downcast_ref::<&'static FaultInfo>().unwrap().source, @source_path@);
|
||||
assert!(stream.next().is_none());
|
||||
assert_eq!(file.read(3).unwrap().unwrap().as_ref(), b"123");
|
||||
file.close().unwrap();
|
||||
assert_eq!(@collect@(name, 3).unwrap().iter().map(|bytes| bytes.as_ref()).collect::<Vec<_>>(), expected);
|
||||
assert_eq!(task::run(true, 1, async |scope| @offload@(scope, name.to_owned(), 3).await).unwrap().unwrap().iter().map(|bytes| bytes.as_ref()).collect::<Vec<_>>(), expected);
|
||||
assert_eq!(task::run(true, 1, async |scope| @spawned@(scope, name.to_owned(), 3).await).unwrap().unwrap().iter().map(|bytes| bytes.as_ref()).collect::<Vec<_>>(), expected);
|
||||
std::fs::remove_file(path).unwrap();
|
||||
@@ -0,0 +1,87 @@
|
||||
flow delay(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(value) |
|
||||
| out | calc | value |
|
||||
|
||||
identity(value: Int) (out: Int) { out = value }
|
||||
|
||||
rule chosen(yes: Bool, millis: Int) (out: Int)
|
||||
| yes | millis | out |
|
||||
| true | - | delay(millis) |
|
||||
| false | - | 7 |
|
||||
|
||||
loop eachDelay(values: List<Int>) (out: List<Int>)
|
||||
| each value in values | result |
|
||||
| out | list delay(value) |
|
||||
|
||||
rule advance(state: Int) (out: Walk<Int, Int>)
|
||||
| state | out |
|
||||
| < 3 | Next(state, state + 1) |
|
||||
| >= 3 | Done |
|
||||
|
||||
flow next(state: Int) (out: Walk<Int, Int>)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(state) |
|
||||
| out | rule | advance(state) |
|
||||
|
||||
loop walked() (out: List<Int>)
|
||||
| each value in walk(0, next) | result |
|
||||
| out | list value |
|
||||
|
||||
flow apply(value: Int, transform: handler(value: Int) (out: Int)) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | calc | transform(value) |
|
||||
|
||||
flow handled() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | flow | apply(1, delay) |
|
||||
|
||||
type Attempt {
|
||||
Done
|
||||
error Failed(value: dever.time.SleepResult)
|
||||
}
|
||||
|
||||
rule resolve(value: Attempt) (out: Int) recover("invalid duration is explicitly reported as -1")
|
||||
| value | out |
|
||||
| Done | 1 |
|
||||
| Failed(error) | -1 |
|
||||
|
||||
flow captured(millis: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| value: Attempt | flow | result(dever.time.sleep(millis)) |
|
||||
| out | rule | resolve(value) |
|
||||
|
||||
measureText(text: Text) (out: Int) { out = length(text) }
|
||||
|
||||
flow borrowed(text: Text) (out: Int)
|
||||
| step | kind | do |
|
||||
| before | calc | measureText(text) |
|
||||
| - | flow | dever.time.sleep(1) |
|
||||
| out | calc | before + measureText(text) |
|
||||
|
||||
flow timestamp() (out: DateTime)
|
||||
| step | kind | do |
|
||||
| out | flow | dever.time.now() |
|
||||
|
||||
flow faultAfterSleep(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(0) |
|
||||
| out | calc | value + 1 |
|
||||
|
||||
flow update(value: Int, previous: Int) (acc: Int, stop: Bool)
|
||||
| step | kind | do |
|
||||
| - | flow | dever.time.sleep(value) |
|
||||
| acc | calc | previous + value |
|
||||
| stop | calc | value >= 2 |
|
||||
|
||||
loop accumulated(values: List<Int>) (out: Int)
|
||||
| each value in values | result |
|
||||
| out | foldUntil(acc = 0, update(value, acc)) |
|
||||
|
||||
loop firstDelay(values: List<Int>) (out: Int?)
|
||||
| each value in values | result |
|
||||
| out | first delay(value) |
|
||||
|
||||
loop walkFrom(seed: Int) (out: List<Int>)
|
||||
| each value in walk(seed, next) | result |
|
||||
| out | list value |
|
||||
@@ -0,0 +1,365 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stdout_preserves_lines_write_errors_and_blocking_task_calls() {
|
||||
use std::process::Stdio;
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"stdout",
|
||||
include_str!("stdout.dever"),
|
||||
Some(include_str!("stdout.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(&binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert_eq!(
|
||||
String::from_utf8(output.stdout).unwrap(),
|
||||
"雪😀\n\nfirst\nsecond\nblocking\ntask\n"
|
||||
);
|
||||
let full = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open("/dev/full")
|
||||
.unwrap();
|
||||
let output = Command::new(&binary)
|
||||
.arg("fail")
|
||||
.stdout(full)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let (reader, writer) = std::io::pipe().unwrap();
|
||||
drop(reader);
|
||||
let output = Command::new(&binary)
|
||||
.arg("fail")
|
||||
.stdout(Stdio::from(writer))
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdout_command_checks_input_and_propagates_real_write_failure() {
|
||||
let binary = build(
|
||||
"stdout-command",
|
||||
include_str!("stdout.dever"),
|
||||
None,
|
||||
Profile::Dev,
|
||||
);
|
||||
let input = r#"{"text":"命令输出"}"#;
|
||||
let output = Command::new(&binary)
|
||||
.args(["main.main.line", input])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let stdout = String::from_utf8(output.stdout).unwrap();
|
||||
let response = stdout.strip_prefix("命令输出\n").unwrap();
|
||||
let response: dever_runtime::wire::serde_json::Value =
|
||||
dever_runtime::wire::serde_json::from_str(response).unwrap();
|
||||
assert_eq!(response["code"], 0);
|
||||
let output = Command::new(&binary)
|
||||
.args(["main.main.line", r#"{"text":3}"#])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success());
|
||||
assert!(output.stdout.is_empty());
|
||||
let full = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open("/dev/full")
|
||||
.unwrap();
|
||||
let output = Command::new(&binary)
|
||||
.args(["main.main.line", input])
|
||||
.stdout(full)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success());
|
||||
assert!(!output.stderr.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_loops_execute_ordered_results_filters_walk_and_failure() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"concurrent",
|
||||
include_str!("concurrent.dever"),
|
||||
Some(include_str!("concurrent.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synchronous_streams_execute_short_circuit_error_release_and_blocking_consumption() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"sync-stream",
|
||||
include_str!("sync_stream.dever"),
|
||||
Some(include_str!("sync_stream.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_execute_shared_cursor_errors_blocking_tasks_and_resource_release() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"file",
|
||||
include_str!("file.dever"),
|
||||
Some(include_str!("file.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_execute_random_secret_creation_capture_and_tasks() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"token",
|
||||
include_str!("token.dever"),
|
||||
Some(include_str!("token.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streams_execute_single_pass_close_short_circuit_failures_and_cancellation() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"stream",
|
||||
include_str!("stream.dever"),
|
||||
Some(include_str!("stream.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channels_execute_aliases_ownership_cancellation_and_faults() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"channel",
|
||||
include_str!("channel.dever"),
|
||||
Some(include_str!("channel.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_executes_passwords_handlers_groups_capture_and_faults() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"blocking",
|
||||
include_str!("blocking.dever"),
|
||||
Some(include_str!("blocking.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_parallel_executes_owned_inputs_handlers_failures_and_faults() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"worker",
|
||||
include_str!("worker.dever"),
|
||||
Some(include_str!("worker.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_tables_execute_branch_selection_order_handlers_walk_and_failures() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"tasks",
|
||||
include_str!("tasks.dever"),
|
||||
Some(include_str!("tasks.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spawned_tasks_execute_consumption_capture_parallel_and_faults() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"spawn",
|
||||
include_str!("spawn.dever"),
|
||||
Some(include_str!("spawn.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spawned_tasks_share_validated_settings_and_preserve_owned_inputs() {
|
||||
let source = r#"
|
||||
setting title: Text
|
||||
read() (out: Int) { out = length(title) }
|
||||
flow main() (out: Int)
|
||||
| step | kind | do |
|
||||
| task | calc | run(read()) |
|
||||
| out | calc | wait(task) |
|
||||
"#;
|
||||
let harness = r###"
|
||||
let path = std::path::Path::new(@source_path@).with_extension("json");
|
||||
std::fs::write(&path, r##"{"module":{"main":{"main":{"title":"hello"}}}}"##).unwrap();
|
||||
let settings = load_settings(&path).unwrap();
|
||||
assert_eq!(dever_runtime::task::run(true, 1, async |scope| Ok::<_, ()>(@main@(scope, &settings).await)).unwrap().unwrap(), 5);
|
||||
assert_eq!(std::sync::Arc::strong_count(&settings), 1);
|
||||
"###;
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build("spawn-settings", source, Some(harness), profile);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn task_combinations_execute_timeout_race_group_and_captures() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"combinations",
|
||||
include_str!("combinations.dever"),
|
||||
Some(include_str!("combinations.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_task_settings_and_large_race_keep_concrete_codegen() {
|
||||
let source = r#"
|
||||
setting title: Text
|
||||
read() (out: Int) { out = length(title) }
|
||||
fallback() (out: Int) { out = 0 }
|
||||
flow main() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | calc | timeout(run(read()), 60000, fallback) |
|
||||
expectLabel(value: Text) () { check value == "hello" else Invalid }
|
||||
flow member() ()
|
||||
| step | kind | do |
|
||||
| task | calc | run(read()) |
|
||||
| value | calc | wait(task) |
|
||||
| - | check | value == 5 else Invalid |
|
||||
flow groupConfigured() ()
|
||||
| step | kind | do |
|
||||
| tasks | calc | group(2) |
|
||||
| - | calc | run(tasks, expectLabel(title)) |
|
||||
| - | calc | run(tasks, member()) |
|
||||
| - | calc | wait(tasks) |
|
||||
flow cpuConfigured() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | calc | parallel(read()) |
|
||||
"#;
|
||||
let harness = r###"
|
||||
let path = std::path::Path::new(@source_path@).with_extension("json");
|
||||
std::fs::write(&path, r##"{"module":{"main":{"main":{"title":"hello"}}}}"##).unwrap();
|
||||
let settings = load_settings(&path).unwrap();
|
||||
assert_eq!(dever_runtime::task::run(true, 1, async |scope| Ok::<_, ()>(@main@(scope, &settings).await)).unwrap().unwrap(), 5);
|
||||
dever_runtime::task::run(true, 3, async |scope| @groupConfigured@(scope, &settings).await).unwrap().unwrap();
|
||||
assert_eq!(dever_runtime::task::run(true, 1, async |scope| Ok::<_, ()>(@cpuConfigured@(scope, &settings).await)).unwrap().unwrap(), 5);
|
||||
assert_eq!(std::sync::Arc::strong_count(&settings), 1);
|
||||
"###;
|
||||
let binary = build("nested-task-settings", source, Some(harness), Profile::Dev);
|
||||
assert!(Command::new(binary).status().unwrap().success());
|
||||
let tasks = std::iter::repeat_n("run(identity(42))", 65)
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let source = format!(
|
||||
"identity(value: Int) (out: Int) {{ out = value }}\nflow main() (out: Int)\n| step | kind | do |\n| out | calc | race({tasks}) |\n"
|
||||
);
|
||||
let harness = "assert_eq!(dever_runtime::task::run(true, 65, async |scope| Ok::<_, ()>(@main@(scope).await)).unwrap().unwrap(), 42);";
|
||||
let binary = build("large-race", &source, Some(harness), Profile::Dev);
|
||||
assert!(Command::new(binary).status().unwrap().success());
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use dever_runtime::task::execute;
|
||||
execute(false, async {
|
||||
assert_eq!(@chosen@(false, -1).await.unwrap(), 7);
|
||||
assert!(@chosen@(true, -1).await.is_err());
|
||||
assert_eq!(@eachDelay@(&[1, 0, 2]).await.unwrap(), vec![1, 0, 2]);
|
||||
assert!(@eachDelay@(&[0, -1, 60000]).await.is_err());
|
||||
assert_eq!(@accumulated@(&[1, 2, -1]).await.unwrap(), 3);
|
||||
assert!(@accumulated@(&[1, -1, 60000]).await.is_err());
|
||||
assert_eq!(@firstDelay@(&[1, -1]).await.unwrap(), Some(1));
|
||||
assert_eq!(@firstDelay@(&[]).await.unwrap(), None);
|
||||
assert!(@walkFrom@(-1).await.is_err());
|
||||
assert_eq!(@walked@().await.unwrap(), vec![0, 1, 2]);
|
||||
assert_eq!(@handled@().await.unwrap(), 1);
|
||||
assert_eq!(@captured@(-1).await, -1);
|
||||
assert_eq!(@captured@(0).await, 1);
|
||||
assert_eq!(@borrowed@("雪abc").await.unwrap(), 8);
|
||||
}).unwrap();
|
||||
let before = dever_runtime::value::calendar::DateTime::now().unwrap();
|
||||
let actual = @timestamp@().unwrap();
|
||||
let after = dever_runtime::value::calendar::DateTime::now().unwrap();
|
||||
assert!(before <= actual && actual <= after);
|
||||
let error = std::panic::catch_unwind(|| execute(false, @faultAfterSleep@(i64::MAX))).unwrap_err();
|
||||
let info = error.downcast_ref::<&'static dever_runtime::value::FaultInfo>().unwrap();
|
||||
assert_eq!(info.source, @source_path@);
|
||||
assert_eq!(execute(false, @delay@(0)).unwrap().unwrap(), 0);
|
||||
@@ -0,0 +1,16 @@
|
||||
defaultTls() (config: dever.system.ClientTls) {
|
||||
config = dever.tls.system()
|
||||
}
|
||||
|
||||
clientTls(ca: Bytes) (config: dever.system.ClientTls) {
|
||||
config = dever.tls.client(ca)
|
||||
}
|
||||
|
||||
serverTls(cert: Bytes, key: Bytes) (config: dever.system.ServerTls) {
|
||||
config = dever.tls.server(cert, key)
|
||||
}
|
||||
|
||||
flow scheduledTls(ca: Bytes) (config: dever.system.ClientTls)
|
||||
| step | kind | do |
|
||||
| pending | calc | run(clientTls(ca)) |
|
||||
| config | calc | wait(pending) |
|
||||
@@ -0,0 +1,12 @@
|
||||
use dever_runtime::{task, Bytes};
|
||||
let fixtures = std::path::Path::new(@tls_fixtures@);
|
||||
let ca = Bytes::from(std::fs::read(fixtures.join("root.pem")).unwrap());
|
||||
let cert = Bytes::from(std::fs::read(fixtures.join("server.pem")).unwrap());
|
||||
let key = Bytes::from(std::fs::read(fixtures.join("server-key.pem")).unwrap());
|
||||
assert_eq!(format!("{:?}", @defaultTls@()), "ClientTls");
|
||||
assert_eq!(format!("{:?}", @clientTls@(&ca).unwrap()), "ClientTls");
|
||||
assert_eq!(format!("{:?}", @serverTls@(&cert, &key).unwrap()), "ServerTls");
|
||||
assert!(@clientTls@(&Bytes::new()).is_err());
|
||||
assert!(@serverTls@(&cert, &Bytes::new()).is_err());
|
||||
let configured = task::run(true, 8, async |scope| @scheduledTls@(scope, ca.clone()).await).unwrap().unwrap();
|
||||
assert_eq!(format!("{configured:?}"), "ClientTls");
|
||||
@@ -0,0 +1,33 @@
|
||||
flow generate(size: Int) (out: Secret)
|
||||
| step | kind | do |
|
||||
| out | flow | dever.crypto.token(size) |
|
||||
|
||||
flow sign(size: Int, message: Bytes) (out: Bytes)
|
||||
| step | kind | do |
|
||||
| key | flow | generate(size) |
|
||||
| out | calc | dever.crypto.hmacSha256(key, message) |
|
||||
|
||||
flow spawned(size: Int) (out: Secret)
|
||||
| step | kind | do |
|
||||
| task | calc | run(generate(size)) |
|
||||
| out | calc | wait(task) |
|
||||
|
||||
type Attempt { Ready(value: Secret), error Failed(value: dever.crypto.TokenResult) }
|
||||
|
||||
rule accepted(value: Attempt) (out: Bool) recover("report whether token length was accepted")
|
||||
| value | out |
|
||||
| Ready(secret) | true |
|
||||
| Failed(error) | false |
|
||||
|
||||
flow captured(size: Int) (out: Bool)
|
||||
| step | kind | do |
|
||||
| value: Attempt | flow | result(generate(size)) |
|
||||
| out | rule | accepted(value) |
|
||||
|
||||
flow invoke(size: Int, create: handler(bytes: Int) (value: Secret)) (out: Secret)
|
||||
| step | kind | do |
|
||||
| out | calc | create(size) |
|
||||
|
||||
flow handled(size: Int) (out: Secret)
|
||||
| step | kind | do |
|
||||
| out | flow | invoke(size, dever.crypto.token) |
|
||||
@@ -0,0 +1,21 @@
|
||||
use dever_runtime::{crypto, task, Bytes};
|
||||
for size in [16, 32, 1024] {
|
||||
let secret = @generate@(size).unwrap();
|
||||
assert_eq!(format!("{secret:?}"), "Secret([REDACTED])");
|
||||
let message = Bytes::from_static(b"public-test-message");
|
||||
let first = crypto::hmac_sha256(&secret, &message);
|
||||
let second = crypto::hmac_sha256(&secret, &message);
|
||||
assert!(crypto::constant_time_eq(&first, &second));
|
||||
let different = @sign@(size, &message).unwrap();
|
||||
assert!(!crypto::constant_time_eq(&first, &different));
|
||||
assert!(@captured@(size));
|
||||
@handled@(size).unwrap();
|
||||
task::run(true, 1, async |scope| @spawned@(scope, size).await).unwrap().unwrap();
|
||||
}
|
||||
for size in [i64::MIN, 0, 15, 1025, i64::MAX] {
|
||||
let error = @generate@(size).unwrap_err();
|
||||
assert!(format!("{error:?}").contains("token length must be between 16 and 1024 bytes"));
|
||||
assert!(!@captured@(size));
|
||||
assert!(@handled@(size).is_err());
|
||||
assert!(task::run(true, 1, async |scope| @spawned@(scope, size).await).unwrap().is_err());
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
parseUuid(value: Text) (out: Uuid?) {
|
||||
out = uuid.parse(value)
|
||||
}
|
||||
|
||||
writeUuid(value: Uuid) (out: Text) {
|
||||
out = uuid.toText(value)
|
||||
}
|
||||
|
||||
rule requiredUuid(value: Uuid?) (out: Uuid)
|
||||
| value | out |
|
||||
| null | fail(Invalid) |
|
||||
| other | value |
|
||||
|
||||
readUuid(value: Text) (out: Uuid) {
|
||||
out = requiredUuid(uuid.parse(value))
|
||||
}
|
||||
|
||||
sameUuid(left: Uuid, right: Uuid) (out: Bool) {
|
||||
out = left == right
|
||||
}
|
||||
|
||||
lookupUuid(values: Map<Uuid, Int>, key: Uuid) (out: Int?) {
|
||||
out = get(values, key)
|
||||
}
|
||||
|
||||
mapUuid(first: Uuid, second: Uuid) (out: Map<Uuid, Int>) {
|
||||
values: Map<Uuid, Int> = {}
|
||||
out = put(put(values, first, 1), second, 2)
|
||||
}
|
||||
|
||||
type Identifier {
|
||||
value: Uuid
|
||||
previous: Uuid?
|
||||
}
|
||||
|
||||
uuidEcho(value: Identifier) (out: Identifier) {
|
||||
out = value
|
||||
}
|
||||
|
||||
uuidJson(value: Identifier) (out: Identifier) {
|
||||
out = dever.json.decode(dever.json.encode(value))
|
||||
}
|
||||
|
||||
cmd echo = app.uuidEcho
|
||||
cmd json = app.uuidJson
|
||||
@@ -0,0 +1,96 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn opaque_id_moves_text_without_allocating_or_changing_its_contents() {
|
||||
let source = r#"
|
||||
roundTrip(text: Text) (out: Text) {
|
||||
out = dever.id.toText(dever.id.fromText(text))
|
||||
}
|
||||
fromText(text: Text) (out: Id) { out = dever.id.fromText(text) }
|
||||
equal(left: Id, right: Id) (out: Bool) { out = left == right }
|
||||
lookup(value: Id) (out: Int?) {
|
||||
values: Map<Id, Int> = {}
|
||||
out = get(put(values, value, 7), value)
|
||||
}
|
||||
type Opaque { value: Id }
|
||||
jsonRoundTrip(value: Opaque) (out: Opaque) {
|
||||
out = dever.json.decode(dever.json.encode(value))
|
||||
}
|
||||
"#;
|
||||
let assertions = r#"
|
||||
let text = String::from(" 中文-id:Not-A-UUID ");
|
||||
let pointer = text.as_ptr();
|
||||
let result = @roundTrip@(text);
|
||||
assert_eq!(result, " 中文-id:Not-A-UUID ");
|
||||
assert_eq!(result.as_ptr(), pointer);
|
||||
assert!(@equal@(&@fromText@("id".into()), &@fromText@("id".into())));
|
||||
assert!(!@equal@(&@fromText@("id".into()), &@fromText@("ID".into())));
|
||||
assert_eq!(@lookup@(@fromText@("lookup".into())), Some(7));
|
||||
let input = @Opaque@ { f0: @fromText@(" unchanged ".into()) };
|
||||
assert_eq!(@jsonRoundTrip@(&input).unwrap(), input);
|
||||
"#;
|
||||
let binary = build("opaque-id", source, Some(assertions), Profile::Dev);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uuid_executes_as_an_inline_value_and_checks_only_its_text_boundary() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"uuid",
|
||||
include_str!("uuid.dever"),
|
||||
Some(include_str!("uuid.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uuid_command_and_json_codecs_keep_strict_inputs_and_canonical_outputs() {
|
||||
let binary = build(
|
||||
"uuid-command",
|
||||
include_str!("uuid.dever"),
|
||||
None,
|
||||
Profile::Dev,
|
||||
);
|
||||
let run = |name: &str, value: &str| Command::new(&binary).args([name, value]).output().unwrap();
|
||||
for name in ["main.main.echo", "main.main.json"] {
|
||||
let input = r#"{"value":{"value":"550E8400-E29B-41D4-A716-446655440000","previous":null}}"#;
|
||||
let output = run(name, input);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let result: dever_runtime::wire::serde_json::Value =
|
||||
dever_runtime::wire::serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!(
|
||||
result["data"]["value"],
|
||||
"550e8400-e29b-41d4-a716-446655440000"
|
||||
);
|
||||
assert!(result["data"]["previous"].is_null());
|
||||
for invalid in [
|
||||
input.replace(
|
||||
"550E8400-E29B-41D4-A716-446655440000",
|
||||
"550E8400E29B41D4A716446655440000",
|
||||
),
|
||||
input.replace(r#""550E8400-E29B-41D4-A716-446655440000""#, "1"),
|
||||
input.replace(r#""550E8400-E29B-41D4-A716-446655440000""#, "null"),
|
||||
] {
|
||||
let output = run(name, &invalid);
|
||||
assert!(!output.status.success(), "{invalid}");
|
||||
assert!(output.stdout.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
use dever_runtime::value::uuid::Uuid;
|
||||
let lower = "550e8400-e29b-41d4-a716-446655440000";
|
||||
let upper = "550E8400-E29B-41D4-A716-446655440000";
|
||||
let value = @parseUuid@(upper).unwrap();
|
||||
assert_eq!(std::mem::size_of::<Uuid>(), 16);
|
||||
assert!(!std::mem::needs_drop::<Uuid>());
|
||||
assert_eq!(@writeUuid@(value), lower);
|
||||
assert!(@sameUuid@(value, @parseUuid@(lower).unwrap()));
|
||||
let map = @mapUuid@(value, @parseUuid@(lower).unwrap());
|
||||
assert_eq!(map.len(), 1);
|
||||
assert_eq!(@lookupUuid@(&map, value), Some(2));
|
||||
assert_eq!(@lookupUuid@(&map, @parseUuid@("00000000-0000-0000-0000-000000000000").unwrap()), None);
|
||||
assert_eq!(@readUuid@(upper).unwrap(), value);
|
||||
for text in ["", "550e8400e29b41d4a716446655440000", "{550e8400-e29b-41d4-a716-446655440000}", "urn:uuid:550e8400-e29b-41d4-a716-446655440000", "00000000-0000-0000-0000-00000000000-", "é0e8400-e29b-41d4-a716-446655440000"] {
|
||||
assert_eq!(@parseUuid@(text), None, "{text}");
|
||||
assert!(@readUuid@(text).is_err());
|
||||
}
|
||||
for index in 0..36 {
|
||||
let mut text = lower.as_bytes().to_vec();
|
||||
text[index] = if [8, 13, 18, 23].contains(&index) { b'0' } else { b'-' };
|
||||
assert_eq!(@parseUuid@(std::str::from_utf8(&text).unwrap()), None);
|
||||
}
|
||||
for text in ["00000000-0000-0000-0000-000000000000", "ffffffff-ffff-ffff-ffff-ffffffffffff"] {
|
||||
assert_eq!(@writeUuid@(@parseUuid@(text).unwrap()), text);
|
||||
}
|
||||
let id = @Identifier@ { f0: value, f1: Some(value) };
|
||||
assert_eq!(@uuidJson@(&id).unwrap(), id);
|
||||
@allocation_counter@
|
||||
let before = ALLOCATIONS.load(Ordering::Relaxed);
|
||||
assert_eq!(@parseUuid@(std::hint::black_box(upper)), Some(value));
|
||||
assert!(@sameUuid@(value, std::hint::black_box(value)));
|
||||
assert_eq!(@lookupUuid@(&map, value), Some(2));
|
||||
assert_eq!(ALLOCATIONS.load(Ordering::Relaxed) - before, 0);
|
||||
@@ -0,0 +1,22 @@
|
||||
let nodes = vec![
|
||||
@Node@ { f0: 1, f1: "根".into(), f2: vec![2, 3] },
|
||||
@Node@ { f0: 2, f1: "子甲".into(), f2: vec![3, 1] },
|
||||
@Node@ { f0: 3, f1: "子乙".into(), f2: vec![] },
|
||||
];
|
||||
assert_eq!(@names@(nodes, 1).unwrap(), vec!["根", "子甲", "子乙"]);
|
||||
assert!(matches!(@names@(vec![], 1), Err(Failure::Api(ApiError::Invalid))));
|
||||
let missing = vec![@Node@ { f0: 1, f1: "缺少孩子".into(), f2: vec![2] }];
|
||||
assert!(matches!(@names@(missing, 1), Err(Failure::Api(ApiError::Invalid))));
|
||||
let duplicate = vec![
|
||||
@Node@ { f0: 1, f1: "同一编号".into(), f2: vec![] },
|
||||
@Node@ { f0: 1, f1: "重复编号".into(), f2: vec![] },
|
||||
];
|
||||
assert!(matches!(@names@(duplicate, 1), Err(Failure::@Error@(@Error@::DuplicateKey))));
|
||||
let nodes = vec![@Node@ { f0: 1, f1: "游标保留节点表原存储".into(), f2: vec![] }];
|
||||
let cursor = @start@(nodes, 1).unwrap();
|
||||
let name_pointer = cursor.f0.get(&1).unwrap().f1.as_ptr();
|
||||
let cursor = @enqueueChild@(2, cursor);
|
||||
assert_eq!(cursor.f0.get(&1).unwrap().f1.as_ptr(), name_pointer);
|
||||
let cursor = @enqueueChildren@(&[3, 4, 2], cursor);
|
||||
assert_eq!(cursor.f0.get(&1).unwrap().f1.as_ptr(), name_pointer);
|
||||
assert_eq!(cursor.f1, vec![1, 2, 3, 4]);
|
||||
@@ -0,0 +1,46 @@
|
||||
rule readMessage(state: dever.websocket.ReceiveState) (message: dever.websocket.Message)
|
||||
| state | message |
|
||||
| Read(value) | value |
|
||||
| End | fail(Invalid) |
|
||||
|
||||
done() () {}
|
||||
|
||||
rule ended(state: dever.websocket.ReceiveState) ()
|
||||
| state | do |
|
||||
| Read(value) | fail(Invalid) |
|
||||
| End | done() |
|
||||
|
||||
flow echo(request: dever.http.Request, reply: dever.system.HttpReply) ()
|
||||
| step | kind | do |
|
||||
| socket | flow | dever.websocket.accept(reply, dever.websocket.defaultLimits()) |
|
||||
| state | flow | dever.websocket.receive(socket) |
|
||||
| message | rule | readMessage(state) |
|
||||
| - | flow | dever.websocket.send(socket, message) |
|
||||
| ending | flow | dever.websocket.receive(socket) |
|
||||
| - | rule | ended(ending) |
|
||||
|
||||
flow start(listener: dever.system.Listener) ()
|
||||
| step | kind | do |
|
||||
| - | flow | dever.http.serveLive(echo, listener, dever.http.defaultLimits(), dever.http.defaultLiveLimits()) |
|
||||
|
||||
flow exchange(port: Int) (message: dever.websocket.Message)
|
||||
| step | kind | do |
|
||||
| socket | flow | dever.websocket.connect("127.0.0.1", port, "/chat", dever.websocket.defaultLimits()) |
|
||||
| - | flow | dever.websocket.send(socket, dever.websocket.Message.Text("hello")) |
|
||||
| state | flow | dever.websocket.receive(socket) |
|
||||
| message | rule | readMessage(state) |
|
||||
| - | flow | dever.websocket.close(socket, 1000, "done") |
|
||||
|
||||
rule messageSize(event: dever.websocket.MessageEvent) (size: Int)
|
||||
| event | size |
|
||||
| Read(value) | 1 |
|
||||
| Failed(message) | fail(dever.websocket.MessageEvent.Failed(message)) |
|
||||
|
||||
loop countMessages(events: AsyncStream<dever.websocket.MessageEvent>) (count: Int)
|
||||
| each event in events | result |
|
||||
| count | sum messageSize(event) |
|
||||
|
||||
flow drain(socket: dever.system.WebSocket) (count: Int)
|
||||
| step | kind | do |
|
||||
| events | flow | dever.websocket.messages(socket) |
|
||||
| count | loop | countMessages(events) |
|
||||
@@ -0,0 +1,20 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn websocket_runs_generated_upgrade_echo_and_close() {
|
||||
for profile in [Profile::Dev, Profile::Release] {
|
||||
let binary = build(
|
||||
"websocket",
|
||||
include_str!("websocket.dever"),
|
||||
Some(include_str!("websocket.rs.txt")),
|
||||
profile,
|
||||
);
|
||||
let output = Command::new(binary).output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert!(output.stdout.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use dever_runtime::{net, task, http::websocket::Message};
|
||||
task::run(true, 32, async |scope| {
|
||||
let listener = net::listen("127.0.0.1", 0, scope).await.unwrap();
|
||||
let port = listener.port().unwrap();
|
||||
let active = listener.clone();
|
||||
let server = scope.spawn(move |child| async move { @start@(&child, &active).await }).unwrap();
|
||||
let message = @exchange@(scope, port).await.unwrap();
|
||||
assert_eq!(message, Message::Text("hello".into()));
|
||||
listener.close().unwrap();
|
||||
server.await.unwrap().unwrap();
|
||||
Ok::<_, ()>(())
|
||||
}).unwrap().unwrap();
|
||||
@@ -0,0 +1,75 @@
|
||||
identity(value: Text) (out: Text) { out = value }
|
||||
size(value: Text) (out: Int) { out = length(value) }
|
||||
pair(value: Int) (left: Int, right: Int) {
|
||||
left = value
|
||||
right = value + 1
|
||||
}
|
||||
|
||||
flow text(value: Text) (out: Text)
|
||||
| step | kind | do |
|
||||
| out | calc | parallel(identity(value)) |
|
||||
|
||||
flow borrowed(value: Text) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | calc | parallel(size(value)) |
|
||||
|
||||
flow multiple(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| received | calc | parallel(pair(value)) |
|
||||
| out | calc | received.left + received.right |
|
||||
|
||||
flow apply(value: Int, action: handler(value: Int) (left: Int, right: Int)) (out: Int)
|
||||
| step | kind | do |
|
||||
| received | calc | parallel(action(value)) |
|
||||
| out | calc | received.left + received.right |
|
||||
|
||||
flow handled() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | flow | apply(20, pair) |
|
||||
|
||||
flow together() (out: Int)
|
||||
| step | kind | parallel | do |
|
||||
| a | calc | calculate | parallel(pair(10)) |
|
||||
| b | calc | calculate | parallel(pair(20)) |
|
||||
| out | calc | - | a.left + a.right + b.left + b.right |
|
||||
|
||||
type Problem { error Invalid }
|
||||
guard(value: Int) (out: Int) {
|
||||
check value > 0 else Problem.Invalid
|
||||
out = value
|
||||
}
|
||||
alwaysFail() (out: Int) { out = fail(Problem.Invalid) }
|
||||
type Attempt { Done(value: Int), error Failed(reason: Problem) }
|
||||
rule resolve(value: Attempt) (out: Int) recover("report a rejected input as -1")
|
||||
| value | out |
|
||||
| Done(number) | number |
|
||||
| Failed(reason) | -1 |
|
||||
|
||||
flow captured(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| attempt: Attempt | calc | result(parallel(guard(value))) |
|
||||
| out | rule | resolve(attempt) |
|
||||
|
||||
flow argumentFailure(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| attempt: Attempt | calc | result(parallel(guard(guard(value)))) |
|
||||
| out | rule | resolve(attempt) |
|
||||
|
||||
flow neverReturns() (out: Int)
|
||||
| step | kind | do |
|
||||
| out | calc | parallel(alwaysFail()) |
|
||||
|
||||
flow capturedNever() (out: Int)
|
||||
| step | kind | do |
|
||||
| attempt: Attempt | calc | result(parallel(alwaysFail())) |
|
||||
| out | rule | resolve(attempt) |
|
||||
|
||||
flow child(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | calc | parallel(guard(value)) |
|
||||
fallback() (out: Int) { out = 0 }
|
||||
flow nested(value: Int) (out: Int)
|
||||
| step | kind | do |
|
||||
| out | calc | timeout(run(child(value)), 60000, fallback) |
|
||||
|
||||
cmd together = together
|
||||
@@ -0,0 +1,22 @@
|
||||
use dever_runtime::task::{self, RunError};
|
||||
let value = String::from("move to the worker");
|
||||
let address = value.as_ptr() as usize;
|
||||
let result = task::run(true, 1, async |scope| Ok::<_, ()>(@text@(scope, value).await)).unwrap().unwrap();
|
||||
assert_eq!(result.as_ptr() as usize, address);
|
||||
assert_eq!(task::run(true, 1, async |scope| Ok::<_, ()>(@borrowed@(scope, "hello".into()).await)).unwrap().unwrap(), 5);
|
||||
assert_eq!(task::run(true, 1, async |scope| Ok::<_, ()>(@multiple@(scope, 20).await)).unwrap().unwrap(), 41);
|
||||
assert_eq!(task::run(true, 1, async |scope| Ok::<_, ()>(@handled@(scope).await)).unwrap().unwrap(), 41);
|
||||
assert_eq!(task::run(true, 1, async |scope| Ok::<_, ()>(@together@(scope).await)).unwrap().unwrap(), 62);
|
||||
assert_eq!(task::run(true, 1, async |scope| Ok::<_, ()>(@captured@(scope, 42).await)).unwrap().unwrap(), 42);
|
||||
assert_eq!(task::run(true, 1, async |scope| Ok::<_, ()>(@captured@(scope, 0).await)).unwrap().unwrap(), -1);
|
||||
assert_eq!(task::run(true, 1, async |scope| Ok::<_, ()>(@capturedNever@(scope).await)).unwrap().unwrap(), -1);
|
||||
assert!(matches!(task::run(true, 1, async |scope| @neverReturns@(scope).await).unwrap(), Err(RunError::Business { .. })));
|
||||
assert!(matches!(task::run(true, 1, async |scope| @argumentFailure@(scope, 0).await).unwrap(), Err(RunError::Business { .. })));
|
||||
assert_eq!(task::run(true, 1, async |scope| @nested@(scope, 42).await).unwrap().unwrap(), 42);
|
||||
match task::run(true, 1, async |scope| Ok::<_, ()>(@multiple@(scope, i64::MAX).await)).unwrap() {
|
||||
Err(RunError::Fault { primary, additional }) => {
|
||||
assert_eq!(primary.downcast_ref::<&'static FaultInfo>().unwrap().source, @source_path@);
|
||||
assert!(additional.is_empty());
|
||||
}
|
||||
_ => panic!("expected original arithmetic fault"),
|
||||
}
|
||||
Reference in new issue
Block a user