Dever v0.0.2

This commit is contained in:
Codex committed 2026-11-27 06:03:56 +00:00
commit e6e175ebcf
816 files changed
+120349

No files matched your search

+131
View File
@@ -0,0 +1,131 @@
//! Cargo 维护依赖图和锁;首次生成只允许使用核心锁中已有的依赖版本。
use super::*;
use serde_json::Value;
use std::collections::BTreeSet;
#[cfg(test)]
#[path = "../../../../test/rust/build/lock.rs"]
mod tests;
fn command() -> Result<Command> {
if std::env::var_os("DEVER_ROOT").is_some() {
Ok(Command::new(
crate::compiler::root()?.join("toolchain/bin/cargo"),
))
} else {
let mut command = Command::new("cargo");
command.arg("+1.95.0");
Ok(command)
}
}
fn metadata(directory: &Path, locked: bool) -> Result<Value> {
let mut command = command()?;
command.args(["metadata", "--offline", "--format-version=1"]);
if locked {
command.args(["--locked", "--all-features"]);
}
let output = command.current_dir(directory).output()?;
if !output.status.success() {
return Err(String::from_utf8_lossy(&output.stderr).into_owned().into());
}
Ok(serde_json::from_slice(&output.stdout)?)
}
fn packages(metadata: &Value) -> BTreeSet<(String, String, String)> {
metadata["packages"]
.as_array()
.expect("Cargo metadata packages")
.iter()
.filter_map(|package| {
package["source"].as_str().map(|source| {
(
package["name"].as_str().unwrap().into(),
package["version"].as_str().unwrap().into(),
source.into(),
)
})
})
.collect()
}
pub(super) fn prepare_lock(root: &Path, directory: &Path, changed: bool) -> Result<()> {
let lock = fs::read(root.join("Cargo.lock"))?;
// 依赖版本不变时,运行库 feature 仍可能改变生成项目的锁闭包。
let mut identity = Sha256::new();
identity.update(Sha256::digest(&lock));
for path in ["Cargo.toml", "src/runtime/Cargo.toml"] {
identity.update(Sha256::digest(fs::read(root.join(path))?));
}
let identity = format!("{:x}", identity.finalize());
let marker = directory.join("core-lock.sha256");
let previous = match fs::read_to_string(&marker) {
Ok(value) => Some(value),
Err(error) if error.kind() == io::ErrorKind::NotFound => None,
Err(error) => return Err(error.into()),
};
if !changed && previous.as_deref() == Some(&identity) && directory.join("Cargo.lock").is_file()
{
return Ok(());
}
let expected = packages(&metadata(root, true)?);
crate::compiler::files::write(&directory.join("Cargo.lock"), &lock)?;
let actual = packages(&metadata(directory, false)?);
if !actual.is_subset(&expected) {
return Err(format!(
"generated dependencies differ from core lock: {:?}",
actual.difference(&expected).collect::<Vec<_>>()
)
.into());
}
crate::compiler::files::write(&marker, identity.as_bytes())?;
Ok(())
}
pub(super) fn build(
directory: &Path,
target: &Path,
profile: Profile,
generated: &BTreeMap<String, emit::Generated>,
sources: &[crate::syntax::source::Source],
platform: Target,
) -> Result<()> {
let mut command = command()?;
command
.args([
"build",
"--locked",
"--offline",
"--message-format=json",
"--target-dir",
])
.arg(target)
// rustc 1.95 在万层直接调用链上默认线程栈溢出;独立 Rust 同样复现。
// 使用其诊断建议的固定栈大小,整体地址空间与 RSS 验收预算不变。
.env("RUST_MIN_STACK", "16777216")
.current_dir(directory);
if matches!(profile, Profile::Release) {
command.arg("--release");
}
if platform != Target::host()? {
command.args(["--target", platform.triple()]);
}
let output = command.output()?;
if output.status.success() {
return Ok(());
}
let mut diagnostics = String::from_utf8_lossy(&output.stderr).into_owned();
for line in output
.stdout
.split(|byte| *byte == b'\n')
.filter(|line| !line.is_empty())
{
let event: Value = serde_json::from_slice(line)?;
if event["reason"] != "compiler-message" {
continue;
}
files::diagnostic(&event["message"], generated, sources, &mut diagnostics);
}
crate::compiler::files::write(&directory.join("build.log"), diagnostics.as_bytes())?;
Err(format!("native build failed ({}):\n{diagnostics}", output.status).into())
}
+212
View File
@@ -0,0 +1,212 @@
//! ELF 依赖解析交给 lddtree;构建时固定资源快照,运行时不搜索构建机器的库。
use super::*;
use crate::compiler::{
model::{Body, Builtin, ExpressionKind},
project::external,
};
use crate::syntax::source::Source;
use std::{collections::BTreeSet, os::unix::fs::PermissionsExt};
#[derive(Default)]
pub(super) struct Assets {
pub commands: bool,
pub workers: bool,
pub source: String,
}
pub(super) fn prepare(
root: &Path,
directory: &Path,
program: &Program,
sources: &[Source],
target: Target,
) -> Result<Assets> {
let mut assets = Assets::default();
let mut emitted = BTreeSet::new();
let mut entries = Vec::new();
for function in &program.functions {
let Body::Statements { statements, .. } = &function.body else {
continue;
};
for statement in statements {
let value = statement.value();
let (entry, worker) = match &value.kind {
ExpressionKind::Builtin(Builtin::Command { entry, .. }, _) => {
assets.commands = true;
(entry, None)
}
ExpressionKind::Builtin(
Builtin::Worker {
entry, contract, ..
},
_,
) => {
assets.workers = true;
(entry, Some(contract))
}
_ => continue,
};
let source = &sources[value.span.source];
let symbol = external::symbol(source, entry);
// 同一 external 声明可以为多个 Port 函数生成实现,它们共用资产。
if !emitted.insert(symbol.clone()) {
continue;
}
let contract = worker
.map(|contract| serde_json::from_str::<serde_json::Value>(contract))
.transpose()?
.filter(|contract| contract["ecosystem"] != "exec");
let file = external::path(source, entry).canonicalize()?;
let domain = external::path(source, "").canonicalize()?;
validate(&file, &domain, contract.is_some(), target)?;
entries.push((symbol, file, contract));
}
}
let mut resources = BTreeMap::new();
for (symbol, mut file, contract) in entries {
let mut archive = "None".to_owned();
let mut arguments = Vec::new();
let mut native_libraries = BTreeMap::new();
let mut python_home = None;
if let Some(contract) = contract {
let artifact = crate::compiler::external::build(
root,
&directory.join("native").join(&symbol),
&file,
&contract,
target,
)?;
file = artifact.executable;
arguments = artifact.arguments;
native_libraries = artifact.libraries;
python_home = artifact.python_home;
if let Some(path) = artifact.resources {
let path = snapshot(directory, &path, &mut resources)?;
archive = format!("Some(include_bytes!({path:?}))");
}
}
let tree = lddtree::DependencyAnalyzer::default().analyze(&file)?;
let mut libraries = BTreeMap::new();
for (name, library) in tree.libraries {
// 带斜杠的 DT_NEEDED 由 loader 按原路径打开,不能伪称可搬移。
if Path::new(&name).file_name().and_then(|v| v.to_str()) != Some(&name) {
return Err(
format!("external library must use a relocatable SONAME: {name}").into(),
);
}
let path = library.realpath.ok_or_else(|| {
format!(
"external library not found: {name} (required by {})",
file.display()
)
})?;
libraries.insert(name, snapshot(directory, &path, &mut resources)?);
}
for (name, path) in native_libraries {
if Path::new(&name).file_name().and_then(|v| v.to_str()) != Some(&name) {
return Err(
format!("external library must use a relocatable SONAME: {name}").into(),
);
}
let path = snapshot(directory, &path, &mut resources)?;
if let Some(previous) = libraries.insert(name.clone(), path.clone())
&& previous != path
{
return Err(format!("external libraries have conflicting SONAMEs: {name}").into());
}
}
let loader = match tree.interpreter {
None if libraries.is_empty() => "None".to_owned(),
None => return Err("dynamic external executable has no interpreter".into()),
Some(path) => {
let path = Path::new(&path);
let name = path.file_name().unwrap().to_string_lossy();
if !(name.starts_with("ld-linux-") || name.starts_with("ld-musl-")) {
return Err(format!(
"unsupported external ELF interpreter: {}",
path.display()
)
.into());
}
let bytes = snapshot(directory, path, &mut resources)?;
let (relocated, offset, capacity) = crate::compiler::external::image::relocate(
&file,
&directory.join("images").join(&symbol),
)?;
file = relocated;
format!("Some(({offset},{capacity},include_bytes!({bytes:?})))")
}
};
let main = snapshot(directory, &file, &mut resources)?;
write!(assets.source, "static {symbol}: dever_runtime::process::Image = dever_runtime::process::Image {{ key:{symbol:?}, executable:include_bytes!({main:?}), loader:{loader}, libraries:&[").unwrap();
for (name, path) in libraries {
write!(assets.source, "({name:?},include_bytes!({path:?})),").unwrap();
}
writeln!(
assets.source,
"],resources:{archive},arguments:&{arguments:?},python_home:{python_home:?} }};"
)
.unwrap();
}
if !emitted.is_empty() {
super::super::files::write(
&directory.join("external-resources.json"),
&serde_json::to_vec_pretty(&resources)?,
)?;
}
Ok(assets)
}
fn validate(file: &Path, domain: &Path, native: bool, target: Target) -> Result<()> {
if !file.starts_with(domain) {
return Err("external executable symlink escapes its domain".into());
}
let metadata = fs::metadata(file)?;
if native {
if !metadata.is_file() {
return Err("external native entry must be a regular source file".into());
}
return Ok(());
}
if !metadata.is_file() || metadata.permissions().mode() & 0o111 == 0 {
return Err("external command requires an executable regular ELF file".into());
}
let bytes = fs::read(file)?;
let elf = goblin::elf::Elf::parse(&bytes)?;
if !elf.is_64
|| !elf.little_endian
|| elf.header.e_machine != target.machine()
|| !matches!(
elf.header.e_type,
goblin::elf::header::ET_EXEC | goblin::elf::header::ET_DYN
)
|| elf.entry == 0
{
return Err(format!(
"external command is not an executable for {}: {}",
target.arch(),
file.display()
)
.into());
}
if target != Target::host()? && (elf.interpreter.is_some() || !elf.libraries.is_empty()) {
return Err("cross-target external exec requires a static ELF; build dynamic Workers on the target host".into());
}
Ok(())
}
fn snapshot(
directory: &Path,
source: &Path,
resources: &mut BTreeMap<PathBuf, String>,
) -> Result<PathBuf> {
if let Some(digest) = resources.get(source) {
return Ok(directory.join("external").join(digest));
}
let bytes = fs::read(source)?;
let digest = format!("{:x}", Sha256::digest(&bytes));
let path = directory.join("external").join(&digest);
super::super::files::write(&path, &bytes)?;
resources.insert(source.to_owned(), digest);
Ok(path)
}
+99
View File
@@ -0,0 +1,99 @@
//! 仅替换编译器记录的生成文件,原子写入且不碰未登记文件。
use super::*;
use crate::compiler::files::write;
use serde_json::json;
pub(super) fn stage(
directory: &Path,
generated: &BTreeMap<String, emit::Generated>,
sources: &[crate::syntax::source::Source],
resources: &str,
) -> Result<()> {
let manifest = directory.join("generated-files.json");
let previous: Vec<String> = match fs::read(&manifest) {
Ok(bytes) => serde_json::from_slice(&bytes)?,
Err(error) if error.kind() == io::ErrorKind::NotFound => Vec::new(),
Err(error) => return Err(error.into()),
};
for path in &previous {
if !Path::new(path)
.components()
.all(|part| matches!(part, std::path::Component::Normal(_)))
|| !path.ends_with(".rs")
{
return Err("invalid generated-file manifest path".into());
}
}
for (path, source) in generated {
write(
&directory.join(path),
if path == "external.rs" {
resources.as_bytes()
} else {
source.text.as_bytes()
},
)?;
}
for path in previous {
if !generated.contains_key(&path) {
match fs::remove_file(directory.join(&path)) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
}
}
write(
&manifest,
&serde_json::to_vec(&generated.keys().collect::<Vec<_>>())?,
)?;
let mappings = generated.iter().map(|(file, output)| (file, output.mappings.iter().map(|mapping| json!({"start":mapping.start,"end":mapping.end,"source":mapping.source.source,"source_start":mapping.source.start,"source_end":mapping.source.end})).collect::<Vec<_>>())).collect::<BTreeMap<_, _>>();
write(
&directory.join("source-map.json"),
&serde_json::to_vec(
&json!({"files":sources.iter().map(|source| &source.path).collect::<Vec<_>>(),"mappings":mappings}),
)?,
)?;
Ok(())
}
pub(super) fn diagnostic(
message: &serde_json::Value,
generated: &BTreeMap<String, emit::Generated>,
sources: &[crate::syntax::source::Source],
diagnostics: &mut String,
) {
if message["level"] != "error" {
return;
}
if let Some(rendered) = message["rendered"].as_str() {
diagnostics.push_str(rendered);
}
for span in message["spans"].as_array().expect("rustc diagnostic spans") {
if span["is_primary"] != true {
continue;
}
let Some(file) = span["file_name"]
.as_str()
.and_then(|name| generated.get(name))
else {
continue;
};
let start = span["byte_start"].as_u64().unwrap() as usize;
let end = span["byte_end"].as_u64().unwrap() as usize;
if let Some(mapping) = file
.mappings
.iter()
.filter(|mapping| mapping.start <= start && end <= mapping.end)
.min_by_key(|mapping| mapping.end - mapping.start)
{
let source = &sources[mapping.source.source];
let (line, column) = source.position(mapping.source.start);
diagnostics.push_str(&format!(
"\nDever: {}:{line}:{column}\n",
source.path.display()
));
}
}
}
+200
View File
@@ -0,0 +1,200 @@
use super::{Artifact, ArtifactStorage, Profile, Result, Target, emit, external, files};
use crate::compiler::{home, model::Program, project::Project};
use lzma_rust2::XzReader;
use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, memfd_create};
use std::{
collections::BTreeMap,
fs::{self, File},
io::{self, BufReader, Read, Seek, SeekFrom},
os::{fd::AsRawFd, unix::fs::symlink},
path::{Component, Path, PathBuf},
process::Command,
};
const FOOTER: &[u8; 8] = b"DVRLOC01";
const LICENSES: &str = "THIRD-PARTY.txt";
const LOADER: &str = "/lib64/ld-linux-x86-64.so.2";
pub(super) struct Image {
file: File,
length: u64,
}
impl Image {
pub(super) fn open() -> io::Result<Option<Self>> {
let mut file = File::open("/proc/self/exe")?;
let size = file.seek(SeekFrom::End(-16))?;
let mut footer = [0; 16];
file.read_exact(&mut footer)?;
if &footer[8..] != FOOTER {
return Ok(None);
}
let length = u64::from_le_bytes(footer[..8].try_into().unwrap());
let start = size.checked_sub(length).ok_or_else(invalid_image)?;
file.seek(SeekFrom::Start(start))?;
Ok(Some(Self { file, length }))
}
fn archive(self) -> tar::Archive<impl Read> {
let compressed = BufReader::new(self.file.take(self.length));
tar::Archive::new(XzReader::new(compressed, false))
}
fn memory_files(self, directory: &Path) -> io::Result<Vec<File>> {
let mut archive = self.archive();
let mut files = Vec::new();
for entry in archive.entries()? {
let mut entry = entry?;
let path = entry.path()?.into_owned();
if path == Path::new(LICENSES) {
continue;
}
if !entry.header().entry_type().is_file()
|| !path
.components()
.all(|part| matches!(part, Component::Normal(_)))
{
return Err(invalid_image());
}
let mut file = File::from(memfd_create("dever-build", MemfdFlags::ALLOW_SEALING)?);
io::copy(&mut entry, &mut file)?;
fcntl_add_seals(
&file,
SealFlags::SHRINK | SealFlags::GROW | SealFlags::WRITE | SealFlags::SEAL,
)?;
let resource = directory.join(path);
fs::create_dir_all(resource.parent().unwrap())?;
symlink(format!("/proc/self/fd/{}", file.as_raw_fd()), resource)?;
files.push(file);
}
io::copy(&mut archive.into_inner(), &mut io::sink())?;
Ok(files)
}
pub(super) fn compile(
self,
project: &Project,
program: &Program,
generated: &BTreeMap<String, emit::Generated>,
profile: Profile,
target: Target,
) -> Result<Artifact> {
if target != Target::LinuxX86_64 || target != Target::host()? {
return Err("this dever executable builds for Linux x86_64".into());
}
let work = tempfile::Builder::new().prefix("dever-build-").tempdir()?;
let directory = work.path().canonicalize()?;
let assets =
external::prepare(&project.root, &directory, program, &project.sources, target)?;
files::stage(&directory, generated, &project.sources, &assets.source)?;
let image = directory.join("tool");
let handles = self.memory_files(&image)?;
let binary = directory.join("application");
let output = command(&image, profile)?
.current_dir(&directory)
.arg("--error-format=json")
.arg("main.rs")
.arg("-o")
.arg(&binary)
.output()?;
drop(handles);
if !output.status.success() {
let mut diagnostics = String::new();
for line in String::from_utf8_lossy(&output.stderr).lines() {
match serde_json::from_str::<serde_json::Value>(line) {
Ok(event) => {
files::diagnostic(&event, generated, &project.sources, &mut diagnostics)
}
Err(_) => {
diagnostics.push_str(line);
diagnostics.push('\n');
}
}
}
return Err(format!("native build failed ({}):\n{diagnostics}", output.status).into());
}
Ok(Artifact {
binary,
directory,
storage: ArtifactStorage::Temporary { _directory: work },
})
}
}
pub fn write_licenses(output: &mut impl io::Write) -> Result<()> {
let mut archive = Image::open()?
.ok_or("this dever executable has no embedded distribution notices")?
.archive();
let mut entry = archive.entries()?.next().ok_or_else(invalid_image)??;
if entry.path()? != Path::new(LICENSES) {
return Err(invalid_image().into());
}
io::copy(&mut entry, output)?;
Ok(())
}
fn invalid_image() -> io::Error {
io::Error::new(
io::ErrorKind::InvalidData,
"invalid embedded Dever build resources",
)
}
fn command(image: &Path, profile: Profile) -> io::Result<Command> {
let backend = fs::read_link(image.join("lib/backend"))?;
let zlib = fs::read_link(image.join("lib/zlib"))?;
let engine = fs::read_link(image.join("lib/engine"))?;
let mut preload = backend.into_os_string();
preload.push(":");
preload.push(zlib);
let mut command = Command::new(LOADER);
command
.env("LD_PRELOAD", preload)
.env("RUST_MIN_STACK", "16777216")
.arg("--preload")
.arg(engine)
.arg(image.join("bin/compile"))
.args([
"--edition=2024",
"--crate-name",
"dever_application",
"--sysroot",
])
.arg(image.join("sysroot"))
.arg("--extern")
.arg(format!(
"dever_runtime={}/crates/libdever_runtime.rlib",
image.display()
))
.args(["-C", "overflow-checks=yes", "-C", "linker-flavor=ld.lld"])
.arg(format!("-Clinker={}/bin/link", image.display()))
.arg(format!("-Ldependency={}/crates", image.display()))
.arg(format!("-Lnative={}/crt", image.display()))
.arg(format!("-Lnative={}/native", image.display()))
.args([
"-Clink-arg=--dynamic-linker",
&format!("-Clink-arg={LOADER}"),
]);
for name in ["Scrt1.o", "crti.o", "libc_nonshared.a", "crtn.o"] {
command.arg(format!("-Clink-arg={}/crt/{name}", image.display()));
}
if matches!(profile, Profile::Release) {
command.args([
"-Copt-level=3",
"-Clto=fat",
"-Ccodegen-units=1",
"-Cstrip=symbols",
]);
}
Ok(command)
}
pub(crate) fn standard_root() -> io::Result<Option<PathBuf>> {
Image::open()?
.map(|_| {
home()
.map(|path| path.join("standard").join(env!("CARGO_PKG_VERSION")))
.map_err(|error| io::Error::other(error.to_string()))
})
.transpose()
}
+244
View File
@@ -0,0 +1,244 @@
//! 稳定项目身份、内容未变不写与官方 Cargo 增量构建;源码摘要不进入包名。
mod cargo;
mod external;
mod files;
pub(crate) mod local;
pub use local::write_licenses;
mod target;
pub use target::Target;
use super::{
check::ownership,
emit,
model::Program,
project::{Project, front, web},
};
use sha2::{Digest, Sha256};
use std::{
collections::BTreeMap,
fmt::Write,
fs::{self, File, OpenOptions},
io,
path::{Path, PathBuf},
process::Command,
};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[derive(Clone, Copy)]
pub enum Profile {
Dev,
Release,
}
impl Profile {
pub fn directory(self) -> &'static str {
match self {
Self::Dev => "debug",
Self::Release => "release",
}
}
}
pub struct Artifact {
pub binary: PathBuf,
pub directory: PathBuf,
storage: ArtifactStorage,
}
enum ArtifactStorage {
Cached { _lock: File },
Temporary { _directory: tempfile::TempDir },
}
impl Artifact {
pub fn publish(&self, output: &Path) -> Result<()> {
let mut source = File::open(&self.binary)?;
let mut destination = OpenOptions::new()
.write(true)
.create_new(true)
.open(output)?;
let result = io::copy(&mut source, &mut destination)
.and_then(|_| destination.set_permissions(source.metadata()?.permissions()))
.and_then(|()| destination.sync_all());
if let Err(error) = result {
fs::remove_file(output)
.map_err(|cleanup| format!("{error}; removing incomplete output: {cleanup}"))?;
return Err(error.into());
}
Ok(())
}
pub fn run(self, arguments: &[String]) -> Result<std::process::ExitStatus> {
let mut child = Command::new(&self.binary).args(arguments).spawn()?;
drop(self.storage);
Ok(child.wait()?)
}
}
pub fn build(
project: &Project,
program: &Program,
entry: &str,
profile: Profile,
target: Option<Target>,
) -> Result<Artifact> {
project.check_api(program)?;
let _lock = front::build_lock(project)?;
let assets = front::prepare(project, &project.setting_path(), front::Mode::Build)?;
build_native(project, program, entry, profile, target, &assets)
}
pub fn run(
project: &Project,
program: &Program,
entry: &str,
profile: Profile,
mut arguments: Vec<String>,
) -> Result<std::process::ExitStatus> {
project.check_api(program)?;
let explicit_config = arguments.first().is_some_and(|value| value == "--config");
let config = if explicit_config {
PathBuf::from(arguments.get(1).ok_or("--config requires a path")?)
} else {
project.setting_path()
};
let assets = front::prepare(project, &config, front::Mode::Run)?;
if !explicit_config && (program.has_config() || !assets.is_empty()) {
arguments.splice(
0..0,
["--config".into(), config.to_string_lossy().into_owned()],
);
}
build_native(project, program, entry, profile, None, &assets)?.run(&arguments)
}
fn build_native(
project: &Project,
program: &Program,
entry: &str,
profile: Profile,
target: Option<Target>,
assets: &[web::Asset],
) -> Result<Artifact> {
let web = !assets.is_empty();
let decisions = ownership::analyze(program);
let mut generated = emit::emit_with_web(program, &decisions, &project.sources, web);
if web {
generated.insert("web.rs".into(), web::emit(assets));
generated
.get_mut("main.rs")
.unwrap()
.text
.push_str("include!(\"web.rs\");\n");
}
let main = if program.commands.is_empty()
&& program.jobs.is_empty()
&& program.http.is_empty()
&& !web
{
emit::application::standalone(program, entry)?
} else {
if entry != "main" {
return Err("application entry is selected by command binding".into());
}
emit::application::emit_with_web(program, &decisions, web)
};
generated.get_mut("main.rs").unwrap().text.push_str(&main);
compile(&project.root, program, &generated, profile, project, target)
}
pub fn compile(
identity: &Path,
program: &Program,
generated: &BTreeMap<String, emit::Generated>,
profile: Profile,
project: &Project,
target: Option<Target>,
) -> Result<Artifact> {
let sources = &project.sources;
let target = target.unwrap_or(Target::host()?);
if let Some(image) = local::Image::open()? {
return image.compile(project, program, generated, profile, target);
}
let root = crate::compiler::root()?.join("rust");
let identity = identity.canonicalize()?;
let digest = Sha256::digest(identity.as_os_str().as_encoded_bytes());
let name = format!("dever-program-{digest:x}");
let directory = root
.join("target/generated")
.join(&name)
.join(target.arch());
fs::create_dir_all(&directory)?;
let lock = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(directory.join("build.lock"))?;
lock.lock()?;
let assets = external::prepare(&project.root, &directory, program, sources, target)?;
let mut features = String::from("\"wire\"");
let tls = program.uses_tls();
let http = program.uses_http();
let web = generated.contains_key("web.rs");
let database_setup = program.database_setup(web);
for (enabled, name) in [
(assets.commands, "process"),
(assets.workers, "worker"),
(
program.functions.iter().any(|f| {
f.signature
.inputs
.iter()
.any(|f| f.kind == crate::compiler::model::Type::Upload)
}),
"upload",
),
(program.stages_files(), "stored-bytes"),
(program.testing, "testing"),
(
!program.http.is_empty()
|| web
|| program
.functions
.iter()
.any(|f| f.effects.session || f.effects.request),
"api",
),
(program.uses_database(), "database"),
(
database_setup || program.functions.iter().any(|f| f.effects.identity),
"auth",
),
(!program.jobs.is_empty(), "job"),
(database_setup, "postgres"),
(tls, "tls"),
(http, "http"),
(!tls && !http && program.uses_network(), "net"),
] {
if enabled {
write!(features, ", {name:?}").unwrap();
}
}
let manifest = format!(
"[package]\nname = {name:?}\nversion = \"0.0.1\"\nedition = \"2024\"\n[workspace]\n[[bin]]\nname = {name:?}\npath = \"main.rs\"\n[dependencies]\ndever-runtime = {{ path = {:?}, features = [{features}] }}\n[profile.dev]\ndebug = 0\nincremental = true\noverflow-checks = true\n[profile.release]\nlto = \"fat\"\ncodegen-units = 1\noverflow-checks = true\nstrip = \"symbols\"\n",
root.join("src/runtime")
);
let manifest_changed = super::files::write(&directory.join("Cargo.toml"), manifest.as_bytes())?;
files::stage(&directory, generated, sources, &assets.source)?;
cargo::prepare_lock(&root, &directory, manifest_changed)?;
let output = root.join("target/programs");
cargo::build(&directory, &output, profile, generated, sources, target)?;
let output = if target == Target::host()? {
output
} else {
output.join(target.triple())
};
Ok(Artifact {
binary: output.join(profile.directory()).join(name),
directory,
storage: ArtifactStorage::Cached { _lock: lock },
})
}
+47
View File
@@ -0,0 +1,47 @@
//! 构建目标独立于宿主;Cargo 负责目标标准库、链接器及交叉缓存。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Target {
LinuxX86_64,
LinuxAarch64,
}
impl Target {
pub fn parse(value: &str) -> Result<Self, String> {
match value {
"linux-x86_64" => Ok(Self::LinuxX86_64),
"linux-aarch64" => Ok(Self::LinuxAarch64),
_ => Err(format!(
"unsupported build target {value}; expected linux-x86_64 or linux-aarch64"
)),
}
}
pub fn host() -> Result<Self, String> {
match (std::env::consts::OS, std::env::consts::ARCH) {
("linux", "x86_64") => Ok(Self::LinuxX86_64),
("linux", "aarch64") => Ok(Self::LinuxAarch64),
_ => Err("Dever requires a Linux x86_64 or aarch64 host".into()),
}
}
pub fn arch(self) -> &'static str {
match self {
Self::LinuxX86_64 => "x86_64",
Self::LinuxAarch64 => "aarch64",
}
}
pub fn triple(self) -> &'static str {
match self {
Self::LinuxX86_64 => "x86_64-unknown-linux-gnu",
Self::LinuxAarch64 => "aarch64-unknown-linux-gnu",
}
}
pub(crate) fn machine(self) -> u16 {
match self {
Self::LinuxX86_64 => goblin::elf::header::EM_X86_64,
Self::LinuxAarch64 => goblin::elf::header::EM_AARCH64,
}
}
}
+106
View File
@@ -0,0 +1,106 @@
//! 静态调用按实例绑定;同一源码位置在不同 handler 绑定中可以指向不同目标。
mod expand;
use crate::compiler::{model::Call, project::Module};
use crate::syntax::{ast, diagnostic::Diagnostic, source::Span};
use std::{
borrow::Cow,
collections::{HashMap, HashSet},
};
pub struct Contract<'a> {
pub target: usize,
pub parameter: &'a ast::Field,
pub span: Span,
pub forwarded: bool,
}
pub struct Calls<'a> {
pub dispatches: HashMap<usize, Vec<usize>>,
pub ports: HashMap<usize, &'a ast::Function>,
pub functions: Vec<Cow<'a, ast::Function>>,
pub identities: Vec<String>,
pub source_names: Vec<String>,
pub labels: Vec<String>,
pub edges: Vec<Call>,
pub outgoing: Vec<Vec<usize>>,
pub incoming: Vec<Vec<usize>>,
pub order: Vec<usize>,
pub by_span: HashMap<(usize, Span), usize>,
pub walks: HashSet<(usize, Span)>,
pub by_name: HashMap<String, usize>,
pub contracts: Vec<Vec<Contract<'a>>>,
pub diagnostics: Vec<Diagnostic>,
pub invalid: HashSet<usize>,
pub concrete: usize,
}
pub fn bind<'a>(
declarations: &'a [ast::Declaration],
modules: &[Module],
) -> Result<Calls<'a>, Diagnostic> {
let calls = analyze(declarations, modules);
if let Some(error) = calls.diagnostics.first() {
return Err(error.clone());
}
Ok(calls)
}
pub fn analyze<'a>(declarations: &'a [ast::Declaration], modules: &[Module]) -> Calls<'a> {
expand::analyze(declarations, modules)
}
/// Kahn 顺序保留不依赖环的部分;环及依赖环的定义均不进入可检查顺序。
pub(crate) fn partial_order(
edges: &[Vec<(usize, Span)>],
names: &[String],
problem: &str,
) -> (Vec<usize>, Option<Diagnostic>) {
let mut incoming = vec![Vec::new(); edges.len()];
let mut remaining = Vec::new();
for (source, targets) in edges.iter().enumerate() {
remaining.push(targets.len());
for (target, _) in targets {
incoming[*target].push(source);
}
}
let mut ready = remaining
.iter()
.enumerate()
.filter_map(|(index, count)| (*count == 0).then_some(index))
.rev()
.collect::<Vec<_>>();
let mut result = Vec::with_capacity(edges.len());
while let Some(target) = ready.pop() {
result.push(target);
for source in &incoming[target] {
remaining[*source] -= 1;
if remaining[*source] == 0 {
ready.push(*source);
}
}
}
if result.len() == edges.len() {
return (result, None);
}
let mut current = remaining.iter().position(|count| *count > 0).unwrap();
let mut visited = HashMap::new();
let mut path = Vec::new();
loop {
if let Some(start) = visited.insert(current, path.len()) {
let cycle: &[(usize, Span)] = &path[start..];
let mut error = Diagnostic::new("C010", problem, cycle[0].1);
for (source, span) in cycle {
error.related.push((*span, names[*source].clone()));
}
return (result, Some(error));
}
let (target, span) = edges[current]
.iter()
.find(|(target, _)| remaining[*target] > 0)
.unwrap();
path.push((current, *span));
current = *target;
}
}
+422
View File
@@ -0,0 +1,422 @@
//! 只展开实际使用的静态组合;未调用模板另用声明原型检查,不输出这些检查实例。
mod ports;
mod resolve;
use super::*;
use crate::compiler::project::Role;
use crate::syntax::names::{self, Style};
use sha2::{Digest, Sha256};
struct Expander<'a, 'm> {
graph: Calls<'a>,
templates: Vec<&'a ast::Function>,
names: HashMap<String, usize>,
modules: &'m [Module],
invalid: HashSet<usize>,
templates_for: Vec<Option<usize>>,
bindings: Vec<HashMap<String, usize>>,
cache: HashMap<(usize, Vec<usize>), usize>,
cursor: usize,
ports: HashMap<usize, &'a ast::Function>,
}
pub(super) fn analyze<'a>(declarations: &'a [ast::Declaration], modules: &[Module]) -> Calls<'a> {
let implementations = declarations
.iter()
.filter_map(|d| match d {
ast::Declaration::Function(f)
if modules[f.span.source].role == Role::Adapter && f.name.starts_with("port.") =>
{
Some(format!(
"{}.{}.{}",
modules[f.span.source].component, modules[f.span.source].domain, f.name
))
}
_ => None,
})
.fold(HashMap::<String, usize>::new(), |mut counts, name| {
*counts.entry(name).or_default() += 1;
counts
});
let templates = declarations
.iter()
.filter_map(|d| match d {
ast::Declaration::Function(f)
if !matches!(f.body, ast::Body::Contract)
|| implementations
.get(&modules[f.span.source].qualify(&f.name))
.is_some_and(|n| *n > 1) =>
{
Some(f)
}
_ => None,
})
.collect::<Vec<_>>();
let mut names = HashMap::new();
let mut invalid = HashSet::new();
let mut diagnostics = Vec::new();
check_templates(
&templates,
modules,
&mut names,
&mut invalid,
&mut diagnostics,
);
for (index, function) in templates.iter().enumerate() {
let module = &modules[function.span.source];
if matches!(module.role, Role::Adapter | Role::Test) && function.name.starts_with("port.") {
names.remove(&module.qualify(&function.name));
let name = format!("{}.{}.{}", module.component, module.domain, function.name);
if implementations.get(&name).is_none_or(|count| *count <= 1) {
names.insert(name, index);
}
}
}
let ports = ports::bind(
declarations,
modules,
&templates,
&mut diagnostics,
&mut invalid,
);
let mut state = Expander {
graph: Calls {
ports: HashMap::new(),
dispatches: HashMap::new(),
functions: Vec::new(),
identities: Vec::new(),
source_names: Vec::new(),
labels: Vec::new(),
edges: Vec::new(),
outgoing: Vec::new(),
incoming: Vec::new(),
order: Vec::new(),
by_span: HashMap::new(),
walks: HashSet::new(),
by_name: HashMap::new(),
contracts: Vec::new(),
diagnostics,
invalid: HashSet::new(),
concrete: 0,
},
templates,
names,
modules,
invalid,
templates_for: Vec::new(),
bindings: Vec::new(),
cache: HashMap::new(),
cursor: 0,
ports,
};
for template in 0..state.templates.len() {
if state.templates[template]
.inputs
.iter()
.all(|f| f.kind.handler.is_none())
{
let index = state.instance(template, Vec::new());
state
.graph
.by_name
.insert(state.graph.source_names[index].clone(), index);
}
}
// 多实现 Port 本身是静态图节点;所有候选都进入拓扑、效果与失败检查。
for template in 0..state.templates.len() {
let contract = state.templates[template];
if !matches!(contract.body, ast::Body::Contract) {
continue;
}
let caller = state.instance(template, Vec::new());
let mut targets = state
.ports
.iter()
.filter_map(|(&index, bound)| (bound.span == contract.span).then_some(index))
.collect::<Vec<_>>();
targets.sort_unstable();
let mut variants = Vec::new();
for target in targets {
let target = state.instance(target, Vec::new());
let span = state.graph.functions[target].span;
state.edge(caller, target, span, span, false, Vec::new());
variants.push(target);
}
state.graph.dispatches.insert(caller, variants);
}
state.resolve();
state.graph.concrete = state.graph.functions.len();
// 原型代表已声明的 handler 合同,不是假造实现;仅供模板检查,不进入原生程序。
for template in 0..state.templates.len() {
let function = state.templates[template];
let mut bindings = Vec::new();
for field in &function.inputs {
let Some(handler) = &field.kind.handler else {
continue;
};
let index = state.push(
Cow::Owned(ast::Function {
block: false,
transaction: false,
name: field.name.clone(),
inputs: handler.inputs.clone(),
outputs: handler.outputs.clone(),
recover: None,
fails: None,
body: ast::Body::Contract,
span: field.span,
}),
format!(
"{}.handler.{}",
state.modules[function.span.source].qualify(&function.name),
field.name
),
None,
HashMap::new(),
);
bindings.push(index);
}
if !bindings.is_empty() {
let index = state.instance(template, bindings);
state
.graph
.by_name
.insert(state.graph.source_names[index].clone(), index);
}
}
state.resolve();
let adjacency = state
.graph
.outgoing
.iter()
.map(|edges| {
edges
.iter()
.map(|&edge| {
let call = &state.graph.edges[edge];
(call.target, call.span)
})
.collect()
})
.collect::<Vec<_>>();
let (order, error) = partial_order(&adjacency, &state.graph.source_names, "recursive calls");
state.graph.order = order;
state.graph.diagnostics.extend(error);
state.graph
}
fn check_templates(
templates: &[&ast::Function],
modules: &[Module],
names: &mut HashMap<String, usize>,
invalid: &mut HashSet<usize>,
diagnostics: &mut Vec<Diagnostic>,
) {
for (index, function) in templates.iter().enumerate() {
let module = &modules[function.span.source];
let operation = if matches!(module.role, Role::Adapter | Role::Test) {
function
.name
.strip_prefix("port.")
.unwrap_or(&function.name)
} else {
&function.name
};
if let Err(error) = names::validate(operation, Style::Function, function.span) {
diagnostics.push(error);
invalid.insert(index);
}
if !(matches!(
module.role,
Role::App | Role::Domain | Role::Adapter | Role::Test
) || module.role == Role::Port && matches!(function.body, ast::Body::Contract))
{
diagnostics.push(Diagnostic::new(
"C003",
"this role does not allow function bodies",
function.span,
));
invalid.insert(index);
}
if matches!(function.body, ast::Body::Flow(_)) && module.role == Role::Domain {
diagnostics.push(Diagnostic::new(
"C003",
"flow definitions belong in app or adapter",
function.span,
));
invalid.insert(index);
}
let identity = module.qualify(&function.name);
if let Some(previous) = names.insert(identity.clone(), index) {
let mut error = Diagnostic::new(
"C001",
format!("duplicate definition {identity}"),
function.span,
);
error
.related
.push((templates[previous].span, "first definition".into()));
diagnostics.push(error);
invalid.extend([previous, index]);
}
// 静态参数擦除之前核对原声明;仅有 handler 的规则仍有一个编译期输入。
if matches!(function.body, ast::Body::Rule(_)) && function.inputs.is_empty() {
diagnostics.push(Diagnostic::new(
"C009",
"a rule requires at least one input",
function.span,
));
invalid.insert(index);
}
let mut parameters = HashSet::new();
for field in function.inputs.iter().chain(&function.outputs) {
if let Err(error) = names::validate(&field.name, Style::Value, field.span) {
diagnostics.push(error);
invalid.insert(index);
}
if !parameters.insert(&field.name) {
diagnostics.push(Diagnostic::new(
"C001",
"input and output names must be distinct",
field.span,
));
invalid.insert(index);
}
if field.kind.handler.is_some()
&& (field.kind.nullable
|| !field.kind.arguments.is_empty()
|| !field.kind.bounds.is_empty())
{
diagnostics.push(Diagnostic::new(
"C005",
"handler cannot have type arguments, nullability or value bounds",
field.span,
));
invalid.insert(index);
}
}
}
}
impl<'a> Expander<'a, '_> {
fn push(
&mut self,
function: Cow<'a, ast::Function>,
identity: String,
template: Option<usize>,
bindings: HashMap<String, usize>,
) -> usize {
let index = self.graph.functions.len();
self.graph.functions.push(function);
self.graph.identities.push(identity.clone());
self.graph.source_names.push(identity.clone());
self.graph.labels.push(identity);
self.graph.outgoing.push(Vec::new());
self.graph.incoming.push(Vec::new());
self.graph.contracts.push(Vec::new());
self.templates_for.push(template);
self.bindings.push(bindings);
index
}
fn instance(&mut self, template: usize, targets: Vec<usize>) -> usize {
let key = (template, targets);
if let Some(&index) = self.cache.get(&key) {
return index;
}
let source = self.templates[template];
let static_inputs = source
.inputs
.iter()
.enumerate()
.filter(|(_, f)| f.kind.handler.is_some())
.map(|(i, _)| i)
.collect::<Vec<_>>();
let bindings = static_inputs
.iter()
.zip(&key.1)
.map(|(&i, &target)| (source.inputs[i].name.clone(), target))
.collect();
let source_name = self.modules[source.span.source].qualify(&source.name);
let identity = if key.1.is_empty() {
source_name.clone()
} else {
let mut digest = Sha256::new();
for target in &key.1 {
let name = &self.graph.identities[*target];
digest.update(name.len().to_le_bytes());
digest.update(name.as_bytes());
}
format!("{source_name}__handler_{:x}", digest.finalize())
};
let function = if static_inputs.is_empty() {
Cow::Borrowed(source)
} else {
let mut function = source.clone();
function.inputs.retain(|f| f.kind.handler.is_none());
if let ast::Body::Rule(rule) = &mut function.body {
let offset = usize::from(rule.rows[0].name.is_some());
for &position in static_inputs.iter().rev() {
if rule.header[position + offset].0 != source.inputs[position].name
|| rule.rows.iter().any(|row| {
!matches!(
row.conditions[position].alternatives.as_slice(),
[ast::Pattern::Any]
)
})
{
self.graph.diagnostics.push(Diagnostic::new("C005", "a static handler column must use its parameter name and '-' conditions", source.inputs[position].span));
self.invalid.insert(template);
}
rule.header.remove(position + offset);
for row in &mut rule.rows {
row.conditions.remove(position);
}
}
}
Cow::Owned(function)
};
let index = self.push(function, identity, Some(template), bindings);
if let Some(contract) = self.ports.get(&template) {
self.graph.ports.insert(index, *contract);
}
self.graph.labels[index] = if key.1.is_empty() {
source_name.clone()
} else {
let labels = static_inputs
.iter()
.zip(&key.1)
.map(|(&position, &target)| {
format!(
"{} = {}",
source.inputs[position].name, self.graph.source_names[target]
)
})
.collect::<Vec<_>>()
.join(", ");
format!("{source_name} [{labels}]")
};
self.graph.source_names[index] = source_name;
if self.invalid.contains(&template) {
self.graph.invalid.insert(index);
}
self.cache.insert(key, index);
index
}
fn resolve(&mut self) {
while self.cursor < self.graph.functions.len() {
let caller = self.cursor;
self.cursor += 1;
let Some(template) = self.templates_for[caller] else {
continue;
};
let function = self.templates[template];
if let Err(error) = self.body(caller, function) {
self.graph.diagnostics.push(error);
self.graph.invalid.insert(caller);
}
}
}
}
@@ -0,0 +1,122 @@
//! 每个实现独立满足完整 Port;单实现直连,多实现交给已检查的选择节点。
use super::*;
pub(super) fn bind<'a>(
declarations: &'a [ast::Declaration],
modules: &[Module],
templates: &[&ast::Function],
diagnostics: &mut Vec<Diagnostic>,
invalid: &mut HashSet<usize>,
) -> HashMap<usize, &'a ast::Function> {
let mut contracts = HashMap::new();
for declaration in declarations {
let ast::Declaration::Function(function) = declaration else {
continue;
};
if !matches!(function.body, ast::Body::Contract) {
continue;
}
let module = &modules[function.span.source];
if module.role != Role::Port || function.recover.is_some() {
diagnostics.push(Diagnostic::new(
"C003",
"bodyless signatures belong in port files and cannot recover",
function.span,
));
continue;
}
if let Err(error) = names::validate(&function.name, Style::Function, function.span) {
diagnostics.push(error);
}
if function
.inputs
.iter()
.chain(&function.outputs)
.any(|field| field.kind.handler.is_some())
{
diagnostics.push(Diagnostic::new(
"C005",
"Port signatures cannot accept static handlers",
function.span,
));
}
let name = module.qualify(&function.name);
if contracts.insert(name, function).is_some() {
diagnostics.push(Diagnostic::new(
"C001",
"duplicate Port operation",
function.span,
));
}
}
let mut bound = HashMap::new();
let mut implemented = HashSet::new();
for (index, function) in templates.iter().enumerate() {
let module = &modules[function.span.source];
if function.fails.is_some() && !matches!(function.body, ast::Body::Contract) {
diagnostics.push(Diagnostic::new(
"C005",
"fails belongs on the Port contract; implementations infer failures",
function.span,
));
invalid.insert(index);
}
if !matches!(module.role, Role::Adapter | Role::Test) || !function.name.starts_with("port.")
{
continue;
}
let name = format!("{}.{}.{}", module.component, module.domain, function.name);
match contracts.get(&name) {
Some(contract) => {
bound.insert(index, *contract);
implemented.insert(name);
}
None => {
diagnostics.push(Diagnostic::new(
"C004",
"Adapter operation has no Port declaration",
function.span,
));
invalid.insert(index);
}
}
}
let active_sources = declarations
.iter()
.map(|d| d.span().source)
.collect::<HashSet<_>>();
for (_source, module) in modules
.iter()
.enumerate()
.filter(|(i, m)| m.role == Role::Adapter && active_sources.contains(i))
{
for (name, contract) in &contracts {
if !module.same_domain(&modules[contract.span.source]) {
continue;
}
if !templates.iter().any(|f| {
modules[f.span.source].identity() == module.identity()
&& format!("{}.{}.{}", module.component, module.domain, f.name) == *name
}) {
diagnostics.push(Diagnostic::new(
"C004",
format!(
"Port operation requires an Adapter implementation in {}",
module.identity()
),
contract.span,
));
}
}
}
for (name, contract) in contracts {
if !implemented.contains(&name) {
diagnostics.push(Diagnostic::new(
"C004",
"Port operation requires an Adapter implementation",
contract.span,
));
}
}
bound
}
@@ -0,0 +1,422 @@
//! 具名参数只在静态调用位置使用;作用域绑定不改写源码名字或全局来源索引。
use super::*;
use crate::syntax::ast::{Body, Expression, ExpressionKind, Statement};
impl<'a> Expander<'a, '_> {
pub(super) fn body(
&mut self,
caller: usize,
function: &'a ast::Function,
) -> Result<(), Diagnostic> {
let inputs = function
.inputs
.iter()
.chain(&function.outputs)
.map(|field| field.name.as_str())
.collect::<HashSet<_>>();
match &function.body {
Body::Loop(iteration) => self.loop_calls(caller, iteration, inputs)?,
Body::Statements(statements) => {
let mut locals = inputs;
for statement in statements {
self.statement(caller, statement, &mut locals)?;
}
}
Body::Flow(steps) => {
let mut locals = inputs;
for step in steps {
self.statement(caller, &step.statement, &mut locals)?;
}
}
Body::Rule(rule) => self.rule_calls(caller, rule, &inputs)?,
Body::Contract | Body::Command { .. } | Body::Worker { .. } => {}
}
Ok(())
}
fn rule_calls(
&mut self,
caller: usize,
rule: &'a ast::Rule,
inputs: &HashSet<&'a str>,
) -> Result<(), Diagnostic> {
for row in &rule.rows {
let mut locals = inputs.clone();
for condition in &row.conditions {
for pattern in &condition.alternatives {
if let ast::Pattern::Variant(_, bindings) = pattern {
locals.extend(bindings.iter().map(String::as_str));
}
}
}
for value in row.results.iter().flatten() {
self.expression(caller, value, &locals)?;
}
}
Ok(())
}
fn statement(
&mut self,
caller: usize,
statement: &'a Statement,
locals: &mut HashSet<&'a str>,
) -> Result<(), Diagnostic> {
match statement {
Statement::Assign { target, value, .. } => {
if let ExpressionKind::Name(name) = &target.kind
&& self.bindings[caller].contains_key(name)
{
return Err(Diagnostic::new(
"C005",
"handler input parameters are read-only",
target.span,
));
}
self.expression(caller, value, locals)?;
self.expression(caller, target, locals)?;
if let ExpressionKind::Name(name) = &target.kind {
locals.insert(name);
}
}
Statement::Check {
condition, error, ..
} => {
self.expression(caller, condition, locals)?;
self.expression(caller, error, locals)?;
}
Statement::Action(value) => self.expression(caller, value, locals)?,
}
Ok(())
}
fn loop_calls(
&mut self,
caller: usize,
iteration: &'a ast::Loop,
inputs: HashSet<&'a str>,
) -> Result<(), Diagnostic> {
if let ExpressionKind::Call(target, arguments) = &iteration.source.kind
&& target.path().as_deref() == Some("walk")
&& !self
.names
.contains_key(&self.modules[target.span.source].reference("walk"))
&& !self.bindings[caller].contains_key("walk")
{
let [seed, next] = arguments.as_slice() else {
return Err(Diagnostic::new(
"C005",
"walk requires a seed and named next function",
iteration.source.span,
));
};
self.expression(caller, seed, &inputs)?;
let target = self.named(caller, next, &inputs)?;
self.access(next.span.source, target, next.span)?;
let through_handler = next
.path()
.is_some_and(|name| self.bindings[caller].contains_key(&name));
self.edge(
caller,
target,
iteration.source.span,
next.span,
through_handler,
Vec::new(),
);
self.graph.walks.insert((caller, iteration.source.span));
} else {
self.expression(caller, &iteration.source, &inputs)?;
}
if let Some(limit) = &iteration.parallel {
self.expression(caller, limit, &inputs)?;
}
for row in &iteration.rows {
for value in row
.take
.iter()
.chain(row.fold.iter().map(|fold| &fold.seed))
{
self.expression(caller, value, &inputs)?;
}
}
let mut locals = inputs;
locals.insert(&iteration.item);
for filter in &iteration.filters {
self.expression(caller, filter, &locals)?;
}
for row in &iteration.rows {
let mut locals = locals.clone();
for pattern in row
.conditions
.iter()
.flat_map(|condition| &condition.alternatives)
{
if let ast::Pattern::Variant(_, bindings) = pattern {
locals.extend(bindings.iter().map(String::as_str));
}
}
if let Some((guard, _)) = &row.guard {
self.expression(caller, guard, &locals)?;
}
if let Some(sort) = &row.sort {
self.expression(caller, sort, &locals)?;
}
if let Some(value) = &row.value {
if let Some(fold) = &row.fold {
locals.insert(&fold.accumulator);
}
self.expression(caller, value, &locals)?;
}
}
Ok(())
}
fn expression(
&mut self,
caller: usize,
root: &'a Expression,
locals: &HashSet<&'a str>,
) -> Result<(), Diagnostic> {
let mut pending = vec![root];
while let Some(expression) = pending.pop() {
match &expression.kind {
ExpressionKind::Rule(rule) => self.rule_calls(caller, rule, locals)?,
ExpressionKind::Loop(l) => self.loop_calls(caller, l, locals.clone())?,
ExpressionKind::Call(target, arguments) => {
let static_arguments =
self.call(caller, expression, target, arguments, locals)?;
pending.extend(arguments.iter().enumerate().filter_map(|(index, value)| {
(!static_arguments.contains(&index)).then_some(value)
}));
}
ExpressionKind::Field(value, _)
| ExpressionKind::Unary(_, value)
| ExpressionKind::Channel(_, value) => pending.push(value),
ExpressionKind::Binary(_, left, right) => {
pending.extend([left.as_ref(), right.as_ref()])
}
ExpressionKind::List(values) => pending.extend(values),
ExpressionKind::Map(values) => {
for (key, value) in values {
pending.extend([key, value]);
}
}
ExpressionKind::Record(_, values) => {
pending.extend(values.iter().map(|(_, value)| value))
}
ExpressionKind::Name(name) if self.bindings[caller].contains_key(name) => {
return Err(Diagnostic::new(
"C005",
"handler parameters can only be called or forwarded as static arguments",
expression.span,
));
}
ExpressionKind::Literal(_) | ExpressionKind::Name(_) => {}
}
}
Ok(())
}
fn call(
&mut self,
caller: usize,
expression: &'a Expression,
target: &'a Expression,
arguments: &'a [Expression],
locals: &HashSet<&str>,
) -> Result<Vec<usize>, Diagnostic> {
let Some(name) = target.path() else {
return Ok(Vec::new());
};
let bound = self.bindings[caller].get(&name).copied();
let (target_index, static_arguments) = if let Some(target) = bound {
(target, Vec::new())
} else {
let module = &self.modules[expression.span.source];
let Some(&template) = self.names.get(&module.reference(&name)) else {
if matches!(
name.as_str(),
"dever.system.httpServe"
| "dever.system.httpServeTls"
| "dever.system.httpServeLive"
| "dever.system.httpServeLiveTls"
) && let Some(route) = arguments.first()
{
let target = self.named(caller, route, locals)?;
let bound = route
.path()
.is_some_and(|name| self.bindings[caller].contains_key(&name));
self.edge(caller, target, route.span, route.span, bound, Vec::new());
return Ok(vec![0]);
}
if name == "timeout"
&& let [_, _, fallback] = arguments
{
let target = self.named(caller, fallback, locals)?;
let bound = fallback
.path()
.is_some_and(|name| self.bindings[caller].contains_key(&name));
self.edge(
caller,
target,
fallback.span,
fallback.span,
bound,
Vec::new(),
);
return Ok(vec![2]);
}
// 内建调用和构造器由表达式类型检查解析,不伪造函数边。
return Ok(Vec::new());
};
self.application(caller, template, arguments, locals, expression.span)?
};
self.access(expression.span.source, target_index, expression.span)?;
self.edge(
caller,
target_index,
expression.span,
target.span,
bound.is_some(),
static_arguments.clone(),
);
Ok(static_arguments)
}
pub(super) fn edge(
&mut self,
caller: usize,
target: usize,
span: Span,
site: Span,
through_handler: bool,
static_arguments: Vec<usize>,
) {
let edge = self.graph.edges.len();
self.graph.outgoing[caller].push(edge);
self.graph.incoming[target].push(edge);
self.graph.by_span.insert((caller, span), edge);
self.graph.edges.push(Call {
caller,
target,
span,
site,
through_handler,
static_arguments,
});
}
fn application(
&mut self,
caller: usize,
template: usize,
arguments: &'a [Expression],
locals: &HashSet<&str>,
span: Span,
) -> Result<(usize, Vec<usize>), Diagnostic> {
let source = self.templates[template];
if source.inputs.len() != arguments.len() {
return Err(Diagnostic::new(
"C005",
"function argument count differs",
span,
));
}
let mut targets = Vec::new();
let mut static_arguments = Vec::new();
for (position, parameter) in source.inputs.iter().enumerate() {
if parameter.kind.handler.is_none() {
continue;
}
let argument = &arguments[position];
let target = self.named(caller, argument, locals)?;
targets.push(target);
static_arguments.push(position);
self.graph.contracts[caller].push(Contract {
target,
parameter,
span: argument.span,
forwarded: argument
.path()
.is_some_and(|name| self.bindings[caller].contains_key(&name)),
});
}
Ok((self.instance(template, targets), static_arguments))
}
fn named(
&mut self,
caller: usize,
value: &'a Expression,
locals: &HashSet<&str>,
) -> Result<usize, Diagnostic> {
let name = value.path().ok_or_else(|| {
Diagnostic::new(
"C005",
"handler must be a statically named function or handler parameter",
value.span,
)
})?;
if let Some(&target) = self.bindings[caller].get(&name) {
return Ok(target);
}
if locals.contains(name.as_str()) {
return Err(Diagnostic::new(
"C005",
"runtime values cannot be handlers",
value.span,
));
}
let module = &self.modules[value.span.source];
let &template = self
.names
.get(&module.reference(&name))
.ok_or_else(|| Diagnostic::new("C004", "unknown handler target", value.span))?;
if self.templates[template]
.inputs
.iter()
.any(|field| field.kind.handler.is_some())
{
return Err(Diagnostic::new(
"C005",
"a handler target cannot require unbound static parameters",
value.span,
));
}
let target = self.instance(template, Vec::new());
self.access(value.span.source, target, value.span)?;
Ok(target)
}
fn access(&self, source: usize, target: usize, span: Span) -> Result<(), Diagnostic> {
let target_source = self.graph.functions[target].span.source;
let module = &self.modules[source];
let target_module = &self.modules[self
.graph
.ports
.get(&target)
.map_or(target_source, |port| port.span.source)];
if module.can_call(target_module)
&& (module.role != Role::Adapter
|| source == target_source
|| target_module.bundled_library())
{
return Ok(());
}
let mut error = Diagnostic::new(
"C003",
format!(
"{} cannot call {}",
module.identity(),
self.graph.source_names[target]
),
span,
);
error.related.push((
self.graph.functions[target].span,
"target definition".into(),
));
Err(error)
}
}
+251
View File
@@ -0,0 +1,251 @@
//! 常量在编译期解析为具体标量。引用沿用角色边界,不把文件加载顺序变成初始化顺序。
mod settings;
use super::{calls, types::Types, value::Checker};
use crate::compiler::{
model::*,
project::{Module, Role},
};
use crate::syntax::{
ast,
diagnostic::Diagnostic,
names::{self, Style},
source::Span,
};
use std::collections::{BTreeSet, HashMap, HashSet};
pub struct Constants<'a> {
pub settings: Vec<Setting>,
setting_names: HashMap<String, usize>,
pub values: Vec<Option<Constant>>,
names: HashMap<String, usize>,
modules: &'a [Module],
}
pub(super) fn analyze<'a>(
declarations: &[ast::Declaration],
modules: &'a [Module],
types: &Types<'_>,
calls: &calls::Calls<'_>,
) -> (Constants<'a>, Vec<Diagnostic>) {
let setting_declarations = declarations;
let declarations = declarations
.iter()
.filter_map(|item| match item {
ast::Declaration::Constant(value) => Some(value),
_ => None,
})
.collect::<Vec<_>>();
let identities = declarations
.iter()
.map(|value| modules[value.span.source].qualify(&value.name))
.collect::<Vec<_>>();
let mut constants = Constants {
settings: Vec::new(),
setting_names: HashMap::new(),
values: (0..declarations.len()).map(|_| None).collect(),
names: HashMap::new(),
modules,
};
let mut diagnostics = Vec::new();
let mut invalid = HashSet::new();
for (index, value) in declarations.iter().enumerate() {
if let Some(previous) = constants.names.insert(identities[index].clone(), index) {
let mut error = Diagnostic::new("C001", "duplicate constant", value.span);
error
.related
.push((declarations[previous].span, "first declaration".into()));
diagnostics.push(error);
invalid.extend([previous, index]);
}
if calls.by_name.contains_key(&identities[index]) {
diagnostics.push(Diagnostic::new(
"C001",
"constant and function cannot share a name",
value.span,
));
invalid.insert(index);
}
}
diagnostics.extend(settings::analyze(
setting_declarations,
&mut constants,
types,
calls,
));
let mut edges = vec![Vec::new(); declarations.len()];
for (index, value) in declarations.iter().enumerate() {
if let Some(path) = value.value.path()
&& let Some(&target) = constants
.names
.get(&modules[value.span.source].reference(&path))
{
edges[index].push((target, value.value.span));
let previous = declarations[target];
if previous.span.source == value.span.source && previous.span.start > value.span.start {
diagnostics.push(Diagnostic::new(
"C004",
"constant must reference a preceding declaration in the same file",
value.value.span,
));
invalid.insert(index);
}
}
}
let (order, cycle) = calls::partial_order(&edges, &identities, "cyclic constant references");
diagnostics.extend(cycle);
for index in order {
if invalid.contains(&index) {
continue;
}
match check(
declarations[index],
&identities[index],
&constants,
types,
calls,
) {
Ok(value) => constants.values[index] = Some(value),
Err(error) => diagnostics.push(error),
}
}
(constants, diagnostics)
}
fn check(
declaration: &ast::Constant,
name: &str,
constants: &Constants<'_>,
types: &Types<'_>,
calls: &calls::Calls<'_>,
) -> Result<Constant, Diagnostic> {
names::validate(&declaration.name, Style::Value, declaration.span)?;
if !matches!(
constants.modules[declaration.span.source].role,
Role::App | Role::Domain | Role::Adapter
) {
return Err(Diagnostic::new(
"C003",
"constants belong in app, domain or adapter",
declaration.span,
));
}
let value = &declaration.value;
let literal = matches!(value.kind, ast::ExpressionKind::Literal(_))
|| matches!(&value.kind, ast::ExpressionKind::Unary(operation, inner) if operation == "-" && matches!(inner.kind, ast::ExpressionKind::Literal(ast::Literal::Number(_))));
if !literal && value.path().is_none() {
return Err(Diagnostic::new(
"C005",
"const requires a scalar literal or a constant reference",
value.span,
));
}
let mut checker = Checker {
constants,
constant_references: Vec::new(),
test_settings: false,
setting_references: Vec::new(),
allow_settings: false,
caller: 0,
unknown_failures: false,
types,
calls,
functions: &[],
locals: Vec::new(),
names: HashMap::new(),
ranges: HashMap::new(),
bools: HashMap::new(),
variants: HashMap::new(),
failures: BTreeSet::new(),
contracts: HashMap::new(),
};
let mut value = if let Some(kind) = &declaration.kind {
let field = ast::Field {
modifiers: Vec::new(),
name: declaration.name.clone(),
kind: kind.clone(),
private: false,
span: declaration.span,
};
let fields = types.fields(&[field])?;
checker.field_value(value, &fields[0])?
} else {
checker.expression(value, None)?
};
let kind = match &value.value_type {
Type::Optional(inner) => inner.as_ref(),
other => other,
};
let scalar = match kind {
Type::Bool | Type::Int | Type::Float | Type::Decimal | Type::Text => true,
Type::Named(index) => {
matches!(&types.definitions[*index].shape, Shape::Choice(variants) if variants.iter().all(|v| v.fields.is_empty()))
}
_ => false,
};
if !scalar {
return Err(Diagnostic::new(
"C005",
"const requires a concrete scalar type or a payload-free choice",
declaration.span,
));
}
// 内部只保留已解析值;Decimal 生成固定字节,文本只读使用静态字面量。
normalize(&mut value, declaration.value.span);
Ok(Constant {
name: name.into(),
value,
span: declaration.span,
references: checker.constant_references,
})
}
fn normalize(value: &mut Expression, span: Span) {
value.span = span;
match &mut value.kind {
ExpressionKind::Some(inner) => normalize(inner, span),
ExpressionKind::DecimalFromInt(inner) => {
let ExpressionKind::Number(numeric::Number::Int(number)) = inner.kind else {
unreachable!("constant integer")
};
value.kind =
ExpressionKind::Number(numeric::Number::Decimal(dec::Decimal128::from(number)));
}
_ => {}
}
}
impl Checker<'_> {
pub(super) fn constant(
&mut self,
name: &str,
span: Span,
) -> Result<Option<Expression>, Diagnostic> {
let module = &self.constants.modules[span.source];
let Some(&index) = self.constants.names.get(&module.reference(name)) else {
return Ok(None);
};
let value = self.constants.values[index].as_ref().ok_or_else(|| {
Diagnostic::new("C004", "reference depends on an invalid constant", span)
})?;
if !module.can_call(&self.constants.modules[value.span.source]) {
return Err(Diagnostic::new(
"C003",
"application role cannot access this constant",
span,
));
}
let kind = match &value.value.value_type {
Type::Optional(inner) => inner.as_ref(),
other => other,
};
if let Type::Named(definition) = kind {
self.types.access(*definition, span)?;
}
self.constant_references.push((index, span));
let mut expression = value.value.clone();
normalize(&mut expression, span);
Ok(Some(expression))
}
}
@@ -0,0 +1,166 @@
//! 配置声明只建立一次边界合同;读取保留来源,供领域依赖、导航和隐藏参数分析使用。
use super::*;
pub(super) fn analyze(
declarations: &[ast::Declaration],
constants: &mut Constants<'_>,
types: &Types<'_>,
calls: &calls::Calls<'_>,
) -> Vec<Diagnostic> {
let mut diagnostics = Vec::new();
let fields = declarations
.iter()
.filter_map(ast::Declaration::setting)
.collect::<Vec<_>>();
let mut keys = HashMap::new();
let mut invalid = HashSet::new();
for field in &fields {
let module = &constants.modules[field.span.source];
let key = format!(
"{}.{}.{}.{}.{}",
if field.private { "adapter" } else { "module" },
module.component,
module.domain,
if field.private {
module.topic.as_deref().unwrap_or("")
} else {
""
},
field.name
);
if let Some(previous) = keys.insert(key, field.span) {
let mut error = Diagnostic::new("C001", "duplicate domain setting", field.span);
error.related.push((previous, "first declaration".into()));
diagnostics.push(error);
invalid.extend([previous, field.span]);
}
}
for field in fields {
if invalid.contains(&field.span) {
continue;
}
let module = &constants.modules[field.span.source];
let name = module.qualify(&field.name);
let checked = (|| {
names::validate(&field.name, Style::Value, field.span)?;
if (field.private && module.role != Role::Adapter)
|| (!field.private && !matches!(module.role, Role::App | Role::Domain))
{
return Err(Diagnostic::new(
"C003",
"setting { ... } belongs in adapter; named settings belong in app or domain",
field.span,
));
}
if constants.names.contains_key(&name) || calls.by_name.contains_key(&name) {
return Err(Diagnostic::new(
"C001",
"setting cannot share a name with a constant or function",
field.span,
));
}
let field = types.fields(std::slice::from_ref(&field))?.remove(0);
allowed(&field.kind, &types.definitions, field.span)?;
Ok(field)
})();
match checked {
Ok(field) => {
constants
.setting_names
.insert(name.clone(), constants.settings.len());
constants.settings.push(Setting {
adapter: module.role == Role::Adapter,
name,
component: module.component.clone(),
domain: module.domain.clone(),
field,
});
}
Err(error) => diagnostics.push(error),
}
}
diagnostics
}
fn allowed(kind: &Type, definitions: &[Definition], span: Span) -> Result<(), Diagnostic> {
let mut pending = vec![kind];
let mut seen = HashSet::new();
while let Some(kind) = pending.pop() {
match kind {
Type::Bool
| Type::Int
| Type::Float
| Type::Decimal
| Type::Text
| Type::Secret
| Type::Uuid
| Type::Id
| Type::DateTime
| Type::Date
| Type::Time
| Type::Duration => {}
Type::Optional(inner) | Type::List(inner) => pending.push(inner),
Type::Named(index) if seen.insert(*index) => match &definitions[*index].shape {
Shape::Record(fields) => pending.extend(fields.iter().map(|field| &field.kind)),
Shape::Choice(variants)
if variants.iter().all(|v| !v.error && v.fields.is_empty()) => {}
_ => {
return Err(Diagnostic::new(
"C005",
"setting requires a plain record or payload-free non-error choice",
span,
));
}
},
Type::Named(_) => {}
_ => {
return Err(Diagnostic::new(
"C005",
"setting requires a concrete configuration value type",
span,
));
}
}
}
Ok(())
}
impl Checker<'_> {
pub(in crate::compiler::check) fn setting(
&mut self,
name: &str,
span: Span,
) -> Result<Option<Expression>, Diagnostic> {
let module = &self.constants.modules[span.source];
let Some(&index) = self.constants.setting_names.get(&module.reference(name)) else {
return Ok(None);
};
if !self.allow_settings {
return Err(Diagnostic::new("C005", "const cannot read setting", span));
}
let setting = &self.constants.settings[index];
if !module.can_call(&self.constants.modules[setting.field.span.source]) {
return Err(Diagnostic::new(
"C003",
"application role cannot access this setting",
span,
));
}
let mut kind = &setting.field.kind;
while let Type::Optional(inner) | Type::List(inner) = kind {
kind = inner;
}
if let Type::Named(definition) = kind {
self.types.access(*definition, span)?;
}
self.setting_references.push((index, span));
Ok(Some(Expression {
kind: ExpressionKind::Setting(index),
value_type: setting.field.kind.clone(),
range: setting.field.guaranteed_range(),
known_bool: None,
span,
}))
}
}
+232
View File
@@ -0,0 +1,232 @@
//! 领域依赖统一包含调用、签名和构造类型;互不递归的函数也不能组成领域环。
use super::calls;
use crate::compiler::{model::*, project::Module};
use crate::syntax::{diagnostic::Diagnostic, source::Span};
use std::collections::{BTreeMap, HashMap};
pub(super) fn analyze(
definitions: &[Definition],
functions: &[Option<Function>],
constants: &[Option<Constant>],
settings: &[Setting],
modules: &[Module],
calls: &calls::Calls<'_>,
) -> (std::collections::HashSet<usize>, Option<Diagnostic>) {
let mut names = Vec::new();
let mut domains = HashMap::new();
let sources = modules
.iter()
.map(|module| {
let name = format!("{}.{}", module.component, module.domain);
*domains.entry(name.clone()).or_insert_with(|| {
let index = names.len();
names.push(name);
index
})
})
.collect::<Vec<_>>();
let mut edges = vec![BTreeMap::new(); names.len()];
let mut add = |source: usize, target: usize, span: Span| {
if sources[source] != sources[target] {
edges[sources[source]]
.entry(sources[target])
.or_insert(span);
}
};
for call in &calls.edges {
if !call.through_handler {
add(
call.span.source,
calls.functions[call.target].span.source,
call.span,
);
}
}
for bindings in &calls.contracts {
for binding in bindings.iter().filter(|binding| !binding.forwarded) {
add(
binding.span.source,
calls.functions[binding.target].span.source,
binding.span,
);
}
}
for definition in definitions {
if definition.span.is_none() {
continue;
}
let fields = match &definition.shape {
Shape::Record(fields) => fields.iter().collect::<Vec<_>>(),
Shape::Choice(variants) => variants
.iter()
.flat_map(|variant| &variant.fields)
.collect(),
};
for field in fields {
types(&field.kind, field.span, definitions, &mut add);
}
}
for setting in settings {
types(
&setting.field.kind,
setting.field.span,
definitions,
&mut add,
);
}
for function in functions.iter().flatten() {
for (target, span) in &function.setting_references {
add(span.source, settings[*target].field.span.source, *span);
}
for (target, span) in &function.constant_references {
add(
span.source,
constants[*target]
.as_ref()
.expect("checked constant")
.span
.source,
*span,
);
}
for field in function
.signature
.inputs
.iter()
.chain(&function.signature.outputs)
.chain(&function.locals)
{
types(&field.kind, field.span, definitions, &mut add);
}
let mut expressions = Vec::new();
match &function.body {
Body::Contract => {}
Body::Dispatch(dispatch) => {
expressions.extend(dispatch.variants.iter().map(|v| &v.call))
}
Body::Statements { statements, .. } => {
for statement in statements {
match statement {
Statement::Assign { value, .. } | Statement::Action(value) => {
expressions.push(value)
}
Statement::Check { condition, error } => {
expressions.extend([condition, error])
}
Statement::NonNull { value, error, .. } => {
expressions.extend([value, error])
}
}
}
}
Body::Rule(rows) => expressions.extend(rows.iter().flat_map(|row| &row.results)),
Body::Loop(iteration) => expressions.extend(iteration.expressions()),
}
while let Some(expression) = expressions.pop() {
types(
&expression.value_type,
expression.span,
definitions,
&mut add,
);
use ExpressionKind::*;
match &expression.kind {
Call(_, arguments) => expressions.extend(arguments),
Field(value, _)
| Some(value)
| Unary(_, value)
| DecimalFromInt(value)
| Fail(value) => expressions.push(value),
Binary(_, left, right) | UpdateField(left, _, right) => {
expressions.extend([left.as_ref(), right.as_ref()])
}
Builtin(_, values) | List(values) | Variant(_, _, values) => {
expressions.extend(values)
}
Record(_, fields) => expressions.extend(fields.iter().map(|(_, value)| value)),
Map {
entries: values, ..
} => {
for (key, value) in values {
expressions.extend([key, value]);
}
}
Capture(capture) => expressions.push(&capture.call),
_ => {}
}
}
}
for constant in constants.iter().flatten() {
for (target, span) in &constant.references {
add(
span.source,
constants[*target]
.as_ref()
.expect("checked constant")
.span
.source,
*span,
);
}
types(
&constant.value.value_type,
constant.span,
definitions,
&mut add,
);
}
let edges = edges
.into_iter()
.map(|edges| edges.into_iter().collect())
.collect::<Vec<_>>();
let (order, error) = calls::partial_order(
&edges,
&names,
"cyclic domain dependencies through calls or types",
);
let mut blocked = vec![true; names.len()];
for domain in order {
blocked[domain] = false;
}
let excluded = sources
.iter()
.enumerate()
.filter_map(|(source, domain)| blocked[*domain].then_some(source))
.collect();
(excluded, error)
}
fn types(
kind: &Type,
span: Span,
definitions: &[Definition],
add: &mut impl FnMut(usize, usize, Span),
) {
let mut pending = vec![kind];
while let Some(kind) = pending.pop() {
match kind {
Type::ModelId(source) => add(span.source, *source, span),
Type::Named(index) => {
if let Some(origin) = definitions[*index].span {
add(span.source, origin.source, span);
} else if let Shape::Choice(variants) = &definitions[*index].shape {
pending.extend(
variants
.iter()
.flat_map(|variant| variant.fields.iter().map(|field| &field.kind)),
);
}
}
Type::Optional(inner)
| Type::List(inner)
| Type::Channel(inner)
| Type::AsyncStream(inner)
| Type::Stream(inner) => pending.push(inner),
Type::Map(key, value) | Type::MapEntry(key, value) => {
pending.extend([key.as_ref(), value.as_ref()])
}
_ => {}
}
}
}
+330
View File
@@ -0,0 +1,330 @@
//! 在调用图的依赖顺序中检查真实效果;普通计算与表格参数不能隐藏外部动作。
use crate::compiler::{
model::*,
project::{Module, Role},
};
use crate::syntax::diagnostic::Diagnostic;
pub(super) fn check(
body: &Body,
module: &Module,
functions: &[Option<Function>],
transaction: bool,
) -> Result<Effects, Diagnostic> {
let mut checker = Check {
transaction,
functions,
effects: Effects::default(),
blocking_site: None,
};
let allowed = matches!(module.role, Role::App | Role::Adapter | Role::Test);
match body {
Body::Contract => {}
Body::Dispatch(dispatch) => {
for variant in &dispatch.variants {
checker.expression(&variant.call, true)?;
}
}
Body::Statements {
statements, flow, ..
} => {
if let Some(rows) = flow {
for (statement, row) in statements.iter().zip(rows) {
if row.parallel.is_some() && statement.value().effects(functions).database {
if transaction {
return Err(Diagnostic::new(
"C013",
"transaction cannot access its connection concurrently",
row.span,
));
}
checker.effects.concurrent_database = true;
}
}
}
for statement in statements {
match statement {
Statement::Assign { value, .. } | Statement::Action(value) => {
checker.expression(value, allowed && flow.is_some())?;
}
Statement::Check { condition, error } => {
checker.expression(condition, false)?;
checker.expression(error, false)?;
}
Statement::NonNull { value, error, .. } => {
checker.expression(value, false)?;
checker.expression(error, false)?;
}
}
}
}
Body::Rule(rows) => {
for value in rows.iter().flat_map(|row| &row.results) {
checker.expression(value, allowed)?;
}
}
Body::Loop(iteration) => checker.iteration(iteration, allowed)?,
}
if matches!(body,Body::Loop(iteration) if iteration.parallel.is_some())
&& checker.effects.database
{
checker.effects.concurrent_database = true;
}
if checker.effects.blocking && checker.effects.suspends {
return Err(Diagnostic::new(
"C013",
"suspending code must place synchronous blocking calls inside blocking(...)",
checker.blocking_site.expect("blocking effect has a source"),
));
}
Ok(checker.effects)
}
pub(super) fn pure(value: &Expression, functions: &[Option<Function>]) -> Result<(), Diagnostic> {
Check {
transaction: false,
functions,
effects: Effects::default(),
blocking_site: None,
}
.expression(value, false)
}
struct Check<'a> {
transaction: bool,
functions: &'a [Option<Function>],
effects: Effects,
blocking_site: Option<crate::syntax::source::Span>,
}
impl Check<'_> {
fn iteration(&mut self, iteration: &Loop, allowed: bool) -> Result<(), Diagnostic> {
if let Some(limit) = &iteration.parallel {
self.expression(limit, false)?;
if !allowed {
return Err(Diagnostic::new(
"C013",
"parallel loop belongs in app/adapter",
limit.span,
));
}
self.effects.suspends = true;
}
match &iteration.source {
LoopSource::Stream(value) | LoopSource::SyncStream(value) => {
if self.transaction {
return Err(Diagnostic::new(
"C013",
"transaction flow cannot consume a stream",
value.span,
));
}
self.expression(value, allowed)?;
if !allowed {
return Err(Diagnostic::new(
"C013",
"stream consumption belongs in app/adapter",
value.span,
));
}
self.effects.stream = true;
if matches!(iteration.source, LoopSource::Stream(_)) {
self.effects.suspends = true;
} else {
self.effects.file = true;
self.effects.blocking = true;
self.blocking_site.get_or_insert(value.span);
}
}
LoopSource::List(value) | LoopSource::Bytes(value) => {
self.expression(value, allowed)?
}
LoopSource::Range(start, end) => {
self.expression(start, false)?;
self.expression(end, false)?;
}
LoopSource::Walk { seed, update, .. } => {
self.expression(seed, false)?;
self.expression(update, allowed)?;
}
}
for row in &iteration.rows {
if let Some(fold) = &row.fold {
self.expression(&fold.seed, false)?;
}
if let Some(value) = &row.value {
self.expression(value, allowed)?;
}
}
Ok(())
}
fn expression(&mut self, value: &Expression, allowed: bool) -> Result<(), Diagnostic> {
let effects = value.effects(self.functions);
if self.transaction {
// 读时钟可用于同一事务的时间字段;等待、随机和其他外部效果不能藏在子调用中。
if !effects.transaction_safe() {
let mut error = Diagnostic::new(
"C013",
"transaction flow cannot perform external I/O, wait, spawn tasks or compute passwords",
value.span,
);
if let ExpressionKind::Call(target, _) = value.kind {
error.related.push((
self.functions[target].as_ref().unwrap().signature.span,
"effectful target in transaction".into(),
));
}
return Err(error);
}
}
if effects.blocking {
self.blocking_site.get_or_insert(value.span);
}
if !allowed && !effects.pure() {
let mut error = Diagnostic::new(
"C013",
"effectful calls require an explicit app/adapter table step or result cell; ordinary functions, arguments, checks, filters and sort keys must be pure",
value.span,
);
if let ExpressionKind::Call(target, _) = value.kind {
error.related.push((
self.functions[target].as_ref().unwrap().signature.span,
"effectful target; its effects include callees and bound handlers".into(),
));
}
return Err(error);
}
self.effects.include(effects);
use ExpressionKind::*;
match &value.kind {
// 捕获只改变失败出口;可空/数值提升是编译器转换,不是隐藏调用。
Rule { rows, .. } => {
for r in rows {
self.expression(&r.results[0], allowed)?;
}
}
Loop(l) => self.iteration(l, allowed)?,
Capture(capture) => self.expression(&capture.call, allowed)?,
Some(inner) | DecimalFromInt(inner) => self.expression(inner, allowed)?,
Builtin(crate::compiler::model::Builtin::Task(op), arguments) => {
for (index, argument) in arguments.iter().enumerate() {
let nested = matches!(op, TaskOp::Race(_))
|| (index == 0
&& matches!(
op,
TaskOp::Wait(_) | TaskOp::Stop(_) | TaskOp::Timeout { .. }
));
self.expression(argument, allowed && nested)?;
}
}
Builtin(crate::compiler::model::Builtin::Test(TestOp::AssertRow(_)), arguments) => {
self.expression(&arguments[0], allowed)?;
}
Call(_, arguments)
| Builtin(_, arguments)
| Variant(_, _, arguments)
| List(arguments) => {
for argument in arguments {
self.expression(argument, false)?;
}
}
Field(inner, _) | Unary(_, inner) | Fail(inner) => self.expression(inner, false)?,
Binary(_, left, right) | UpdateField(left, _, right) => {
self.expression(left, false)?;
self.expression(right, false)?;
}
Record(_, fields) => {
for (_, value) in fields {
self.expression(value, false)?;
}
}
Map { entries, .. } => {
for (key, value) in entries {
self.expression(key, false)?;
self.expression(value, false)?;
}
}
Number(_)
| Text(_)
| QuerySql { .. }
| JsonLiteral { .. }
| Bool(_)
| Null
| ApiError(_)
| Variable(_)
| Setting(_) => {}
}
Ok(())
}
}
/// long 入口中写库必须属于显式事务;沿已绑定调用图检查,handler 也不能绕过。
pub(super) fn long_entry(
root: usize,
functions: &[Option<Function>],
span: crate::syntax::source::Span,
) -> Result<(), Diagnostic> {
let mut pending = vec![root];
let mut seen = std::collections::HashSet::new();
while let Some(index) = pending.pop() {
if !seen.insert(index) {
continue;
}
let function = functions[index].as_ref().unwrap();
if function.transaction {
continue;
}
let expressions = match &function.body {
Body::Statements { statements, .. } => {
statements.iter().map(Statement::value).collect::<Vec<_>>()
}
Body::Rule(rows) => rows.iter().flat_map(|row| &row.results).collect(),
Body::Loop(iteration) => iteration.expressions().collect(),
Body::Contract => Vec::new(),
Body::Dispatch(dispatch) => dispatch.variants.iter().map(|v| &v.call).collect(),
};
let mut invalid = None;
for expression in expressions {
expression.visit(&mut |value| {
match &value.kind {
ExpressionKind::Call(target, _) => pending.push(*target),
ExpressionKind::Builtin(Builtin::Task(op), arguments) => {
pending.extend(op.targets(arguments))
}
ExpressionKind::Builtin(
Builtin::Standard(StandardOp::HttpServe { target, .. }),
_,
) => pending.push(*target),
ExpressionKind::Builtin(
Builtin::Database {
operation:
DatabaseOp::Sql { write: true, .. }
| DatabaseOp::NotifyChange
| DatabaseOp::Create
| DatabaseOp::CreateMany
| DatabaseOp::Upsert(_)
| DatabaseOp::Update(_)
| DatabaseOp::UpdateOne
| DatabaseOp::Delete(_),
..
},
_,
) => invalid = Some(value.span),
ExpressionKind::Builtin(
Builtin::Standard(StandardOp::StageBytes) | Builtin::Enqueue { .. },
_,
) => invalid = Some(value.span),
_ => {}
}
true
});
}
if let Some(site) = invalid {
let mut error =
Diagnostic::new("C013", "long entry writes require a transaction flow", site);
error.related.push((span, "long entry".into()));
return Err(error);
}
}
Ok(())
}
@@ -0,0 +1,391 @@
//! 仅真正返回或处理的值转移义务;短路右侧不能替左侧路径处理错误。
use super::*;
impl State<'_> {
pub(super) fn expression(&mut self, expression: &Expression) -> Result<ErrorValue, Diagnostic> {
self.budget(0)?;
use ExpressionKind::*;
let value = match &expression.kind {
Rule { selectors, rows } => self.rule_value(selectors, rows)?,
Loop(l) => self.iteration(l, 1)?,
Variable(local) => self.values[*local].clone(),
Number(_)
| Text(_)
| QuerySql { .. }
| JsonLiteral { .. }
| Bool(_)
| Null
| ApiError(_)
| Setting(_) => ErrorValue::default(),
Field(base, field) => self
.expression(base)?
.fields
.remove(field)
.unwrap_or_default(),
Some(value) => ErrorValue::variants([(1, self.expression(value)?)]),
Record(_, fields) => ErrorValue::fields(
fields
.iter()
.map(|(index, value)| Ok((*index, self.expression(value)?)))
.collect::<Result<Vec<_>, Diagnostic>>()?,
),
Variant(definition, variant, fields) => {
let fields = ErrorValue::fields(
fields
.iter()
.enumerate()
.map(|(index, value)| Ok((index, self.expression(value)?)))
.collect::<Result<Vec<_>, Diagnostic>>()?,
);
ErrorValue::variants([(*variant, self.variant(*definition, *variant, fields))])
}
List(values) => ErrorValue::sequence(ErrorSequence::Known(
values
.iter()
.map(|value| self.expression(value))
.collect::<Result<_, _>>()?,
)),
Map {
entries: values, ..
} => ErrorValue::sequence(ErrorSequence::Known(
values
.iter()
.map(|(key, value)| {
Ok(ErrorValue::fields([
(0, self.expression(key)?),
(1, self.expression(value)?),
]))
})
.collect::<Result<_, Diagnostic>>()?,
)),
UpdateField(base, field, value) => {
let mut base = self.expression(base)?;
base.fields.insert(*field, self.expression(value)?);
ErrorValue::fields(base.fields)
}
Unary(_, value) | DecimalFromInt(value) => {
self.expression(value)?;
ErrorValue::default()
}
Binary(operation, left, right) => {
self.expression(left)?;
let short = matches!(operation, super::Binary::And | super::Binary::Or);
let skip = matches!(
(operation, left.known_bool),
(super::Binary::And, std::option::Option::Some(false))
| (super::Binary::Or, std::option::Option::Some(true))
);
if !skip {
let before = self.pending.clone();
let was_terminated = self.terminated;
self.expression(right)?;
if short && left.known_bool.is_none() {
self.pending.extend(before);
self.terminated = was_terminated;
}
}
ErrorValue::default()
}
Call(target, arguments) => self.call(*target, arguments, false)?,
Capture(capture) => {
let (success, outputs, can_succeed, unknown_failures) = match &capture.call.kind {
Call(target, arguments) => {
let success = self.call(*target, arguments, true)?;
let function = self.functions[*target].as_ref().expect("checked callee");
(
success,
function.signature.outputs.len(),
function.failure_summary.output.is_some(),
function.unknown_failures,
)
}
Builtin(super::Builtin::Task(operation), arguments) => {
let success = self.task(*operation, arguments, true)?;
let targets = operation.targets(arguments);
let outputs = operation.output_target().map_or(0, |target| {
self.functions[target]
.as_ref()
.unwrap()
.signature
.outputs
.len()
});
let unknown = targets.iter().any(|target| {
self.functions[*target].as_ref().unwrap().unknown_failures
});
(
success,
outputs,
capture.call.value_type != Type::Never,
unknown,
)
}
Builtin(
super::Builtin::Json(JsonOp::Decode(_))
| super::Builtin::Database { .. }
| super::Builtin::Enqueue { .. }
| super::Builtin::JobStates { .. },
arguments,
) => {
for argument in arguments {
self.expression(argument)?;
}
(ErrorValue::default(), 1, true, false)
}
_ => unreachable!("checked captured call"),
};
let mut variants = BTreeMap::new();
if can_succeed {
let fields = match outputs {
0 => ErrorValue::default(),
1 => ErrorValue::fields([(0, success)]),
_ => success,
};
variants.insert(capture.success, fields);
}
// 原型没有具体失败集合,按接收 choice 保留所有错误义务;具体绑定仍逐项核对。
if unknown_failures {
let Shape::Choice(choices) = &self.definitions[capture.definition].shape else {
unreachable!()
};
for index in (0..choices.len()).filter(|index| choices[*index].error) {
variants.insert(index, self.unknown_variant(capture.definition, index, 0)?);
}
}
for (_, variant, _) in &capture.errors {
if let std::collections::btree_map::Entry::Vacant(entry) =
variants.entry(*variant)
{
entry.insert(self.unknown_variant(capture.definition, *variant, 0)?);
}
}
ErrorValue::variants(variants)
}
Fail(value) => {
self.expression(value)?;
self.terminated = true;
ErrorValue::default()
}
Builtin(operation, arguments) => {
self.builtin(operation.clone(), arguments, expression)?
}
};
self.normalize(value)
}
fn call(
&mut self,
target: usize,
arguments: &[Expression],
captured: bool,
) -> Result<ErrorValue, Diagnostic> {
let values = arguments
.iter()
.map(|value| self.expression(value))
.collect::<Result<Vec<_>, _>>()?;
self.call_values(target, &values, captured)
}
pub(super) fn call_values(
&mut self,
target: usize,
values: &[ErrorValue],
captured: bool,
) -> Result<ErrorValue, Diagnostic> {
let function = self.functions[target].as_ref().expect("checked callee");
let mut mapping = BTreeMap::new();
let mut positions = BTreeMap::new();
if let Some(output) = &function.failure_summary.output {
self.positions(output, &mut 0, &mut positions)?;
}
for (template, value) in function.failure_summary.inputs.iter().zip(values) {
self.bind(template, value, &mut mapping, &positions)?;
}
self.pending = self.expand(&self.pending.clone())?;
let interrupted = function
.failure_summary
.interrupted
.iter()
.flat_map(|token| mapping.get(token).into_iter().flatten().copied())
.collect();
let interrupted = self.expand(&interrupted)?;
if !captured && !interrupted.is_empty() {
self.interrupted.extend(&self.pending);
}
for value in values {
let tokens = self.expand(&value.tokens)?;
self.pending.retain(|token| !tokens.contains(token));
}
if captured {
self.pending.extend(interrupted);
}
for tokens in mapping.values_mut() {
*tokens = self.expand(tokens)?;
}
match &function.failure_summary.output {
Some(output) => self.instantiate(output, &mut mapping, 0),
None => {
self.terminated |= !captured;
Ok(ErrorValue::default())
}
}
}
fn builtin(
&mut self,
operation: Builtin,
arguments: &[Expression],
expression: &Expression,
) -> Result<ErrorValue, Diagnostic> {
if let Builtin::Task(operation) = operation {
return self.task(operation, arguments, false);
}
let mut values = arguments
.iter()
.map(|value| self.expression(value))
.collect::<Result<Vec<_>, _>>()?;
if let Builtin::Stream(operation) = operation {
return if operation == StreamOp::New && matches!(arguments[0].value_type, Type::List(_))
{
Ok(values.remove(0))
} else {
self.unknown(&expression.value_type, 0)
};
}
if operation == Builtin::Standard(StandardOp::HttpOpenStream) {
let output = self.unknown(&expression.value_type, 0)?;
// 协议边界接管上传源:已读取的失败转换到打开结果或响应流,
// 调用方仍须处理返回错误,不能因跨过系统操作就清空义务。
for token in &values[1].tokens {
self.splits.insert(*token, output.tokens.clone());
}
return Ok(output);
}
if matches!(operation, Builtin::Worker { .. }) {
return Ok(ErrorValue::default());
}
if matches!(
operation,
Builtin::Json(_)
| Builtin::Calendar(_)
| Builtin::Clock(_)
| Builtin::Channel(_)
| Builtin::Standard(_)
| Builtin::Database { .. }
| Builtin::Enqueue { .. }
| super::Builtin::JobStates { .. }
| Builtin::Command { .. }
| Builtin::Request(_)
| Builtin::Test(_)
| Builtin::Identity(_)
| Builtin::Authorization(_)
| Builtin::Session(_)
| Builtin::ModelInput { .. }
| Builtin::ModelUuid
| Builtin::ModelNow
) {
return self.unknown(&expression.value_type, 0);
}
let collection = values.remove(0);
match operation {
Builtin::Request(_)
| Builtin::Test(_)
| Builtin::Identity(_)
| Builtin::Authorization(_)
| Builtin::Session(_)
| Builtin::Database { .. }
| Builtin::Enqueue { .. }
| super::Builtin::JobStates { .. }
| Builtin::Command { .. }
| Builtin::Worker { .. }
| Builtin::ModelInput { .. }
| Builtin::ModelUuid
| Builtin::ModelNow
| Builtin::Task(_)
| Builtin::Json(_)
| Builtin::Calendar(_)
| Builtin::Clock(_)
| Builtin::Standard(_)
| Builtin::Channel(_) => {
unreachable!("library result handled above")
}
Builtin::Stream(_)
| Builtin::Length
| Builtin::Contains
| Builtin::BytesFromText
| Builtin::BytesAt
| Builtin::BytesConcat => Ok(ErrorValue::default()),
Builtin::BytesFromBase64
| Builtin::BytesToText
| Builtin::BytesFromInts
| Builtin::BytesSlice => self.unknown(&expression.value_type, 0),
Builtin::Entries => Ok(collection),
Builtin::Remove => {
if matches!(&collection.sequence, Some(ErrorSequence::Known(items)) if items.is_empty())
{
Ok(collection)
} else {
// 删除可能丢掉错误;剩余结果不能替原集合解除处理义务。
self.unknown(&expression.value_type, 0)
}
}
Builtin::Put => {
let entry = ErrorValue::fields(values.into_iter().enumerate());
if matches!(&collection.sequence, Some(ErrorSequence::Known(items)) if items.is_empty())
{
return Ok(ErrorValue::sequence(ErrorSequence::Known(vec![entry])));
}
let mut output = self.unknown(&expression.value_type, 0)?;
let mut element = output
.sequence
.take()
.expect("Map failure summary")
.element();
element.merge(&entry);
output = ErrorValue::sequence(ErrorSequence::Unknown(Box::new(element)));
output.guaranteed = entry.guaranteed;
Ok(output)
}
Builtin::Append => {
let next = values.remove(0);
let sequence = match collection.sequence {
Some(ErrorSequence::Known(mut values)) => {
values.push(next);
ErrorSequence::Known(values)
}
Some(ErrorSequence::Unknown(mut value)) => {
value.merge(&next);
ErrorSequence::Unknown(value)
}
// 不含错误的记录不建立字段树,其集合字段也没有错误摘要。
None => return Ok(ErrorValue::default()),
};
Ok(ErrorValue::sequence(sequence))
}
Builtin::Get => {
if let (
Some(ErrorSequence::Known(values)),
ExpressionKind::Number(numeric::Number::Int(index)),
) = (&collection.sequence, &arguments[1].kind)
&& matches!(arguments[0].value_type, Type::List(_))
{
return Ok(
match usize::try_from(*index)
.ok()
.and_then(|index| values.get(index))
{
Some(value) if matches!(&arguments[0].value_type, Type::List(element) if matches!(element.as_ref(), Type::Optional(_))) => {
value.clone()
}
Some(value) => ErrorValue::variants([(1, value.clone())]),
None => ErrorValue::default(),
},
);
}
// 未知下标只取一个元素,不能借此解除整个集合中尚未处理的错误。
self.unknown(&expression.value_type, 0)
}
}
}
}
+233
View File
@@ -0,0 +1,233 @@
//! 累积状态用有限结构归纳:初值和每次更新都进入不动点,不展开运行次数。
use super::*;
#[derive(Clone, Default, PartialEq, Eq)]
pub(super) struct Reachable {
own: bool,
guaranteed: bool,
fields: BTreeMap<usize, Reachable>,
variants: BTreeMap<usize, Reachable>,
element: Option<Box<Reachable>>,
}
impl Reachable {
pub(super) fn of(value: &ErrorValue) -> Self {
let mut nested = value
.fields
.values()
.chain(value.variants.values())
.flat_map(|value| value.tokens.iter().copied())
.collect::<BTreeSet<_>>();
let element = value.sequence.as_ref().map(|sequence| {
let values: Vec<_> = match sequence {
ErrorSequence::Known(values) => values.iter().collect(),
ErrorSequence::Unknown(value) => vec![value.as_ref()],
};
let mut joined = None;
for value in values {
nested.extend(&value.tokens);
let shape = Self::of(value);
if let Some(previous) = &mut joined {
Self::join(previous, &shape);
} else {
joined = Some(shape);
}
}
Box::new(joined.unwrap_or_default())
});
Self {
own: !value.tokens.is_subset(&nested),
guaranteed: value.guaranteed,
fields: value
.fields
.iter()
.map(|(index, value)| (*index, Self::of(value)))
.collect(),
variants: value
.variants
.iter()
.map(|(index, value)| (*index, Self::of(value)))
.collect(),
element,
}
}
pub(super) fn join(&mut self, other: &Self) {
self.own |= other.own;
self.guaranteed &= other.guaranteed;
for (index, value) in &other.fields {
self.fields.entry(*index).or_default().join(value);
}
for (index, value) in &other.variants {
if let Some(previous) = self.variants.get_mut(index) {
previous.join(value);
} else {
self.variants.insert(*index, value.clone());
}
}
if let Some(value) = &other.element {
if let Some(previous) = &mut self.element {
previous.join(value);
} else {
self.element = Some(value.clone());
}
}
}
}
impl State<'_> {
pub(super) fn reachable(
&mut self,
shape: &Reachable,
depth: usize,
) -> Result<ErrorValue, Diagnostic> {
self.budget(depth)?;
let mut value = ErrorValue {
guaranteed: shape.guaranteed,
..ErrorValue::default()
};
if shape.own {
value.tokens.insert(self.token());
}
for (index, field) in &shape.fields {
let field = self.reachable(field, depth + 1)?;
value.tokens.extend(&field.tokens);
value.fields.insert(*index, field);
}
for (index, variant) in &shape.variants {
let variant = self.reachable(variant, depth + 1)?;
value.tokens.extend(&variant.tokens);
value.variants.insert(*index, variant);
}
if let Some(element) = &shape.element {
let element = self.reachable(element, depth + 1)?;
value.tokens.extend(&element.tokens);
value.sequence = Some(ErrorSequence::Unknown(Box::new(element)));
}
Ok(value)
}
pub(super) fn fold(
&mut self,
row: &LoopRow,
seed: &ErrorValue,
) -> Result<ErrorValue, Diagnostic> {
let fold = row.fold.as_ref().expect("checked fold");
let mut invariant = Reachable::of(seed);
let identity = loop {
let mut probe = self.clone();
let input = probe.reachable(&invariant, 0)?;
probe.values[fold.accumulator] = input.clone();
let updated = probe.fold_update(row)?;
let input = probe.normalize(input)?;
probe.pending = probe.expand(&probe.pending.clone())?;
// 每个可能到达的位置独立带义务;不能用本轮新错误的别名代替上一轮。
if !probe.terminated
&& !updated.guaranteed
&& !input
.tokens
.intersection(&probe.pending)
.all(|token| updated.tokens.contains(token))
{
return Err(Diagnostic::new(
"C012",
"fold update may discard an earlier accumulator failure",
row.span,
));
}
self.work = probe.work;
let mut next = invariant.clone();
if !probe.terminated {
next.join(&Reachable::of(&updated));
}
if next == invariant {
break input == updated;
}
invariant = next;
};
let mut initial = self.clone();
initial.values[fold.accumulator] = seed.clone();
initial.pending.extend(&seed.tokens);
let first = initial.fold_update(row)?;
let identity = identity && first == initial.normalize(seed.clone())?;
self.work = initial.work;
let input = self.reachable(&invariant, 0)?;
self.values[fold.accumulator] = input.clone();
let updated = self.fold_update(row)?;
let expanded = self.normalize(input.clone())?;
self.pending = self.expand(&self.pending.clone())?;
self.pending
.retain(|token| !expanded.tokens.contains(token) && !updated.tokens.contains(token));
if identity || self.terminated {
self.normalize(seed.clone())
} else {
self.fold_origins(&input, &updated, seed)
}
}
fn fold_origins(
&mut self,
input: &ErrorValue,
updated: &ErrorValue,
seed: &ErrorValue,
) -> Result<ErrorValue, Diagnostic> {
let seed = self.normalize(seed.clone())?;
let mut initial = BTreeMap::new();
let mut transfer = BTreeMap::new();
let mut owners = BTreeMap::new();
// 每个状态位置只有一个原型身份;用现有字段绑定取得初值和更新的来源。
self.bind(input, &seed, &mut initial, &BTreeMap::new())?;
self.bind(input, updated, &mut transfer, &BTreeMap::new())?;
for token in &input.tokens {
for leaf in self.expand(&[*token].into())? {
owners.insert(leaf, *token);
}
}
let mut origins = initial.clone();
loop {
let mut next = initial.clone();
for (position, values) in &transfer {
for token in values {
self.budget(0)?;
let sources = if let Some(owner) = owners.get(token) {
origins[owner].clone()
} else {
[*token].into()
};
next.get_mut(position).unwrap().extend(sources);
}
}
if origins == next {
break;
}
origins = next;
}
let mut mapping = BTreeMap::new();
let mut aliases: BTreeMap<usize, BTreeSet<usize>> = BTreeMap::new();
for (position, sources) in origins {
let mut tokens = BTreeSet::new();
for source in sources {
self.budget(0)?;
let token = self.token();
tokens.insert(token);
// 初值总会进入结果或被更新明确处理;保留其别名。每轮新错误仍独立,
// 不让短路结果或空遍历冒充处理了来源/捕获参数中的全部错误。
if seed.tokens.contains(&source) {
aliases.entry(source).or_default().insert(token);
}
}
mapping.insert(position, tokens);
}
self.splits.extend(aliases);
self.instantiate(input, &mut mapping, 0)
}
fn fold_update(&mut self, row: &LoopRow) -> Result<ErrorValue, Diagnostic> {
let mut value = self.expression(row.value.as_ref().expect("fold update"))?;
if row.aggregate == Aggregate::FoldUntil && !self.terminated {
value = value.fields.remove(&0).expect("checked acc output");
}
Ok(value)
}
}
@@ -0,0 +1,223 @@
//! 单次元素摘要证明整遍处理;短路输出不能替尚未消费的元素解除错误义务。
use super::*;
impl State<'_> {
pub(super) fn iteration(
&mut self,
iteration: &Loop,
outputs: usize,
) -> Result<ErrorValue, Diagnostic> {
let source = match &iteration.source {
LoopSource::Walk {
seed,
state,
update,
..
} => self.walk(seed, *state, update, &iteration.rows)?,
LoopSource::List(value) | LoopSource::Bytes(value) | LoopSource::Stream(value) => {
self.expression(value)?
}
LoopSource::SyncStream(value) => {
self.expression(value)?;
// 文件流的错误在拉取时才产生;关闭或 take=0 不制造未来的读取错误。
if self.terminated || iteration.rows.iter().all(LoopRow::takes_none) {
ErrorValue::default()
} else {
let Type::Stream(item) = &value.value_type else {
unreachable!("checked synchronous stream")
};
ErrorValue::sequence(ErrorSequence::Unknown(Box::new(self.unknown(item, 0)?)))
}
}
LoopSource::Range(start, end) => {
self.expression(start)?;
self.expression(end)?;
ErrorValue::default()
}
};
if self.terminated {
return Ok(ErrorValue::default());
}
if let Some(limit) = &iteration.parallel {
self.expression(limit)?;
}
let element = source
.sequence
.as_ref()
.map(ErrorSequence::element)
.unwrap_or_default();
self.values[iteration.item] = element.clone();
let mut seeds = Vec::new();
for row in &iteration.rows {
if let Some(limit) = &row.take {
self.expression(limit)?;
}
let seed = row
.fold
.as_ref()
.map(|fold| self.expression(&fold.seed))
.transpose()?;
if self.terminated {
return Ok(ErrorValue::default());
}
if let Some(seed) = &seed {
self.pending = self.expand(&self.pending.clone())?;
// 初值转交累积状态;空遍历仍直接返回它,非空路径由归纳检查接管。
self.pending.retain(|token| !seed.tokens.contains(token));
}
seeds.push(seed);
}
let mut entry = self.pending.clone();
let mut handled = BTreeSet::new();
let mut values = vec![ErrorValue::default(); outputs];
let empty =
matches!(&source.sequence, Some(ErrorSequence::Known(items)) if items.is_empty());
let terminated = self.terminated;
for (row_index, row) in iteration.rows.iter().enumerate() {
self.values[iteration.item] = element.clone();
if empty || row.takes_none() {
if let Some(seed) = &seeds[row_index] {
values[row.output.unwrap()] = seed.clone();
}
if matches!(
row.aggregate,
Aggregate::List | Aggregate::Group | Aggregate::Index
) {
values[row.output.unwrap()] =
ErrorValue::sequence(ErrorSequence::Known(Vec::new()));
}
continue;
}
self.pending.extend(&entry);
self.terminated = false;
self.iteration_filters(iteration.item, &row.filters)?;
for key in &row.sort {
self.expression(&key.value)?;
}
let value = if let Some(seed) = &seeds[row_index] {
self.fold(row, seed)?
} else {
row.value
.as_ref()
.map(|value| self.expression(value))
.transpose()?
.unwrap_or_default()
};
let value = if let Some(element) = &row.element {
let element = self.expression(element)?;
let element = if row.aggregate == Aggregate::Group {
ErrorValue::sequence(ErrorSequence::Unknown(Box::new(element)))
} else {
element
};
ErrorValue::fields([(0, value), (1, element)])
} else {
value
};
let all_selected = row.filters.iter().all(|filter| matches!(filter.value.kind, ExpressionKind::Variable(local) if local == iteration.item));
entry = self.expand(&entry)?;
handled = self.expand(&handled)?;
self.pending = self.expand(&self.pending.clone())?;
let selected = self.expand(&self.values[iteration.item].tokens.clone())?;
let complete = (!row.short_circuit()
|| (iteration.rows.len() == 1
&& matches!(
iteration.source,
LoopSource::Walk { .. } | LoopSource::SyncStream(_)
))
|| row
.value
.as_ref()
.is_some_and(|value| value.value_type == Type::Never))
&& all_selected;
if complete {
if self.terminated {
handled.extend(&selected);
} else {
handled.extend(selected.difference(&self.pending).copied());
}
}
let value = match row.aggregate {
Aggregate::Fold | Aggregate::FoldUntil => value,
Aggregate::List | Aggregate::Group | Aggregate::Index | Aggregate::First => {
// 原输入中的非元素值在空遍历时仍未处理。短路还可能留有其余元素。
// 只给可能漏掉的输入义务重新编号,新生成的失败仍保留原身份。
let partial = entry
.iter()
.filter(|token| !complete || !selected.contains(token));
let mut mapping = value
.tokens
.iter()
.map(|token| (*token, [*token].into()))
.collect::<BTreeMap<_, BTreeSet<_>>>();
for token in partial {
if value.tokens.contains(token) {
mapping.insert(*token, [self.token()].into());
}
}
let value = self.instantiate(&value, &mut mapping, 0)?;
if matches!(
row.aggregate,
Aggregate::List | Aggregate::Group | Aggregate::Index
) {
ErrorValue::sequence(ErrorSequence::Unknown(Box::new(value)))
} else {
ErrorValue::variants([(0, ErrorValue::default()), (1, value)])
}
}
_ => ErrorValue::default(),
};
if let Some(output) = row.output {
values[output] = value;
}
}
// 遍历可能为空;只有整遍完成的元素处理可以消去来源集合的义务。
self.pending.extend(entry.difference(&handled).copied());
self.pending.retain(|token| !handled.contains(token));
self.terminated = terminated;
Ok(output(values))
}
fn iteration_filters(&mut self, item: usize, filters: &[LoopFilter]) -> Result<(), Diagnostic> {
for filter in filters {
if matches!(filter.value.kind, ExpressionKind::Variable(local) if local == item) {
self.values[item] = narrow(
self.values[item].clone(),
&filter.value.value_type,
filter.fact.as_ref().expect("checked variable filter"),
);
}
let value = self.expression(&filter.value)?;
let value = if matches!(filter.value.value_type, Type::Optional(_)) {
value.variants.get(&1).cloned().unwrap_or_default()
} else {
value
};
for binding in &filter.bindings {
let mut bound = ErrorValue::default();
for pattern in &filter.condition.alternatives {
let Pattern::Variant(index, _) = pattern else {
unreachable!("checked payload condition")
};
if let Some(field) = value
.variants
.get(index)
.and_then(|variant| variant.fields.get(&binding.field))
{
bound.merge(field);
}
}
self.values[binding.local] = bound;
}
if let Some(present) = &filter.present {
self.values[present.local] = self.values[present.input]
.variants
.get(&1)
.cloned()
.unwrap_or_default();
}
}
Ok(())
}
}
+153
View File
@@ -0,0 +1,153 @@
//! 调用摘要保留互斥分支的身份;原值和别名仍覆盖拆分后的全部路径。
use super::*;
impl State<'_> {
pub(super) fn expand(
&mut self,
tokens: &BTreeSet<usize>,
) -> Result<BTreeSet<usize>, Diagnostic> {
let mut pending = tokens.iter().copied().collect::<Vec<_>>();
let mut leaves = BTreeSet::new();
while let Some(token) = pending.pop() {
self.budget(0)?;
if let Some(children) = self.splits.get(&token) {
pending.extend(children);
} else {
leaves.insert(token);
}
}
Ok(leaves)
}
pub(super) fn normalize(&mut self, mut value: ErrorValue) -> Result<ErrorValue, Diagnostic> {
if self.splits.is_empty() {
return Ok(value);
}
value.tokens = self.expand(&value.tokens)?;
for field in value.fields.values_mut().chain(value.variants.values_mut()) {
*field = self.normalize(std::mem::take(field))?;
}
match &mut value.sequence {
Some(ErrorSequence::Known(values)) => {
for value in values {
*value = self.normalize(std::mem::take(value))?;
}
}
Some(ErrorSequence::Unknown(value)) => {
**value = self.normalize(std::mem::take(value))?;
}
None => {}
}
Ok(value)
}
pub(super) fn bind(
&mut self,
template: &ErrorValue,
actual: &ErrorValue,
mapping: &mut BTreeMap<usize, BTreeSet<usize>>,
positions: &BTreeMap<usize, Vec<usize>>,
) -> Result<(), Diagnostic> {
self.budget(0)?;
for token in &template.tokens {
mapping.entry(*token).or_default();
}
let mut nested = template
.fields
.values()
.chain(template.variants.values())
.flat_map(|value| value.tokens.iter().copied())
.collect::<BTreeSet<_>>();
if let Some(sequence) = &template.sequence {
nested.extend(sequence.element().tokens);
}
let direct = template
.tokens
.difference(&nested)
.copied()
.collect::<Vec<_>>();
let mut groups: BTreeMap<_, Vec<_>> = BTreeMap::new();
for token in direct {
groups.entry(positions.get(&token)).or_default().push(token);
}
let actual_tokens = self.expand(&actual.tokens)?;
if groups.len() > 1 {
// 只拆同一输入位置的分支,不把两个参数传入同一别名误认成分支。
for token in actual_tokens {
let mut children = BTreeSet::new();
for branches in groups.values() {
self.budget(0)?;
let child = self.token();
children.insert(child);
for branch in branches {
mapping.get_mut(branch).unwrap().insert(child);
}
}
self.splits.insert(token, children);
}
} else if let Some(branches) = groups.values().next() {
for token in branches {
mapping.get_mut(token).unwrap().extend(&actual_tokens);
}
}
let absent = ErrorValue::default();
for (index, field) in &template.fields {
self.bind(
field,
actual.fields.get(index).unwrap_or(&absent),
mapping,
positions,
)?;
}
for (index, variant) in &template.variants {
self.bind(
variant,
actual.variants.get(index).unwrap_or(&absent),
mapping,
positions,
)?;
}
if let Some(sequence) = &template.sequence {
self.bind(
&sequence.element(),
&actual
.sequence
.as_ref()
.map(ErrorSequence::element)
.unwrap_or_default(),
mapping,
positions,
)?;
}
Ok(())
}
pub(super) fn positions(
&mut self,
value: &ErrorValue,
next: &mut usize,
positions: &mut BTreeMap<usize, Vec<usize>>,
) -> Result<(), Diagnostic> {
self.budget(0)?;
// 输出位置完全相同的分支等价,不拆分无差别路径,避免身份链指数增长。
for token in &value.tokens {
self.budget(0)?;
positions.entry(*token).or_default().push(*next);
}
*next += 1;
for value in value.fields.values().chain(value.variants.values()) {
self.positions(value, next, positions)?;
}
match &value.sequence {
Some(ErrorSequence::Known(values)) => {
for value in values {
self.positions(value, next, positions)?;
}
}
Some(ErrorSequence::Unknown(value)) => self.positions(value, next, positions)?,
None => {}
}
Ok(())
}
}
+329
View File
@@ -0,0 +1,329 @@
//! 每条成功路径都必须返回、传播或明确恢复错误;读消息和覆盖变量不解除义务。
mod expression;
mod fold;
mod iteration;
mod mapping;
mod task;
mod trace;
mod walk;
use crate::compiler::model::*;
use crate::syntax::{diagnostic::Diagnostic, source::Span};
use std::collections::{BTreeMap, BTreeSet};
pub(super) fn check(
signature: &Signature,
locals: &[Field],
body: &Body,
recovery: bool,
definitions: &[Definition],
functions: &[Option<Function>],
error_types: &[bool],
) -> Result<FailureSummary, Diagnostic> {
if matches!(body, Body::Contract) {
let mut state = State {
locals,
definitions,
functions,
error_types,
values: Vec::new(),
pending: BTreeSet::new(),
interrupted: BTreeSet::new(),
splits: BTreeMap::new(),
next: 0,
work: 0,
span: signature.span,
terminated: false,
};
let inputs = signature
.inputs
.iter()
.map(|field| state.unknown(&field.kind, 0))
.collect::<Result<_, _>>()?;
let values = signature
.outputs
.iter()
.map(|field| state.unknown(&field.kind, 0))
.collect::<Result<_, _>>()?;
return Ok(FailureSummary {
inputs,
output: Some(output(values)),
interrupted: BTreeSet::new(),
});
}
let mut next = 0;
let mut input_summary: Vec<Option<ErrorValue>> = vec![None; signature.inputs.len()];
let mut output_summary: Option<ErrorValue> = None;
let mut interrupted = BTreeSet::new();
let rows: Vec<(Option<&RuleRow>, Option<&Expression>)> = match body {
Body::Contract => unreachable!(),
Body::Statements { .. } | Body::Loop(_) => vec![(None, None)],
Body::Dispatch(dispatch) => dispatch
.variants
.iter()
.map(|v| (None, Some(&v.call)))
.collect(),
Body::Rule(rows) => rows.iter().map(|row| (Some(row), None)).collect(),
};
for (row, dispatch) in rows {
let mut state = State {
locals,
definitions,
functions,
error_types,
values: vec![ErrorValue::default(); locals.len()],
pending: BTreeSet::new(),
interrupted: BTreeSet::new(),
splits: BTreeMap::new(),
next,
work: 0,
span: signature.span,
terminated: false,
};
for (input, field) in signature.inputs.iter().enumerate() {
let mut value = state.unknown(&field.kind, 0)?;
if let Some(row) = row {
value = narrow(value, &field.kind, &row.facts[input]);
}
state.values[input] = value;
}
// unknown 创建的未选中变体只用于类型摘要,不在本行产生处理义务。
state.pending = state
.values
.iter()
.flat_map(|value| value.tokens.iter().copied())
.collect();
let output = if let Some(call) = dispatch {
state.expression(call)?
} else if let Some(row) = row {
state.bind_row(row);
let values = row
.results
.iter()
.map(|value| state.expression(value))
.collect::<Result<Vec<_>, _>>()?;
if signature.outputs.is_empty() {
ErrorValue::default()
} else {
output(values)
}
} else if let Body::Loop(iteration) = body {
state.iteration(iteration, signature.outputs.len())?
} else {
let Body::Statements {
statements,
outputs,
..
} = body
else {
unreachable!()
};
for statement in statements {
if state.terminated {
break;
}
match statement {
Statement::Assign { local, value } => {
state.values[*local] = state.expression(value)?
}
Statement::Action(value) => {
state.expression(value)?;
}
Statement::Check { condition, .. } => {
state.expression(condition)?;
}
Statement::NonNull { value, local, .. } => {
let value = state.expression(value)?;
state.values[*local] = value.variants.get(&1).cloned().unwrap_or_default();
}
}
}
output(
outputs
.iter()
.map(|index| state.values[*index].clone())
.collect(),
)
};
// 调用可能把同一错误细分为互斥路径;摘要必须使用执行后的身份。
for (input, summary) in input_summary.iter_mut().enumerate() {
let value = state.normalize(state.values[input].clone())?;
if let Some(previous) = summary {
previous.merge(&value);
} else {
*summary = Some(value);
}
}
let output = state.normalize(output)?;
state.pending = state.expand(&state.pending.clone())?;
if !state.terminated {
if !recovery && !output.guaranteed && !state.pending.is_subset(&output.tokens) {
return Err(Diagnostic::new(
"C012",
"failure is not handled: return, propagate, or declare an explicit recovery",
row.map_or(signature.span, |row| row.span),
));
}
if let Some(previous) = &mut output_summary {
previous.merge(&output);
} else {
output_summary = Some(output);
}
}
interrupted.extend(state.expand(&state.interrupted.clone())?);
next = state.next;
}
Ok(FailureSummary {
inputs: input_summary
.into_iter()
.map(|input| input.expect("checked body has a path"))
.collect(),
output: output_summary,
interrupted,
})
}
fn output(mut values: Vec<ErrorValue>) -> ErrorValue {
if values.len() == 1 {
values.remove(0)
} else {
ErrorValue::fields(values.into_iter().enumerate())
}
}
fn narrow(mut value: ErrorValue, kind: &Type, fact: &InputFact) -> ErrorValue {
if let Type::Optional(inner) = kind {
if fact.present {
value.variants.remove(&0);
}
if fact.absent {
value.variants.remove(&1);
}
if let Some(inner_value) = value.variants.remove(&1) {
value.variants.insert(1, narrow(inner_value, inner, fact));
}
return ErrorValue::variants(value.variants);
}
if let Some(variants) = &fact.variants {
value.variants.retain(|index, _| variants.contains(index));
value = ErrorValue::variants(value.variants);
}
value
}
#[derive(Clone)]
struct State<'a> {
locals: &'a [Field],
definitions: &'a [Definition],
error_types: &'a [bool],
functions: &'a [Option<Function>],
values: Vec<ErrorValue>,
pending: BTreeSet<usize>,
interrupted: BTreeSet<usize>,
splits: BTreeMap<usize, BTreeSet<usize>>,
next: usize,
work: usize,
span: Span,
terminated: bool,
}
impl State<'_> {
fn rule_value(
&mut self,
selectors: &[Expression],
rows: &[RuleRow],
) -> Result<ErrorValue, Diagnostic> {
let entry = self.clone();
let obligations = self.expand(&entry.pending)?;
let mut paths = BTreeMap::<usize, BTreeSet<usize>>::new();
let mut result: Option<ErrorValue> = None;
self.pending.clear();
for row in rows {
let mut branch = entry.clone();
branch.next = self.next;
branch.work = self.work;
branch.pending.clear();
// 同一错误在不同分支可能分别被返回、处理或遗漏,保持路径身份直到汇合。
for &token in &obligations {
branch.budget(0)?;
let child = branch.token();
paths.entry(token).or_default().insert(child);
branch.splits.insert(token, [child].into());
}
for (selector, fact) in selectors.iter().zip(&row.facts) {
let input = selector.local();
let prior = branch.normalize(branch.values[input].clone())?;
let selected = narrow(prior.clone(), &selector.value_type, fact);
for excluded in prior.tokens.difference(&selected.tokens) {
branch.pending.remove(excluded);
}
branch.values[input] = selected;
}
branch.bind_row(row);
let value = branch.expression(&row.results[0])?;
if !branch.terminated {
let value = branch.normalize(value)?;
if let Some(prior) = &mut result {
prior.merge(&value);
} else {
result = Some(value);
}
self.pending.extend(branch.expand(&branch.pending.clone())?);
}
self.interrupted
.extend(branch.expand(&branch.interrupted.clone())?);
self.splits
.extend(branch.splits.into_iter().filter(|(id, _)| *id >= self.next));
self.work = branch.work;
self.next = branch.next;
}
self.splits.extend(paths);
self.terminated = result.is_none();
Ok(result.unwrap_or_default())
}
fn bind_row(&mut self, row: &RuleRow) {
for present in &row.present {
self.values[present.local] = self.values[present.input]
.variants
.get(&1)
.cloned()
.unwrap_or_default();
}
for binding in &row.bindings {
let value = &self.values[binding.input];
let value = if matches!(self.locals[binding.input].kind, Type::Optional(_)) {
value.variants.get(&1).expect("present choice")
} else {
value
};
let mut fields = value
.variants
.values()
.filter_map(|variant| variant.fields.get(&binding.field));
let mut bound = fields.next().cloned().unwrap_or_default();
for field in fields {
bound.merge(field);
}
self.values[binding.local] = bound;
}
}
fn token(&mut self) -> usize {
let token = self.next;
self.next += 1;
self.pending.insert(token);
token
}
fn budget(&mut self, depth: usize) -> Result<(), Diagnostic> {
self.work += 1;
if self.work > 1_000_000 || depth > 128 {
return Err(Diagnostic::new(
"C015",
"failure structure analysis budget exceeded; handling has not been proved",
self.span,
));
}
Ok(())
}
}
+123
View File
@@ -0,0 +1,123 @@
//! 提交保存输入义务;只有实际等待的成功路径才能兑现处理承诺。
use super::*;
impl State<'_> {
pub(super) fn task(
&mut self,
operation: TaskOp,
arguments: &[Expression],
captured: bool,
) -> Result<ErrorValue, Diagnostic> {
match operation {
TaskOp::Parallel(target) | TaskOp::Blocking(target) => {
let values = arguments
.iter()
.map(|value| self.expression(value))
.collect::<Result<Vec<_>, _>>()?;
self.call_values(target, &values, captured)
}
TaskOp::Run(_) => Ok(ErrorValue {
task: Some(
arguments
.iter()
.map(|v| self.expression(v))
.collect::<Result<_, _>>()?,
),
..ErrorValue::default()
}),
TaskOp::Group => {
self.expression(&arguments[0])?;
Ok(ErrorValue::default())
}
TaskOp::GroupRun(target) => {
let ExpressionKind::Variable(local) = arguments[0].kind else {
unreachable!()
};
let values = arguments[1..]
.iter()
.map(|v| self.expression(v))
.collect::<Result<_, _>>()?;
self.values[local].group.push((target, values));
Ok(ErrorValue::default())
}
TaskOp::GroupWait => {
let group = self.expression(&arguments[0])?;
let before = self.pending.clone();
let may_cancel = captured
&& group.group.iter().any(|(target, _)| {
let function = self.functions[*target].as_ref().unwrap();
!function.failures.is_empty() || function.unknown_failures
});
for (target, values) in group.group {
self.call_values(target, &values, captured)?;
}
if may_cancel {
self.pending.extend(before);
}
Ok(ErrorValue::default())
}
TaskOp::Wait(target) => {
let values = self.expression(&arguments[0])?.task.expect("checked run");
self.call_values(target, &values, captured)
}
TaskOp::Stop(_) | TaskOp::GroupStop => {
self.expression(&arguments[0])?;
Ok(ErrorValue::default())
}
TaskOp::Timeout { target, fallback } => {
let values = self.expression(&arguments[0])?.task.expect("checked run");
self.expression(&arguments[1])?;
self.task_alternatives(&[(target, values), (fallback, Vec::new())], captured)
}
TaskOp::Race(_) => {
let alternatives = arguments
.iter()
.map(|argument| {
let Type::Task(target) = argument.value_type else {
unreachable!()
};
Ok((
target,
self.expression(argument)?.task.expect("checked run"),
))
})
.collect::<Result<Vec<_>, Diagnostic>>()?;
self.task_alternatives(&alternatives, captured)
}
}
}
fn task_alternatives(
&mut self,
alternatives: &[(usize, Vec<ErrorValue>)],
captured: bool,
) -> Result<ErrorValue, Diagnostic> {
let before = self.pending.clone();
let terminated = self.terminated;
let mut remaining = BTreeSet::new();
let mut output: Option<ErrorValue> = None;
for (target, inputs) in alternatives {
self.pending = before.clone();
self.terminated = terminated;
let value = self.call_values(*target, inputs, captured)?;
let function = self.functions[*target].as_ref().unwrap();
let succeeds = function.failure_summary.output.is_some();
if succeeds
|| (captured && (!function.failures.is_empty() || function.unknown_failures))
{
remaining.extend(&self.pending);
}
if succeeds {
if let Some(output) = &mut output {
output.merge(&value);
} else {
output = Some(value);
}
}
}
// 分支并集留下任一路径未处理的输入;不同结果的错误义务也不能遗漏。
self.pending = self.expand(&remaining)?;
self.terminated = terminated || (output.is_none() && !captured);
Ok(output.unwrap_or_default())
}
}
+127
View File
@@ -0,0 +1,127 @@
//! 按真实字段保留错误来源;不同调用重新编号,别名仍指向同一处理义务。
use super::*;
impl State<'_> {
pub(super) fn unknown(&mut self, kind: &Type, depth: usize) -> Result<ErrorValue, Diagnostic> {
self.budget(depth)?;
match kind {
Type::Named(index) if !self.error_types[*index] => Ok(ErrorValue::default()),
Type::Named(index) => match &self.definitions[*index].shape {
Shape::Record(fields) => Ok(ErrorValue::fields(
fields
.iter()
.enumerate()
.map(|(index, field)| Ok((index, self.unknown(&field.kind, depth + 1)?)))
.collect::<Result<Vec<_>, Diagnostic>>()?,
)),
Shape::Choice(variants) => Ok(ErrorValue::variants(
(0..variants.len())
.map(|variant| {
Ok((variant, self.unknown_variant(*index, variant, depth + 1)?))
})
.collect::<Result<Vec<_>, Diagnostic>>()?,
)),
},
Type::Optional(inner) => Ok(ErrorValue::variants([
(0, ErrorValue::default()),
(1, self.unknown(inner, depth + 1)?),
])),
Type::List(inner) | Type::AsyncStream(inner) => Ok(ErrorValue::sequence(
ErrorSequence::Unknown(Box::new(self.unknown(inner, depth + 1)?)),
)),
Type::MapEntry(key, value) => Ok(ErrorValue::fields([
(0, self.unknown(key, depth + 1)?),
(1, self.unknown(value, depth + 1)?),
])),
Type::Map(key, value) => {
let entry = ErrorValue::fields([
(0, self.unknown(key, depth + 1)?),
(1, self.unknown(value, depth + 1)?),
]);
Ok(ErrorValue::sequence(ErrorSequence::Unknown(Box::new(
entry,
))))
}
_ => Ok(ErrorValue::default()),
}
}
pub(super) fn unknown_variant(
&mut self,
definition: usize,
variant: usize,
depth: usize,
) -> Result<ErrorValue, Diagnostic> {
self.budget(depth)?;
let Shape::Choice(variants) = &self.definitions[definition].shape else {
unreachable!()
};
let fields = variants[variant]
.fields
.iter()
.enumerate()
.map(|(index, field)| Ok((index, self.unknown(&field.kind, depth + 1)?)))
.collect::<Result<Vec<_>, Diagnostic>>()?;
Ok(self.variant(definition, variant, ErrorValue::fields(fields)))
}
pub(super) fn variant(
&mut self,
definition: usize,
variant: usize,
mut fields: ErrorValue,
) -> ErrorValue {
let Shape::Choice(variants) = &self.definitions[definition].shape else {
unreachable!()
};
if variants[variant].error {
fields.tokens.insert(self.token());
fields.guaranteed = true;
}
fields
}
pub(super) fn instantiate(
&mut self,
template: &ErrorValue,
mapping: &mut BTreeMap<usize, BTreeSet<usize>>,
depth: usize,
) -> Result<ErrorValue, Diagnostic> {
self.budget(depth)?;
let mut value = ErrorValue {
guaranteed: template.guaranteed,
..ErrorValue::default()
};
for token in &template.tokens {
let actual = mapping
.entry(*token)
.or_insert_with(|| [self.token()].into());
self.pending.extend(actual.iter().copied());
value.tokens.extend(actual.iter().copied());
}
for (index, field) in &template.fields {
value
.fields
.insert(*index, self.instantiate(field, mapping, depth + 1)?);
}
for (index, variant) in &template.variants {
value
.variants
.insert(*index, self.instantiate(variant, mapping, depth + 1)?);
}
value.sequence = match &template.sequence {
Some(ErrorSequence::Known(values)) => Some(ErrorSequence::Known(
values
.iter()
.map(|value| self.instantiate(value, mapping, depth + 1))
.collect::<Result<_, _>>()?,
)),
Some(ErrorSequence::Unknown(value)) => Some(ErrorSequence::Unknown(Box::new(
self.instantiate(value, mapping, depth + 1)?,
))),
None => None,
};
Ok(value)
}
}
+64
View File
@@ -0,0 +1,64 @@
//! walk 只对实际产生的元素建立义务;提前停止时仍须处理留在状态中的错误。
use super::{fold::Reachable, *};
impl State<'_> {
pub(super) fn walk(
&mut self,
seed: &Expression,
state: usize,
update: &Expression,
rows: &[LoopRow],
) -> Result<ErrorValue, Diagnostic> {
let seed = self.expression(seed)?;
if self.terminated || rows.iter().all(LoopRow::takes_none) {
return Ok(ErrorValue::sequence(ErrorSequence::Known(Vec::new())));
}
let mut invariant = Reachable::of(&seed);
loop {
let mut probe = self.clone();
probe.values[state] = probe.reachable(&invariant, 0)?;
let step = probe.expression(update)?;
let next_state = step
.variants
.get(&0)
.and_then(|next| next.fields.get(&1))
.cloned()
.unwrap_or_default();
let mut next = invariant.clone();
if !probe.terminated {
next.join(&Reachable::of(&next_state));
}
self.work = probe.work;
if next == invariant {
break;
}
invariant = next;
}
let input = self.reachable(&invariant, 0)?;
self.values[state] = input.clone();
let terminated = self.terminated;
let step = self.expression(update)?;
self.terminated = terminated;
let mut fields = step
.variants
.get(&0)
.map(|next| next.fields.clone())
.unwrap_or_default();
let item = fields.remove(&0).unwrap_or_default();
let remaining = fields.remove(&1).unwrap_or_default();
let input = self.normalize(input)?;
let seed = self.normalize(seed)?;
self.pending = self.expand(&self.pending.clone())?;
self.pending
.retain(|token| !input.tokens.contains(token) && !step.tokens.contains(token));
if rows.iter().all(LoopRow::short_circuit) {
self.pending.extend(&remaining.tokens);
} else {
// 耗尽一定经过 Done;next 自身已证明在 Done 路径处理了输入状态。
self.pending.retain(|token| !seed.tokens.contains(token));
}
self.pending.extend(&item.tokens);
Ok(ErrorValue::sequence(ErrorSequence::Unknown(Box::new(item))))
}
}
+15
View File
@@ -0,0 +1,15 @@
//! 名称、类型和规则证明;诊断保留违反合同的位置。
pub mod rules;
pub mod types;
pub mod calls;
pub mod constants;
mod dependencies;
mod effects;
mod failure;
pub mod ownership;
pub mod program;
mod value;
pub mod wire;
@@ -0,0 +1,130 @@
//! 表达式保持左到右求值;逆序活跃分析决定每次读取是否需要拥有。
use super::*;
impl State<'_> {
pub(super) fn expression(&mut self, expression: &Expression, owned: bool) {
let owned = owned
|| self
.result
.temporaries
.contains(&std::ptr::from_ref(expression));
use ExpressionKind::*;
match &expression.kind {
Rule { selectors, rows } => {
self.rules(rows, true);
for value in selectors {
self.expression(value, false);
}
}
Loop(l) => self.iteration(l),
Variable(local) => {
let access = self.read(*local, owned);
self.result.reads.insert(expression.span, access);
}
Field(base, field) => {
let scalar = copy(&expression.value_type, self.program);
let keep_base = matches!(base.kind, Variable(local) if self.live[local].is_some()
&& self.fields.get(&local).is_none_or(|fields| fields.contains(field)));
let access = if scalar {
Access::Copy
} else if !owned {
Access::Borrow
} else if keep_base || loans::setting_value(base, &self.settings) {
Access::Clone
} else {
Access::Move
};
self.result.reads.insert(expression.span, access);
if let Variable(local) = base.kind {
if self.live[local].is_none() {
self.fields.insert(local, [*field].into());
} else if let std::option::Option::Some(fields) = self.fields.get_mut(&local) {
fields.insert(*field);
}
self.live[local] = std::option::Option::Some(
access == Access::Move || self.live[local].unwrap_or(false),
);
if let std::option::Option::Some(owner) = self.origins[local] {
self.live[owner].get_or_insert(false);
self.fields.remove(&owner);
}
self.result.reads.insert(
base.span,
if access == Access::Move {
Access::Move
} else {
Access::Borrow
},
);
} else {
self.expression(base, access == Access::Move);
}
}
Call(target, arguments) => {
let parameters = &self.callees[*target]
.as_ref()
.expect("callee analyzed")
.parameters;
for (argument, parameter) in arguments.iter().zip(parameters).rev() {
self.expression(argument, *parameter == Storage::Owned);
}
}
Capture(capture) => self.expression(&capture.call, true),
Some(value) => self.expression(value, owned),
Fail(value) => self.expression(value, true),
Unary(_, value) | DecimalFromInt(value) => self.expression(value, false),
Binary(operation, left, right) => {
self.expression(right, false);
self.expression(
left,
*operation == super::Binary::Add && left.value_type == Type::Text,
);
}
Record(_, fields) => {
for (_, value) in fields.iter().rev() {
self.expression(value, true);
}
}
Variant(_, _, fields) | List(fields) => {
for value in fields.iter().rev() {
self.expression(value, true);
}
}
Map {
entries: values, ..
} => {
for (key, value) in values.iter().rev() {
self.expression(value, true);
self.expression(key, true);
}
}
UpdateField(base, _, value) => {
// base 已验证是局部变量,先算右侧再移动原记录,避免为 x.f = x.f + 1 复制整个 x。
self.expression(base, true);
self.expression(value, true);
}
Builtin(operation, values) => {
if operation.receiver_last(values) {
self.expression(&values[0], true);
for value in values[1..].iter().rev() {
self.expression(value, true);
}
return;
}
for (index, value) in values.iter().enumerate().rev() {
let owned = operation.owns(index);
self.expression(value, owned);
}
}
Number(_)
| Text(_)
| QuerySql { .. }
| JsonLiteral { .. }
| Bool(_)
| Null
| ApiError(_)
| Setting(_) => {}
}
}
}
@@ -0,0 +1,134 @@
//! 跨轮次输入始终存活;只有本轮元素的最后使用可以移动,不为遍历复制整份来源。
use super::*;
impl State<'_> {
pub(super) fn iteration(&mut self, iteration: &Loop) {
// 跨轮次读取必须保留。只扫描循环体,避免嵌套时重复执行所有权分析。
let mut outer = self.live.clone();
for row in iteration.rows.iter().filter(|r| !r.takes_none()) {
for value in row
.value
.iter()
.chain(row.element.iter())
.chain(row.filters.iter().map(|f| &f.value))
.chain(row.sort.iter().map(|s| &s.value))
{
value.visit(&mut |e| {
if let ExpressionKind::Variable(id) = e.kind
&& id < iteration.item
{
outer[id].get_or_insert(false);
}
true
});
}
}
self.live.clone_from(&outer);
self.fields.clear();
self.iteration_rows(iteration);
let storage = self.storage(iteration.item);
self.live = outer;
self.fields.clear();
for row in iteration.rows.iter().rev() {
if let Some(fold) = &row.fold {
self.expression(&fold.seed, true);
}
if let Some(limit) = &row.take {
self.expression(limit, false);
}
}
if let Some(limit) = &iteration.parallel {
self.expression(limit, false);
}
match &iteration.source {
LoopSource::Walk {
seed,
state,
update,
..
} => {
self.expression(update, true);
self.storage(*state);
self.result.locals[*state] = Storage::Owned;
self.expression(seed, true);
}
LoopSource::List(value) => {
if let Some(map) = entry_source(value, self.program) {
self.expression(map, false);
return;
}
let item = &self.function.locals[iteration.item].kind;
self.expression(
value,
storage == Storage::Owned && !copy(item, self.program),
);
}
LoopSource::Range(start, end) => {
self.expression(end, false);
self.expression(start, false);
}
LoopSource::Bytes(value)
| LoopSource::Stream(value)
| LoopSource::SyncStream(value) => self.expression(value, false),
}
}
fn iteration_rows(&mut self, iteration: &Loop) {
for row in iteration.rows.iter().rev() {
if row.takes_none() {
continue;
}
if let Some(element) = &row.element {
self.expression(element, true);
}
if let Some(value) = &row.value {
self.expression(
value,
matches!(
row.aggregate,
Aggregate::List
| Aggregate::Group
| Aggregate::Index
| Aggregate::First
| Aggregate::Min
| Aggregate::Max
| Aggregate::Fold
| Aggregate::FoldUntil
),
);
}
if let Some(fold) = &row.fold {
let storage = self.storage(fold.accumulator);
if storage != Storage::Unused {
self.result.locals[fold.accumulator] = Storage::Owned;
}
}
for key in row.sort.iter().rev() {
self.expression(&key.value, true);
}
for filter in row.filters.iter().rev() {
self.bindings(&filter.bindings, filter.present.as_slice());
if let Some(present) = &filter.present {
self.present(present);
}
// 列头源码相同,但各行的求值是不同使用点;分开保存移动与借用决策。
let surrounding = std::mem::take(&mut self.result.reads);
if filter.temporary {
let local = filter.binding_source.unwrap();
self.read(local, false);
let mut storage = self.storage(local);
if storage == Storage::Borrowed && !borrowable(&filter.value) {
storage = Storage::Owned;
self.result.locals[local] = storage;
}
self.expression(&filter.value, storage == Storage::Owned);
} else {
self.expression(&filter.value, false);
}
let reads = std::mem::replace(&mut self.result.reads, surrounding);
self.result.filters.insert(filter.condition.span, reads);
}
}
}
}
+107
View File
@@ -0,0 +1,107 @@
//! SSA 别名只指向先前的值,按定义顺序一次折叠到真正持有数据的局部值。
use super::*;
pub(super) fn origins(function: &Function, ownership: &Ownership) -> Vec<Option<usize>> {
let mut origins = vec![None; function.locals.len()];
let mut bind = |local: usize, source: usize| {
if ownership.locals[local] == Storage::Borrowed {
origins[local] = Some(origins[source].unwrap_or(source));
}
};
match &function.body {
Body::Contract => unreachable!("handler contracts are not emitted"),
Body::Dispatch(_) => {}
Body::Loop(iteration) => {
for filter in iteration.rows.iter().flat_map(|row| &row.filters) {
if filter.temporary
&& let Some(source) = base(&filter.value)
{
bind(filter.binding_source.unwrap(), source);
}
let moved = filter.bindings.iter().any(|binding| {
ownership.projections.get(&binding.local) == Some(&Access::Move)
});
if !moved {
for binding in &filter.bindings {
bind(binding.local, binding.input);
}
}
if let Some(present) = &filter.present {
bind(present.local, present.input);
}
}
}
Body::Statements { statements, .. } => {
for statement in statements {
match statement {
Statement::Assign { local, value }
| Statement::NonNull { local, value, .. } => {
if let Some(source) = base(value) {
bind(*local, source);
}
}
_ => {}
}
}
}
Body::Rule(rows) => {
for row in rows {
let moved_inputs = row
.bindings
.iter()
.filter(|binding| {
ownership.projections.get(&binding.local) == Some(&Access::Move)
})
.map(|binding| binding.input)
.collect::<std::collections::HashSet<_>>();
for binding in &row.bindings {
// 同次解构可以分别移动字段和借用剩余字段,不需复制整个 choice。
if !moved_inputs.contains(&binding.input) {
bind(binding.local, binding.input);
}
}
for present in &row.present {
bind(present.local, present.input);
}
}
}
}
origins
}
fn base(value: &Expression) -> Option<usize> {
match &value.kind {
ExpressionKind::Variable(local) => Some(*local),
ExpressionKind::Field(value, _) | ExpressionKind::Some(value) => base(value),
// 查询结果借用集合中的元素;元素的最后读取也延长集合所有者的使用期。
ExpressionKind::Builtin(Builtin::Get, arguments) => base(&arguments[0]),
_ => None,
}
}
/// 启动配置在整个调用期间存活;局部别名可一直借用,只在真正需要拥有的读取处复制。
pub(super) fn settings(function: &Function) -> HashSet<usize> {
let mut locals = HashSet::new();
if let Body::Statements { statements, .. } = &function.body {
for statement in statements {
if let Statement::Assign { local, value } | Statement::NonNull { local, value, .. } =
statement
&& setting_value(value, &locals)
{
locals.insert(*local);
}
}
}
locals
}
pub(super) fn setting_value(value: &Expression, locals: &HashSet<usize>) -> bool {
match &value.kind {
ExpressionKind::Setting(_) => true,
ExpressionKind::Variable(local) => locals.contains(local),
ExpressionKind::Field(base, _) | ExpressionKind::Some(base) => setting_value(base, locals),
ExpressionKind::Builtin(Builtin::Get, arguments) => setting_value(&arguments[0], locals),
_ => false,
}
}
+330
View File
@@ -0,0 +1,330 @@
//! 按调用依赖顺序分析参数,再按实际控制结构逆序确定值的最后使用。
mod expression;
mod iteration;
mod loans;
mod parallel;
mod rule;
use crate::compiler::model::*;
use std::collections::{HashMap, HashSet};
pub fn analyze(program: &Program) -> Vec<Ownership> {
let mut decisions = (0..program.functions.len())
.map(|_| None)
.collect::<Vec<_>>();
for &index in &program.order {
let function = &program.functions[index];
let mut state = State {
program,
function,
callees: &decisions,
live: vec![None; function.locals.len()],
fields: HashMap::new(),
origins: vec![None; function.locals.len()],
settings: loans::settings(function),
fixed_storage: false,
result: Ownership {
temporaries: HashSet::new(),
parameters: Vec::new(),
locals: vec![Storage::Unused; function.locals.len()],
reads: HashMap::new(),
filters: HashMap::new(),
projections: HashMap::new(),
outputs: Vec::new(),
},
};
state.body();
// 先确定局部值是否持有数据,再把借用别名的使用期传回所有者。
// 两遍有界分析;第二遍不改变存储形态,也不在生成阶段补 clone。
state.origins = loans::origins(function, &state.result);
state.fixed_storage = true;
state.live.fill(None);
state.fields.clear();
state.result.outputs.clear();
state.body();
for (index, field) in function.signature.inputs.iter().enumerate() {
let storage = if field
.input_contract()
.is_some_and(|c| c.text != TextMode::Raw)
|| copy(&field.kind, program)
|| state.live[index] == Some(true)
{
Storage::Owned
} else {
Storage::Borrowed
};
state.result.parameters.push(storage);
state.result.locals[index] = storage;
}
decisions[index] = Some(state.result);
}
decisions
.into_iter()
.map(|decision| decision.expect("checked dependency order"))
.collect()
}
impl State<'_> {
fn body(&mut self) {
match &self.function.body {
Body::Contract => unreachable!("handler contracts are not emitted"),
Body::Statements {
statements,
outputs,
flow,
} => {
for local in outputs.iter().rev() {
let access = self.read(*local, true);
self.result.outputs.push(access);
}
self.result.outputs.reverse();
let mut end = statements.len();
while end > 0 {
let mut start = end - 1;
if let Some(steps) = flow
&& let Some(group) = &steps[start].parallel
{
while start > 0 && steps[start - 1].parallel.as_ref() == Some(group) {
start -= 1;
}
}
if end - start > 1 {
self.parallel(&statements[start..end]);
} else {
self.statement(&statements[start]);
}
end = start;
}
}
Body::Dispatch(dispatch) => {
let mut inputs = vec![None; self.function.locals.len()];
for variant in &dispatch.variants {
self.live.fill(None);
self.fields.clear();
self.expression(&variant.call, true);
for (input, demand) in inputs.iter_mut().zip(&self.live) {
if let Some(owned) = demand {
*input = Some(*owned || input.unwrap_or(false));
}
}
}
self.live = inputs;
self.fields.clear();
}
Body::Rule(rows) => self.rules(rows, !self.function.signature.outputs.is_empty()),
Body::Loop(iteration) => self.iteration(iteration),
}
}
}
/// 直接遍历 Copy 条目时借用 Map,不先复制 Map 再物化条目列表。
pub fn entry_source<'a>(value: &'a Expression, program: &Program) -> Option<&'a Expression> {
if let ExpressionKind::Builtin(Builtin::Entries, values) = &value.kind
&& let Type::List(item) = &value.value_type
&& copy(item, program)
{
Some(&values[0])
} else {
None
}
}
pub fn copy(kind: &Type, program: &Program) -> bool {
match kind {
Type::Unit
| Type::Never
| Type::Null
| Type::ApiError
| Type::Bool
| Type::Int
| Type::Float
| Type::Decimal
| Type::Uuid
| Type::ModelId(_)
| Type::DateTime
| Type::Date
| Type::Time
| Type::Duration => true,
Type::Optional(inner) => copy(inner, program),
Type::MapEntry(key, value) => copy(key, program) && copy(value, program),
Type::Named(index) => {
matches!(&program.definitions[*index].shape, Shape::Choice(variants) if variants.iter().all(|variant| variant.fields.is_empty()))
}
Type::Outputs(index) => program.functions[*index]
.signature
.outputs
.iter()
.all(|field| copy(&field.kind, program)),
Type::Task(_)
| Type::Upload
| Type::File
| Type::Socket
| Type::Listener
| Type::ClientTls
| Type::ServerTls
| Type::HttpClient
| Type::HttpReply
| Type::WebSocket
| Type::Channel(_)
| Type::AsyncStream(_)
| Type::Stream(_)
| Type::Group(_)
| Type::Text
| Type::Id
| Type::Bytes
| Type::Json
| Type::Secret
| Type::List(_)
| Type::Map(_, _) => false,
}
}
struct State<'a> {
program: &'a Program,
function: &'a Function,
callees: &'a [Option<Ownership>],
live: Vec<Option<bool>>,
/// 有活跃读取但不在此表中,表示整个值仍被使用;表内只保留实际读取的字段。
fields: HashMap<usize, HashSet<usize>>,
origins: Vec<Option<usize>>,
settings: HashSet<usize>,
fixed_storage: bool,
result: Ownership,
}
impl State<'_> {
fn read(&mut self, local: usize, owned: bool) -> Access {
self.fields.remove(&local);
let access = if copy(&self.function.locals[local].kind, self.program) {
Access::Copy
} else if !owned {
Access::Borrow
} else if self.live[local].is_some() || self.settings.contains(&local) {
Access::Clone
} else {
Access::Move
};
self.live[local] = Some(owned || self.live[local].unwrap_or(false));
if let Some(owner) = self.origins[local] {
self.live[owner].get_or_insert(false);
self.fields.remove(&owner);
}
access
}
fn storage(&mut self, local: usize) -> Storage {
self.fields.remove(&local);
if self.fixed_storage {
self.live[local] = None;
return self.result.locals[local];
}
let storage = match self.live[local].take() {
None => Storage::Unused,
Some(_)
if self.settings.contains(&local)
&& !copy(&self.function.locals[local].kind, self.program) =>
{
Storage::Borrowed
}
Some(owned) if owned || copy(&self.function.locals[local].kind, self.program) => {
Storage::Owned
}
Some(_) => Storage::Borrowed,
};
self.result.locals[local] = storage;
storage
}
fn present(&mut self, present: &PresentInput) {
let storage = self.storage(present.local);
if storage == Storage::Unused {
return;
}
let access = if copy(&self.function.locals[present.local].kind, self.program) {
Access::Copy
} else if storage == Storage::Borrowed {
Access::Borrow
} else if self.live[present.input].is_some() {
Access::Clone
} else {
Access::Move
};
self.result.projections.insert(present.local, access);
self.read(present.input, access == Access::Move);
}
fn merge_live(&mut self, other: &[Option<bool>]) {
for (live, other) in self.live.iter_mut().zip(other) {
if let Some(other) = other {
*live = Some(*other || live.unwrap_or(false));
}
}
}
fn error_branch(&mut self, error: &Expression) {
let success = std::mem::replace(&mut self.live, vec![None; self.function.locals.len()]);
let success_fields = std::mem::take(&mut self.fields);
self.expression(error, true);
for (local, fields) in &success_fields {
if self.live[*local].is_none() {
self.fields.insert(*local, fields.clone());
} else if let Some(current) = self.fields.get_mut(local) {
current.extend(fields);
}
}
self.fields
.retain(|local, _| success[*local].is_none() || success_fields.contains_key(local));
self.merge_live(&success);
}
fn statement(&mut self, statement: &Statement) {
match statement {
Statement::Assign { local, value } => {
let mut storage = self.storage(*local);
// 新构造值由局部变量持有;只有已有值及其字段才借用,避免引用临时结果。
if storage == Storage::Borrowed && !borrowable(value) {
storage = Storage::Owned;
self.result.locals[*local] = storage;
}
self.expression(value, storage == Storage::Owned);
}
Statement::Action(value) => self.expression(value, false),
Statement::Check { condition, error } => {
self.error_branch(error);
self.expression(condition, false);
}
Statement::NonNull {
local,
value,
error,
} => {
let storage = self.storage(*local);
let ExpressionKind::Variable(original) = value.kind else {
unreachable!()
};
let access = if copy(&self.function.locals[*local].kind, self.program) {
Access::Copy
} else if storage != Storage::Owned {
Access::Borrow
} else if self.live[original].is_some() {
Access::Clone
} else {
Access::Move
};
self.result.projections.insert(*local, access);
self.expression(value, access == Access::Move);
self.error_branch(error);
}
}
}
}
pub(crate) fn borrowable(value: &Expression) -> bool {
match &value.kind {
ExpressionKind::Variable(_) | ExpressionKind::Setting(_) => true,
ExpressionKind::Field(base, _) | ExpressionKind::Some(base) => borrowable(base),
ExpressionKind::Builtin(Builtin::Get, arguments) => borrowable(&arguments[0]),
_ => false,
}
}
@@ -0,0 +1,126 @@
//! 并发参数在启动前求值;借用持续到整组退出,独立字段仍可分别移动。
use super::*;
type Held = HashMap<usize, Option<HashSet<usize>>>;
impl State<'_> {
fn hold(&mut self, value: &Expression, held: &mut Held) {
if holder(value, self.program) {
self.result.temporaries.insert(std::ptr::from_ref(value));
} else {
borrow(value, held);
}
}
pub(super) fn parallel(&mut self, statements: &[Statement]) {
let mut held = Held::new();
for statement in statements {
let value = statement.value().operation();
match &value.kind {
ExpressionKind::Call(target, arguments) => {
let parameters = &self.callees[*target].as_ref().unwrap().parameters;
for (argument, storage) in arguments.iter().zip(parameters) {
if *storage == Storage::Borrowed {
self.hold(argument, &mut held);
}
}
}
ExpressionKind::Builtin(operation, arguments) => {
for (index, argument) in arguments.iter().enumerate() {
if !operation.owns(index) {
self.hold(argument, &mut held);
}
}
}
_ => {}
}
}
// 纯表达式的自由值也在启动前捕获;先确定读取方式,再延长实际借用。
let live = self.live.clone();
let fields = self.fields.clone();
for statement in statements.iter().rev() {
self.statement(statement);
}
for statement in statements {
let value = statement.value().operation();
if matches!(
value.kind,
ExpressionKind::Call(..) | ExpressionKind::Builtin(..)
) {
continue;
}
value.visit(&mut |value| match &value.kind {
ExpressionKind::Field(base, _)
if matches!(base.kind, ExpressionKind::Variable(_)) =>
{
if self.result.reads[&value.span] == Access::Borrow {
borrow(value, &mut held);
}
false
}
ExpressionKind::Variable(_) => {
if self.result.reads[&value.span] == Access::Borrow {
borrow(value, &mut held);
}
false
}
_ => true,
});
}
self.live = live;
self.fields = fields;
for statement in statements.iter().rev() {
for (&local, fields) in &held {
if self.live[local].is_none() {
if let Some(fields) = fields {
self.fields.insert(local, fields.clone());
}
} else if let (Some(current), Some(fields)) = (self.fields.get_mut(&local), fields)
{
current.extend(fields);
}
if fields.is_none() {
self.fields.remove(&local);
}
self.live[local].get_or_insert(false);
if let Some(owner) = self.origins[local] {
self.live[owner].get_or_insert(false);
self.fields.remove(&owner);
}
}
self.statement(statement);
}
}
}
fn borrow(value: &Expression, held: &mut Held) {
use ExpressionKind::*;
match &value.kind {
Variable(local) => {
held.insert(*local, None);
}
Field(base, field) => {
if let Variable(local) = base.kind {
if let std::option::Option::Some(fields) = held
.entry(local)
.or_insert_with(|| std::option::Option::Some(HashSet::new()))
{
fields.insert(*field);
}
} else {
borrow(base, held);
}
}
Some(value) => borrow(value, held),
Builtin(super::Builtin::Get, arguments) => borrow(&arguments[0], held),
_ => {}
}
}
fn holder(value: &Expression, program: &Program) -> bool {
if let ExpressionKind::Some(inner) = &value.kind {
return holder(inner, program);
}
!copy(&value.value_type, program)
&& !borrowable(value)
&& !matches!(value.kind, ExpressionKind::Text(_) | ExpressionKind::Null)
}
+65
View File
@@ -0,0 +1,65 @@
//! 每个分支独立计算最后使用,再合并输入需求;分支间不会相互制造复制。
use super::*;
impl State<'_> {
pub(super) fn rules(&mut self, rows: &[RuleRow], outputs: bool) {
let tail = self.live.clone();
let mut inputs = tail.clone();
for row in rows {
self.live.clone_from(&tail);
self.fields.clear();
for value in row.results.iter().rev() {
self.expression(value, outputs);
}
self.bindings(&row.bindings, &row.present);
for present in &row.present {
self.present(present);
}
for (input, demand) in inputs.iter_mut().zip(&self.live) {
if let Some(owned) = demand {
*input = Some(*owned || input.unwrap_or(false));
}
}
}
self.live = inputs;
self.fields.clear();
}
pub(super) fn bindings(&mut self, bindings: &[Binding], present: &[PresentInput]) {
let mut by_input: HashMap<usize, Vec<(usize, Storage)>> = HashMap::new();
for binding in bindings {
let storage = self.storage(binding.local);
if storage == Storage::Unused {
continue;
}
by_input
.entry(binding.input)
.or_default()
.push((binding.local, storage));
}
for (input, bindings) in by_input {
let whole_used = self.live[input].is_some()
|| present
.iter()
.any(|present| present.input == input && self.live[present.local].is_some());
let moves = !whole_used
&& bindings.iter().any(|(local, storage)| {
*storage == Storage::Owned
&& !copy(&self.function.locals[*local].kind, self.program)
});
for (local, storage) in bindings {
let access = if copy(&self.function.locals[local].kind, self.program) {
Access::Copy
} else if storage == Storage::Borrowed {
Access::Borrow
} else if moves {
Access::Move
} else {
Access::Clone
};
self.result.projections.insert(local, access);
}
self.read(input, moves);
}
}
}
+140
View File
@@ -0,0 +1,140 @@
//! verify 的可信性来自受限调用链;Claims 本身不是已认证身份。
use super::*;
pub(super) fn check(
functions: &[Option<Function>],
definitions: &[Definition],
modules: &[Module],
calls: &calls::Calls<'_>,
) -> Vec<Diagnostic> {
let Some(claims) = definitions
.iter()
.position(|d| d.name == "dever.auth.app.Claims")
else {
return Vec::new();
};
let mut errors = Vec::new();
for (index, function) in functions.iter().enumerate() {
let Some(function) = function else { continue };
let signature = &function.signature;
let source = &modules[signature.span.source];
if source.role != Role::App
|| signature.inputs.len() != 1
|| signature.inputs[0].kind != Type::Named(claims)
{
continue;
}
let result = (|| {
if function.transaction
|| function.effects.identity
|| function.effects.session
|| function.effects.request
|| function.effects.database_write
|| !function.effects.transaction_safe()
|| function.unknown_failures
|| index >= calls.concrete
{
return Err(Diagnostic::new(
"C014",
"Provider verify permits only values, clock reads and global Model reads",
signature.span,
));
}
identity(signature, definitions, modules)?;
let forbidden = reachable_expression(index, functions, calls, |value| {
uses_tenant_model(value, definitions)
});
if let Some(span) = forbidden {
let mut error =
Diagnostic::new("C014", "Provider verify cannot read a tenant Model", span);
error
.related
.push((signature.span, "Provider verify".into()));
return Err(error);
}
Ok(())
})();
if let Err(error) = result {
errors.push(error);
}
}
errors
}
pub(super) fn tenant_models<'a>(
value: &'a Expression,
definitions: &'a [Definition],
) -> Option<impl Iterator<Item = usize> + 'a> {
let ExpressionKind::Builtin(
Builtin::Database {
record,
operation,
relations,
..
},
_,
) = &value.kind
else {
return None;
};
let model = definitions[*record].model.as_ref().unwrap();
let dependencies = match operation {
DatabaseOp::Sql { index, .. } => model.sql[*index].dependencies.as_slice(),
_ => &[],
};
Some(
std::iter::once(*record)
.chain(dependencies.iter().copied())
.chain(relations.iter().map(|&index| model.relations[index].target))
.filter(|&index| !definitions[index].model.as_ref().unwrap().global),
)
}
pub(super) fn uses_tenant_model(value: &Expression, definitions: &[Definition]) -> bool {
tenant_models(value, definitions).is_some_and(|mut models| models.next().is_some())
}
fn identity(
signature: &Signature,
definitions: &[Definition],
modules: &[Module],
) -> Result<(), Diagnostic> {
let invalid = || {
Diagnostic::new(
"C005",
"Provider verify must return its own App identity with id: Text, user_id: UserModelId? and tenant_id: TenantModelId?",
signature.span,
)
};
let [output] = signature.outputs.as_slice() else {
return Err(invalid());
};
let Type::Named(index) = output.kind else {
return Err(invalid());
};
let definition = &definitions[index];
let Shape::Record(fields) = &definition.shape else {
return Err(invalid());
};
let owner = &modules[definition.span.unwrap().source];
if owner.role != Role::App
|| !owner.same_domain(&modules[signature.span.source])
|| fields.len() != 3
|| fields.iter().any(|f| f.private || f.range.is_some())
{
return Err(invalid());
}
for (name, id) in [("id", false), ("user_id", true), ("tenant_id", true)] {
let Some(field) = fields.iter().find(|f| f.name == name) else {
return Err(invalid());
};
if if id {
!matches!(&field.kind,Type::Optional(inner) if matches!(**inner,Type::ModelId(_)))
} else {
field.kind != Type::Text
} {
return Err(invalid());
}
}
Ok(())
}
@@ -0,0 +1,321 @@
//! 入口绑定统一复用目标、wire 和事务合同,HTTP 仅增加协议与访问约束。
use super::*;
use crate::syntax::source::Span;
pub(super) mod rest;
pub(super) fn command(
declaration: &ast::Declaration,
modules: &[Module],
calls: &calls::Calls<'_>,
functions: &[Option<Function>],
types: &Types<'_>,
names: &HashMap<String, usize>,
) -> Result<Command, Diagnostic> {
let ast::Declaration::Command {
name,
target,
span,
long,
} = declaration
else {
unreachable!()
};
let span = *span;
let module = &modules[span.source];
if module.role != Role::Api && !module.standalone {
return Err(Diagnostic::new(
"C003",
"command bindings belong in API files",
span,
));
}
let identity = format!("{}.{}.{name}", module.component, module.domain);
if names[&identity] > 1 {
return Err(Diagnostic::new("C001", "duplicate command", span));
}
let (function, checked) = target_function(target, module, span, modules, calls, functions)?;
if checked.effects.identity || checked.effects.session || checked.effects.request {
return Err(Diagnostic::new(
"C013",
"CMD cannot read an HTTP identity or request context",
span,
));
}
crate::compiler::check::wire::signature(&checked.signature, &types.definitions, span, false)?;
transaction(function, *long, checked, functions, span)?;
let mut components = BTreeSet::new();
if checked.effects.database {
reachable_expression(function, functions, calls, |value| {
if let Some(models) = auth::tenant_models(value, &types.definitions) {
for index in models {
let source = types.definitions[index].span.unwrap().source;
components.insert(&modules[source].component);
}
} else if let ExpressionKind::Builtin(Builtin::Enqueue { job, .. }, _) = &value.kind {
components.insert(&modules[types.jobs[*job].span.source].component);
}
false
});
}
let tenant_components = (!components.is_empty()).then(|| {
components.insert(&module.component);
components.into_iter().cloned().collect()
});
Ok(Command {
tenant_components,
long: *long,
name: identity,
function,
span,
})
}
fn target_function<'f>(
target: &str,
module: &Module,
span: Span,
modules: &[Module],
calls: &calls::Calls<'_>,
functions: &'f [Option<Function>],
) -> Result<(usize, &'f Function), Diagnostic> {
let reference = module.reference(target);
let &function = calls
.by_name
.get(&reference)
.ok_or_else(|| Diagnostic::new("C004", "unknown entry target", span))?;
if function >= calls.concrete {
return Err(Diagnostic::new(
"C005",
"entry target cannot require static handler parameters",
span,
));
}
let target_module = &modules[calls.functions[function].span.source];
if !module.same_domain(target_module) || target_module.role != Role::App {
return Err(Diagnostic::new(
"C003",
"entry target must be an App in the same domain",
span,
));
}
let checked = functions[function]
.as_ref()
.ok_or_else(|| Diagnostic::new("C004", "entry depends on an invalid definition", span))?;
Ok((function, checked))
}
fn transaction(
function: usize,
long: bool,
checked: &Function,
functions: &[Option<Function>],
span: Span,
) -> Result<(), Diagnostic> {
if checked.effects.database_write && !long && !checked.effects.transaction_safe() {
return Err(Diagnostic::new(
"C013",
"ordinary writing entry is transactional; external effects require a long entry and explicit transaction flows",
span,
));
}
if long {
crate::compiler::check::effects::long_entry(function, functions, span)?;
}
Ok(())
}
pub(super) fn http(
declarations: &[ast::Declaration],
modules: &[Module],
calls: &calls::Calls<'_>,
functions: &[Option<Function>],
definitions: &[Definition],
) -> (Vec<HttpEntry>, Vec<Diagnostic>) {
let mut entries = Vec::new();
let mut errors = Vec::new();
let mut seen = HashMap::new();
for declaration in declarations {
let ast::Declaration::Http(entry) = declaration else {
continue;
};
let result = (|| {
let span = entry.span;
let module = &modules[span.source];
if module.role != Role::Api {
return Err(Diagnostic::new(
"C003",
"HTTP bindings belong in API files",
span,
));
}
let (function, checked) =
target_function(&entry.target, module, span, modules, calls, functions)?;
crate::compiler::check::wire::signature(&checked.signature, definitions, span, true)?;
if checked
.signature
.inputs
.iter()
.any(|f| f.kind == Type::Upload)
{
if entry.method != "post" {
return Err(Diagnostic::new(
"C014",
"Upload requires a POST multipart entry",
span,
));
}
for field in checked
.signature
.inputs
.iter()
.filter(|f| f.kind != Type::Upload)
{
let kind = match &field.kind {
Type::Optional(inner) => inner.as_ref(),
kind => kind,
};
if matches!(kind, Type::List(_) | Type::Json)
|| matches!(kind,Type::Named(i) if matches!(definitions[*i].shape,Shape::Record(_)))
{
return Err(Diagnostic::new(
"C005",
"multipart fields must be scalar",
field.span,
));
}
}
}
if checked.effects.session && entry.method == "get" {
return Err(Diagnostic::new(
"C014",
"session issuance and Cookie changes require an HTTP write entry",
span,
));
}
if checked.effects.authorization_write
&& (entry.access != HttpAccess::Protected || entry.long || entry.method == "get")
{
return Err(Diagnostic::new(
"C014",
"authorization changes require an ordinary protected HTTP write entry",
span,
));
}
if entry.access == HttpAccess::Public && checked.effects.identity {
return Err(Diagnostic::new(
"C013",
"public HTTP cannot read a verified identity",
span,
));
}
if checked.effects.blocking || checked.effects.output {
return Err(Diagnostic::new(
"C013",
"HTTP handlers cannot block the executor or write stdout; use explicit blocking for synchronous I/O",
span,
));
}
transaction(function, entry.long, checked, functions, span)?;
if entry.method == "get" && (entry.long || checked.effects.database_write) {
return Err(Diagnostic::new(
"C013",
"GET cannot be long, write a Model or enqueue a Job",
span,
));
}
if matches!(entry.method.as_str(), "get" | "delete") {
for field in &checked.signature.inputs {
let kind = match &field.kind {
Type::Optional(inner) => inner,
kind => kind,
};
if !matches!(
kind,
Type::Bool
| Type::Int
| Type::Float
| Type::Decimal
| Type::Text
| Type::Uuid
| Type::Id
| Type::ModelId(_)
| Type::DateTime
| Type::Date
| Type::Time
| Type::Duration
) && !matches!(kind, Type::Named(i) if matches!(definitions[*i].shape, Shape::Choice(_)))
{
return Err(Diagnostic::new(
"C005",
"HTTP query inputs must be scalar",
field.span,
));
}
}
}
let mut tenant_model = None;
if entry.access != HttpAccess::Protected {
let public_database =
entry.access == HttpAccess::Public && checked.effects.database;
if let Some(site) = reachable_expression(function, functions, calls, |value| {
if public_database
&& tenant_model.is_none()
&& auth::uses_tenant_model(value, definitions)
{
tenant_model = Some(value.span);
}
matches!(
value.kind,
ExpressionKind::Builtin(Builtin::Enqueue { .. }, _)
) || (entry.access == HttpAccess::Public
&& matches!(
value.kind,
ExpressionKind::Builtin(Builtin::JobStates { .. }, _)
))
}) {
return Err(Diagnostic::new(
"C014",
"HTTP entry cannot access this Job queue with its declared identity",
site,
));
}
}
let topic = module.topic.as_deref().unwrap_or("").replace('.', "/");
let path = format!(
"/{}/{}/{}{}",
module.component,
module.domain,
if topic.is_empty() {
String::new()
} else {
format!("{topic}/")
},
entry.name
);
let method = entry.method.to_ascii_uppercase();
if let Some(previous) = seen.insert((method.clone(), path.clone()), span) {
let mut error = Diagnostic::new("C001", "duplicate HTTP method and path", span);
error.related.push((previous, "previous entry".into()));
return Err(error);
}
Ok(HttpEntry {
rest: None,
tenant_model,
access: entry.access,
long: entry.long,
method,
path,
topic,
component: module.component.clone(),
domain: module.domain.clone(),
action: entry.name.clone(),
function,
span,
})
})();
match result {
Ok(entry) => entries.push(entry),
Err(error) => errors.push(error),
}
}
(entries, errors)
}
@@ -0,0 +1,206 @@
//! REST 展开成普通具体函数;查询、写入、归属过滤复用 Model 检查器。
use super::*;
mod bindings;
mod operation;
mod validation;
pub(in crate::compiler::check::program) fn build(
declarations: &[ast::Declaration],
types: &Types<'_>,
calls: &mut calls::Calls<'_>,
constants: &constants::Constants<'_>,
functions: &[Option<Function>],
http: &mut Vec<HttpEntry>,
) -> (Vec<Function>, Vec<Diagnostic>) {
let mut result = Vec::new();
let mut errors = Vec::new();
for declaration in declarations {
let ast::Declaration::Rest { model, span } = declaration else {
continue;
};
let edge_start = calls.edges.len();
let checked = (|| {
let module = types.module(span.source);
if module.role != Role::Api {
return Err(Diagnostic::new(
"C003",
"REST belongs in an API file",
*span,
));
}
let claims = types.named("dever.auth.Claims", span.source);
if !claims.is_some_and(|claims| {
functions.iter().flatten().any(|f| {
types.module(f.signature.span.source).role == Role::App
&& f.signature.inputs.len() == 1
&& f.signature.inputs[0].kind == Type::Named(claims)
})
}) {
return Err(Diagnostic::new(
"C014",
"REST requires a compiled App verify function",
*span,
));
}
let identity = if model == "data" {
module
.reference("data.id")
.trim_end_matches(".id")
.to_owned()
} else {
module.reference(model)
};
let (source, record_name) = types.models.get(&identity).ok_or_else(|| {
Diagnostic::new("C014", "REST requires a same-domain Model", *span)
})?;
if !module.same_domain(types.module(*source)) {
return Err(Diagnostic::new(
"C014",
"REST requires a same-domain Model",
*span,
));
}
let record = types.named(record_name, span.source).unwrap();
let fields = types.definitions[record].columns();
if fields.len() < 2 {
return Err(Diagnostic::new(
"C014",
"REST depends on an invalid Model",
*span,
));
}
bindings::validate(fields, true)?;
let owners = fields
.iter()
.enumerate()
.filter_map(|(i, f)| f.model.as_ref().and_then(|m| m.owner).map(|user| (i, user)))
.collect::<Vec<_>>();
if owners.len() > 1 {
return Err(Diagnostic::new(
"C014",
"REST permits one owner field",
*span,
));
}
let owner = owners.first().copied();
for field in fields.iter().filter(|f| !f.private) {
crate::compiler::check::wire::collect_types(
&field.kind,
&types.definitions,
field.span,
&mut BTreeSet::new(),
)?;
}
let topic = module.topic.as_deref().unwrap_or("").replace('.', "/");
let path = format!(
"/{}/{}{}",
module.component,
module.domain,
if topic.is_empty() {
String::new()
} else {
format!("/{topic}")
}
);
if http.iter().any(|e| {
e.path == path
|| e.path.starts_with(&format!("{path}/"))
|| (e.rest.is_some() && path.starts_with(&format!("{}/", e.path)))
}) {
return Err(Diagnostic::new(
"C001",
"REST route overlaps an existing HTTP route",
*span,
));
}
let mut entries = Vec::new();
let mut generated = Vec::new();
for (method, action, detail) in [
("GET", "read", false),
("GET", "read", true),
("POST", "create", false),
("PUT", "replace", true),
("DELETE", "delete", true),
] {
let mut entry = HttpEntry {
rest: Some(RestEntry {
search: None,
record,
detail,
owner,
}),
tenant_model: None,
access: HttpAccess::Protected,
long: false,
method: method.into(),
action: action.into(),
path: path.clone(),
topic: topic.clone(),
component: module.component.clone(),
domain: module.domain.clone(),
function: functions.len() + result.len() + generated.len(),
span: *span,
};
for field in fields.iter().skip(2) {
let model = field.model.as_ref().unwrap();
let value = match method {
"POST" => model.create.as_ref(),
"PUT" => model.replace.as_ref(),
_ => None,
};
if let Some(value) = value {
bindings::bind(value, entry.function, types, calls, functions)?;
}
}
let search = if method == "GET" && !detail {
fields
.iter()
.position(|f| f.model.as_ref().is_some_and(|m| m.search.is_some()))
} else {
None
};
if let Some(field) = search {
entry.rest.as_mut().unwrap().search = Some((field, entry.function + 1));
}
generated.push(operation::function(
&entry, &identity, types, calls, constants, functions, false,
)?);
if let Some(field) = search {
let mut helper = entry.clone();
helper.function += 1;
bindings::bind(
fields[field]
.model
.as_ref()
.unwrap()
.search
.as_ref()
.unwrap(),
helper.function,
types,
calls,
functions,
)?;
generated.push(operation::function(
&helper, &identity, types, calls, constants, functions, true,
)?);
}
entries.push(entry);
}
Ok((entries, generated))
})();
match checked {
Ok((entries, generated)) => {
http.extend(entries);
result.extend(generated);
}
Err(error) => {
calls.edges.truncate(edge_start);
calls.by_span.retain(|_, index| *index < edge_start);
errors.push(error);
}
}
}
errors.extend(validation::unused(types, calls, constants, functions, http));
(result, errors)
}
@@ -0,0 +1,180 @@
//! 字段转换仅绑定真实纯函数和可信身份读取;没有运行时解释或动态调用。
use super::*;
pub(super) fn input(value: &ast::Expression) -> bool {
let mut found = false;
visit(value, &mut |value| {
found |= matches!(&value.kind,ast::ExpressionKind::Name(name) if name=="input");
Ok(())
})
.unwrap();
found
}
pub(super) fn validate(fields: &[Field], rest: bool) -> Result<(), Diagnostic> {
let mut search = false;
for field in fields.iter().skip(2) {
let model = field.model.as_ref().unwrap();
for value in [&model.create, &model.replace, &model.search]
.into_iter()
.flatten()
{
if model.generated || model.owner.is_some() {
return Err(Diagnostic::new(
"C014",
"generated and owner fields cannot have REST bindings",
field.span,
));
}
if field.private && input(value) {
return Err(Diagnostic::new(
"C014",
"private REST fields cannot read client input",
field.span,
));
}
}
if let Some(value) = &model.search {
if search
|| !input(value)
|| field.private
|| !(model.index || model.unique)
|| matches!(field.kind, Type::Optional(_) | Type::Json | Type::Bytes)
|| matches!(field.name.as_str(), "page" | "size")
{
return Err(Diagnostic::new(
"C014",
"REST permits one indexed public scalar search field; page and size are reserved",
field.span,
));
}
search = true;
}
if rest
&& field.private
&& model.create.is_none()
&& model.default.is_none()
&& model.owner.is_none()
&& !model.generated
&& !matches!(field.kind, Type::Optional(_))
{
return Err(Diagnostic::new(
"C014",
"REST private required field needs a source",
field.span,
));
}
}
Ok(())
}
pub(super) fn bind(
value: &ast::Expression,
caller: usize,
types: &Types<'_>,
calls: &mut calls::Calls<'_>,
functions: &[Option<Function>],
) -> Result<(), Diagnostic> {
visit(value, &mut |value| {
let ast::ExpressionKind::Call(target, _) = &value.kind else {
return Ok(());
};
let Some(name) = target.path() else {
return Err(Diagnostic::new(
"C004",
"REST calls must be statically named",
target.span,
));
};
let module = types.module(target.span.source);
let Some(&target) = calls.by_name.get(&module.reference(&name)) else {
return Ok(());
};
if target >= calls.concrete {
return Err(Diagnostic::new(
"C014",
"REST field calls cannot require static handler arguments",
value.span,
));
}
let function = functions[target].as_ref().ok_or_else(|| {
Diagnostic::new(
"C004",
"REST binding depends on an invalid function",
value.span,
)
})?;
let origin = types.module(function.signature.span.source);
if !(origin.bundled_library() || module.same_domain(origin) && origin.role == Role::Domain)
{
return Err(Diagnostic::new(
"C014",
"REST fields call same-domain pure functions or standard value operations",
value.span,
));
}
if !function.effects.pure() {
return Err(Diagnostic::new(
"C014",
"REST field functions must be pure",
value.span,
));
}
calls
.by_span
.insert((caller, value.span), calls.edges.len());
calls.edges.push(Call {
caller,
target,
span: value.span,
site: value.span,
through_handler: false,
static_arguments: Vec::new(),
});
Ok(())
})
}
fn visit(
value: &ast::Expression,
action: &mut impl FnMut(&ast::Expression) -> Result<(), Diagnostic>,
) -> Result<(), Diagnostic> {
let mut pending = vec![value];
while let Some(value) = pending.pop() {
action(value)?;
use ast::ExpressionKind::*;
match &value.kind {
Rule(rule) => pending.extend(
rule.rows
.iter()
.flat_map(|row| row.results.iter().flatten()),
),
Loop(l) => {
pending.push(&l.source);
for row in &l.rows {
pending.extend(
row.value
.iter()
.chain(row.fold.iter().map(|f| &f.seed))
.chain(row.guard.iter().map(|(g, _)| g)),
);
}
}
Call(target, args) => {
pending.push(target);
pending.extend(args);
}
Field(value, _) | Unary(_, value) | Channel(_, value) => pending.push(value),
Binary(_, a, b) => pending.extend([a.as_ref(), b.as_ref()]),
List(items) => pending.extend(items),
Map(items) => {
for (key, value) in items {
pending.extend([key, value]);
}
}
Record(_, items) => pending.extend(items.iter().map(|(_, v)| v)),
Literal(_) | Name(_) => {}
}
}
Ok(())
}
@@ -0,0 +1,432 @@
// REST 共享普通表达式与 Model SQL。
use super::*;
pub(super) fn function(
entry: &HttpEntry,
identity: &str,
types: &Types<'_>,
calls: &calls::Calls<'_>,
constants: &constants::Constants<'_>,
functions: &[Option<Function>],
filtered: bool,
) -> Result<Function, Diagnostic> {
let rest = entry.rest.as_ref().unwrap();
let span = entry.span;
let fields = types.definitions[rest.record].columns();
let field = |name: &str, kind| Field {
name: name.into(),
kind,
span,
model: None,
range: None,
private: false,
};
let mut inputs = Vec::new();
if rest.detail {
inputs.push(field("id", fields[0].kind.clone()));
}
let writing = matches!(entry.method.as_str(), "POST" | "PUT" | "DELETE");
if entry.method == "GET" && !rest.detail {
inputs.extend([field("page", Type::Int), field("size", Type::Int)]);
}
if filtered {
let mut field = fields[rest.search.unwrap().0].clone();
field.range = None;
inputs.push(field);
}
if matches!(entry.method.as_str(), "POST" | "PUT") {
inputs.extend(
fields
.iter()
.skip(2)
.filter(|f| {
let m = f.model.as_ref().unwrap();
let binding = if entry.method == "POST" {
&m.create
} else {
&m.replace
};
!f.private
&& binding.as_ref().is_none_or(bindings::input)
&& !f
.model
.as_ref()
.is_some_and(|m| m.generated || m.owner.is_some())
})
.cloned()
.map(|mut f| {
f.range = None;
f
}),
);
}
let mut checker = Checker {
constants,
constant_references: Vec::new(),
test_settings: false,
setting_references: Vec::new(),
allow_settings: false,
caller: entry.function,
unknown_failures: false,
types,
calls,
functions,
locals: inputs.clone(),
names: inputs
.iter()
.enumerate()
.map(|(i, f)| (f.name.clone(), i))
.collect(),
ranges: HashMap::new(),
bools: HashMap::new(),
variants: HashMap::new(),
failures: BTreeSet::new(),
contracts: HashMap::new(),
};
let (mut statements, value, extra_effects, empty_update) =
query(&mut checker, entry, rest, identity, &inputs, filtered)?;
let kind = if rest.detail && (entry.method == "GET" || empty_update) {
Type::Named(rest.record)
} else {
value.value_type.clone()
};
let output = checker.bind("rest_result".into(), kind.clone(), None, None, span);
if rest.detail && (entry.method == "GET" || empty_update) {
required(
&mut checker,
&mut statements,
value,
output,
node(
span,
ExpressionKind::ApiError(ApiError::NotFound),
Type::ApiError,
),
);
checker.failures.insert(Failure::Api(ApiError::NotFound));
} else {
statements.push(Statement::Assign {
local: output,
value,
});
}
let outputs = if entry.method == "DELETE" {
statements.push(Statement::Check {
condition: node(
span,
ExpressionKind::Binary(
Binary::Greater,
Box::new(checker.variable(output, span)),
Box::new(node(
span,
ExpressionKind::Number(numeric::Number::Int(0)),
Type::Int,
)),
),
Type::Bool,
),
error: node(
span,
ExpressionKind::ApiError(ApiError::NotFound),
Type::ApiError,
),
});
checker.failures.insert(Failure::Api(ApiError::NotFound));
Vec::new()
} else {
vec![output]
};
let function_name = format!(
"{}.rest{}{}",
types.module(span.source).identity(),
entry.method,
if rest.detail {
"Detail"
} else if filtered {
"Search"
} else {
"Collection"
}
);
let signature = Signature {
name: function_name.clone(),
source_name: function_name.clone(),
label: function_name,
inputs,
outputs: outputs
.iter()
.map(|_| field("value", kind.clone()))
.collect(),
span,
};
let body = Body::Statements {
statements,
outputs,
flow: None,
};
let failure_summary = crate::compiler::check::failure::check(
&signature,
&checker.locals,
&body,
false,
&types.definitions,
functions,
&types.error_types,
)?;
Ok(Function {
test_trace: false,
transaction: false,
effects: Effects {
request: extra_effects.request,
identity: rest.owner.is_some() || extra_effects.identity,
database: true,
database_write: writing,
suspends: true,
..Effects::default()
},
setting_references: Vec::new(),
uses_settings: false,
adapter_setting: None,
constant_references: checker.constant_references,
signature,
locals: checker.locals,
body,
failures: checker.failures,
failure_summary,
unknown_failures: false,
})
}
fn query(
checker: &mut Checker<'_>,
entry: &HttpEntry,
rest: &RestEntry,
identity: &str,
inputs: &[Field],
filtered: bool,
) -> Result<(Vec<Statement>, Expression, Effects, bool), Diagnostic> {
let span = entry.span;
let types = checker.types;
let fields = types.definitions[rest.record].columns();
let functions = checker.functions;
let name = |name: &str| ast::Expression {
kind: ast::ExpressionKind::Name(name.into()),
span,
depth: 0,
};
let block = |items: Vec<(&str, ast::Expression)>| ast::Expression {
kind: ast::ExpressionKind::Map(
items
.into_iter()
.map(|(key, value)| (name(key), value))
.collect(),
),
span,
depth: 1,
};
let binary = |op: &str, a, b| ast::Expression {
kind: ast::ExpressionKind::Binary(op.into(), Box::new(a), Box::new(b)),
span,
depth: 1,
};
let mut statements = Vec::new();
let mut filter = if rest.detail {
Some(binary("==", name("id"), name("id")))
} else {
None
};
if let Some((position, user)) = rest.owner {
let Type::ModelId(source) = fields[position].kind else {
unreachable!()
};
let local = checker.bind(
"#rest_owner".into(),
fields[position].kind.clone(),
None,
None,
span,
);
required(
checker,
&mut statements,
node(
span,
ExpressionKind::Builtin(
Builtin::Identity(if user {
IdentityOp::User(source)
} else {
IdentityOp::Tenant(source)
}),
vec![],
),
Type::Optional(Box::new(fields[position].kind.clone())),
),
local,
node(
span,
ExpressionKind::ApiError(ApiError::Forbidden),
Type::ApiError,
),
);
checker.failures.insert(Failure::Api(ApiError::Forbidden));
let condition = binary("==", name(&fields[position].name), name("#rest_owner"));
filter = Some(match filter {
Some(previous) => binary("and", previous, condition),
None => condition,
});
}
let mut write_values = Vec::new();
let mut extra_effects = Effects::default();
let mut search_local = None;
if filtered {
let position = rest.search.unwrap().0;
let field = &fields[position];
let binding = field.model.as_ref().unwrap().search.as_ref().unwrap();
let names = std::mem::take(&mut checker.names);
checker.names.insert("input".into(), 2);
let value = validation::expression(checker, binding, &field.kind)?;
checker.names = names;
let effects = value.effects(functions);
extra_effects.include(effects);
let local = checker.bind(
"#rest_search".into(),
field.kind.clone(),
None,
None,
binding.span,
);
statements.push(Statement::Assign { local, value });
let condition = binary("==", name(&field.name), name("#rest_search"));
filter = Some(match filter {
Some(previous) => binary("and", previous, condition),
None => condition,
});
search_local = Some((position, local));
}
if matches!(entry.method.as_str(), "POST" | "PUT") {
for (position, field) in fields.iter().enumerate().skip(2) {
let model = field.model.as_ref().unwrap();
if model.generated || model.owner.is_some() {
continue;
}
let binding = if entry.method == "POST" {
&model.create
} else {
&model.replace
};
if let Some(binding) = binding {
let names = std::mem::take(&mut checker.names);
if bindings::input(binding) {
checker.names.insert(
"input".into(),
inputs.iter().position(|f| f.name == field.name).unwrap(),
);
}
let value = validation::expression(checker, binding, &field.kind)?;
checker.names = names;
let effects = value.effects(functions);
extra_effects.include(effects);
let key = format!("#rest_field_{position}");
let local = checker.bind(key.clone(), field.kind.clone(), None, None, binding.span);
statements.push(Statement::Assign { local, value });
write_values.push((field.name.as_str(), name(&key)));
} else if !field.private {
write_values.push((field.name.as_str(), name(&field.name)));
}
}
if entry.method == "POST"
&& let Some((position, _)) = rest.owner
{
write_values.push((&fields[position].name, name("#rest_owner")));
}
}
let mut query = Vec::new();
if let Some(filter) = filter {
query.push(("where", filter));
}
if entry.method == "GET" && !rest.detail {
query.extend([("page", name("page")), ("size", name("size"))]);
}
let query = block(query);
let empty_update = entry.method == "PUT" && write_values.is_empty();
let (operation, arguments) = match entry.method.as_str() {
"POST" => ("create", vec![block(write_values)]),
"PUT" if empty_update => ("first", vec![query]),
"PUT" => ("update", vec![query, block(write_values)]),
"DELETE" => ("delete", vec![query]),
_ if rest.detail => ("first", vec![query]),
_ => ("page", vec![query]),
};
let mut value =
checker.model_operation(identity, rest.record, operation, &arguments, span, true)?;
search_input(&mut value, rest.record, search_local, span);
if entry.method == "PUT" && !empty_update {
checker.model_returning(&mut value, rest.record);
}
Ok((statements, value, extra_effects, empty_update))
}
fn search_input(value: &mut Expression, record: usize, search: Option<(usize, usize)>, span: Span) {
if let Some((position, local)) = search {
let ExpressionKind::Builtin(_, parameters) = &mut value.kind else {
unreachable!()
};
for parameter in parameters {
if matches!(parameter.kind,ExpressionKind::Variable(index) if index==local) {
*parameter = node(
span,
ExpressionKind::Builtin(
Builtin::ModelInput {
write: true,
record,
field: position,
},
vec![parameter.clone()],
),
parameter.value_type.clone(),
);
} else if let ExpressionKind::Builtin(Builtin::ModelInput { field, write, .. }, _) =
&mut parameter.kind
&& *field == position
{
*write = true;
}
}
}
}
fn node(span: Span, kind: ExpressionKind, value_type: Type) -> Expression {
Expression {
kind,
value_type,
span,
range: None,
known_bool: None,
}
}
fn required(
checker: &mut Checker<'_>,
statements: &mut Vec<Statement>,
value: Expression,
local: usize,
error: Expression,
) {
let span = value.span;
let original = checker.bind(
format!("#rest_optional_{}", checker.locals.len()),
value.value_type.clone(),
None,
None,
span,
);
statements.push(Statement::Assign {
local: original,
value,
});
statements.push(Statement::NonNull {
value: checker.variable(original, span),
local,
error,
});
}
@@ -0,0 +1,87 @@
//! 未绑定 REST 的字段来源也检查;验证产生的调用边不进入可执行程序。
use super::*;
pub(super) fn unused(
types: &Types<'_>,
calls: &mut calls::Calls<'_>,
constants: &constants::Constants<'_>,
functions: &[Option<Function>],
http: &[HttpEntry],
) -> Vec<Diagnostic> {
let used = http
.iter()
.filter_map(|e| e.rest.as_ref().map(|r| r.record))
.collect::<BTreeSet<_>>();
let mut errors = Vec::new();
for (index, definition) in types.definitions.iter().enumerate() {
if definition.model.is_none() || used.contains(&index) {
continue;
}
let fields = definition.columns();
if let Err(error) = bindings::validate(fields, false) {
errors.push(error);
continue;
}
for field in fields.iter().skip(2) {
let model = field.model.as_ref().unwrap();
for source in [&model.create, &model.replace, &model.search]
.into_iter()
.flatten()
{
let first = calls.edges.len();
let checked = (|| {
bindings::bind(source, functions.len(), types, calls, functions)?;
let mut input = field.clone();
input.name = "input".into();
input.range = None;
input.model = None;
let mut checker = Checker {
constants,
constant_references: Vec::new(),
test_settings: false,
setting_references: Vec::new(),
allow_settings: false,
caller: functions.len(),
unknown_failures: false,
types,
calls,
functions,
locals: vec![input],
names: [("input".into(), 0)].into(),
ranges: HashMap::new(),
bools: HashMap::new(),
variants: HashMap::new(),
failures: BTreeSet::new(),
contracts: HashMap::new(),
};
expression(&mut checker, source, &field.kind).map(|_| ())
})();
calls.edges.truncate(first);
calls.by_span.retain(|_, edge| *edge < first);
if let Err(error) = checked {
errors.push(error);
}
}
}
}
errors
}
pub(super) fn expression(
checker: &mut Checker<'_>,
source: &ast::Expression,
kind: &Type,
) -> Result<Expression, Diagnostic> {
let value = checker.expression(source, Some(kind))?;
let mut effects = value.effects(checker.functions);
effects.identity = false;
effects.request = effects.response_headers;
if !effects.pure() {
return Err(Diagnostic::new(
"C014",
"REST fields permit only values, trusted identity and read-only request metadata",
source.span,
));
}
Ok(value)
}
+165
View File
@@ -0,0 +1,165 @@
//! 顺序流使用相同的语句、范围和失败分析;这里只检查行绑定与声明种类。
use super::*;
pub(super) fn check(
checker: &mut Checker<'_>,
signature: &Signature,
steps: &[ast::FlowStep],
) -> Result<Body, Diagnostic> {
groups(steps)?;
let mut body = statements::check(
checker,
signature,
steps.iter().map(|step| &step.statement),
Some(steps),
)?;
let Body::Statements {
statements, flow, ..
} = &mut body
else {
unreachable!()
};
let mut rows = Vec::with_capacity(steps.len());
for (step, statement) in steps.iter().zip(statements.iter()) {
let kind = if matches!(step.statement, ast::Statement::Check { .. }) {
StepKind::Check
} else {
let value = match statement {
Statement::Assign { value, .. } | Statement::Action(value) => value,
_ => unreachable!("checked expression step"),
};
kind(checker, value)
};
if step.kind.is_some_and(|declared| declared != kind) {
return Err(Diagnostic::new(
"C005",
format!("flow step kind must be {}", kind.name()),
step.kind_span,
));
}
rows.push(FlowStep {
parallel: step.parallel.clone(),
kind,
span: step.span,
});
}
dependencies(statements, &rows)?;
*flow = Some(rows);
Ok(body)
}
fn kind(checker: &Checker<'_>, value: &Expression) -> StepKind {
let value = match &value.kind {
ExpressionKind::Capture(capture) => &capture.call,
_ => value,
};
match &value.kind {
ExpressionKind::Rule { .. } => return StepKind::Rule,
ExpressionKind::Loop(_) => return StepKind::Loop,
_ => {}
}
if matches!(
value.kind,
ExpressionKind::Builtin(Builtin::Database { .. }, _)
) {
return StepKind::Model;
}
let ExpressionKind::Call(target, _) = value.kind else {
return StepKind::Calc;
};
if checker.calls.ports.contains_key(&target) {
return StepKind::Port;
}
let edge = &checker.calls.edges[checker.calls.by_span[&(checker.caller, value.span)]];
if edge.through_handler {
return StepKind::Calc;
}
match checker.functions[target]
.as_ref()
.expect("checked target")
.body
{
Body::Rule(_) => StepKind::Rule,
Body::Loop(_) => StepKind::Loop,
Body::Statements { flow: Some(_), .. } => StepKind::Flow,
Body::Dispatch(_) => StepKind::Port,
Body::Statements { .. } | Body::Contract => StepKind::Calc,
}
}
// 一组必须连续且至少两步;守卫只在明确的顺序位置建立事实。
fn groups(steps: &[ast::FlowStep]) -> Result<(), Diagnostic> {
let mut seen = HashSet::new();
let mut start = 0;
while start < steps.len() {
let Some(name) = &steps[start].parallel else {
start += 1;
continue;
};
crate::syntax::names::validate(
name,
crate::syntax::names::Style::Value,
steps[start].span,
)?;
let end = start
+ steps[start..]
.iter()
.take_while(|step| step.parallel.as_ref() == Some(name))
.count();
if end - start < 2 || !seen.insert(name) {
return Err(Diagnostic::new(
"C013",
"parallel group requires one contiguous segment of at least two steps",
steps[start].span,
));
}
for step in &steps[start..end] {
if matches!(step.statement, ast::Statement::Check { .. }) {
return Err(Diagnostic::new(
"C013",
"parallel groups cannot contain check steps",
step.span,
));
}
}
start = end;
}
Ok(())
}
fn dependencies(statements: &[Statement], steps: &[FlowStep]) -> Result<(), Diagnostic> {
let mut start = 0;
while start < steps.len() {
let end = FlowStep::end(steps, start);
if steps[start].parallel.is_some() {
let locals = statements[start..end]
.iter()
.filter_map(|statement| match statement {
Statement::Assign { local, .. } => Some(*local),
_ => None,
})
.collect::<HashSet<_>>();
for statement in &statements[start..end] {
let mut invalid = None;
statement.value().visit(&mut |value| {
if let ExpressionKind::Variable(local) = value.kind
&& locals.contains(&local)
{
invalid = Some(value.span);
}
true
});
if let Some(span) = invalid {
return Err(Diagnostic::new(
"C013",
"parallel steps cannot read another result in the same group",
span,
));
}
}
}
start = end;
}
Ok(())
}
+70
View File
@@ -0,0 +1,70 @@
//! 初值使用输出合同;每轮只依赖累积状态合同,不把初值的字面量事实带进后续轮次。
use super::*;
use crate::syntax::names::{self, Style};
pub(super) fn check(
checker: &mut Checker<'_>,
source: &ast::Fold,
row: &ast::LoopRow,
field: &Field,
seed: Expression,
reserved: &HashSet<String>,
) -> Result<(Fold, Expression), Diagnostic> {
names::validate(&source.accumulator, Style::Value, source.span)?;
if reserved.contains(&source.accumulator) {
return Err(Diagnostic::new(
"C005",
"fold accumulator cannot shadow inputs, outputs or row bindings",
source.span,
));
}
let accumulator = checker.bind(
source.accumulator.clone(),
field.kind.clone(),
field.range,
None,
source.span,
);
let value = checker.expression(row.value.as_ref().expect("parsed fold update"), None)?;
let ExpressionKind::Call(target, _) = value.kind else {
return Err(Diagnostic::new(
"C005",
"fold update must be a statically named function call",
value.span,
));
};
let outputs = &checker.functions[target]
.as_ref()
.expect("checked update")
.signature
.outputs;
let valid = if row.aggregate == Aggregate::Fold {
outputs.len() == 1 && outputs[0].kind == field.kind
} else {
outputs.len() == 2
&& outputs[0].name == "acc"
&& outputs[0].kind == field.kind
&& outputs[1].name == "stop"
&& outputs[1].kind == Type::Bool
};
if !valid {
return Err(Diagnostic::new(
"C005",
"fold update must return the state type; foldUntil requires (acc: S, stop: Bool)",
value.span,
));
}
if let Some(required) = field.range
&& !outputs[0]
.guaranteed_range()
.is_some_and(|actual| required.contains(actual))
{
return Err(Diagnostic::new(
"C008",
"cannot prove fold update preserves the accumulator range",
value.span,
));
}
Ok((Fold { accumulator, seed }, value))
}
@@ -0,0 +1,57 @@
//! handler 输入接收合同内的所有值,输出保证不得弱于声明;不依赖实现的检查顺序。
use super::*;
pub(super) fn check(
index: usize,
types: &Types<'_>,
calls: &calls::Calls<'_>,
) -> Result<(), Diagnostic> {
for binding in &calls.contracts[index] {
let contract = binding
.parameter
.kind
.handler
.as_ref()
.expect("handler parameter");
let target = &calls.functions[binding.target];
let expected_inputs = types.inputs(&contract.inputs)?;
let expected_outputs = types.fields(&contract.outputs)?;
let actual_inputs = types.inputs(&target.inputs)?;
let actual_outputs = types.fields(&target.outputs)?;
let compatible = expected_inputs.len() == actual_inputs.len()
&& expected_outputs.len() == actual_outputs.len()
&& expected_inputs
.iter()
.zip(&actual_inputs)
.all(|(expected, actual)| accepts(actual, expected))
&& expected_outputs
.iter()
.zip(&actual_outputs)
.all(|(expected, actual)| {
expected.name == actual.name && accepts(expected, actual)
});
if !compatible {
let mut error = Diagnostic::new(
"C005",
"handler input, named output or numeric range does not satisfy its declaration",
binding.span,
);
error
.related
.push((binding.parameter.span, "handler contract".into()));
error.related.push((target.span, "bound function".into()));
return Err(error);
}
}
Ok(())
}
fn accepts(receiver: &Field, value: &Field) -> bool {
receiver.kind == value.kind
&& receiver.range.is_none_or(|required| {
value
.guaranteed_range()
.is_some_and(|range| required.contains(range))
})
}
@@ -0,0 +1,396 @@
//! 循环一次绑定来源和元素,各输出独立计算;输出不是可供其他行读取的局部变量。
mod filters;
use super::*;
use crate::syntax::names::{self, Style};
pub(in crate::compiler::check) fn check(
checker: &mut Checker<'_>,
fields: &[Field],
iteration: &ast::Loop,
) -> Result<Loop, Diagnostic> {
names::validate(&iteration.item, Style::Value, iteration.item_span)?;
if checker.names.contains_key(&iteration.item)
|| fields.iter().any(|f| f.name == iteration.item)
{
return Err(Diagnostic::new(
"C005",
"loop item cannot shadow inputs or outputs",
iteration.item_span,
));
}
let (source, kind) = super::iteration_source::check(checker, &iteration.source)?;
let parallel = parallel(checker, iteration)?;
let range = matches!(source, LoopSource::Bytes(_)).then_some(numeric::Range {
minimum: numeric::Number::Int(0),
maximum: numeric::Number::Int(255),
});
let item = checker.bind(
iteration.item.clone(),
kind,
range,
None,
iteration.item_span,
);
let mut headers = Vec::new();
for filter in &iteration.filters {
let value = infallible(checker, filter, None)?;
headers.push(value);
}
let mut outputs = HashSet::new();
let mut rows = Vec::new();
let names = checker.names.clone();
for row in &iteration.rows {
checker.names.clone_from(&names);
checker.ranges.clear();
checker.bools.clear();
checker.variants.clear();
let output = row
.output
.as_ref()
.map(|name| {
let index = fields.iter().position(|f| f.name == *name).ok_or_else(|| {
Diagnostic::new("C005", "loop row must name a declared output", row.span)
})?;
if !outputs.insert(index) {
return Err(Diagnostic::new("C005", "duplicate loop output", row.span));
}
Ok(index)
})
.transpose()?;
let field = output.map(|index| &fields[index]);
if output.is_none()
&& (!fields.is_empty() || iteration.rows.len() != 1 || row.aggregate != Aggregate::Do)
{
return Err(Diagnostic::new(
"C005",
"zero-output loop requires exactly one '-' do row",
row.span,
));
}
checker.names.remove(&iteration.item);
let seed = row
.fold
.as_ref()
.map(|fold| {
let field = field.ok_or_else(|| {
Diagnostic::new("C005", "fold requires a declared output", row.span)
})?;
checker
.field_value(&fold.seed, field)
.map(|seed| (fold, field, seed))
})
.transpose()?;
let take = take_limit(checker, row)?;
checker.names.insert(iteration.item.clone(), item);
let guard = row
.guard
.as_ref()
.map(|(selector, branch)| {
let value = infallible(checker, selector, Some(&Type::Bool))?;
let condition = ast::Condition {
alternatives: vec![ast::Pattern::Literal(ast::Literal::Bool(*branch))],
span: selector.span,
};
Ok::<_, Diagnostic>((condition, value))
})
.transpose()?;
let conditions = row
.conditions
.iter()
.zip(&headers)
.chain(guard.as_ref().map(|(c, v)| (c, v)));
let (filters, bound) = filters::check(checker, fields, conditions)?;
let sort = sort_keys(checker, row)?;
let expected = aggregate_type(row, field.map(|f| &f.kind), &checker.locals[item].kind)?;
let (fold, value) = if let Some((source, field, seed)) = seed {
let (fold, value) = super::fold::check(checker, source, row, field, seed, &bound)?;
(Some(fold), Some(value))
} else {
(
None,
row.value
.as_ref()
.map(|value| checker.expression(value, expected))
.transpose()?,
)
};
let element =
matches!(row.aggregate, Aggregate::Group | Aggregate::Index).then(|| Expression {
kind: ExpressionKind::Variable(item),
value_type: checker.locals[item].kind.clone(),
range: None,
known_bool: None,
span: row.span,
});
if row.aggregate == Aggregate::Index {
checker
.failures
.insert(Failure::Choice(COLLECTION_ERROR, 0));
}
if row.aggregate == Aggregate::Do {
let module = checker.calls.functions[checker.caller].span.source;
// 与 flow 的动作行相同:真实失败必须传播,纯无用结果不能藏在 do 中。
if checker.types.module(module).role == Role::Domain {
return Err(Diagnostic::new(
"C003",
"loop do belongs in app or adapter",
row.span,
));
}
let value = value.as_ref().expect("parsed do call");
let call = matches!(
row.value.as_ref().unwrap().kind,
ast::ExpressionKind::Call(..)
);
let fallible = matches!(value.kind, ExpressionKind::Call(target, _) if !checker.functions[target].as_ref().expect("checked target").failures.is_empty());
if !call
|| (!matches!(value.value_type, Type::Unit | Type::Never)
&& !fallible
&& value.effects(checker.functions).pure())
{
return Err(Diagnostic::new(
"C005",
"loop do requires a call; discarding a pure infallible value is unused computation",
row.span,
));
}
}
if let Some(field) = field
&& let Some(required) = field.range
&& fold.is_none()
{
let actual = match row.aggregate {
Aggregate::Count | Aggregate::Do => numeric::Range {
minimum: numeric::Number::Int(0),
maximum: numeric::Number::Int(i64::MAX),
},
_ => numeric::Range::full(&field.kind),
};
if !required.contains(actual) {
return Err(Diagnostic::new(
"C008",
"cannot prove numeric range for loop output including empty input",
row.span,
));
}
}
rows.push(LoopRow {
output,
filters,
take,
sort,
aggregate: row.aggregate,
value,
element,
fold,
span: row.span,
});
}
if outputs.len() != fields.len() {
return Err(Diagnostic::new(
"C005",
"every loop output requires one row",
iteration.item_span,
));
}
Ok(Loop {
source,
parallel,
item,
rows,
})
}
fn infallible(
checker: &mut Checker<'_>,
source: &ast::Expression,
expected: Option<&Type>,
) -> Result<Expression, Diagnostic> {
// 独立收集效果,不能因来源或其他行已有同类失败而漏报。
let failures = std::mem::take(&mut checker.failures);
let unknown = std::mem::replace(&mut checker.unknown_failures, false);
let value = checker.expression(source, expected)?;
super::super::effects::pure(&value, checker.functions)?;
if !checker.failures.is_empty() || checker.unknown_failures {
return Err(Diagnostic::new(
"C005",
"loop filter or limit must not propagate a business failure",
source.span,
));
}
checker.failures = failures;
checker.unknown_failures = unknown;
Ok(value)
}
fn parallel(
checker: &mut Checker<'_>,
iteration: &ast::Loop,
) -> Result<Option<Expression>, Diagnostic> {
iteration
.parallel
.as_ref()
.map(|limit| {
let value = infallible(checker, limit, Some(&Type::Int))?;
if !value.range.is_some_and(|range| {
range.minimum >= numeric::Number::Int(1)
&& range.maximum <= numeric::Number::Int(65536)
}) {
return Err(Diagnostic::new(
"C008",
"parallel loop capacity must be proved within 1..65536",
limit.span,
));
}
if iteration.sort
|| iteration.take
|| iteration
.rows
.iter()
.any(|row| !matches!(row.aggregate, Aggregate::List | Aggregate::Do))
{
return Err(Diagnostic::new(
"C005",
"parallel loop allows only list/do rows, without sort or take",
limit.span,
));
}
Ok(value)
})
.transpose()
}
fn sort_keys(checker: &mut Checker<'_>, row: &ast::LoopRow) -> Result<Vec<SortKey>, Diagnostic> {
let mut sort = Vec::new();
if let Some(keys) = &row.sort {
if row.aggregate != Aggregate::List {
return Err(Diagnostic::new(
"C005",
"sort is only allowed on list rows",
keys.span,
));
}
let ast::ExpressionKind::List(keys) = &keys.kind else {
return Err(Diagnostic::new(
"C005",
"sort requires a list of asc or desc keys",
keys.span,
));
};
if keys.is_empty() {
return Err(Diagnostic::new(
"C005",
"sort requires at least one key",
row.span,
));
}
for key in keys {
let ast::ExpressionKind::Field(source, direction) = &key.kind else {
return Err(Diagnostic::new(
"C005",
"sort key requires .asc or .desc",
key.span,
));
};
if direction != "asc" && direction != "desc" {
return Err(Diagnostic::new(
"C005",
"sort key requires .asc or .desc",
key.span,
));
}
let value = infallible(checker, source, None)?;
if !total_order(&value.value_type) {
return Err(Diagnostic::new(
"C005",
"sort key requires a non-null total order",
source.span,
));
}
sort.push(SortKey {
value,
descending: direction == "desc",
});
}
}
Ok(sort)
}
fn aggregate_type<'a>(
row: &ast::LoopRow,
output_type: Option<&'a Type>,
item_kind: &Type,
) -> Result<Option<&'a Type>, Diagnostic> {
Ok(match (row.aggregate, output_type) {
(Aggregate::Fold | Aggregate::FoldUntil, Some(_)) => None,
(Aggregate::List, Some(Type::List(inner))) => Some(inner.as_ref()),
(Aggregate::Group, Some(Type::Map(key, values))) if matches!(values.as_ref(), Type::List(inner) if **inner == *item_kind) => {
Some(key.as_ref())
}
(Aggregate::Index, Some(Type::Map(key, value))) if **value == *item_kind => {
Some(key.as_ref())
}
(Aggregate::Sum, Some(kind @ (Type::Int | Type::Float | Type::Decimal))) => Some(kind),
(Aggregate::Count, Some(Type::Int)) => None,
(Aggregate::First, Some(Type::Optional(inner))) => Some(inner.as_ref()),
(Aggregate::Min | Aggregate::Max, Some(Type::Optional(inner))) if total_order(inner) => {
Some(inner.as_ref())
}
(Aggregate::Any | Aggregate::All, Some(Type::Bool)) => Some(&Type::Bool),
(Aggregate::Do, None | Some(Type::Int)) => None,
_ => {
return Err(Diagnostic::new(
"C005",
"loop aggregate does not match its output type",
row.span,
));
}
})
}
fn take_limit(
checker: &mut Checker<'_>,
row: &ast::LoopRow,
) -> Result<Option<Expression>, Diagnostic> {
row.take
.as_ref()
.map(|limit| {
if row.aggregate != Aggregate::List {
return Err(Diagnostic::new(
"C005",
"take is only allowed on list rows",
limit.span,
));
}
let value = infallible(checker, limit, Some(&Type::Int))?;
if !value
.range
.is_some_and(|range| range.minimum >= numeric::Number::Int(0))
{
return Err(Diagnostic::new(
"C008",
"take requires a proved nonnegative Int",
limit.span,
));
}
Ok(value)
})
.transpose()
}
fn total_order(kind: &Type) -> bool {
matches!(
kind,
Type::Int
| Type::Decimal
| Type::Text
| Type::Bool
| Type::ModelId(_)
| Type::DateTime
| Type::Date
| Type::Time
| Type::Duration
)
}
@@ -0,0 +1,103 @@
//! 过滤条件建立本行的类型事实与绑定,其他行从原环境重新检查。
use super::*;
use crate::compiler::check::rules;
pub(super) fn check<'a>(
checker: &mut Checker<'_>,
fields: &[Field],
conditions: impl Iterator<Item = (&'a ast::Condition, &'a Expression)>,
) -> Result<(Vec<LoopFilter>, HashSet<String>), Diagnostic> {
let mut filters = Vec::new();
let mut bound = checker.names.keys().cloned().collect::<HashSet<_>>();
bound.extend(fields.iter().map(|field| field.name.clone()));
for (condition, value) in conditions {
if condition
.alternatives
.iter()
.any(|pattern| matches!(pattern, ast::Pattern::Other))
{
return Err(Diagnostic::new(
"C005",
"loop filters do not have an other complement",
condition.span,
));
}
let condition =
rules::resolve_condition(condition, &value.value_type, checker.types, &mut bound)?;
// '-' 不求值列头;同格有任意条件时其他候选也不增加计算。
if !condition
.alternatives
.iter()
.any(|pattern| matches!(pattern, Pattern::Any))
{
let mut present = None;
let mut input_fact = None;
if let ExpressionKind::Variable(input) = value.kind {
let mut local = checker.names[&checker.locals[input].name];
let mut field = checker.locals[local].clone();
field.range = checker.ranges.get(&local).copied().or(field.range);
let fact = rules::filter_fact(&field, &condition, checker.types)?;
input_fact = Some(fact.clone());
if fact.present
&& let Type::Optional(inner) = &checker.locals[local].kind
{
let source = local;
local = checker.bind(
field.name,
inner.as_ref().clone(),
fact.range,
fact.boolean,
condition.span,
);
present = Some(PresentInput {
input: source,
local,
});
}
if let Some(range) = fact.range {
checker.ranges.insert(local, range);
}
if let Some(value) = fact.boolean {
checker.bools.insert(local, value);
}
if let Some(variants) = fact.variants {
checker.variants.insert(local, variants);
}
}
let has_bindings = matches!(&condition.alternatives[0], Pattern::Variant(_, names) if !names.is_empty());
let (binding_source, temporary, bindings) = if has_bindings {
let (source, temporary) = if let ExpressionKind::Variable(local) = value.kind {
(local, false)
} else {
let local = checker.locals.len();
checker.locals.push(Field {
model: None,
name: String::new(),
kind: value.value_type.clone(),
range: value.range,
private: false,
span: value.span,
});
(local, true)
};
(
Some(source),
temporary,
super::super::rule::bind_payloads(checker, source, &condition),
)
} else {
(None, false, Vec::new())
};
filters.push(LoopFilter {
value: value.clone(),
condition,
fact: input_fact,
present,
binding_source,
temporary,
bindings,
});
}
}
Ok((filters, bound))
}
@@ -0,0 +1,164 @@
//! 来源合同独立于各输出行;walk 的每次推进都是现有调用图中的具名调用。
use super::*;
pub(super) fn check(
checker: &mut Checker<'_>,
source: &ast::Expression,
) -> Result<(LoopSource, Type), Diagnostic> {
if checker.calls.walks.contains(&(checker.caller, source.span)) {
return walk(checker, source);
}
if let ast::ExpressionKind::Call(target, arguments) = &source.kind
&& target.path().as_deref() == Some("range")
&& !checker
.calls
.by_span
.contains_key(&(checker.caller, source.span))
{
let [start, end] = arguments.as_slice() else {
return Err(Diagnostic::new(
"C005",
"range requires start and end",
source.span,
));
};
return Ok((
LoopSource::Range(
checker.expression(start, Some(&Type::Int))?,
checker.expression(end, Some(&Type::Int))?,
),
Type::Int,
));
}
let value = checker.expression(source, None)?;
// 必定失败的具名调用仍有声明合同,用它检查不可达的循环体。
let declared = if value.value_type == Type::Never
&& let ExpressionKind::Call(target, _) = &value.kind
{
match checker.functions[*target]
.as_ref()
.unwrap()
.signature
.outputs
.as_slice()
{
[field] => Some(&field.kind),
_ => None,
}
} else {
Some(&value.value_type)
};
if declared == Some(&Type::Bytes) {
return Ok((LoopSource::Bytes(value), Type::Int));
}
if let Some(Type::AsyncStream(item)) = declared {
let kind = item.as_ref().clone();
if matches!(&kind, Type::Named(index) if checker.types.definitions[*index].model.is_some())
{
let error = checker
.types
.named("dever.database.Error", source.span.source)
.unwrap();
checker
.failures
.extend((0..10).map(|variant| Failure::Choice(error, variant)));
}
return Ok((LoopSource::Stream(value), kind));
}
if let Some(Type::Stream(item)) = declared {
let kind = item.as_ref().clone();
return Ok((LoopSource::SyncStream(value), kind));
}
let Some(Type::List(item)) = declared else {
return Err(Diagnostic::new(
"C005",
"loop source must be a List, Bytes, Stream, AsyncStream, range or walk",
source.span,
));
};
let kind = item.as_ref().clone();
Ok((LoopSource::List(value), kind))
}
fn walk(
checker: &mut Checker<'_>,
source: &ast::Expression,
) -> Result<(LoopSource, Type), Diagnostic> {
let ast::ExpressionKind::Call(_, arguments) = &source.kind else {
unreachable!("bound walk")
};
let edge = checker.calls.by_span[&(checker.caller, source.span)];
let target = checker.calls.edges[edge].target;
let function = checker.functions[target]
.as_ref()
.expect("checked walk step");
let ([parameter], [output]) = (
function.signature.inputs.as_slice(),
function.signature.outputs.as_slice(),
) else {
return Err(Diagnostic::new(
"C005",
"walk next requires one state input and one Walk output",
arguments[1].span,
));
};
let Some((item, kind)) = checker.types.walk(&output.kind) else {
return Err(Diagnostic::new(
"C005",
"walk next must return Walk<T, S>",
arguments[1].span,
));
};
if *kind != parameter.kind {
return Err(Diagnostic::new(
"C005",
"walk next must preserve its state type",
arguments[1].span,
));
}
if let Some(required) = parameter.range
&& !required.contains(numeric::Range::full(kind))
{
return Err(Diagnostic::new(
"C008",
"walk state range must hold after every Next",
arguments[1].span,
));
}
let seed = checker.field_value(&arguments[0], parameter)?;
let state = checker.locals.len();
checker.locals.push(Field {
model: None,
name: String::new(),
kind: kind.clone(),
range: None,
private: false,
span: source.span,
});
let update = Expression {
kind: ExpressionKind::Call(target, vec![checker.variable(state, arguments[1].span)]),
value_type: if function.failure_summary.output.is_none() {
Type::Never
} else {
output.kind.clone()
},
range: None,
known_bool: None,
span: source.span,
};
checker.failures.extend(&function.failures);
checker.unknown_failures |= function.unknown_failures;
let Type::Named(definition) = output.kind else {
unreachable!("concrete Walk choice")
};
Ok((
LoopSource::Walk {
seed,
state,
update,
definition,
},
item.clone(),
))
}
+104
View File
@@ -0,0 +1,104 @@
//! 队列处理器独立验收:参数匹配、零输出、普通事务与 long 显式事务。
use super::*;
pub(super) fn check(
jobs: &[Job],
functions: &[Option<Function>],
definitions: &[Definition],
modules: &[Module],
calls: &calls::Calls<'_>,
) -> Vec<Diagnostic> {
jobs.iter()
.filter_map(|job| {
let result = (|| {
let invalid = |message| Diagnostic::new("C005", message, job.span);
let &target = calls
.by_name
.get(&job.target)
.ok_or_else(|| invalid("unknown Job target"))?;
if target >= calls.concrete {
return Err(invalid("Job target cannot require a static handler"));
}
let function = functions[target]
.as_ref()
.ok_or_else(|| invalid("invalid Job target"))?;
if function.effects.authorization_write {
return Err(invalid(
"authorization changes require an ordinary protected HTTP write entry",
));
}
if function.effects.session || function.effects.request {
return Err(invalid(
"Job cannot use HTTP request context, issue tokens or change Cookies",
));
}
if job.cron.is_some() && function.effects.identity {
return Err(invalid("scheduled System Job cannot read a user identity"));
}
let origin = &modules[function.signature.span.source];
if origin.role != Role::App || !origin.same_domain(&modules[job.span.source]) {
return Err(invalid("Job target must be an App in the same domain"));
}
if !function.signature.outputs.is_empty()
|| function.signature.inputs.len() != job.inputs.len()
|| function
.signature
.inputs
.iter()
.zip(&job.inputs)
.any(|(target, input)| {
target.kind != input.kind || target.range != input.range
})
{
return Err(invalid(
"Job target requires matching inputs and no outputs",
));
}
super::super::wire::signature(&function.signature, definitions, job.span, false)?;
if job.long {
super::super::effects::long_entry(target, functions, job.span)?;
} else if !function.effects.transaction_safe() {
return Err(Diagnostic::new(
"C013",
"ordinary Job is transactional; external effects require long job",
job.span,
));
}
if !job.long {
queue_database(job, target, jobs, functions, definitions, calls)?;
}
Ok(())
})();
result.err()
})
.collect()
}
// 普通 Job 的确认与业务共用事务,不能到另一个命名库执行后才报错。
fn queue_database(
job: &Job,
root: usize,
jobs: &[Job],
functions: &[Option<Function>],
definitions: &[Definition],
calls: &calls::Calls<'_>,
) -> Result<(), Diagnostic> {
let invalid = reachable_expression(root, functions, calls, |value| {
let database = match &value.kind {
ExpressionKind::Builtin(Builtin::Database { record, .. }, _) => {
&definitions[*record].model.as_ref().unwrap().database
}
ExpressionKind::Builtin(Builtin::JobStates { .. }, _) => {
return job.database != "default";
}
ExpressionKind::Builtin(Builtin::Enqueue { job, .. }, _) => &jobs[*job].database,
_ => return false,
};
*database != job.database
});
if let Some(span) = invalid {
let mut error = Diagnostic::new("C013", "ordinary Job must use its queue database", span);
error.related.push((job.span, "Job queue binding".into()));
return Err(error);
}
Ok(())
}
+476
View File
@@ -0,0 +1,476 @@
//! 按依赖顺序构造具体程序;被拒绝的定义不会变成可生成的占位函数。
mod auth;
mod entry;
mod flow;
mod fold;
mod handler;
pub(super) mod iteration;
mod iteration_source;
mod job;
mod port;
pub(super) mod rule;
mod statements;
mod upload;
use super::{calls, constants, types::Types, value::Checker};
use crate::compiler::{
model::*,
project::{Module, Role},
};
use crate::syntax::{ast, diagnostic::Diagnostic, source::Span};
use std::collections::{BTreeSet, HashMap, HashSet};
// 从入口沿已检查的调用图找违规表达式,保留原函数内的诊断位置。
fn reachable_expression(
root: usize,
functions: &[Option<Function>],
calls: &calls::Calls<'_>,
mut matches: impl FnMut(&Expression) -> bool,
) -> Option<Span> {
let mut pending = vec![root];
let mut seen = HashSet::new();
while let Some(target) = pending.pop() {
if !seen.insert(target) {
continue;
}
let mut found = None;
let mut inspect = |expression: &Expression| {
expression.visit(&mut |value| {
if matches(value) {
found = Some(value.span);
}
true
});
};
match &functions[target].as_ref().unwrap().body {
Body::Statements { statements, .. } => {
statements
.iter()
.map(Statement::value)
.for_each(&mut inspect);
}
Body::Rule(rows) => rows
.iter()
.flat_map(|row| &row.results)
.for_each(&mut inspect),
Body::Loop(iteration) => iteration.expressions().for_each(&mut inspect),
Body::Contract => (),
Body::Dispatch(dispatch) => dispatch
.variants
.iter()
.map(|v| &v.call)
.for_each(&mut inspect),
}
if found.is_some() {
return found;
}
pending.extend(
calls.outgoing[target]
.iter()
.map(|edge| calls.edges[*edge].target),
);
}
None
}
pub struct Analysis {
pub generated_start: usize,
pub http: Vec<HttpEntry>,
pub jobs: Vec<Job>,
pub ports: Vec<(ast::Function, usize)>,
pub settings: Vec<Setting>,
pub constants: Vec<Option<Constant>>,
pub concrete: usize,
pub templates: HashSet<usize>,
pub definitions: Vec<Definition>,
pub functions: Vec<Option<Function>>,
pub commands: Vec<Command>,
pub calls: Vec<Call>,
pub order: Vec<usize>,
pub diagnostics: Vec<Diagnostic>,
pub excluded_sources: HashSet<usize>,
}
impl Analysis {
pub fn complete(self) -> Result<Program, Diagnostic> {
if let Some(error) = self.diagnostics.into_iter().next() {
return Err(error);
}
let generated_start = self.generated_start;
let concrete = self.concrete;
let emitted = |index| index < concrete || index >= generated_start;
let remap = |index| {
if index >= generated_start {
concrete + index - generated_start
} else {
index
}
};
Ok(Program {
testing: false,
http: self
.http
.into_iter()
.map(|mut entry| {
entry.function = remap(entry.function);
if let Some(rest) = &mut entry.rest
&& let Some((_, function)) = &mut rest.search
{
*function = remap(*function);
}
entry
})
.collect(),
jobs: self.jobs,
settings: self.settings,
definitions: self.definitions,
functions: self
.functions
.into_iter()
.enumerate()
.filter(|(i, _)| emitted(*i))
.map(|(_, f)| f.expect("checked function"))
.collect(),
commands: self.commands,
calls: self
.calls
.into_iter()
.filter(|call| emitted(call.caller))
.map(|mut call| {
call.caller = remap(call.caller);
call.target = remap(call.target);
call
})
.collect(),
order: self
.order
.into_iter()
.filter(|index| emitted(*index))
.map(remap)
.collect(),
})
}
}
pub fn check(declarations: &[ast::Declaration], modules: &[Module]) -> Result<Program, Diagnostic> {
analyze(declarations, modules).complete()
}
pub fn analyze(declarations: &[ast::Declaration], modules: &[Module]) -> Analysis {
let (types, mut diagnostics) = Types::analyze(declarations, modules);
let mut calls = calls::analyze(declarations, modules);
let (constants, constant_diagnostics) =
constants::analyze(declarations, modules, &types, &calls);
diagnostics.extend(constant_diagnostics);
let mut functions = (0..calls.functions.len()).map(|_| None).collect::<Vec<_>>();
diagnostics.append(&mut calls.diagnostics);
for index in 0..calls.functions.len() {
if let Err(error) = handler::check(index, &types, &calls) {
diagnostics.push(error);
calls.invalid.insert(index);
}
}
for &index in &calls.order {
if calls.invalid.contains(&index) {
continue;
}
// 依赖失败的定义没有可用合同;不把占位函数交给表达式检查或导航。
if let Some(call) = calls.outgoing[index]
.iter()
.map(|edge| &calls.edges[*edge])
.find(|call| functions[call.target].is_none())
{
let mut error =
Diagnostic::new("C004", "call depends on an invalid definition", call.site);
error
.related
.push((calls.functions[call.target].span, "invalid target".into()));
diagnostics.push(error);
continue;
}
match function(index, &types, &calls, &constants, &functions) {
Ok(function) => functions[index] = Some(function),
Err(error) => diagnostics.push(error),
}
}
diagnostics.extend(job::check(
&types.jobs,
&functions,
&types.definitions,
modules,
&calls,
));
diagnostics.extend(auth::check(&functions, &types.definitions, modules, &calls));
let mut commands = Vec::new();
let mut names = HashMap::<String, usize>::new();
for declaration in declarations {
if let ast::Declaration::Command { name, span, .. } = declaration {
let module = &modules[span.source];
*names
.entry(format!("{}.{}.{name}", module.component, module.domain))
.or_default() += 1;
}
}
for declaration in declarations {
if matches!(declaration, ast::Declaration::Command { .. }) {
match entry::command(declaration, modules, &calls, &functions, &types, &names) {
Ok(command) => commands.push(command),
Err(error) => diagnostics.push(error),
}
}
}
let (mut http, errors) = entry::http(
declarations,
modules,
&calls,
&functions,
&types.definitions,
);
diagnostics.extend(errors);
let (excluded_sources, error) = super::dependencies::analyze(
&types.definitions,
&functions,
&constants.values,
&constants.settings,
modules,
&calls,
);
diagnostics.extend(error);
for function in &mut functions {
if function
.as_ref()
.is_some_and(|f| excluded_sources.contains(&f.signature.span.source))
{
*function = None;
}
}
http.retain(|entry| functions[entry.function].is_some());
commands.retain(|command| functions[command.function].is_some());
let generated_start = functions.len();
let (rest, errors) = entry::rest::build(
declarations,
&types,
&mut calls,
&constants,
&functions,
&mut http,
);
diagnostics.extend(errors);
functions.extend(rest.into_iter().map(Some));
calls.order.extend(generated_start..functions.len());
let edges = calls
.edges
.into_iter()
.filter(|call| functions[call.caller].is_some() && functions[call.target].is_some())
.collect();
let mut ports = calls
.ports
.into_iter()
.filter(|(target, _)| functions[*target].is_some())
.map(|(target, port)| (port.clone(), target))
.collect::<Vec<_>>();
ports.sort_by_key(|(_, target)| *target);
Analysis {
generated_start,
http,
jobs: types.jobs,
ports,
settings: constants.settings,
constants: constants.values,
concrete: calls.concrete,
templates: calls
.by_name
.values()
.filter(|&&index| index >= calls.concrete)
.copied()
.collect(),
definitions: types.definitions,
functions,
commands,
calls: edges,
order: calls.order,
diagnostics,
excluded_sources,
}
}
fn function(
index: usize,
types: &Types<'_>,
calls: &calls::Calls<'_>,
constants: &constants::Constants<'_>,
functions: &[Option<Function>],
) -> Result<Function, Diagnostic> {
let declaration = calls.functions[index].as_ref();
if declaration.transaction && types.module(declaration.span.source).role != Role::App {
return Err(Diagnostic::new(
"C003",
"transaction flow belongs in app",
declaration.span,
));
}
let inputs = types.inputs(&declaration.inputs)?;
let outputs = types.fields(&declaration.outputs)?;
if declaration
.recover
.as_ref()
.is_some_and(|reason| reason.trim().is_empty())
{
return Err(Diagnostic::new(
"C011",
"recovery requires a concrete business reason",
declaration.span,
));
}
let signature = Signature {
name: calls.identities[index].clone(),
source_name: calls.source_names[index].clone(),
label: calls.labels[index].clone(),
inputs,
outputs,
span: declaration.span,
};
let mut checker = Checker {
constants,
constant_references: Vec::new(),
test_settings: false,
setting_references: Vec::new(),
allow_settings: true,
caller: index,
unknown_failures: matches!(declaration.body, ast::Body::Contract)
&& !calls.dispatches.contains_key(&index),
types,
calls,
functions,
locals: signature.inputs.clone(),
names: signature
.inputs
.iter()
.enumerate()
.map(|(index, input)| (input.name.clone(), index))
.collect(),
ranges: HashMap::new(),
bools: HashMap::new(),
variants: HashMap::new(),
failures: signature
.inputs
.iter()
.any(|f| f.input_contract().is_some_and(|c| c.length.is_some()))
.then_some(Failure::Api(ApiError::Invalid))
.into_iter()
.collect(),
contracts: signature
.outputs
.iter()
.map(|field| (field.name.clone(), field.clone()))
.collect(),
};
let body = match &declaration.body {
ast::Body::Contract if calls.dispatches.contains_key(&index) => {
port::dispatch(index, &signature, &mut checker)?
}
ast::Body::Worker {
ecosystem,
entry,
files,
libraries,
capabilities,
} => port::worker(
&signature,
&mut checker,
ecosystem,
entry,
files,
libraries,
capabilities,
)?,
ast::Body::Command {
entry,
timeout_ms,
output_limit,
} => port::command(&signature, &mut checker, entry, *timeout_ms, *output_limit)?,
ast::Body::Contract => Body::Contract,
ast::Body::Statements(statements) => {
statements::check(&mut checker, &signature, statements, None)?
}
ast::Body::Rule(rule) => rule::check(&mut checker, declaration, &signature, rule)?,
ast::Body::Flow(steps) => flow::check(&mut checker, &signature, steps)?,
ast::Body::Loop(iteration) => Body::Loop(Box::new(iteration::check(
&mut checker,
&signature.outputs,
iteration,
)?)),
};
upload::check(&signature, &body, &checker)?;
super::value::task::check(&body, &checker.locals, signature.span)?;
let effects = super::effects::check(
&body,
types.module(declaration.span.source),
functions,
declaration.transaction,
)?;
if let Some(contract) = calls.ports.get(&index) {
port::check(contract, types, &signature, &checker.failures)?;
}
if effects.suspends
&& signature.inputs.iter().any(|field| {
!transferable(&field.kind, &types.definitions, |index| {
&functions[index].as_ref().unwrap().signature.outputs
})
})
{
return Err(Diagnostic::new(
"C014",
"suspending calls cannot retain synchronous Stream inputs; create and consume the stream inside a synchronous blocking call",
signature.span,
));
}
let mut failure_summary = super::failure::check(
&signature,
&checker.locals,
&body,
declaration.recover.is_some(),
&types.definitions,
functions,
&types.error_types,
)?;
if matches!(&body, Body::Loop(iteration) if iteration.parallel.is_some())
&& (!checker.failures.is_empty() || checker.unknown_failures)
{
failure_summary.interrupted.extend(
failure_summary
.inputs
.iter()
.flat_map(|value| value.tokens.iter().copied()),
);
}
let adapter_setting = port::setting(index, &checker);
let uses_settings = checker.test_settings
|| matches!(body, Body::Dispatch(_))
|| checker
.setting_references
.iter()
.any(|(index, _)| Some(*index) != adapter_setting)
|| calls.outgoing[index].iter().any(|edge| {
functions[calls.edges[*edge].target]
.as_ref()
.expect("checked callee")
.uses_settings
});
Ok(Function {
test_trace: false,
transaction: declaration.transaction,
effects,
setting_references: checker.setting_references,
uses_settings,
adapter_setting,
constant_references: checker.constant_references,
signature,
locals: checker.locals,
body,
failures: checker.failures,
failure_summary,
unknown_failures: checker.unknown_failures,
})
}
@@ -0,0 +1,62 @@
//! 外部进程直接生成具体参数和结果;失败仍受 Port 的名义错误合同约束。
use super::*;
pub(in crate::compiler::check::program) fn check(
signature: &Signature,
checker: &mut Checker<'_>,
entry: &str,
timeout_ms: u64,
output_limit: usize,
) -> Result<Body, Diagnostic> {
let span = signature.span;
if checker.types.module(span.source).role != Role::Adapter {
return Err(Diagnostic::new(
"C003",
"external belongs in an Adapter",
span,
));
}
let error = checker
.types
.named("dever.process.Error", span.source)
.expect("bundled process error");
checker.failures.insert(Failure::Choice(error, 0));
let args = signature
.inputs
.iter()
.enumerate()
.map(|(local, field)| Expression {
kind: ExpressionKind::Variable(local),
value_type: field.kind.clone(),
range: None,
known_bool: None,
span,
})
.collect();
let value = Expression {
kind: ExpressionKind::Builtin(
Builtin::Command {
entry: entry.into(),
timeout_ms,
output_limit,
error,
},
args,
),
value_type: signature.outputs[0].kind.clone(),
range: None,
known_bool: None,
span,
};
let local = checker.locals.len();
checker.locals.push(signature.outputs[0].clone());
Ok(Body::Statements {
statements: vec![Statement::Assign { local, value }],
outputs: vec![local],
flow: Some(vec![FlowStep {
parallel: None,
kind: StepKind::Port,
span,
}]),
})
}
+168
View File
@@ -0,0 +1,168 @@
//! 实现签名逐项符合 Port,实际失败只能来自声明集合;间接调用也已计入摘要。
use super::*;
mod command;
mod worker;
pub(super) use command::check as command;
pub(super) use worker::check as worker;
pub(super) fn check(
contract: &ast::Function,
types: &Types<'_>,
signature: &Signature,
failures: &BTreeSet<Failure>,
) -> Result<(), Diagnostic> {
for (declared, actual) in [
(&contract.inputs, &signature.inputs),
(&contract.outputs, &signature.outputs),
] {
let expected = types.fields(declared)?;
if expected.len() != actual.len()
|| expected.iter().zip(actual).any(|(a, b)| {
a.name != b.name || a.kind != b.kind || a.range != b.range || a.private != b.private
})
{
let mut error = Diagnostic::new(
"C005",
"Adapter signature must exactly match its Port",
signature.span,
);
error
.related
.push((contract.span, "declared Port signature".into()));
return Err(error);
}
}
let mut allowed = BTreeSet::new();
if let Some(reference) = &contract.fails {
let Type::Named(index) = types.reference(reference)? else {
return Err(Diagnostic::new(
"C005",
"Port fails requires an error choice",
reference.span,
));
};
let Shape::Choice(variants) = &types.definitions[index].shape else {
return Err(Diagnostic::new(
"C005",
"Port fails requires an error choice",
reference.span,
));
};
allowed.extend(
variants
.iter()
.enumerate()
.filter(|(_, variant)| variant.error)
.map(|(variant, _)| Failure::Choice(index, variant)),
);
if allowed.is_empty() {
return Err(Diagnostic::new(
"C005",
"Port fails choice has no error variants",
reference.span,
));
}
}
if !failures.is_subset(&allowed) {
let mut error = Diagnostic::new(
"C011",
"Adapter can only propagate failures declared by its Port",
signature.span,
);
error
.related
.push((contract.span, "allowed failures".into()));
return Err(error);
}
Ok(())
}
/// 每个候选仍用自身完整失败摘要;多输出调用在每条分支只执行一次。
pub(super) fn dispatch(
index: usize,
signature: &Signature,
checker: &mut Checker<'_>,
) -> Result<Body, Diagnostic> {
let module = checker.types.module(signature.span.source);
let mut variants = Vec::new();
for &target in &checker.calls.dispatches[&index] {
let function = checker.functions[target].as_ref().unwrap();
let implementation = checker.types.module(function.signature.span.source);
let arguments = signature
.inputs
.iter()
.enumerate()
.map(|(index, field)| Expression {
kind: ExpressionKind::Variable(index),
value_type: field.kind.clone(),
range: field.guaranteed_range(),
known_bool: None,
span: function.signature.inputs[index].span,
})
.collect();
let value_type = match function.signature.outputs.as_slice() {
[] => Type::Unit,
[field] => field.kind.clone(),
_ => Type::Outputs(target),
};
checker.failures.extend(&function.failures);
checker.unknown_failures |= function.unknown_failures;
variants.push(AdapterVariant {
name: implementation
.topic
.clone()
.unwrap_or_else(|| "default".into()),
setting: checker
.constants
.settings
.iter()
.position(|s| s.adapter && s.field.span.source == function.signature.span.source),
call: Expression {
kind: ExpressionKind::Call(target, arguments),
value_type,
range: None,
known_bool: None,
span: function.signature.span,
},
});
}
variants.sort_by(|a, b| a.name.cmp(&b.name));
let mut names = HashSet::new();
if variants.iter().any(|variant| !names.insert(&variant.name)) {
return Err(Diagnostic::new(
"C001",
"Adapter implementation names must be distinct (adapter.dever uses default)",
signature.span,
));
}
Ok(Body::Dispatch(Dispatch {
group: format!("{}.{}", module.component, module.domain),
variants,
}))
}
pub(super) fn setting(index: usize, checker: &Checker<'_>) -> Option<usize> {
let source = checker.calls.functions[index].span.source;
let selected = checker
.calls
.dispatches
.values()
.flatten()
.any(|&target| checker.calls.functions[target].span.source == source);
if !selected {
return None;
}
checker
.setting_references
.iter()
.map(|(setting, _)| *setting)
.find(|&setting| checker.constants.settings[setting].adapter)
.or_else(|| {
checker.calls.outgoing[index].iter().find_map(|&edge| {
checker.functions[checker.calls.edges[edge].target]
.as_ref()
.unwrap()
.adapter_setting
})
})
}
@@ -0,0 +1,248 @@
//! Worker 签名来自 Port;运行时只在外部边界解码具体字段,内部继续使用既有保证。
use super::*;
use crate::compiler::model::numeric::Number;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
pub(in crate::compiler::check::program) fn check(
signature: &Signature,
checker: &mut Checker<'_>,
ecosystem: &str,
entry: &str,
files: &[String],
libraries: &[String],
capabilities: &[String],
) -> Result<Body, Diagnostic> {
let span = signature.span;
let module = checker.types.module(span.source);
let mut inputs = serde_json::Map::new();
let mut outputs = serde_json::Map::new();
let mut errors = serde_json::Map::new();
for contract in checker
.calls
.ports
.values()
.filter(|f| module.same_domain(checker.types.module(f.span.source)))
{
let fields = checker.types.inputs(&contract.inputs)?;
inputs.insert(
contract.name.clone(),
record(&fields, &checker.types.definitions, false, 0)?,
);
let fields = checker.types.fields(&contract.outputs)?;
outputs.insert(
contract.name.clone(),
record(&fields, &checker.types.definitions, false, 0)?,
);
if let Some(fails) = &contract.fails {
let Type::Named(index) = checker.types.reference(fails)? else {
return Err(Diagnostic::new(
"C005",
"Port fails requires an error choice",
fails.span,
));
};
let definition = &checker.types.definitions[index];
let Shape::Choice(variants) = &definition.shape else {
return Err(Diagnostic::new(
"C005",
"Port fails requires an error choice",
fails.span,
));
};
for (variant, choice) in variants.iter().enumerate().filter(|(_, v)| v.error) {
errors.insert(
format!("{}.{}", definition.name, choice.name),
record(&choice.fields, &checker.types.definitions, false, 0)?,
);
if contract.span == checker.calls.ports[&checker.caller].span {
checker.failures.insert(Failure::Choice(index, variant));
}
}
}
}
let setting = checker
.constants
.settings
.iter()
.position(|s| s.adapter && s.field.span.source == span.source);
let setting_schema = if let Some(index) = setting {
checker.setting_references.push((index, span));
schema(
&checker.constants.settings[index].field.kind,
&checker.types.definitions,
true,
0,
span,
)?
} else {
Value::Null
};
let mut contract = json!({"port":format!("{}.{}", module.component, module.domain), "adapter":module.topic.as_deref().unwrap_or("default"), "capabilities":capabilities, "operations":inputs.keys().collect::<Vec<_>>(), "inputs":inputs, "outputs":outputs, "errors":errors, "setting":setting_schema});
contract["ecosystem"] = ecosystem.into();
contract["libraries"] = json!(libraries);
contract["files"] = json!(files);
contract["schema"] = format!("{:x}", Sha256::digest(contract.to_string().as_bytes())).into();
let value_type = match signature.outputs.as_slice() {
[] => Type::Unit,
[field] => field.kind.clone(),
_ => Type::Outputs(checker.caller),
};
let value = Expression {
kind: ExpressionKind::Builtin(
Builtin::Worker {
entry: entry.into(),
contract: contract.to_string(),
target: checker.caller,
setting,
},
signature
.inputs
.iter()
.enumerate()
.map(|(i, f)| Expression {
kind: ExpressionKind::Variable(i),
value_type: f.kind.clone(),
range: f.guaranteed_range(),
known_bool: None,
span: f.span,
})
.collect(),
),
value_type: value_type.clone(),
range: None,
known_bool: None,
span,
};
let local = checker.locals.len();
let mut temporary = signature.outputs.first().cloned().unwrap_or_else(|| Field {
name: "worker_result".into(),
kind: Type::Unit,
private: false,
range: None,
span,
model: None,
});
temporary.kind = value_type;
checker.locals.push(temporary);
let mut statements = vec![Statement::Assign { local, value }];
let outputs = match signature.outputs.as_slice() {
[] => Vec::new(),
[_] => vec![local],
fields => fields
.iter()
.enumerate()
.map(|(field, contract)| {
let target = checker.locals.len();
checker.locals.push(contract.clone());
statements.push(Statement::Assign {
local: target,
value: Expression {
kind: ExpressionKind::Field(
Box::new(Expression {
kind: ExpressionKind::Variable(local),
value_type: Type::Outputs(checker.caller),
range: None,
known_bool: None,
span,
}),
field,
),
value_type: contract.kind.clone(),
range: contract.guaranteed_range(),
known_bool: None,
span: contract.span,
},
});
target
})
.collect(),
};
let flow = Some(
statements
.iter()
.map(|_| FlowStep {
parallel: None,
kind: StepKind::Port,
span,
})
.collect(),
);
Ok(Body::Statements {
statements,
outputs,
flow,
})
}
fn record(
fields: &[Field],
definitions: &[Definition],
setting: bool,
depth: usize,
) -> Result<Value, Diagnostic> {
let fields = fields
.iter()
.map(|field| {
if field.private {
return Err(Diagnostic::new(
"C006",
"private fields cannot cross a Worker boundary",
field.span,
));
}
let mut value = schema(&field.kind, definitions, setting, depth, field.span)?;
if let Some(range) = field.range {
value["minimum"] = number(range.minimum).into();
value["maximum"] = number(range.maximum).into();
}
Ok((field.name.clone(), value))
})
.collect::<Result<serde_json::Map<_, _>, _>>()?;
Ok(json!({"type":"record", "fields":fields}))
}
fn schema(
kind: &Type,
definitions: &[Definition],
setting: bool,
depth: usize,
span: crate::syntax::source::Span,
) -> Result<Value, Diagnostic> {
if depth >= 64 {
return Err(Diagnostic::new(
"C005",
"Worker schema exceeds 64 levels",
span,
));
}
Ok(match kind {
Type::List(inner) | Type::Optional(inner) => {
json!({"type":if matches!(kind,Type::List(_)){"list"}else{"nullable"}, "value":schema(inner,definitions,setting,depth+1,span)?})
}
Type::Named(index) => match &definitions[*index].shape {
Shape::Record(fields) => record(fields, definitions, setting, depth + 1)?,
Shape::Choice(variants) if variants.iter().all(|v| v.fields.is_empty() && !v.error) => {
json!({"type":"enum", "values":variants.iter().map(|v| &v.name).collect::<Vec<_>>()})
}
Shape::Choice(_) => {
return Err(Diagnostic::new(
"C005",
"Worker choices must be payload-free and contain no error variants",
span,
));
}
},
_ => json!({"type":match kind {
Type::Bool=>"bool", Type::Int=>"int64", Type::Float=>"float64", Type::Decimal=>"decimal", Type::Text=>"text", Type::Json=>"json", Type::Uuid=>"uuid", Type::Id=>"id", Type::ModelId(_)=>"model_id", Type::DateTime=>"datetime", Type::Date=>"date", Type::Time=>"time", Type::Duration=>"duration", Type::Secret if setting=>"secret",
_=>return Err(Diagnostic::new("C005", "Worker requires portable wire types; Secret belongs only in setting",span)),
}}),
})
}
fn number(value: Number) -> String {
match value {
Number::Int(value) => value.to_string(),
Number::Decimal(value) => value.to_string(),
Number::Float(_) => unreachable!("Float has no range contract"),
}
}
+229
View File
@@ -0,0 +1,229 @@
//! 每行使用独立的输入事实和载荷绑定,输出格不能读取同排其他输出。
use super::*;
use crate::compiler::check::rules;
pub(super) fn check(
checker: &mut Checker<'_>,
declaration: &ast::Function,
signature: &Signature,
source: &ast::Rule,
) -> Result<Body, Diagnostic> {
let resolved = rules::resolve(declaration, source, checker.types)?;
let locals = (0..signature.inputs.len()).collect::<Vec<_>>();
Ok(Body::Rule(branches(
checker,
source,
resolved,
&locals,
Some(&signature.outputs),
None,
)?))
}
pub(in crate::compiler::check) fn inline(
checker: &mut Checker<'_>,
source: &ast::Rule,
expected: Option<&Type>,
span: Span,
) -> Result<Expression, Diagnostic> {
let mut selectors = Vec::new();
let mut locals = Vec::new();
let mut inputs = Vec::new();
for (name, at) in &source.header {
let &local = checker
.names
.get(name)
.ok_or_else(|| Diagnostic::new("C004", format!("unknown rule selector {name}"), *at))?;
locals.push(local);
let value = checker.variable(local, *at);
let mut field = checker.locals[local].clone();
field.range = value.range;
inputs.push(field);
selectors.push(value);
}
let resolved = rules::resolve_rows(inputs, source, false, checker.types, span)?;
let rows = branches(checker, source, resolved, &locals, None, expected)?;
let values = rows
.iter()
.map(|r| &r.results[0])
.filter(|v| v.value_type != Type::Never);
let mut kind = Type::Never;
let mut range = None;
for (i, value) in values.enumerate() {
if i == 0 {
kind = value.value_type.clone();
range = value.range;
} else if value.value_type != kind {
return Err(Diagnostic::new(
"C005",
"rule branches must return the same type",
value.span,
));
} else {
range = range.zip(value.range).map(|(a, b)| a.hull(b));
}
}
Ok(Expression {
kind: ExpressionKind::Rule { selectors, rows },
value_type: kind,
known_bool: None,
range,
span,
})
}
fn branches(
checker: &mut Checker<'_>,
source: &ast::Rule,
resolved: rules::RuleConditions,
locals: &[usize],
outputs: Option<&[Field]>,
expected: Option<&Type>,
) -> Result<Vec<RuleRow>, Diagnostic> {
let scope = (
checker.names.clone(),
checker.ranges.clone(),
checker.bools.clone(),
checker.variants.clone(),
);
let mut rows = Vec::new();
for ((row, conditions), facts) in source.rows.iter().zip(resolved.rows).zip(resolved.facts) {
checker.names.clone_from(&scope.0);
checker.ranges.clone_from(&scope.1);
checker.bools.clone_from(&scope.2);
checker.variants.clone_from(&scope.3);
let mut bindings = Vec::new();
let mut present = Vec::new();
for (column, condition) in conditions.iter().enumerate() {
let input = locals[column];
let input_type = &resolved.inputs[column].kind;
let fact = &facts[column];
let mut variable = input;
if fact.present
&& let Type::Optional(inner) = input_type
{
variable = checker.bind(
resolved.inputs[column].name.clone(),
inner.as_ref().clone(),
None,
None,
condition.span,
);
present.push(PresentInput {
input,
local: variable,
});
}
if let Some(range) = fact.range {
checker.ranges.insert(variable, range);
}
if let Some(value) = fact.boolean {
checker.bools.insert(variable, value);
}
let kind = match input_type {
Type::Optional(inner) => inner.as_ref(),
other => other,
};
if let Type::Named(definition) = kind
&& matches!(
&checker.types.definitions[*definition].shape,
Shape::Choice(_)
)
{
if let Some(variants) = &fact.variants {
checker.variants.insert(variable, variants.clone());
}
bindings.extend(bind_payloads(checker, input, condition));
}
}
let mut results = Vec::new();
for (column, expression) in row.results.iter().enumerate() {
let Some(expression) = expression else {
continue;
};
let value = match outputs.and_then(|fields| fields.get(column)) {
Some(field) => checker.field_value(expression, field)?,
None => checker.expression(expression, expected)?,
};
if outputs.is_some_and(<[_]>::is_empty)
&& !matches!(value.value_type, Type::Unit | Type::Never)
{
let can_discard = matches!(value.kind, ExpressionKind::Call(target, _) if !checker.functions[target].as_ref().expect("checked callee").failures.is_empty());
if !can_discard && value.effects(checker.functions).pure() {
return Err(Diagnostic::new(
"C005",
"discarding a pure infallible value is unused computation",
expression.span,
));
}
}
results.push(value);
}
if outputs.is_some_and(|fields| results.len() < fields.len())
&& !results.iter().any(|value| value.value_type == Type::Never)
{
return Err(Diagnostic::new(
"C009",
"a successful row must provide every output",
row.span,
));
}
rows.push(RuleRow {
name: row.name.as_ref().map(|(name, _)| name.clone()),
conditions,
facts,
bindings,
present,
results,
span: row.span,
});
}
(
checker.names,
checker.ranges,
checker.bools,
checker.variants,
) = scope;
Ok(rows)
}
pub(super) fn bind_payloads(
checker: &mut Checker<'_>,
input: usize,
condition: &Condition,
) -> Vec<Binding> {
let kind = match &checker.locals[input].kind {
Type::Optional(inner) => inner.as_ref(),
kind => kind,
};
let mut bindings = Vec::new();
if let Type::Named(definition) = kind
&& let Shape::Choice(variants) = &checker.types.definitions[*definition].shape
&& let Pattern::Variant(index, names) = &condition.alternatives[0]
&& !names.is_empty()
{
let mut fields = variants[*index].fields.clone();
// 同格候选共享绑定,但只能使用所有候选都成立的范围。
for pattern in condition.alternatives.iter().skip(1) {
let Pattern::Variant(other, _) = pattern else {
unreachable!("checked payload alternatives")
};
for (field, alternative) in fields.iter_mut().zip(&variants[*other].fields) {
field.range = field
.guaranteed_range()
.zip(alternative.guaranteed_range())
.map(|(a, b)| a.hull(b));
}
}
for (field, (name, value)) in names.iter().zip(fields).enumerate() {
let local = checker.bind(name.clone(), value.kind, value.range, None, condition.span);
bindings.push(Binding {
input,
field,
local,
});
}
}
bindings
}
@@ -0,0 +1,350 @@
//! 局部赋值生成新版本;输入只读,输出必须明确赋值,检查成功后的事实继续使用。
use super::*;
use crate::syntax::{
names::{self, Style},
source::Span,
};
pub(super) fn check<'a>(
checker: &mut Checker<'_>,
signature: &Signature,
statements: impl IntoIterator<Item = &'a ast::Statement>,
flow: Option<&[ast::FlowStep]>,
) -> Result<Body, Diagnostic> {
let mut checked = Vec::new();
let mut terminated = false;
for (position, statement) in statements.into_iter().enumerate() {
let same_group = flow.is_some_and(|steps| {
position > 0
&& steps[position].parallel.is_some()
&& steps[position].parallel == steps[position - 1].parallel
});
if terminated && !same_group {
return Err(Diagnostic::new(
"C012",
"unreachable statement after unconditional failure",
signature.span,
));
}
match statement {
ast::Statement::Assign {
target,
kind,
value,
span,
} => {
let ast::ExpressionKind::Name(name) = &target.kind else {
update_field(checker, signature, target, kind, value, *span, &mut checked)?;
continue;
};
names::validate(name, Style::Value, target.span)?;
if flow.is_some() && checker.names.contains_key(name) {
return Err(Diagnostic::new(
"C005",
"flow bindings must be new and cannot shadow inputs",
target.span,
));
}
if signature.inputs.iter().any(|input| input.name == *name) {
return Err(Diagnostic::new(
"C005",
"input parameters are read-only",
target.span,
));
}
let declaration = checker.contracts.get(name).cloned();
let annotation = kind
.as_ref()
.map(|kind| {
checker.types.fields(&[ast::Field {
modifiers: Vec::new(),
name: name.clone(),
kind: kind.clone(),
private: false,
span: *span,
}])
})
.transpose()?
.map(|mut fields| fields.remove(0));
if let (Some(declared), Some(annotation)) = (&declaration, &annotation)
&& (declared.kind != annotation.kind || declared.range != annotation.range)
{
return Err(Diagnostic::new(
"C005",
"assignment annotation changes an existing type",
*span,
));
}
if let Some(field) = &annotation {
checker.contracts.insert(name.clone(), field.clone());
}
let value = match annotation.as_ref().or(declaration.as_ref()) {
Some(field) => checker.field_value(value, field)?,
None => checker.expression(value, None)?,
};
if matches!(value.value_type, Type::Unit | Type::Null) {
return Err(Diagnostic::new(
"C005",
"assignment needs a concrete value type",
value.span,
));
}
terminated |= value.value_type == Type::Never;
checker
.contracts
.entry(name.clone())
.or_insert_with(|| Field {
model: None,
name: name.clone(),
kind: value.value_type.clone(),
range: None,
private: false,
span: *span,
});
let local = checker.bind(
name.clone(),
value.value_type.clone(),
value.range,
value.known_bool,
*span,
);
checked.push(Statement::Assign { local, value });
}
ast::Statement::Check {
condition,
error,
span,
} => {
let condition = checker.expression(condition, Some(&Type::Bool))?;
// 模板已按声明合同检查;实际 handler 的更强保证可消去该实例的守卫。
// 原始源码和抽象模板仍拒绝恒真检查,不让合法的较强回调破坏可替换性。
if condition.known_bool == Some(true)
&& checker.caller < checker.calls.concrete
&& signature.name != signature.source_name
{
checked.push(Statement::Action(condition));
continue;
}
let error = checker.expression(error, None)?;
let error = checker.error(error)?;
if let Some(known) = condition.known_bool {
return Err(Diagnostic::new(
"C012",
if known {
"check is already guaranteed; remove the redundant check"
} else {
"check always fails"
},
*span,
));
}
if let Some((original, inner, value)) = nonnull(&condition) {
let local = checker.bind(
checker.locals[original].name.clone(),
inner.clone(),
None,
None,
*span,
);
checked.push(Statement::NonNull {
value: value.clone(),
local,
error,
});
} else {
refine(checker, &condition);
checked.push(Statement::Check { condition, error });
}
}
ast::Statement::Action(value) => {
let value = checker.expression(value, None)?;
let discard = flow.is_some()
&& (!value.effects(checker.functions).pure()
|| matches!(&value.kind, ExpressionKind::Call(target, _)
if checker.functions[*target].as_ref().is_some_and(|f| !f.failures.is_empty() || f.unknown_failures)));
if !matches!(value.value_type, Type::Unit | Type::Never) && !discard {
return Err(Diagnostic::new(
"C005",
if flow.is_some() {
"discarded flow steps require an effect or a fallible call"
} else {
"ordinary function actions require a zero-output call"
},
value.span,
));
}
terminated |= value.value_type == Type::Never;
checked.push(Statement::Action(value));
}
}
}
let outputs = if terminated {
Vec::new()
} else {
signature
.outputs
.iter()
.map(|output| {
checker.names.get(&output.name).copied().ok_or_else(|| {
Diagnostic::new(
"C005",
format!("output {} is not assigned", output.name),
signature.span,
)
})
})
.collect::<Result<_, _>>()?
};
Ok(Body::Statements {
statements: checked,
outputs,
flow: None,
})
}
fn update_field(
checker: &mut Checker<'_>,
signature: &Signature,
target: &ast::Expression,
kind: &Option<ast::TypeRef>,
value: &ast::Expression,
span: Span,
checked: &mut Vec<Statement>,
) -> Result<(), Diagnostic> {
let ast::ExpressionKind::Field(base, name) = &target.kind else {
return Err(Diagnostic::new(
"C005",
"assignment target must be a local value or its field",
target.span,
));
};
let ast::ExpressionKind::Name(local_name) = &base.kind else {
return Err(Diagnostic::new(
"C005",
"field assignment requires a named local record",
target.span,
));
};
if kind.is_some()
|| signature
.inputs
.iter()
.any(|input| input.name == *local_name)
{
return Err(Diagnostic::new(
"C005",
"input fields are read-only; copy to a local value before changing fields",
target.span,
));
}
let base = checker.expression(base, None)?;
if !matches!(base.value_type, Type::Named(_) | Type::MapEntry(_, _)) {
return Err(Diagnostic::new(
"C005",
"field assignment requires a record",
target.span,
));
}
let (field, contract) = checker.member(&base.value_type, name, target.span)?;
let value = checker.field_value(value, &contract)?;
let value_type = base.value_type.clone();
let value = Expression {
kind: ExpressionKind::UpdateField(Box::new(base), field, Box::new(value)),
value_type,
range: None,
known_bool: None,
span,
};
let local = checker.bind(
local_name.clone(),
value.value_type.clone(),
None,
None,
span,
);
checked.push(Statement::Assign { local, value });
Ok(())
}
fn nonnull(condition: &Expression) -> Option<(usize, &Type, &Expression)> {
let ExpressionKind::Binary(Binary::NotEqual, left, right) = &condition.kind else {
return None;
};
let value = if matches!(left.kind, ExpressionKind::Null) {
right
} else if matches!(right.kind, ExpressionKind::Null) {
left
} else {
return None;
};
match (&value.kind, &value.value_type) {
(ExpressionKind::Variable(local), Type::Optional(inner)) => {
Some((*local, inner.as_ref(), value.as_ref()))
}
_ => None,
}
}
fn refine(checker: &mut Checker<'_>, condition: &Expression) {
if let ExpressionKind::Variable(local) = condition.kind {
checker.bools.insert(local, true);
return;
}
if let ExpressionKind::Unary(Unary::Not, value) = &condition.kind
&& let ExpressionKind::Variable(local) = value.kind
{
checker.bools.insert(local, false);
return;
}
let ExpressionKind::Binary(operation, left, right) = &condition.kind else {
return;
};
if *operation == Binary::And {
refine(checker, left);
refine(checker, right);
return;
}
let ExpressionKind::Variable(local) = left.kind else {
return;
};
if !matches!(left.value_type, Type::Int | Type::Decimal) {
return;
}
let Some(point) = right.range.filter(|range| range.minimum == range.maximum) else {
return;
};
let current = left
.range
.unwrap_or_else(|| numeric::Range::full(&left.value_type));
let operator = match operation {
Binary::Less => "<",
Binary::LessEqual => "<=",
Binary::Greater => ">",
Binary::GreaterEqual => ">=",
Binary::Equal => {
checker.ranges.insert(local, point);
return;
}
_ => return,
};
let bound = numeric::Bound {
operator: operator.into(),
value: point.minimum,
};
if let Some(range) = numeric::Range::bounds(&left.value_type, &[bound]) {
let minimum = if current.minimum > range.minimum {
current.minimum
} else {
range.minimum
};
let maximum = if current.maximum < range.maximum {
current.maximum
} else {
range.maximum
};
checker
.ranges
.insert(local, numeric::Range { minimum, maximum });
}
}
@@ -0,0 +1,195 @@
//! Upload 只有一个所有者;正常路径恰好消费,失败和取消由 Rust 析构回收。
use super::*;
use crate::syntax::source::Span;
pub(super) fn check(
signature: &Signature,
body: &Body,
checker: &Checker<'_>,
) -> Result<(), Diagnostic> {
let inputs = signature
.inputs
.iter()
.enumerate()
.filter(|(_, f)| f.kind == Type::Upload)
.map(|(i, _)| i)
.collect::<BTreeSet<_>>();
if signature.outputs.iter().any(|f| f.kind == Type::Upload) {
return Err(error(signature.span, "Upload cannot be returned"));
}
if inputs.is_empty() {
return Ok(());
}
let module = checker.types.module(signature.span.source);
if inputs.len() > 1
|| (!inputs.is_empty() && !matches!(module.role, Role::App | Role::Adapter | Role::Port))
{
return Err(error(
signature.span,
"Upload requires one top-level App or Port/Adapter input",
));
}
if matches!(body, Body::Contract) {
return Ok(());
}
let check_path = |values: Vec<&Expression>| {
let mut live = inputs.clone();
for value in values {
expression(value, &mut live, checker)?;
if value.value_type == Type::Never {
return Ok(());
}
}
if !live.is_empty() {
return Err(error(
signature.span,
"Upload must be closed or consumed by its Port before normal exit",
));
}
Ok(())
};
match body {
Body::Statements {
statements, flow, ..
} => {
if let Some(steps) = flow {
let mut start = 0;
while start < steps.len() {
let end = FlowStep::end(steps, start);
let mut seen = BTreeSet::new();
for statement in &statements[start..end] {
let mut used = BTreeSet::new();
statement.value().visit(&mut |value| {
if value.value_type == Type::Upload
&& let ExpressionKind::Variable(local) = value.kind
{
used.insert(local);
}
true
});
if used.iter().any(|local| !seen.insert(*local)) {
return Err(error(
statement.value().span,
"parallel steps cannot share an Upload",
));
}
}
start = end;
}
}
check_path(statements.iter().map(Statement::value).collect())
}
Body::Rule(rows) => {
for row in rows {
check_path(row.results.iter().collect())?;
}
Ok(())
}
Body::Dispatch(dispatch) => {
for variant in &dispatch.variants {
check_path(vec![&variant.call])?;
}
Ok(())
}
Body::Loop(iteration) => {
if !inputs.is_empty() {
return Err(error(
signature.span,
"Upload cannot be consumed inside a loop",
));
}
check_path(iteration.expressions().collect())
}
Body::Contract => unreachable!(),
}
}
fn expression(
value: &Expression,
live: &mut BTreeSet<usize>,
checker: &Checker<'_>,
) -> Result<(), Diagnostic> {
let mut result = Ok(());
value.visit(&mut |node| {
if result.is_err() {
return false;
}
if let ExpressionKind::Field(base, _) = &node.kind
&& base.value_type == Type::Upload
{
result = resource(base, live, false);
return false;
}
let arguments = match &node.kind {
ExpressionKind::Call(target, args)
if args.iter().any(|a| a.value_type == Type::Upload) =>
{
let caller = checker.types.module(value.span.source);
let target = checker
.types
.module(checker.calls.functions[*target].span.source);
let storage = target.bundled_library() && target.domain == "storage";
let allowed = if storage {
caller.role == Role::Adapter
} else {
caller.same_domain(target) && target.role == Role::Adapter
};
if !allowed {
result = Err(error(
node.span,
"Upload may only pass to its own Port; storage.put belongs in Adapter",
));
return false;
}
Some(args)
}
ExpressionKind::Builtin(
Builtin::Standard(StandardOp::UploadClose | StandardOp::UploadPut),
args,
) => Some(args),
_ => None,
};
if let Some(args) = arguments {
for arg in args {
result = if arg.value_type == Type::Upload {
resource(arg, live, true)
} else {
expression(arg, live, checker)
};
if result.is_err() {
break;
}
}
return false;
}
if node.value_type == Type::Upload {
result = Err(error(
node.span,
"Upload cannot be copied, aliased, captured or passed to a task",
));
return false;
}
true
});
result
}
fn resource(
value: &Expression,
live: &mut BTreeSet<usize>,
consume: bool,
) -> Result<(), Diagnostic> {
let ExpressionKind::Variable(local) = value.kind else {
return Err(error(value.span, "Upload must be its original parameter"));
};
if if consume {
!live.remove(&local)
} else {
!live.contains(&local)
} {
return Err(error(value.span, "Upload was already consumed"));
}
Ok(())
}
fn error(span: Span, message: &str) -> Diagnostic {
Diagnostic::new("C014", message, span)
}
+302
View File
@@ -0,0 +1,302 @@
//! 规则条件解析后执行有界互斥穷尽证明;结果表达式另由共享表达式检查器处理。
mod partition;
mod proof;
use super::types::{self, Types};
use crate::compiler::model::{self, Condition, Pattern, Shape, Type, numeric::Number};
use crate::syntax::names::{self, Style};
use crate::syntax::{ast, diagnostic::Diagnostic, source::Span};
use model::InputFact as Fact;
use std::collections::HashSet;
pub const PROOF_BUDGET: usize = 1_000_000;
/// loop 只需本格匹配后的事实,不要求各输出行互斥或穷尽。
pub(super) fn filter_fact(
input: &model::Field,
condition: &Condition,
types: &Types,
) -> Result<Fact, Diagnostic> {
let cells = partition::cells(input, &[condition], types);
if cells.len().saturating_mul(condition.alternatives.len()) > PROOF_BUDGET {
return Err(Diagnostic::new(
"C009",
"loop filter proof budget exceeded",
condition.span,
));
}
cells
.iter()
.filter(|cell| {
condition
.alternatives
.iter()
.any(|pattern| partition::matches(pattern, cell))
})
.map(|cell| partition::fact(cell, input))
.reduce(partition::union)
.ok_or_else(|| {
Diagnostic::new(
"C009",
"loop filter is outside its input domain",
condition.span,
)
})
}
pub struct RuleConditions {
pub inputs: Vec<model::Field>,
pub rows: Vec<Vec<Condition>>,
pub work: usize,
pub facts: Vec<Vec<Fact>>,
}
pub fn resolve(
function: &ast::Function,
rule: &ast::Rule,
types: &Types,
) -> Result<RuleConditions, Diagnostic> {
let inputs = types.inputs(&function.inputs)?;
let outputs = types.fields(&function.outputs)?;
let named = rule.rows[0].name.is_some();
let mut expected = inputs
.iter()
.chain(&outputs)
.map(|field| field.name.as_str())
.collect::<Vec<_>>();
if outputs.is_empty() {
expected.push("do");
}
if named {
expected.insert(0, "name");
}
if rule.header.iter().map(|cell| cell.0.as_str()).ne(expected) {
return Err(Diagnostic::new(
"C009",
"rule header must name inputs and outputs in signature order",
function.span,
));
}
resolve_rows(inputs, rule, outputs.is_empty(), types, function.span)
}
pub(super) fn resolve_rows(
inputs: Vec<model::Field>,
rule: &ast::Rule,
action: bool,
types: &Types,
span: Span,
) -> Result<RuleConditions, Diagnostic> {
let mut row_names = HashSet::new();
let mut rows = Vec::new();
for row in &rule.rows {
if let Some((name, span)) = &row.name {
names::validate(name, Style::Value, *span)?;
}
if let Some((name, span)) = &row.name
&& !row_names.insert(name)
{
return Err(Diagnostic::new("C009", "duplicate rule row name", *span));
}
let mut bindings = inputs
.iter()
.map(|field| field.name.clone())
.collect::<HashSet<_>>();
let conditions = row
.conditions
.iter()
.zip(&inputs)
.map(|(condition, input)| {
resolve_condition(condition, &input.kind, types, &mut bindings)
})
.collect::<Result<Vec<_>, Diagnostic>>()?;
let failed = row.results[0].as_ref().is_some_and(|expression| matches!(&expression.kind, ast::ExpressionKind::Call(target, _) if target.path().as_deref() == Some("fail")));
if failed {
if row.results.iter().skip(1).any(Option::is_some) {
return Err(Diagnostic::new(
"C009",
"a failed row must discard all later outputs",
row.span,
));
}
} else if row.results.iter().any(Option::is_none) {
return Err(Diagnostic::new(
"C009",
"a successful row must provide every output",
row.span,
));
}
if action
&& !matches!(
&row.results[0].as_ref().unwrap().kind,
ast::ExpressionKind::Call(..)
)
{
return Err(Diagnostic::new(
"C009",
"a rule action must be one call",
row.span,
));
}
rows.push(conditions);
}
let (work, facts) = proof::prove(&inputs, &rows, types, span)?;
Ok(RuleConditions {
inputs,
rows,
work,
facts,
})
}
pub(super) fn resolve_condition(
condition: &ast::Condition,
kind: &Type,
types: &Types,
bindings: &mut HashSet<String>,
) -> Result<Condition, Diagnostic> {
let alternatives = condition
.alternatives
.iter()
.map(|pattern| resolve_pattern(pattern, kind, types, condition.span))
.collect::<Result<Vec<_>, _>>()?;
let mut payload = None;
for pattern in &alternatives {
let names = match pattern {
Pattern::Variant(index, names) => {
let Type::Named(kind) = present(kind) else {
unreachable!()
};
let Shape::Choice(variants) = &types.definitions[*kind].shape else {
unreachable!()
};
names
.iter()
.zip(&variants[*index].fields)
.map(|(name, field)| (name.clone(), field.kind.clone()))
.collect::<Vec<_>>()
}
_ => Vec::new(),
};
if payload.as_ref().is_some_and(|previous| *previous != names) {
return Err(Diagnostic::new(
"C005",
"alternatives must bind the same names and types",
condition.span,
));
}
payload = Some(names);
}
for (name, _) in payload.expect("parsed condition has alternatives") {
names::validate(&name, Style::Value, condition.span)?;
if !bindings.insert(name) {
return Err(Diagnostic::new(
"C005",
"rule payload binding shadows an existing name",
condition.span,
));
}
}
Ok(Condition {
alternatives,
span: condition.span,
})
}
fn present(kind: &Type) -> &Type {
if let Type::Optional(inner) = kind {
inner
} else {
kind
}
}
pub(super) fn resolve_pattern(
pattern: &ast::Pattern,
kind: &Type,
types: &Types,
span: Span,
) -> Result<Pattern, Diagnostic> {
let scalar = present(kind);
let pattern = match pattern {
ast::Pattern::Any => Pattern::Any,
ast::Pattern::Other => Pattern::Other,
ast::Pattern::Literal(ast::Literal::Null) if matches!(kind, Type::Optional(_)) => {
Pattern::Null
}
ast::Pattern::Literal(ast::Literal::Bool(value)) if *scalar == Type::Bool => {
Pattern::Bool(*value)
}
ast::Pattern::Literal(ast::Literal::Text(value)) if *scalar == Type::Text => {
Pattern::Text(value.clone())
}
ast::Pattern::Literal(ast::Literal::Number(value))
if matches!(scalar, Type::Int | Type::Decimal) =>
{
Pattern::Number(
Number::parse(value, scalar)
.map_err(|message| Diagnostic::new("C008", message, span))?,
)
}
ast::Pattern::Range(bounds) => Pattern::Range(types::range(scalar, bounds, span)?),
ast::Pattern::Variant(name, bindings) => {
let Type::Named(index) = scalar else {
return Err(Diagnostic::new(
"C005",
"variant condition requires a choice",
span,
));
};
let definition = &types.definitions[*index];
let Shape::Choice(variants) = &definition.shape else {
return Err(Diagnostic::new(
"C005",
"records cannot be variant conditions",
span,
));
};
let index = variants
.iter()
.position(|variant| {
*name == variant.name
|| *name
== format!(
"{}.{}",
definition.name.rsplit('.').next().unwrap(),
variant.name
)
})
.ok_or_else(|| Diagnostic::new("C004", "unknown choice variant", span))?;
if bindings.len() != variants[index].fields.len() {
return Err(Diagnostic::new(
"C005",
"variant payload binding count differs",
span,
));
}
Pattern::Variant(index, bindings.clone())
}
_ => {
return Err(Diagnostic::new(
"C005",
"condition does not match its input type",
span,
));
}
};
if matches!(pattern, Pattern::Other)
&& !matches!(kind, Type::Optional(_))
&& !matches!(
scalar,
Type::Bool | Type::Int | Type::Decimal | Type::Text | Type::Named(_)
)
{
return Err(Diagnostic::new(
"C005",
"this input only supports an unconstrained condition",
span,
));
}
Ok(pattern)
}
+175
View File
@@ -0,0 +1,175 @@
//! 每列按条件边界划分有限等价类,不枚举数值域或先构造多列笛卡尔积。
use super::{Fact, Types, present};
use crate::compiler::model::{
Condition, Field, Pattern, Shape, Type,
numeric::{Number, Range},
};
#[derive(Clone, Debug)]
pub(super) enum Cell {
Number(Range),
Bool(bool),
Text(String),
Variant(usize),
Null,
Present,
Whole,
}
pub(super) fn cells(input: &Field, conditions: &[&Condition], types: &Types) -> Vec<Cell> {
let patterns = conditions
.iter()
.flat_map(|condition| &condition.alternatives)
.collect::<Vec<_>>();
if patterns
.iter()
.all(|pattern| matches!(pattern, Pattern::Any))
{
return vec![Cell::Whole];
}
let kind = present(&input.kind);
let mut cells = match kind {
Type::Bool => vec![Cell::Bool(false), Cell::Bool(true)],
Type::Int | Type::Decimal => {
let range = input.range.unwrap_or_else(|| Range::full(kind));
let mut edges = vec![range.minimum];
for pattern in &patterns {
match pattern {
Pattern::Number(value) => {
edges.push(*value);
edges.extend(value.successor());
}
Pattern::Range(range) => {
edges.push(range.minimum);
edges.extend(range.maximum.successor());
}
_ => {}
}
}
edges.retain(|value| *value >= range.minimum && *value <= range.maximum);
edges.sort_by(|a, b| a.partial_cmp(b).expect("finite numbers of one type"));
edges.dedup();
edges
.iter()
.enumerate()
.map(|(index, minimum)| {
let maximum = edges
.get(index + 1)
.map(|next| {
next.predecessor()
.expect("partition has a preceding number")
})
.unwrap_or(range.maximum);
Cell::Number(Range {
minimum: *minimum,
maximum,
})
})
.collect()
}
Type::Text => {
let mut values = patterns
.iter()
.filter_map(|pattern| match pattern {
Pattern::Text(value) => Some(value.clone()),
_ => None,
})
.collect::<Vec<_>>();
values.sort();
values.dedup();
let mut remaining = String::new();
while values.binary_search(&remaining).is_ok() {
remaining.push('_');
}
values.push(remaining);
values.into_iter().map(Cell::Text).collect()
}
Type::Named(index) => match &types.definitions[*index].shape {
Shape::Choice(variants) => (0..variants.len()).map(Cell::Variant).collect(),
Shape::Record(_) => vec![Cell::Present],
},
_ => vec![Cell::Present],
};
if matches!(input.kind, Type::Optional(_)) {
cells.push(Cell::Null);
}
cells
}
pub(super) fn matches(pattern: &Pattern, cell: &Cell) -> bool {
match (pattern, cell) {
(Pattern::Any, _) => true,
(Pattern::Null, Cell::Null) => true,
(Pattern::Number(value), Cell::Number(actual)) => *value == actual.minimum,
(Pattern::Range(range), Cell::Number(actual)) => {
actual.minimum >= range.minimum && actual.minimum <= range.maximum
}
(Pattern::Bool(value), Cell::Bool(actual)) => value == actual,
(Pattern::Text(value), Cell::Text(actual)) => value == actual,
(Pattern::Variant(index, _), Cell::Variant(actual)) => index == actual,
_ => false,
}
}
pub(super) fn fact(cell: &Cell, input: &Field) -> Fact {
Fact {
range: match cell {
Cell::Number(range) => Some(*range),
Cell::Whole => input.guaranteed_range(),
_ => None,
},
boolean: if let Cell::Bool(value) = cell {
Some(*value)
} else {
None
},
present: !(matches!(cell, Cell::Null)
|| matches!(cell, Cell::Whole) && matches!(input.kind, Type::Optional(_))),
absent: matches!(cell, Cell::Null),
variants: match cell {
Cell::Variant(index) => Some([*index].into()),
Cell::Null => Some(Default::default()),
_ => None,
},
}
}
pub(super) fn union(previous: Fact, next: Fact) -> Fact {
Fact {
range: previous.range.zip(next.range).map(|(a, b)| a.hull(b)),
boolean: previous
.boolean
.filter(|value| Some(*value) == next.boolean),
present: previous.present && next.present,
absent: previous.absent && next.absent,
variants: previous.variants.zip(next.variants).map(|(mut a, b)| {
a.extend(b);
a
}),
}
}
pub(super) fn witness(cell: &Cell, input: &Field, types: &Types) -> String {
match cell {
Cell::Number(range) => match range.minimum {
Number::Int(value) => value.to_string(),
Number::Decimal(value) => value.to_string(),
Number::Float(_) => unreachable!("Float is not partitioned"),
},
Cell::Bool(value) => value.to_string(),
Cell::Text(value) => format!("{value:?}"),
Cell::Null => "null".into(),
Cell::Present => "<non-null value>".into(),
Cell::Whole => "<any value>".into(),
Cell::Variant(index) => {
let Type::Named(definition) = present(&input.kind) else {
unreachable!()
};
let Shape::Choice(variants) = &types.definitions[*definition].shape else {
unreachable!()
};
variants[*index].name.clone()
}
}
}
+199
View File
@@ -0,0 +1,199 @@
//! 逐轴筛候选行,计入条件匹配与候选展开;超预算是未证明,不是规则错误。
use super::{
Fact, PROOF_BUDGET, Types,
partition::{self},
present,
};
use crate::compiler::model::{Condition, Field, Pattern, Shape, Type};
use crate::syntax::{diagnostic::Diagnostic, source::Span};
pub(super) fn prove(
inputs: &[Field],
rows: &[Vec<Condition>],
types: &Types,
span: Span,
) -> Result<(usize, Vec<Vec<Fact>>), Diagnostic> {
let mut work = Work { used: 0, span };
let mut axes = Vec::new();
let mut facts = vec![Vec::with_capacity(inputs.len()); rows.len()];
for (column, input) in inputs.iter().enumerate() {
let conditions = rows.iter().map(|row| &row[column]).collect::<Vec<_>>();
check_errors(input, &conditions, types, &mut work)?;
work.spend(conditions.iter().map(|cell| cell.alternatives.len()).sum())?;
let cells = partition::cells(input, &conditions, types);
let mut partitions = Vec::new();
let mut column_facts: Vec<Option<Fact>> = vec![None; rows.len()];
for cell in cells {
work.spend(1)?;
// other 是整列显式条件的补集,不能随当前候选行改变含义。
let mut explicit = false;
let mut accepted = Vec::with_capacity(rows.len());
for condition in &conditions {
let mut yes = false;
let mut other = false;
for pattern in &condition.alternatives {
work.spend(1)?;
if matches!(pattern, Pattern::Other) {
other = true;
} else if partition::matches(pattern, &cell) {
yes = true;
explicit |= !matches!(pattern, Pattern::Any);
}
}
accepted.push((yes, other));
}
let accepted = accepted
.into_iter()
.map(|(yes, other)| yes || (other && !explicit))
.collect::<Vec<_>>();
for (row, accepted) in accepted.iter().enumerate() {
work.spend(1)?;
if !accepted {
continue;
}
let next = partition::fact(&cell, input);
column_facts[row] = Some(match column_facts[row].take() {
None => next,
Some(previous) => partition::union(previous, next),
});
}
partitions.push((cell, accepted));
}
for (row, fact) in column_facts.into_iter().enumerate() {
let Some(fact) = fact else {
return Err(Diagnostic::new(
"C009",
"rule row is outside its declared input domain",
rows[row][column].span,
));
};
facts[row].push(fact);
}
axes.push(partitions);
}
// 显式栈避免列数变成 Rust 调用栈深度。路径只保存所选等价类索引。
let mut pending = vec![(0, (0..rows.len()).collect::<Vec<_>>(), Vec::<usize>::new())];
let mut reached = vec![false; rows.len()];
while let Some((column, candidates, path)) = pending.pop() {
work.spend(1)?;
if column == inputs.len() {
if candidates.len() != 1 {
let witness = path
.iter()
.enumerate()
.map(|(column, cell)| {
format!(
"{} = {}",
inputs[column].name,
partition::witness(&axes[column][*cell].0, &inputs[column], types)
)
})
.collect::<Vec<_>>()
.join(", ");
let message = if candidates.is_empty() {
format!("rule does not cover: {witness}")
} else {
format!("rule rows overlap: {witness}")
};
let mut diagnostic = Diagnostic::new("C009", message, span);
for row in &candidates {
diagnostic
.related
.push((rows[*row][0].span, format!("matching row {}", row + 1)));
}
return Err(diagnostic);
}
reached[candidates[0]] = true;
continue;
}
for (cell, (_, accepted)) in axes[column].iter().enumerate().rev() {
work.spend(candidates.len() + 1)?;
let next = candidates
.iter()
.copied()
.filter(|row| accepted[*row])
.collect();
let mut path = path.clone();
path.push(cell);
pending.push((column + 1, next, path));
}
}
if let Some(row) = reached.iter().position(|reached| !reached) {
return Err(Diagnostic::new(
"C009",
"rule row is outside its declared input domain",
rows[row][0].span,
));
}
Ok((work.used, facts))
}
fn check_errors(
input: &Field,
conditions: &[&Condition],
types: &Types,
work: &mut Work,
) -> Result<(), Diagnostic> {
let Type::Named(index) = present(&input.kind) else {
return Ok(());
};
let Shape::Choice(variants) = &types.definitions[*index].shape else {
return Ok(());
};
let mut explicit = std::collections::HashSet::new();
let (mut any, mut other) = (None, None);
for condition in conditions {
for pattern in &condition.alternatives {
work.spend(1)?;
match pattern {
Pattern::Variant(index, _) => {
explicit.insert(*index);
}
Pattern::Any => any = Some(condition.span),
Pattern::Other => other = Some(condition.span),
_ => {}
}
}
}
for (index, variant) in variants
.iter()
.enumerate()
.filter(|(_, variant)| variant.error)
{
work.spend(1)?;
if let Some(span) = any.or_else(|| {
if explicit.contains(&index) {
None
} else {
other
}
}) {
return Err(Diagnostic::new(
"C011",
format!("error variant {} must be handled explicitly", variant.name),
span,
));
}
}
Ok(())
}
struct Work {
used: usize,
span: Span,
}
impl Work {
fn spend(&mut self, amount: usize) -> Result<(), Diagnostic> {
if amount > PROOF_BUDGET - self.used {
return Err(Diagnostic::new(
"C015",
"rule proof work budget exceeded; coverage has not been proved",
self.span,
));
}
self.used += amount;
Ok(())
}
}
+257
View File
@@ -0,0 +1,257 @@
//! 把类型引用解析为具体身份,数值范围只在这一层解析一次。
use crate::compiler::model::{self, Type, numeric};
use crate::compiler::project::Module;
use crate::syntax::names::{self, Style};
use crate::syntax::{ast, diagnostic::Diagnostic, source::Span};
use std::collections::{HashMap, HashSet};
mod access;
mod database;
mod declarations;
mod job;
mod structure;
mod walk;
pub struct Types<'a> {
pub jobs: Vec<model::Job>,
pub definitions: Vec<model::Definition>,
pub error_types: Vec<bool>,
names: HashMap<String, usize>,
walks: HashMap<(Type, Type), usize>,
related: HashMap<Type, usize>,
pub(crate) models: HashMap<String, (usize, String)>,
modules: &'a [Module],
}
impl<'a> Types<'a> {
pub(super) fn module(&self, source: usize) -> &Module {
&self.modules[source]
}
pub fn resolve(
declarations: &[ast::Declaration],
modules: &'a [Module],
) -> Result<Self, Diagnostic> {
let (types, diagnostics) = Self::analyze(declarations, modules);
if let Some(error) = diagnostics.into_iter().next() {
return Err(error);
}
Ok(types)
}
pub fn analyze(
declarations: &[ast::Declaration],
modules: &'a [Module],
) -> (Self, Vec<Diagnostic>) {
declarations::analyze(declarations, modules)
}
pub fn named(&self, name: &str, source: usize) -> Option<usize> {
self.names
.get(&self.modules[source].reference(name))
.copied()
}
pub fn variant(
&self,
name: &str,
source: usize,
expected: Option<&Type>,
) -> Option<(usize, usize)> {
let (definition, variant) = if let Some((type_name, variant)) = name.rsplit_once('.') {
let definition = if type_name == "Walk" {
let Type::Named(index) = expected? else {
return None;
};
self.walks
.values()
.any(|value| value == index)
.then_some(*index)?
} else {
self.named(type_name, source)?
};
(definition, variant)
} else {
let Type::Named(definition) = expected? else {
return None;
};
(*definition, name)
};
let model::Shape::Choice(variants) = &self.definitions[definition].shape else {
return None;
};
variants
.iter()
.position(|value| value.name == variant)
.map(|variant| (definition, variant))
}
pub fn reference(&self, reference: &ast::TypeRef) -> Result<Type, Diagnostic> {
if reference.handler.is_some() {
return Err(Diagnostic::new(
"C005",
"handler is only allowed as a static input parameter",
reference.span,
));
}
if let Some(argument) = reference
.arguments
.iter()
.find(|argument| !argument.bounds.is_empty() || !argument.parameters.is_empty())
{
return Err(Diagnostic::new(
"C005",
"numeric constraints belong to a field or parameter",
argument.span,
));
}
let arguments = reference
.arguments
.iter()
.map(|value| self.reference(value))
.collect::<Result<Vec<_>, _>>()?;
let kind =
match (reference.name.as_str(), arguments.as_slice()) {
("Upload", []) => Type::Upload,
("Bool", []) => Type::Bool,
("Int", []) => Type::Int,
("Float", []) => Type::Float,
("Decimal", []) => Type::Decimal,
("Text", []) => Type::Text,
("Bytes", []) => Type::Bytes,
("Json", []) => Type::Json,
("Secret", []) => Type::Secret,
("dever.system.File", []) => Type::File,
("dever.system.Socket", []) => Type::Socket,
("dever.system.Listener", []) => Type::Listener,
("dever.system.ClientTls", []) => Type::ClientTls,
("dever.system.ServerTls", []) => Type::ServerTls,
("dever.system.HttpClient", []) => Type::HttpClient,
("dever.system.HttpReply", []) => Type::HttpReply,
("dever.system.WebSocket", []) => Type::WebSocket,
("Uuid", []) => Type::Uuid,
("Id", []) => Type::Id,
("Duration", []) => Type::Duration,
("Time", []) => Type::Time,
("Date", []) => Type::Date,
("DateTime", []) => Type::DateTime,
("List", [item]) => Type::List(Box::new(item.clone())),
("Channel", [item]) => Type::Channel(Box::new(item.clone())),
("AsyncStream", [item]) => Type::AsyncStream(Box::new(item.clone())),
("Stream", [item]) => Type::Stream(Box::new(item.clone())),
("Map", [key, value]) => Type::Map(Box::new(key.clone()), Box::new(value.clone())),
("MapEntry", [key, value]) => {
Type::MapEntry(Box::new(key.clone()), Box::new(value.clone()))
}
("Walk", [item, state]) => {
Type::Named(*self.walks.get(&(item.clone(), state.clone())).ok_or_else(
|| Diagnostic::new("C004", "invalid Walk type arguments", reference.span),
)?)
}
("Related", [item]) => Type::Named(*self.related.get(item).ok_or_else(|| {
Diagnostic::new("C004", "invalid Related type argument", reference.span)
})?),
(name, []) => {
if let Some(kind) = self.model_reference(reference)? {
return Ok(if reference.nullable {
Type::Optional(Box::new(kind))
} else {
kind
});
}
let identity = self.modules[reference.span.source].reference(name);
let index = self.names.get(&identity).copied().ok_or_else(|| {
Diagnostic::new("C004", format!("unknown type: {name}"), reference.span)
})?;
self.access(index, reference.span)?;
Type::Named(index)
}
_ => {
return Err(Diagnostic::new(
"C004",
format!("unknown type or invalid type arguments: {}", reference.name),
reference.span,
));
}
};
if reference.nullable {
Ok(Type::Optional(Box::new(kind)))
} else {
Ok(kind)
}
}
pub fn fields(&self, fields: &[ast::Field]) -> Result<Vec<model::Field>, Diagnostic> {
self.resolve_fields(fields, false)
}
pub fn inputs(&self, fields: &[ast::Field]) -> Result<Vec<model::Field>, Diagnostic> {
self.resolve_fields(fields, true)
}
fn resolve_fields(
&self,
fields: &[ast::Field],
inputs: bool,
) -> Result<Vec<model::Field>, Diagnostic> {
let mut names = HashSet::new();
fields
.iter()
.map(|field| {
names::validate(&field.name, Style::Value, field.span)?;
if !names.insert(&field.name) {
return Err(Diagnostic::new(
"C001",
"duplicate field or parameter",
field.span,
));
}
if inputs && let Some(column) = self.input_column(field)? {
return Ok(column);
}
let kind = self.reference(&field.kind)?;
self.validate(&kind, field.span)?;
let range = if field.kind.bounds.is_empty() {
None
} else {
Some(range(&kind, &field.kind.bounds, field.span)?)
};
Ok(model::Field {
model: self.model_options(field, &kind)?,
name: field.name.clone(),
kind,
range,
private: field.private,
span: field.span,
})
})
.collect()
}
}
pub(super) fn range(
kind: &Type,
bounds: &[ast::Bound],
span: Span,
) -> Result<numeric::Range, Diagnostic> {
if !matches!(kind, Type::Int | Type::Decimal) {
return Err(Diagnostic::new(
"C005",
"numeric ranges require Int or Decimal",
span,
));
}
let bounds = bounds
.iter()
.map(|bound| {
let value = numeric::Number::parse(&bound.value, kind)
.map_err(|message| Diagnostic::new("C008", message, bound.span))?;
Ok(numeric::Bound {
operator: bound.operator.clone(),
value,
})
})
.collect::<Result<Vec<_>, Diagnostic>>()?;
numeric::Range::bounds(kind, &bounds)
.ok_or_else(|| Diagnostic::new("C008", "numeric range is empty", span))
}
+45
View File
@@ -0,0 +1,45 @@
//! 类型引用与字段访问沿用旧角色边界;完整路径不能绕过私有字段。
use super::Types;
use crate::compiler::model::Field;
use crate::syntax::{diagnostic::Diagnostic, source::Span};
impl Types<'_> {
pub fn access(&self, definition: usize, span: Span) -> Result<(), Diagnostic> {
let Some(origin) = self.definitions[definition].span else {
return Ok(());
};
if self.modules[span.source].can_use_type(&self.modules[origin.source]) {
Ok(())
} else {
Err(Diagnostic::new(
"C006",
"application role cannot access this type",
span,
))
}
}
pub fn field_access(
&self,
definition: usize,
field: &Field,
span: Span,
) -> Result<(), Diagnostic> {
if field.private
&& !self.modules[span.source].can_use_private(
&self.modules[self.definitions[definition]
.span
.expect("private field has a source")
.source],
)
{
return Err(Diagnostic::new(
"C006",
"field is private to its role",
span,
));
}
Ok(())
}
}
+385
View File
@@ -0,0 +1,385 @@
//! Model 同名记录提供生成字段、名义 ID 和分页类型。
use super::*;
mod constraints;
mod fields;
mod initialization;
mod migration;
mod native;
mod relation;
mod sql;
use crate::compiler::{
model::{Definition, Field, Shape},
project::Role,
};
pub(super) fn models(
declarations: &[&ast::TypeDeclaration],
modules: &[Module],
) -> HashMap<String, (usize, String)> {
declarations
.iter()
.filter_map(|declaration| {
let module = &modules[declaration.span.source];
if module.role != Role::Model {
return None;
}
let name = module
.topic
.as_deref()
.unwrap_or(&module.domain)
.split('_')
.flat_map(|part| {
let mut chars = part.chars();
chars
.next()
.into_iter()
.flat_map(char::to_uppercase)
.chain(chars)
})
.collect::<String>();
(declaration.name == name && matches!(declaration.body, ast::TypeBody::Record(_))).then(
|| {
(
module.identity(),
(declaration.span.source, module.qualify(&name)),
)
},
)
})
.collect()
}
impl Types<'_> {
pub(super) fn model_bindings(
&mut self,
declarations: &[ast::Declaration],
modules: &[Module],
) -> Vec<Diagnostic> {
let mut diagnostics = Vec::new();
let mut bindings = HashMap::new();
for declaration in declarations {
if let ast::Declaration::Database { name, span } = declaration {
if name == "create" {
diagnostics.push(Diagnostic::new(
"C001",
"database name create is reserved by database.create",
*span,
));
continue;
}
if modules[span.source].role == Role::Api {
continue;
}
if modules[span.source].role != Role::Model {
diagnostics.push(Diagnostic::new(
"C003",
"database binding belongs in Model",
*span,
));
} else if let Err(error) = names::validate(name, Style::Value, *span) {
diagnostics.push(error);
} else if bindings.insert(span.source, name).is_some() {
diagnostics.push(Diagnostic::new("C001", "duplicate database binding", *span));
}
}
}
let mut tables = HashMap::new();
for declaration in declarations {
let ast::Declaration::Type(declaration) = declaration else {
continue;
};
let module = &modules[declaration.span.source];
let name = module.qualify(&declaration.name);
let primary = self
.models
.get(&module.identity())
.is_some_and(|(_, record)| *record == name);
if declaration.display_name.is_some() && !primary {
diagnostics.push(Diagnostic::new(
"C003",
"table name requires a persistent record",
declaration.span,
));
}
if declaration.global && !primary {
diagnostics.push(Diagnostic::new(
"C003",
"global requires the primary Model record",
declaration.span,
));
}
if primary {
let index = self.names[&name];
let database = bindings
.get(&declaration.span.source)
.map_or("default", |name| name.as_str());
let table = self.definitions[index].table();
let first = tables
.entry((database, table.clone()))
.or_insert(declaration.span);
if first.source != declaration.span.source {
let mut error = Diagnostic::new(
"C001",
format!("duplicate physical table {table} in database {database}"),
declaration.span,
);
error
.related
.push((*first, "first Model using this table".into()));
diagnostics.push(error);
}
self.definitions[index].model = Some(model::Model {
display_name: declaration.display_name.clone(),
columns: match &self.definitions[index].shape {
Shape::Record(fields) => fields.len(),
_ => unreachable!(),
},
relations: Vec::new(),
migrations: Vec::new(),
sql: Vec::new(),
seeds: Vec::new(),
indexes: Vec::new(),
order: 0,
database: database.into(),
global: declaration.global,
});
}
}
for declaration in declarations {
if let ast::Declaration::Database { span, .. } = declaration
&& modules[span.source].role != Role::Api
&& !self
.models
.values()
.any(|(source, _)| *source == span.source)
{
diagnostics.push(Diagnostic::new(
"C005",
"database binding requires a primary Model in the same file",
*span,
));
}
}
diagnostics
}
pub(super) fn input_column(&self, arg: &ast::Field) -> Result<Option<Field>, Diagnostic> {
let mut parts = arg.kind.name.split('.');
if parts.next() != Some("data") && parts.nth(1) != Some("data") {
return Ok(None);
}
let identity = self.modules[arg.span.source].reference(&arg.kind.name);
let Some((owner, name)) = identity.rsplit_once('.') else {
return Ok(None);
};
let Some((_, record)) = self.models.get(owner) else {
return Ok(None);
};
if name == "id" {
return Ok(None);
}
let record = self.names[record];
let Some(column) = self.definitions[record]
.columns()
.iter()
.find(|f| f.name == name)
else {
return Ok(None);
};
self.access(record, arg.span)?;
self.field_access(record, column, arg.span)?;
if column.kind != Type::Text
|| arg.kind.nullable
|| !arg.kind.arguments.is_empty()
|| !arg.kind.parameters.is_empty()
|| !arg.kind.bounds.is_empty()
|| !arg.modifiers.is_empty()
{
return Err(Diagnostic::new(
"C005",
"input field references require a non-null Text column without new constraints",
arg.span,
));
}
let mut options = model::ModelField {
input_contract: true,
..Default::default()
};
if let Some(source) = &column.model {
options.text = source.text;
options.length = source.length;
}
Ok(Some(Field {
name: arg.name.clone(),
span: arg.span,
private: arg.private,
kind: Type::Text,
range: None,
model: Some(Box::new(options)),
}))
}
pub(super) fn model_reference(
&self,
reference: &ast::TypeRef,
) -> Result<Option<Type>, Diagnostic> {
let identity = self.modules[reference.span.source].reference(&reference.name);
let Some((owner, field)) = identity.rsplit_once('.') else {
return Ok(None);
};
if field != "id" {
return Ok(None);
}
let Some((source, _)) = self.models.get(owner) else {
return Ok(None);
};
if !self.modules[reference.span.source].can_use_type(&self.modules[*source]) {
return Err(Diagnostic::new(
"C006",
"application role cannot access this Model ID",
reference.span,
));
}
Ok(Some(Type::ModelId(*source)))
}
pub(super) fn model_fields(
&self,
declaration: &ast::TypeDeclaration,
fields: &[ast::Field],
) -> Result<Vec<Field>, Diagnostic> {
let module = &self.modules[declaration.span.source];
let mut result = self.fields(fields)?;
if self
.models
.get(&module.identity())
.is_none_or(|(_, name)| *name != module.qualify(&declaration.name))
{
return Ok(result);
}
if let Some(field) = fields
.iter()
.find(|field| matches!(field.name.as_str(), "id" | "created_at"))
{
return Err(Diagnostic::new(
"C014",
"id and created_at are generated Model fields",
field.span,
));
}
for field in &result {
self.model_storage(&field.kind, field.span)?;
if let Some(default) = field.model.as_ref().and_then(|m| m.default.as_ref()) {
self.validate_model_value(default, field)?;
}
}
result.splice(
0..0,
[
("id", Type::ModelId(declaration.span.source)),
("created_at", Type::DateTime),
]
.into_iter()
.map(|(name, kind)| Field {
model: None,
name: name.into(),
kind,
range: None,
private: false,
span: declaration.span,
}),
);
Ok(result)
}
fn model_storage(&self, kind: &Type, span: Span) -> Result<(), Diagnostic> {
match kind {
Type::Json
| Type::Decimal
| Type::Bool
| Type::Int
| Type::Float
| Type::Text
| Type::Bytes
| Type::ModelId(_)
| Type::DateTime
| Type::Date
| Type::Time
| Type::Uuid
| Type::Id => Ok(()),
Type::Optional(inner) => self.model_storage(inner, span),
Type::Named(index) if matches!(&self.definitions[*index].shape, Shape::Choice(v) if v.iter().all(|v| v.fields.is_empty() && !v.error)) => {
Ok(())
}
_ => Err(Diagnostic::new(
"C005",
"unsupported Model storage field",
span,
)),
}
}
pub(super) fn model_pages(&mut self) -> Vec<Diagnostic> {
let mut diagnostics = Vec::new();
// 固定声明顺序,避免 HashMap 迭代改变生成类型身份。
let mut models = self.models.iter().collect::<Vec<_>>();
models.sort_by_key(|(_, (source, _))| *source);
for (owner, (_, record)) in models {
let Some(&definition) = self.names.get(record) else {
continue;
};
let span = self.definitions[definition].span.unwrap();
for (suffix, fields) in [
(
"Page",
vec![
("items", Type::List(Box::new(Type::Named(definition)))),
("page", Type::Int),
("size", Type::Int),
("total", Type::Int),
("pages", Type::Int),
],
),
(
"Cursor",
vec![
("items", Type::List(Box::new(Type::Named(definition)))),
("next", Type::Optional(Box::new(Type::Named(definition)))),
("has_more", Type::Bool),
],
),
] {
let name = format!("{owner}.{suffix}");
if self.names.contains_key(&name) {
diagnostics.push(Diagnostic::new(
"C001",
format!("{suffix} is generated for this Model"),
span,
));
continue;
}
let fields = fields
.into_iter()
.map(|(name, kind)| Field {
model: None,
name: name.into(),
kind,
range: None,
private: false,
span,
})
.collect();
self.names.insert(name.clone(), self.definitions.len());
self.definitions.push(Definition {
related: false,
model: None,
name,
shape: Shape::Record(fields),
span: Some(span),
});
self.error_types.push(false);
}
}
diagnostics
}
}
@@ -0,0 +1,178 @@
//! 索引和外键在 Model 声明处绑定;跨物理库引用在生成 SQL 前拒绝。
use super::*;
impl Types<'_> {
pub(in crate::compiler::check::types) fn model_constraints(
&mut self,
declarations: &[ast::Declaration],
) -> Vec<Diagnostic> {
let mut errors = Vec::new();
for declaration in declarations {
let ast::Declaration::Index {
unique,
fields: names,
span,
} = declaration
else {
continue;
};
let Some((_, record)) = self.models.get(&self.modules[span.source].identity()) else {
errors.push(Diagnostic::new(
"C005",
"index requires a primary Model in the same file",
*span,
));
continue;
};
let definition = &mut self.definitions[self.names[record]];
let Shape::Record(fields) = &definition.shape else {
unreachable!()
};
let positions = names
.iter()
.map(|name| fields.iter().position(|f| f.name == *name))
.collect::<Option<Vec<_>>>();
let Some(positions) = positions else {
errors.push(Diagnostic::new(
"C005",
"index contains an unknown Model field",
*span,
));
continue;
};
if positions.iter().collect::<HashSet<_>>().len() != positions.len() {
errors.push(Diagnostic::new(
"C005",
"duplicate field in Model index",
*span,
));
continue;
}
let model = definition.model.as_mut().unwrap();
if model.indexes.iter().any(|index| index.fields == positions) {
errors.push(Diagnostic::new("C005", "duplicate Model index", *span));
continue;
}
model.indexes.push(model::ModelIndex {
unique: *unique,
fields: positions,
});
}
for definition in &mut self.definitions {
let Some(model) = &mut definition.model else {
continue;
};
let Shape::Record(fields) = &definition.shape else {
unreachable!()
};
if let (Some(owner), Some(search)) = (
fields
.iter()
.position(|f| f.model.as_ref().is_some_and(|m| m.owner.is_some())),
fields
.iter()
.position(|f| f.model.as_ref().is_some_and(|m| m.search.is_some())),
) {
let positions = vec![owner, search];
if !model.indexes.iter().any(|index| index.fields == positions) {
model.indexes.push(model::ModelIndex {
unique: false,
fields: positions,
});
}
}
}
let sources = self
.definitions
.iter()
.enumerate()
.filter(|(_, d)| d.model.is_some())
.map(|(index, d)| (d.span.unwrap().source, index))
.collect::<HashMap<_, _>>();
let mut edges = vec![Vec::new(); self.definitions.len()];
for (index, definition) in self.definitions.iter().enumerate() {
let Some(model) = &definition.model else {
continue;
};
let Shape::Record(fields) = &definition.shape else {
unreachable!()
};
let mut renamed = HashSet::new();
for field in fields {
if let Some(previous) = field.model.as_ref().and_then(|m| m.previous.as_ref())
&& (fields.iter().any(|f| f.name == *previous) || !renamed.insert(previous))
{
errors.push(Diagnostic::new(
"C005",
"from source must be removed and used by one target column",
field.span,
));
}
}
for field in fields.iter().skip(2) {
let kind = match &field.kind {
Type::Optional(inner) => inner.as_ref(),
kind => kind,
};
let Type::ModelId(source) = kind else {
continue;
};
// 错误的目标定义已由类型检查报告,不制造替代 Model。
let Some(&target) = sources.get(source) else {
continue;
};
let binding = self.definitions[target].model.as_ref().unwrap();
if field.model.as_ref().is_some_and(|m| m.owner.is_some()) {
// 身份在控制库验证;租户物理库不能建立指向控制库的外键。
if !binding.global {
errors.push(Diagnostic::new(
"C014",
"owner must reference a global identity Model",
field.span,
));
}
continue;
}
let same_storage =
model.database == binding.database && model.global == binding.global;
if field.model.as_ref().is_some_and(|m| m.external) {
if same_storage || !binding.global {
errors.push(Diagnostic::new(
"C005",
"external requires a global data ID in another storage",
field.span,
));
}
continue;
}
if !same_storage {
errors.push(Diagnostic::new(
"C005",
"foreign keys must share database and global/tenant storage",
field.span,
));
}
if target != index {
edges[index].push((target, field.span));
}
}
}
let names = self
.definitions
.iter()
.map(|d| d.name.clone())
.collect::<Vec<_>>();
let (order, cycle) = crate::compiler::check::calls::partial_order(
&edges,
&names,
"cyclic Model foreign keys are not supported by PostgreSQL",
);
errors.extend(cycle);
for (order, index) in order.into_iter().enumerate() {
if let Some(model) = &mut self.definitions[index].model {
model.order = order;
}
}
errors
}
}
@@ -0,0 +1,326 @@
//! 默认值和存储修饰只定义一次;写入端使用已解析的字段合同。
use super::*;
use crate::compiler::model::{Expression, ExpressionKind, ModelField, TextMode};
impl Types<'_> {
pub(crate) fn model_options(
&self,
field: &ast::Field,
kind: &Type,
) -> Result<Option<Box<ModelField>>, Diagnostic> {
let options = !field.modifiers.is_empty() || !field.kind.parameters.is_empty();
if self.modules[field.span.source].role != Role::Model {
if options {
return Err(Diagnostic::new(
"C005",
"storage constraints belong to Model fields",
field.span,
));
}
return Ok(None);
}
let scalar = match kind {
Type::Optional(inner) => inner.as_ref(),
kind => kind,
};
let mut model = ModelField::default();
if !field.kind.parameters.is_empty() {
let bounds = field
.kind
.parameters
.iter()
.map(|s| s.parse::<usize>())
.collect::<Result<Vec<_>, _>>()
.map_err(|_| {
Diagnostic::new(
"C005",
"storage bounds must be nonnegative integers",
field.span,
)
})?;
match (scalar, bounds.as_slice()) {
(Type::Text | Type::Bytes, &[min, max]) if min <= max => {
model.length = Some((min, max))
}
(Type::Decimal, &[precision, scale])
if (1..=34).contains(&precision) && scale <= precision =>
{
model.decimal = Some((precision as u32, scale as u32))
}
_ => {
return Err(Diagnostic::new(
"C005",
"expected Text/Bytes(min,max) or Decimal(precision,scale) storage bounds",
field.span,
));
}
}
}
if *scalar == Type::Decimal && model.decimal.is_none() {
return Err(Diagnostic::new(
"C005",
"Model Decimal requires explicit precision and scale",
field.span,
));
}
let mut seen = HashSet::new();
for (name, value) in &field.modifiers {
if !seen.insert(name.as_str()) {
return Err(Diagnostic::new(
"C005",
"duplicate field modifier",
field.span,
));
}
match name.as_str() {
"name" | "description" => {
let ast::ExpressionKind::Literal(ast::Literal::Text(text)) =
&value.as_ref().unwrap().kind
else {
unreachable!()
};
if name == "name" {
model.display_name = Some(text.clone());
} else {
model.description = Some(text.clone());
}
}
"create" => model.create = value.clone(),
"replace" => model.replace = value.clone(),
"search" => model.search = value.clone(),
"owner" => {
let ast::ExpressionKind::Call(target, arguments) =
&value.as_ref().unwrap().kind
else {
return Err(Diagnostic::new(
"C014",
"owner requires a direct trusted identity read",
field.span,
));
};
model.owner = match target.path().as_deref() {
Some("dever.auth.userId") => Some(true),
Some("dever.auth.tenantId") => Some(false),
_ => {
return Err(Diagnostic::new(
"C014",
"owner requires userId() or tenantId()",
field.span,
));
}
};
if !arguments.is_empty()
|| !matches!(kind, Type::ModelId(_))
|| field
.modifiers
.iter()
.any(|(n, _)| !matches!(n.as_str(), "owner" | "name" | "description"))
{
return Err(Diagnostic::new(
"C014",
"owner requires a non-null Model ID without storage modifiers",
field.span,
));
}
}
"from" => {
let ast::ExpressionKind::Name(name) = &value.as_ref().unwrap().kind else {
unreachable!()
};
names::validate(name, Style::Value, field.span)?;
if name == &field.name || matches!(name.as_str(), "id" | "created_at") {
return Err(Diagnostic::new(
"C005",
"from must name a different, nongenerated column",
field.span,
));
}
model.previous = Some(name.clone());
}
"default" => {
model.default = Some(self.model_default(value.as_ref().unwrap(), kind)?)
}
"external" if matches!(scalar, Type::ModelId(_)) => model.external = true,
"external" => {
return Err(Diagnostic::new(
"C005",
"external requires a data ID",
field.span,
));
}
"index" => model.index = true,
"unique" => model.unique = true,
"generated" => model.generated = true,
"raw" | "lower" | "upper" => {
if *scalar != Type::Text || model.text != TextMode::Trim {
return Err(Diagnostic::new(
"C005",
"Text normalization modifiers are mutually exclusive",
field.span,
));
}
model.text = match name.as_str() {
"raw" => TextMode::Raw,
"lower" => TextMode::Lower,
_ => TextMode::Upper,
};
}
_ => unreachable!("parsed field modifier"),
}
}
if model.generated && (*kind != Type::Uuid || model.default.is_some()) {
return Err(Diagnostic::new(
"C005",
"generated requires non-null Uuid without a default",
field.span,
));
}
Ok(Some(Box::new(model)))
}
pub(super) fn validate_model_value(
&self,
value: &Expression,
field: &Field,
) -> Result<(), Diagnostic> {
let scalar = match &value.kind {
ExpressionKind::Some(inner) => &inner.kind,
value => value,
};
let model = field.model.as_ref().unwrap();
if let ExpressionKind::Text(text) = scalar {
let normalized = match model.text {
TextMode::Trim => text.trim().to_owned(),
TextMode::Raw => text.clone(),
TextMode::Lower => text.trim().to_lowercase(),
TextMode::Upper => text.trim().to_uppercase(),
};
if model
.length
.is_some_and(|(min, max)| !(min..=max).contains(&normalized.chars().count()))
{
return Err(Diagnostic::new(
"C005",
"Model literal length is outside its field bounds",
value.span,
));
}
}
if let (Some(range), ExpressionKind::Number(number)) = (field.range, scalar)
&& (*number < range.minimum || *number > range.maximum)
{
return Err(Diagnostic::new(
"C005",
"Model literal is outside its field range",
value.span,
));
}
Ok(())
}
pub(super) fn model_default(
&self,
value: &ast::Expression,
kind: &Type,
) -> Result<Expression, Diagnostic> {
let scalar = match kind {
Type::Optional(inner) => inner.as_ref(),
kind => kind,
};
let invalid = || {
Diagnostic::new(
"C005",
"Model default must be a literal of its field type",
value.span,
)
};
let node = match &value.kind {
ast::ExpressionKind::Literal(ast::Literal::Text(raw)) if *scalar == Type::Json => {
let json = dever_runtime::wire::json::Json::from_text(raw.clone())
.map_err(|error| Diagnostic::new("C005", error, value.span))?;
let (values, depth) = json.literal_shape();
ExpressionKind::JsonLiteral {
raw: json.into_text(),
values,
depth,
}
}
ast::ExpressionKind::Literal(ast::Literal::Text(text)) if *scalar == Type::Text => {
ExpressionKind::Text(text.clone())
}
ast::ExpressionKind::Literal(ast::Literal::Bool(value)) if *scalar == Type::Bool => {
ExpressionKind::Bool(*value)
}
ast::ExpressionKind::Literal(ast::Literal::Null)
if matches!(kind, Type::Optional(_)) =>
{
return Ok(Expression {
kind: ExpressionKind::Null,
value_type: kind.clone(),
range: None,
known_bool: None,
span: value.span,
});
}
ast::ExpressionKind::Literal(ast::Literal::Number(text))
if matches!(
scalar,
Type::Int | Type::Float | Type::Decimal | Type::ModelId(_)
) =>
{
let parse_type = if matches!(scalar, Type::ModelId(_)) {
&Type::Int
} else {
scalar
};
let number = numeric::Number::parse(text, parse_type).map_err(|_| invalid())?;
if matches!(scalar, Type::ModelId(_)) && number <= numeric::Number::Int(0) {
return Err(invalid());
}
ExpressionKind::Number(number)
}
ast::ExpressionKind::Unary(op, inner)
if op == "-" && matches!(scalar, Type::Int | Type::Float | Type::Decimal) =>
{
let ast::ExpressionKind::Literal(ast::Literal::Number(number)) = &inner.kind else {
return Err(invalid());
};
ExpressionKind::Number(
numeric::Number::parse(&format!("-{number}"), scalar).map_err(|_| invalid())?,
)
}
_ => {
let path = value.path().ok_or_else(invalid)?;
let (definition, variant) = self
.variant(&path, value.span.source, Some(scalar))
.ok_or_else(invalid)?;
let Shape::Choice(variants) = &self.definitions[definition].shape else {
unreachable!()
};
if !variants[variant].fields.is_empty() || variants[variant].error {
return Err(invalid());
}
ExpressionKind::Variant(definition, variant, Vec::new())
}
};
let range = match &node {
ExpressionKind::Number(value) => Some(numeric::Range::point(*value)),
_ => None,
};
let expression = Expression {
kind: node,
value_type: scalar.clone(),
range,
known_bool: None,
span: value.span,
};
if kind != scalar {
Ok(Expression {
kind: ExpressionKind::Some(Box::new(expression)),
value_type: kind.clone(),
range,
known_bool: None,
span: value.span,
})
} else {
Ok(expression)
}
}
}
@@ -0,0 +1,115 @@
//! 初始化声明只绑定静态数据和显式删除;执行交给已有迁移器。
use super::*;
impl Types<'_> {
pub(in crate::compiler::check::types) fn model_initialization(
&mut self,
declarations: &[ast::Declaration],
) -> Vec<Diagnostic> {
let mut errors = Vec::new();
let mut seen = HashSet::new();
for declaration in declarations {
if let ast::Declaration::Migration { name, steps, span } = declaration {
if let Err(error) = self.model_migration(name, steps, *span) {
errors.push(error);
}
continue;
}
let ast::Declaration::Seed { rows, span } = declaration else {
continue;
};
let Some((_, record)) = self.models.get(&self.modules[span.source].identity()) else {
errors.push(Diagnostic::new(
"C005",
"seed requires a primary Model in the same file",
*span,
));
continue;
};
if !seen.insert(span.source) {
errors.push(Diagnostic::new(
"C005",
"duplicate Model seed declaration",
*span,
));
continue;
}
let index = self.names[record];
match rows
.iter()
.map(|row| self.model_seed(index, row))
.collect::<Result<Vec<_>, _>>()
{
Ok(seeds) => self.definitions[index].model.as_mut().unwrap().seeds = seeds,
Err(error) => errors.push(error),
}
}
errors
}
fn model_seed(&self, index: usize, row: &ast::Expression) -> Result<model::Seed, Diagnostic> {
let invalid = |message| Diagnostic::new("C005", message, row.span);
let ast::ExpressionKind::Map(entries) = &row.kind else {
return Err(invalid("seed row requires a direct field block"));
};
let definition = &self.definitions[index];
let Shape::Record(fields) = &definition.shape else {
unreachable!()
};
let mut values = Vec::new();
for (key, value) in entries {
let ast::ExpressionKind::Name(name) = &key.kind else {
return Err(invalid("seed requires static field names"));
};
let position = fields
.iter()
.position(|f| f.name == *name)
.ok_or_else(|| invalid("unknown seed field"))?;
let field = &fields[position];
if position < 2
|| field.model.as_ref().is_some_and(|m| m.generated)
|| values.iter().any(|(p, _)| *p == position)
{
return Err(invalid(
"seed cannot override generated fields or duplicate fields",
));
}
let value = self.model_default(value, &field.kind)?;
self.validate_model_value(&value, field)?;
values.push((position, value));
}
for (position, field) in fields.iter().enumerate().skip(2) {
let model = field.model.as_ref().unwrap();
if !values.iter().any(|(p, _)| *p == position)
&& !model.generated
&& model.default.is_none()
&& !matches!(field.kind, Type::Optional(_))
{
return Err(invalid("seed omits a required field"));
}
}
let key = fields
.iter()
.enumerate()
.filter(|(_, f)| f.model.as_ref().is_some_and(|m| m.unique))
.map(|(index, _)| vec![index])
.chain(
definition
.model
.as_ref()
.unwrap()
.indexes
.iter()
.filter(|i| i.unique)
.map(|i| i.fields.clone()),
)
.find(|key| {
key.iter().all(|k| {
values.iter().any(|(p, value)| {
p == k && !matches!(value.kind, model::ExpressionKind::Null)
})
})
})
.ok_or_else(|| invalid("seed requires one complete non-null unique key"))?;
Ok(model::Seed { values, key })
}
}
@@ -0,0 +1,165 @@
//! 迁移声明只检查静态合同,数据库变换由现有事务迁移器执行。
use super::*;
use crate::compiler::model::{ModelMigration, ModelStatement, SqlValue};
impl Types<'_> {
pub(super) fn model_migration(
&mut self,
name: &str,
steps: &[ast::MigrationStep],
span: Span,
) -> Result<(), Diagnostic> {
let invalid = |message| Diagnostic::new("C014", message, span);
let (_, record) = self
.models
.get(&self.modules[span.source].identity())
.ok_or_else(|| invalid("migration requires a primary Model in the same file"))?;
names::validate(name, Style::Value, span)?;
let definition = &mut self.definitions[self.names[record]];
let Shape::Record(fields) = &definition.shape else {
unreachable!()
};
let model = definition.model.as_mut().unwrap();
if steps.is_empty() || model.migrations.iter().any(|m| m.name == name) {
return Err(invalid(
"migration requires a unique name and nonempty steps",
));
}
let mut migration = ModelMigration {
name: name.into(),
drops: Vec::new(),
before: Vec::new(),
after: Vec::new(),
};
for step in steps {
match step {
ast::MigrationStep::Drop(name) => {
names::validate(name, Style::Value, span)?;
if migration.drops.contains(name)
|| fields.iter().any(|f| {
f.name == *name
|| f.model.as_ref().and_then(|m| m.previous.as_ref()) == Some(name)
})
{
return Err(invalid(
"drop conflicts with a current column, rename or another drop",
));
}
migration.drops.push(name.clone());
}
ast::MigrationStep::Data { before, value } => {
let statement = statement(value)?;
if *before {
migration.before.push(statement);
} else {
migration.after.push(statement);
}
}
}
}
model.migrations.push(migration);
Ok(())
}
}
fn statement(value: &ast::Expression) -> Result<ModelStatement, Diagnostic> {
let invalid = |message| Diagnostic::new("C014", message, value.span);
let ast::ExpressionKind::Map(entries) = &value.kind else {
return Err(invalid(
"migration data step requires sqlite, postgres and parameters fields",
));
};
let mut sqlite = None;
let mut postgres = None;
let mut parameters = None;
for (key, value) in entries {
let ast::ExpressionKind::Name(name) = &key.kind else {
return Err(invalid("migration data fields must be static names"));
};
match (name.as_str(), &value.kind) {
("sqlite", ast::ExpressionKind::Literal(ast::Literal::Text(text)))
if sqlite.is_none() =>
{
sqlite = Some(text.clone())
}
("postgres", ast::ExpressionKind::Literal(ast::Literal::Text(text)))
if postgres.is_none() =>
{
postgres = Some(text.clone())
}
("parameters", ast::ExpressionKind::List(values)) if parameters.is_none() => {
parameters = Some(
values
.iter()
.map(parameter)
.collect::<Result<Vec<_>, _>>()?,
);
}
_ => {
return Err(invalid(
"unknown, duplicate or invalid migration data field",
));
}
}
}
let (Some(sqlite), Some(postgres), Some(parameters)) = (sqlite, postgres, parameters) else {
return Err(invalid(
"migration data requires both dialects and an explicit parameters list",
));
};
for (text, postgres) in [(&sqlite, false), (&postgres, true)] {
let statement = sql::parse(text, postgres, parameters.len(), value.span)?;
if !matches!(
statement,
sqlparser::ast::Statement::Insert(_)
| sqlparser::ast::Statement::Update(_)
| sqlparser::ast::Statement::Delete(_)
) {
return Err(invalid(
"migration requires one INSERT, UPDATE or DELETE statement",
));
}
}
Ok(ModelStatement {
sqlite,
postgres,
parameters,
})
}
fn parameter(value: &ast::Expression) -> Result<SqlValue, Diagnostic> {
let invalid = || {
Diagnostic::new(
"C014",
"migration parameters require Bool, Int, Text, null or exponent Float literals",
value.span,
)
};
let number = |text: &str| -> Result<SqlValue, Diagnostic> {
let kind = if text.contains(['e', 'E']) {
Type::Float
} else {
Type::Int
};
match numeric::Number::parse(text, &kind).map_err(|_| invalid())? {
numeric::Number::Int(value) => Ok(SqlValue::Integer(value)),
numeric::Number::Float(value) => Ok(SqlValue::Real(value)),
numeric::Number::Decimal(_) => unreachable!("migration scalar kind"),
}
};
match &value.kind {
ast::ExpressionKind::Literal(literal) => match literal {
ast::Literal::Null => Ok(SqlValue::Null),
ast::Literal::Bool(value) => Ok(SqlValue::Bool(*value)),
ast::Literal::Text(value) => Ok(SqlValue::Text(value.clone())),
ast::Literal::Number(value) => number(value),
},
ast::ExpressionKind::Unary(op, value) if op == "-" => match &value.kind {
ast::ExpressionKind::Literal(ast::Literal::Number(value)) => {
number(&format!("-{value}"))
}
_ => Err(invalid()),
},
_ => Err(invalid()),
}
}
@@ -0,0 +1,164 @@
//! 具名 SQL 在 Model 声明;只有已证明的自有表查询能建立只读保证。
use super::*;
use crate::compiler::model::ModelSql;
mod proof;
impl Types<'_> {
pub(in crate::compiler::check::types) fn model_sql(
&mut self,
declarations: &[ast::Declaration],
) -> Vec<Diagnostic> {
declarations
.iter()
.filter_map(|declaration| {
let ast::Declaration::Sql {
name,
inputs,
outputs,
value,
span,
} = declaration
else {
return None;
};
self.native_sql(name, inputs, outputs, value, *span).err()
})
.collect()
}
fn native_sql(
&mut self,
name: &str,
inputs: &[ast::Field],
outputs: &[ast::Field],
value: &ast::Expression,
span: Span,
) -> Result<(), Diagnostic> {
let invalid = |message| Diagnostic::new("C014", message, span);
names::validate(name, Style::Function, span)?;
let module = &self.modules[span.source];
let (_, record) = self
.models
.get(&module.identity())
.ok_or_else(|| invalid("SQL requires a primary Model in the same file"))?;
let model_index = self.names[record];
if model::DatabaseOp::builtin(name).is_some()
|| self.definitions[model_index]
.model
.as_ref()
.unwrap()
.sql
.iter()
.any(|q| q.name == name)
{
return Err(invalid("duplicate or reserved Model SQL operation"));
}
let [output] = outputs else {
return Err(invalid("SQL requires one record output"));
};
for field in inputs.iter().chain(outputs) {
if field.private || !field.modifiers.is_empty() || field.kind.handler.is_some() {
return Err(invalid(
"SQL signatures cannot declare private fields, handlers or storage modifiers",
));
}
}
if !output.kind.bounds.is_empty() || !output.kind.parameters.is_empty() {
return Err(invalid(
"SQL output shape cannot declare scalar constraints",
));
}
let inputs = self.fields(inputs)?;
for field in &inputs {
self.model_storage(&field.kind, field.span)?;
}
let output = self.reference(&output.kind)?;
let row = match &output {
Type::Optional(inner) | Type::List(inner) => inner.as_ref(),
kind => kind,
};
let Type::Named(record) = row else {
return Err(invalid(
"SQL output requires a record, optional record or List of records",
));
};
let definition = &self.definitions[*record];
let Shape::Record(fields) = &definition.shape else {
return Err(invalid("SQL output requires a record"));
};
let origin = definition
.span
.ok_or_else(|| invalid("SQL output requires a source record"))?;
if origin.source != span.source
&& !(self.modules[origin.source].role == Role::App
&& module.same_domain(&self.modules[origin.source]))
{
return Err(invalid("SQL result must belong to this Model or its App"));
}
if *record != model_index && fields.iter().any(|f| f.private || f.range.is_some()) {
return Err(invalid(
"SQL result records require public unconstrained scalar fields",
));
}
for field in fields {
self.model_storage(&field.kind, field.span)?;
}
let ast::ExpressionKind::Map(entries) = &value.kind else {
return Err(invalid("SQL requires sqlite and postgres text fields"));
};
let mut sqlite = None;
let mut postgres = None;
for (key, value) in entries {
let (
ast::ExpressionKind::Name(name),
ast::ExpressionKind::Literal(ast::Literal::Text(text)),
) = (&key.kind, &value.kind)
else {
return Err(invalid("SQL dialects require literal text"));
};
let target = match name.as_str() {
"sqlite" => &mut sqlite,
"postgres" => &mut postgres,
_ => return Err(invalid("unknown SQL dialect field")),
};
if target.replace(text.clone()).is_some() {
return Err(invalid("duplicate SQL dialect field"));
}
}
let (Some(sqlite), Some(postgres)) = (sqlite, postgres) else {
return Err(invalid("SQL requires both sqlite and postgres"));
};
let mut dependencies = Vec::new();
let mut readonly = true;
for (text, postgres) in [(&sqlite, false), (&postgres, true)] {
let statement = sql::parse(text, postgres, inputs.len(), span)?;
readonly &= proof::query(
&statement,
model_index,
&self.definitions,
&mut dependencies,
span,
)?;
}
dependencies.sort_unstable();
dependencies.dedup();
let query = ModelSql {
name: name.into(),
span,
inputs,
record: *record,
output,
sqlite,
postgres,
readonly,
dependencies,
};
self.definitions[model_index]
.model
.as_mut()
.unwrap()
.sql
.push(query);
Ok(())
}
}
@@ -0,0 +1,103 @@
//! 使用库 AST 核对依赖和只读性,不能把函数调用或锁定查询视作纯读取。
use super::*;
use sqlparser::ast::{
Expr, ObjectName, Query, Select, SetExpr, Statement, TableFactor, Visit, Visitor,
};
use std::ops::ControlFlow;
pub(super) fn query(
statement: &Statement,
owner: usize,
definitions: &[Definition],
dependencies: &mut Vec<usize>,
span: Span,
) -> Result<bool, Diagnostic> {
if !matches!(statement, Statement::Query(_)) {
return Err(Diagnostic::new(
"C014",
"named SQL requires one SELECT/WITH query",
span,
));
}
let mut proof = Proof {
owner,
definitions,
dependencies,
readonly: true,
};
if let ControlFlow::Break(message) = statement.visit(&mut proof) {
return Err(Diagnostic::new("C014", message, span));
}
Ok(proof.readonly)
}
struct Proof<'a> {
owner: usize,
definitions: &'a [Definition],
dependencies: &'a mut Vec<usize>,
readonly: bool,
}
impl Visitor for Proof<'_> {
type Break = &'static str;
fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<Self::Break> {
self.readonly &= query.with.is_none()
&& query.locks.is_empty()
&& query.for_clause.is_none()
&& query.settings.is_none()
&& query.format_clause.is_none()
&& query.pipe_operators.is_empty()
&& matches!(query.body.as_ref(), SetExpr::Select(_));
ControlFlow::Continue(())
}
fn pre_visit_select(&mut self, select: &Select) -> ControlFlow<Self::Break> {
self.readonly &= select.into.is_none()
&& select.lateral_views.is_empty()
&& select.connect_by.is_empty()
&& select.from.len() <= 1
&& select.from.iter().all(|table| table.joins.is_empty());
ControlFlow::Continue(())
}
fn pre_visit_table_factor(&mut self, table: &TableFactor) -> ControlFlow<Self::Break> {
self.readonly &= matches!(table, TableFactor::Table { args: None, .. });
ControlFlow::Continue(())
}
fn pre_visit_relation(&mut self, name: &ObjectName) -> ControlFlow<Self::Break> {
let name = match name.0.as_slice() {
[part] => part.as_ident().map(|name| name.value.as_str()),
_ => None,
};
if let Some((index, definition)) = self
.definitions
.iter()
.enumerate()
.find(|(_, d)| d.model.is_some() && name == Some(d.table().as_str()))
{
let owner = self.definitions[self.owner].model.as_ref().unwrap();
let target = definition.model.as_ref().unwrap();
if owner.database != target.database || owner.global != target.global {
return ControlFlow::Break(
"SQL cannot mix database bindings or global and tenant Models",
);
}
self.dependencies.push(index);
self.readonly &= index == self.owner;
} else {
self.readonly = false;
}
ControlFlow::Continue(())
}
fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<Self::Break> {
self.readonly &= matches!(
expr,
Expr::Identifier(_)
| Expr::CompoundIdentifier(_)
| Expr::Value(_)
| Expr::BinaryOp { .. }
| Expr::UnaryOp { .. }
| Expr::Nested(_)
| Expr::IsNull(_)
| Expr::IsNotNull(_)
| Expr::Between { .. }
);
ControlFlow::Continue(())
}
}
@@ -0,0 +1,236 @@
//! 关系只增加明确的 Loaded/Unloaded 字段;数据库仍保存原外键列。
use super::*;
use crate::compiler::model::{Relation, Variant};
use sha2::{Digest, Sha256};
impl Types<'_> {
pub(in crate::compiler::check::types) fn related_type(
&mut self,
kind: Type,
span: Span,
) -> Result<usize, Diagnostic> {
if let Some(index) = self.related.get(&kind) {
return Ok(*index);
}
let target = match &kind {
Type::List(inner) | Type::Optional(inner) => inner.as_ref(),
kind => kind,
};
let Type::Named(target) = target else {
return Err(Diagnostic::new(
"C005",
"Related requires a Model record, optional record or list of records",
span,
));
};
if !self
.models
.values()
.any(|(_, name)| name == &self.definitions[*target].name)
{
return Err(Diagnostic::new(
"C005",
"Related requires a Model record",
span,
));
}
let label = format!("Related<{}>", self.type_name(&kind));
let index = self.definitions.len();
self.definitions.push(Definition {
related: true,
model: None,
name: format!(
"dever.related.app.Value_{:x}",
Sha256::digest(label.as_bytes())
),
span: None,
shape: Shape::Choice(vec![
Variant {
name: "Unloaded".into(),
fields: Vec::new(),
error: false,
display_name: None,
label: None,
},
Variant {
name: "Loaded".into(),
fields: vec![Field {
model: None,
name: "value".into(),
kind: kind.clone(),
range: None,
private: false,
span,
}],
error: false,
display_name: None,
label: None,
},
]),
});
self.error_types.push(false);
self.related.insert(kind, index);
Ok(index)
}
pub(in crate::compiler::check::types) fn model_relations(
&mut self,
declarations: &[ast::Declaration],
) -> Vec<Diagnostic> {
let mut pending = Vec::new();
let mut errors = Vec::new();
let records = self
.definitions
.iter()
.enumerate()
.filter(|(_, d)| d.model.is_some())
.map(|(i, d)| (d.span.unwrap().source, i))
.collect::<HashMap<_, _>>();
for (index, definition) in self.definitions.iter().enumerate() {
if definition.model.is_none() {
continue;
}
let Shape::Record(fields) = &definition.shape else {
unreachable!()
};
for (key, field) in fields.iter().enumerate().skip(2) {
if !field.has_local_reference() {
continue;
}
let kind = match &field.kind {
Type::Optional(inner) => inner.as_ref(),
kind => kind,
};
let Type::ModelId(source) = kind else {
continue;
};
let Some(name) = field.name.strip_suffix("_id") else {
continue;
};
if let Some(&target) = records.get(source) {
pending.push((
index,
name.to_owned(),
target,
key,
false,
field.private,
field.span,
));
}
}
}
for declaration in declarations {
let ast::Declaration::Relation { name, target, span } = declaration else {
continue;
};
let checked = (|| {
names::validate(name, Style::Value, *span)?;
let Some(&record) = records.get(&span.source) else {
return Err(Diagnostic::new(
"C003",
"relation belongs in a primary Model file",
*span,
));
};
let path = self.modules[span.source].reference(target);
let (owner, key_name) = path.rsplit_once('.').ok_or_else(|| {
Diagnostic::new("C004", "relation requires a Model foreign key", *span)
})?;
let (source, _) = self
.models
.get(owner)
.ok_or_else(|| Diagnostic::new("C004", "unknown relation Model", *span))?;
let target = records[source];
let Shape::Record(fields) = &self.definitions[target].shape else {
unreachable!()
};
let key = fields
.iter()
.position(|f| f.name == key_name)
.ok_or_else(|| {
Diagnostic::new("C004", "unknown relation foreign key", *span)
})?;
let field = &fields[key];
let kind = match &field.kind {
Type::Optional(inner) => inner.as_ref(),
kind => kind,
};
if *kind != Type::ModelId(span.source) || !field.has_local_reference() {
return Err(Diagnostic::new(
"C005",
"relation key must reference this Model",
*span,
));
}
Ok((
record,
name.clone(),
target,
key,
true,
field.private,
*span,
))
})();
match checked {
Ok(value) => pending.push(value),
Err(error) => errors.push(error),
}
}
for (record, name, target, key, many, private, span) in pending {
let checked = (|| {
let model = self.definitions[record].model.as_ref().unwrap();
let other = self.definitions[target].model.as_ref().unwrap();
if model.database != other.database || model.global != other.global {
return Err(Diagnostic::new(
"C005",
"relations cannot cross physical databases",
span,
));
}
let Shape::Record(fields) = &self.definitions[record].shape else {
unreachable!()
};
if fields.iter().any(|f| f.name == name) {
return Err(Diagnostic::new(
"C001",
"relation conflicts with an existing field",
span,
));
}
let kind = if many {
Type::List(Box::new(Type::Named(target)))
} else if matches!(fields[key].kind, Type::Optional(_)) {
Type::Optional(Box::new(Type::Named(target)))
} else {
Type::Named(target)
};
let related = self.related_type(kind, span)?;
let definition = &mut self.definitions[record];
let Shape::Record(fields) = &mut definition.shape else {
unreachable!()
};
definition.model.as_mut().unwrap().relations.push(Relation {
field: fields.len(),
target,
key,
many,
});
fields.push(Field {
model: None,
name,
kind: Type::Named(related),
range: None,
private,
span,
});
Ok(())
})();
if let Err(error) = checked {
errors.push(error);
}
}
errors
}
}
@@ -0,0 +1,80 @@
//! SQL 的词法、语法和遍历复用 sqlparser;这里只定义 Dever 迁移边界。
use crate::syntax::{diagnostic::Diagnostic, source::Span};
use sqlparser::{
ast::{Ident, Statement, Value, ValueWithSpan, Visit, Visitor},
dialect::{Dialect, PostgreSqlDialect, SQLiteDialect},
parser::Parser,
};
use std::{collections::BTreeSet, ops::ControlFlow};
pub(super) fn parse(
sql: &str,
postgres: bool,
count: usize,
span: Span,
) -> Result<Statement, Diagnostic> {
let invalid = |message| Diagnostic::new("C014", message, span);
let dialect: &dyn Dialect = if postgres {
&PostgreSqlDialect {}
} else {
&SQLiteDialect {}
};
let statements = Parser::parse_sql(dialect, sql)
.map_err(|error| invalid(format!("invalid SQL: {error}")))?;
if statements.len() != 1 {
return Err(invalid("SQL requires exactly one statement".into()));
}
let mut boundary = Boundary {
prefix: if postgres { '$' } else { '?' },
count,
bindings: BTreeSet::new(),
};
if let ControlFlow::Break(message) = statements.visit(&mut boundary) {
return Err(invalid(message.into()));
}
if boundary.bindings.len() != count {
return Err(invalid("SQL must use every supplied parameter".into()));
}
Ok(statements.into_iter().next().unwrap())
}
struct Boundary {
prefix: char,
count: usize,
bindings: BTreeSet<usize>,
}
impl Visitor for Boundary {
type Break = &'static str;
fn pre_visit_value(&mut self, value: &ValueWithSpan) -> ControlFlow<Self::Break> {
if let Value::Placeholder(name) = &value.value {
let binding = name
.strip_prefix(self.prefix)
.and_then(|n| n.parse::<usize>().ok());
match binding {
Some(index) if (1..=self.count).contains(&index) => {
self.bindings.insert(index);
}
_ => {
return ControlFlow::Break(
"SQL requires complete numbered bindings for its dialect",
);
}
}
}
ControlFlow::Continue(())
}
fn pre_visit_ident(&mut self, ident: &Ident) -> ControlFlow<Self::Break> {
let name = ident.value.to_ascii_lowercase();
if name.starts_with("_dever_")
|| name.starts_with("sqlite_")
|| matches!(
name.as_str(),
"pg_catalog" | "pg_toast" | "information_schema"
)
{
return ControlFlow::Break("SQL cannot access internal database objects");
}
ControlFlow::Continue(())
}
}
@@ -0,0 +1,254 @@
//! 按类型依赖一次解析有效定义;错误类型没有可供内部代码使用的替代结构。
use super::*;
use crate::compiler::check::calls;
pub(super) fn analyze<'a>(
declarations: &[ast::Declaration],
modules: &'a [Module],
) -> (Types<'a>, Vec<Diagnostic>) {
let all = declarations;
let declarations = declarations
.iter()
.filter_map(|item| match item {
ast::Declaration::Type(item) | ast::Declaration::AdapterSetting(item) => Some(item),
_ => None,
})
.collect::<Vec<_>>();
let mut names = HashMap::new();
let mut invalid = HashSet::new();
let mut diagnostics = Vec::new();
let identities = declarations
.iter()
.map(|declaration| modules[declaration.span.source].qualify(&declaration.name))
.collect::<Vec<_>>();
for (index, declaration) in declarations.iter().enumerate() {
if identities[index] == model::COLLECTION_ERROR_NAME {
diagnostics.push(Diagnostic::new(
"C004",
"a built-in type cannot be redefined",
declaration.span,
));
invalid.insert(index);
continue;
}
if let Err(error) = name(declaration) {
diagnostics.push(error);
invalid.insert(index);
continue;
}
if let Some(previous) = names.insert(identities[index].clone(), index) {
let mut error = Diagnostic::new("C001", "duplicate type name", declaration.span);
error
.related
.push((declarations[previous].span, "first definition".into()));
diagnostics.push(error);
invalid.extend([previous, index]);
}
}
let models = database::models(&declarations, modules);
let mut edges = vec![Vec::new(); declarations.len()];
for (index, declaration) in declarations.iter().enumerate() {
let mut pending = match &declaration.body {
ast::TypeBody::Record(fields) => {
fields.iter().map(|field| &field.kind).collect::<Vec<_>>()
}
ast::TypeBody::Choice(variants) => variants
.iter()
.flat_map(|variant| variant.fields.iter().map(|field| &field.kind))
.collect(),
};
while let Some(reference) = pending.pop() {
if let Some(&target) =
names.get(&modules[reference.span.source].reference(&reference.name))
{
edges[index].push((target, reference.span));
}
pending.extend(&reference.arguments);
}
}
let (order, error) =
calls::partial_order(&edges, &identities, "recursive types are not allowed");
diagnostics.extend(error);
let mut types = Types {
jobs: Vec::new(),
definitions: vec![model::Definition {
related: false,
model: None,
name: model::COLLECTION_ERROR_NAME.into(),
shape: model::Shape::Choice(vec![model::Variant {
name: "DuplicateKey".into(),
fields: Vec::new(),
error: true,
display_name: None,
label: None,
}]),
span: None,
}],
error_types: vec![true],
names: [(model::COLLECTION_ERROR_NAME.into(), model::COLLECTION_ERROR)].into(),
walks: HashMap::new(),
related: HashMap::new(),
models,
modules,
};
for index in order {
if invalid.contains(&index) {
continue;
}
let declaration = declarations[index];
match types
.prepare_type(declaration)
.and_then(|()| shape(&types, declaration))
{
Ok(shape) => {
let identity = identities[index].clone();
types
.names
.insert(identity.clone(), types.definitions.len());
types
.error_types
.push(structure::has_errors(&shape, &types.error_types));
types.definitions.push(model::Definition {
related: false,
model: None,
name: identity,
shape,
span: Some(declaration.span),
});
}
Err(error) => diagnostics.push(error),
}
}
types
.models
.retain(|_, (_, record)| types.names.contains_key(record));
diagnostics.extend(types.model_bindings(all, modules));
diagnostics.extend(types.model_constraints(all));
diagnostics.extend(types.model_initialization(all));
diagnostics.extend(types.model_pages());
diagnostics.extend(types.model_sql(all));
diagnostics.extend(types.model_relations(all));
for declaration in all {
if !matches!(
declaration,
ast::Declaration::Type(_) | ast::Declaration::AdapterSetting(_)
) && let Err(error) = types.prepare(declaration)
{
diagnostics.push(error);
}
}
diagnostics.extend(types.jobs(all));
(types, diagnostics)
}
fn name(declaration: &ast::TypeDeclaration) -> Result<(), Diagnostic> {
names::validate(&declaration.name, Style::Type, declaration.span)?;
if matches!(
declaration.name.as_str(),
"Bool"
| "Int"
| "Float"
| "Decimal"
| "Text"
| "Bytes"
| "List"
| "Map"
| "MapEntry"
| "Walk"
| "Related"
| "Json"
| "Secret"
| "Id"
| "Uuid"
| "DateTime"
| "Date"
| "Time"
| "Duration"
| "Task"
| "Group"
| "Channel"
| "Stream"
| "AsyncStream"
| "File"
| "Socket"
| "Listener"
| "ClientTls"
| "ServerTls"
| "HttpClient"
| "HttpReply"
| "WebSocket"
| "Upload"
) {
return Err(Diagnostic::new(
"C004",
"a built-in type name cannot be redefined",
declaration.span,
));
}
Ok(())
}
fn shape(
types: &Types<'_>,
declaration: &ast::TypeDeclaration,
) -> Result<model::Shape, Diagnostic> {
let fields = match &declaration.body {
ast::TypeBody::Record(fields) => fields.iter().collect::<Vec<_>>(),
ast::TypeBody::Choice(variants) => variants.iter().flat_map(|v| &v.fields).collect(),
};
for field in fields {
if types.reference(&field.kind)? == model::Type::Upload {
return Err(Diagnostic::new(
"C014",
"Upload cannot be stored in a record or choice",
field.span,
));
}
}
Ok(match &declaration.body {
ast::TypeBody::Record(fields) => {
model::Shape::Record(types.model_fields(declaration, fields)?)
}
ast::TypeBody::Choice(variants) => {
let mut names = HashSet::new();
let variants = variants
.iter()
.map(|variant| {
names::validate(&variant.name, Style::Type, variant.span)?;
if !names.insert(&variant.name) {
return Err(Diagnostic::new(
"C001",
"duplicate choice variant",
variant.span,
));
}
if (variant.label.is_some() || variant.display_name.is_some())
&& !variant.fields.is_empty()
{
return Err(Diagnostic::new(
"C005",
"choice labels require a variant without payload",
variant.span,
));
}
if variant.fields.iter().any(|field| field.private) {
return Err(Diagnostic::new(
"C005",
"choice payload fields cannot be private",
variant.span,
));
}
Ok(model::Variant {
name: variant.name.clone(),
fields: types.fields(&variant.fields)?,
error: variant.error,
label: variant.label.clone(),
display_name: variant.display_name.clone(),
})
})
.collect::<Result<_, Diagnostic>>()?;
model::Shape::Choice(variants)
}
})
}
+174
View File
@@ -0,0 +1,174 @@
//! 入队只依赖 Job 声明,不把异步执行目标变成同步调用边或传递其效果。
use super::*;
#[path = "../../../runtime/job/schedule/parse.rs"]
mod cron;
use crate::compiler::project::Role;
impl Types<'_> {
pub(super) fn jobs(&mut self, declarations: &[ast::Declaration]) -> Vec<Diagnostic> {
let mut errors = Vec::new();
let mut names = HashSet::new();
let mut databases = HashMap::new();
for declaration in declarations {
if let ast::Declaration::Database { name, span } = declaration
&& self.modules[span.source].role == Role::Api
{
if let Err(error) = names::validate(name, Style::Value, *span) {
errors.push(error);
}
if databases.insert(span.source, name).is_some() {
errors.push(Diagnostic::new(
"C001",
"duplicate API database binding",
*span,
));
}
if !declarations
.iter()
.any(|d| matches!(d,ast::Declaration::Job(job) if job.span.source==span.source))
{
errors.push(Diagnostic::new(
"C005",
"API database binding requires a Job",
*span,
));
}
}
}
for declaration in declarations {
let ast::Declaration::Job(job) = declaration else {
continue;
};
let module = &self.modules[job.span.source];
let result = (|| {
names::validate(&job.name, Style::Function, job.span)?;
if module.role != Role::Api {
return Err(Diagnostic::new(
"C003",
"Job declarations belong in API files",
job.span,
));
}
let name = format!("{}.{}.job.{}", module.component, module.domain, job.name);
if !names.insert(name.clone()) {
return Err(Diagnostic::new("C001", "duplicate Job in domain", job.span));
}
if job.inputs.len() > 1
|| !(1..=100).contains(&job.retries)
|| !(1..=3600000).contains(&job.timeout_ms)
{
return Err(Diagnostic::new(
"C005",
"Job needs zero or one input, retry 1..100 and timeout 1..3600000",
job.span,
));
}
let inputs = self.fields(&job.inputs)?;
for input in &inputs {
let model::Type::Named(index) = input.kind else {
return Err(Diagnostic::new(
"C005",
"Job payload requires its own App record",
input.span,
));
};
let definition = &self.definitions[index];
let origin = &self.modules[definition.span.unwrap().source];
if !matches!(definition.shape, model::Shape::Record(_))
|| origin.role != Role::App
|| !origin.same_domain(module)
{
return Err(Diagnostic::new(
"C006",
"Job payload requires its own App record",
input.span,
));
}
super::super::wire::collect_types(
&input.kind,
&self.definitions,
input.span,
&mut Default::default(),
)?;
if model::sensitive(&input.kind, &self.definitions, |_| unreachable!()) {
return Err(Diagnostic::new(
"C005",
"Job payload cannot persist Secret",
input.span,
));
}
}
Ok(model::Job {
cron: None,
name,
target: module.reference(&job.target),
inputs,
database: databases
.get(&job.span.source)
.map_or("default", |name| name.as_str())
.into(),
retries: job.retries,
timeout_ms: job.timeout_ms,
long: job.long,
span: job.span,
})
})();
match result {
Ok(job) => self.jobs.push(job),
Err(error) => errors.push(error),
}
}
let mut schedules = HashSet::new();
for declaration in declarations {
let ast::Declaration::Schedule {
name,
cron,
target,
span,
} = declaration
else {
continue;
};
let module = &self.modules[span.source];
let result = (|| {
names::validate(name, Style::Value, *span)?;
if module.role != Role::Api
|| !schedules.insert(format!("{}.{}.{name}", module.component, module.domain))
{
return Err(Diagnostic::new(
"C005",
"schedule requires a unique API name",
*span,
));
}
cron::parse(cron).map_err(|cause| Diagnostic::new("C005", cause, *span))?;
let target = module.reference(target);
let jobs = self
.jobs
.iter_mut()
.filter(|job| job.span.source == span.source && job.target == target)
.collect::<Vec<_>>();
let [job] = jobs.as_slice() else {
return Err(Diagnostic::new(
"C005",
"schedule requires exactly one declared Job for this App target in the same API file",
*span,
));
};
if !job.inputs.is_empty() || job.cron.is_some() {
return Err(Diagnostic::new(
"C005",
"schedule requires an unscheduled zero-input Job",
*span,
));
}
jobs.into_iter().next().unwrap().cron = Some(cron.clone());
Ok(())
})();
if let Err(error) = result {
errors.push(error);
}
}
errors
}
}
+104
View File
@@ -0,0 +1,104 @@
//! 类型图同样禁止递归;容器不成为绕过类型和键约束的路径。
use super::Types;
use crate::compiler::model::*;
use crate::syntax::{diagnostic::Diagnostic, source::Span};
pub(super) fn has_errors(shape: &Shape, errors: &[bool]) -> bool {
if matches!(shape, Shape::Choice(variants) if variants.iter().any(|variant| variant.error)) {
return true;
}
let mut pending = fields(shape)
.into_iter()
.map(|field| &field.kind)
.collect::<Vec<_>>();
while let Some(kind) = pending.pop() {
match kind {
Type::Named(index) if errors[*index] => return true,
Type::List(inner)
| Type::Optional(inner)
| Type::Channel(inner)
| Type::AsyncStream(inner)
| Type::Stream(inner) => pending.push(inner),
Type::Map(key, value) | Type::MapEntry(key, value) => {
pending.extend([key.as_ref(), value.as_ref()])
}
_ => {}
}
}
false
}
fn fields(shape: &Shape) -> Vec<&Field> {
match shape {
Shape::Record(fields) => fields.iter().collect(),
Shape::Choice(variants) => variants
.iter()
.flat_map(|variant| &variant.fields)
.collect(),
}
}
impl Types<'_> {
pub fn validate(&self, kind: &Type, span: Span) -> Result<(), Diagnostic> {
let mut pending = vec![kind];
while let Some(current) = pending.pop() {
if *current == Type::Upload && *kind != Type::Upload {
return Err(Diagnostic::new(
"C014",
"Upload cannot be nested in a container",
span,
));
}
let kind = current;
if matches!(
kind,
Type::Null | Type::Unit | Type::Never | Type::Task(_) | Type::Group(_)
) {
return Err(Diagnostic::new(
"C005",
"collection requires a concrete element type; declare its type",
span,
));
}
validate_map(kind, &self.definitions, span)?;
if matches!(kind, Type::Channel(_) | Type::AsyncStream(_))
&& !transferable(kind, &self.definitions, |_| &[])
{
return Err(Diagnostic::new(
"C014",
"Channel and AsyncStream elements must be transferable; synchronous Stream cannot cross this boundary",
span,
));
}
match kind {
Type::List(inner)
| Type::Optional(inner)
| Type::Channel(inner)
| Type::AsyncStream(inner)
| Type::Stream(inner) => pending.push(inner),
Type::Map(key, value) | Type::MapEntry(key, value) => {
pending.extend([key.as_ref(), value.as_ref()])
}
_ => {}
}
}
Ok(())
}
}
fn validate_map(kind: &Type, definitions: &[Definition], span: Span) -> Result<(), Diagnostic> {
let (Type::Map(key, _) | Type::MapEntry(key, _)) = kind else {
return Ok(());
};
let valid = match key.as_ref() {
Type::Bool | Type::Int | Type::Text | Type::Uuid | Type::Id | Type::ModelId(_) => true,
Type::Named(index) => matches!(&definitions[*index].shape, Shape::Choice(variants)
if variants.iter().all(|variant| variant.fields.is_empty())),
_ => false,
};
if !valid {
return Err(Diagnostic::new("C005", "invalid Map key type", span));
}
Ok(())
}
+177
View File
@@ -0,0 +1,177 @@
//! Walk 按具体类型实参建立一个 choice,复用构造、匹配、所有权和错误检查。
use super::*;
use crate::compiler::model::{Definition, Field, Shape, Variant};
use sha2::{Digest, Sha256};
impl Types<'_> {
pub(super) fn prepare_type(
&mut self,
declaration: &ast::TypeDeclaration,
) -> Result<(), Diagnostic> {
let fields = match &declaration.body {
ast::TypeBody::Record(fields) => fields.iter().collect::<Vec<_>>(),
ast::TypeBody::Choice(variants) => variants
.iter()
.flat_map(|variant| &variant.fields)
.collect(),
};
for field in fields {
self.prepare_reference(&field.kind)?;
}
Ok(())
}
pub(super) fn prepare(&mut self, declaration: &ast::Declaration) -> Result<(), Diagnostic> {
let mut references = Vec::new();
match declaration {
ast::Declaration::Function(function) => {
references.extend(function.fails.as_ref());
references.extend(
function
.inputs
.iter()
.chain(&function.outputs)
.map(|field| &field.kind),
);
let statements = match &function.body {
ast::Body::Statements(statements) => statements.iter().collect::<Vec<_>>(),
ast::Body::Flow(steps) => steps.iter().map(|step| &step.statement).collect(),
_ => Vec::new(),
};
for statement in statements {
if let ast::Statement::Assign {
kind: Some(kind), ..
} = statement
{
references.push(kind);
}
}
}
ast::Declaration::Constant(value) => references.extend(value.kind.as_ref()),
_ => {}
}
for reference in references {
self.prepare_reference(reference)?;
}
Ok(())
}
fn prepare_reference(&mut self, reference: &ast::TypeRef) -> Result<(), Diagnostic> {
for argument in &reference.arguments {
self.prepare_reference(argument)?;
}
if let Some(handler) = &reference.handler {
for field in handler.inputs.iter().chain(&handler.outputs) {
self.prepare_reference(&field.kind)?;
}
}
if reference.name == "Related" {
let [item] = reference.arguments.as_slice() else {
return Err(Diagnostic::new(
"C005",
"Related requires one type argument",
reference.span,
));
};
self.related_type(self.reference(item)?, reference.span)?;
return Ok(());
}
if reference.name != "Walk" {
return Ok(());
}
let [item, state] = reference.arguments.as_slice() else {
return Err(Diagnostic::new(
"C005",
"Walk requires item and state types",
reference.span,
));
};
let item = self.reference(item)?;
let state = self.reference(state)?;
self.validate(&item, reference.span)?;
self.validate(&state, reference.span)?;
let key = (item.clone(), state.clone());
if self.walks.contains_key(&key) {
return Ok(());
}
let shape = Shape::Choice(vec![
Variant {
name: "Next".into(),
fields: vec![
Field {
model: None,
name: "item".into(),
kind: item.clone(),
range: None,
private: false,
span: reference.span,
},
Field {
model: None,
name: "next_state".into(),
kind: state.clone(),
range: None,
private: false,
span: reference.span,
},
],
error: false,
display_name: None,
label: None,
},
Variant {
name: "Done".into(),
fields: Vec::new(),
error: false,
display_name: None,
label: None,
},
]);
self.walks.insert(key, self.definitions.len());
self.error_types
.push(structure::has_errors(&shape, &self.error_types));
let identity = format!("Walk<{},{}>", self.type_name(&item), self.type_name(&state));
self.definitions.push(Definition {
related: false,
model: None,
// 使用具体类型名称而非加载顺序编号,保持生成符号稳定。
name: format!(
"dever.walk.app.Step_{:x}",
Sha256::digest(identity.as_bytes())
),
shape,
span: None,
});
Ok(())
}
pub fn walk(&self, kind: &Type) -> Option<(&Type, &Type)> {
let Type::Named(index) = kind else {
return None;
};
self.walks
.iter()
.find_map(|((item, state), definition)| (index == definition).then_some((item, state)))
}
pub(super) fn type_name(&self, kind: &Type) -> String {
match kind {
Type::Named(index) => self.definitions[*index].name.clone(),
Type::List(inner) => format!("List<{}>", self.type_name(inner)),
Type::Channel(inner) => format!("Channel<{}>", self.type_name(inner)),
Type::AsyncStream(inner) => format!("AsyncStream<{}>", self.type_name(inner)),
Type::Stream(inner) => format!("Stream<{}>", self.type_name(inner)),
Type::Optional(inner) => format!("Optional<{}>", self.type_name(inner)),
Type::Map(key, value) => {
format!("Map<{},{}>", self.type_name(key), self.type_name(value))
}
Type::MapEntry(key, value) => format!(
"MapEntry<{},{}>",
self.type_name(key),
self.type_name(value)
),
_ => format!("{kind:?}"),
}
}
}
+302
View File
@@ -0,0 +1,302 @@
//! 捕获只改变被调用函数的失败出口,参数中的失败仍按原顺序向上传播。
use super::Checker;
use crate::compiler::model::*;
use crate::syntax::{ast, diagnostic::Diagnostic, source::Span};
use std::collections::BTreeSet;
impl Checker<'_> {
pub(super) fn call(
&mut self,
target: usize,
arguments: &[ast::Expression],
span: Span,
) -> Result<Expression, Diagnostic> {
let function = self.functions[target].as_ref().expect("checked callee");
let edge = self.calls.by_span[&(self.caller, span)];
let omitted = &self.calls.edges[edge].static_arguments;
if arguments.len() - omitted.len() != function.signature.inputs.len() {
return Err(Diagnostic::new(
"C005",
"function argument count differs",
span,
));
}
let arguments = arguments
.iter()
.enumerate()
.filter_map(|(index, value)| (!omitted.contains(&index)).then_some(value))
.zip(&function.signature.inputs)
.map(|(value, field)| {
if function.signature.name == "dever.json.app.encode" {
let value = self.expression(value, None)?;
super::super::wire::output(
&value.value_type,
&self.types.definitions,
value.span,
&mut BTreeSet::new(),
)?;
Ok(Self::node(
ExpressionKind::Builtin(Builtin::Json(JsonOp::Encode), vec![value]),
field.kind.clone(),
span,
))
} else if function.signature.name == "dever.id.app.toText" {
let id = self.raw(value, Some(&Type::Id))?;
if matches!(id.value_type, Type::ModelId(_)) {
Ok(Self::node(
ExpressionKind::Builtin(
Builtin::Standard(StandardOp::IdFromText),
vec![id],
),
Type::Id,
value.span,
))
} else {
Self::coerce(id, &Type::Id)
}
} else {
self.field_value(value, field)
}
})
.collect::<Result<_, _>>()?;
let (kind, range) = match function.signature.outputs.as_slice() {
[] => (Type::Unit, None),
[field] => (field.kind.clone(), field.guaranteed_range()),
_ => (Type::Outputs(target), None),
};
let mut expression = Self::node(ExpressionKind::Call(target, arguments), kind, span);
expression.range = range;
Ok(expression)
}
pub(super) fn capture(
&mut self,
call: &ast::Expression,
expected: Option<&Type>,
span: Span,
) -> Result<Expression, Diagnostic> {
let Some(Type::Named(definition)) = expected else {
return Err(Diagnostic::new(
"C005",
"result requires a concrete choice from its use context",
span,
));
};
let ast::ExpressionKind::Call(_, arguments) = &call.kind else {
return Err(Diagnostic::new(
"C005",
"result requires a function call",
span,
));
};
let Shape::Choice(variants) = &self.types.definitions[*definition].shape else {
return Err(Diagnostic::new(
"C005",
"result target must be a choice",
span,
));
};
let successes = variants
.iter()
.enumerate()
.filter(|(_, variant)| !variant.error)
.collect::<Vec<_>>();
let [(success, variant)] = successes.as_slice() else {
return Err(Diagnostic::new(
"C005",
"result requires exactly one success branch",
span,
));
};
let (checked, outputs, failures) = if let Some(&edge) =
self.calls.by_span.get(&(self.caller, call.span))
{
let target = self.calls.edges[edge].target;
let function = self.functions[target].as_ref().expect("checked callee");
if function.failures.is_empty() && !function.unknown_failures {
return Err(Diagnostic::new(
"C012",
"result on an infallible call is redundant",
span,
));
}
let outputs = function.signature.outputs.clone();
let failures = function.failures.clone();
(self.call(target, arguments, call.span)?, outputs, failures)
} else if let ast::ExpressionKind::Call(target, arguments) = &call.kind
&& let Some(
name @ ("wait" | "stop" | "timeout" | "race" | "run" | "parallel" | "blocking"),
) = target.path().as_deref()
{
let checked = self.task(name, arguments, call.span, false)?;
let ExpressionKind::Builtin(Builtin::Task(op), arguments) = &checked.kind else {
unreachable!()
};
let targets = op.targets(arguments);
let failures = targets
.iter()
.flat_map(|target| &self.functions[*target].as_ref().unwrap().failures)
.copied()
.collect::<BTreeSet<_>>();
let unknown = targets
.iter()
.any(|target| self.functions[*target].as_ref().unwrap().unknown_failures);
if failures.is_empty() && !unknown {
return Err(Diagnostic::new(
"C012",
"result on an infallible call is redundant",
span,
));
}
let outputs = op.output_target().map_or_else(Vec::new, |target| {
self.functions[target]
.as_ref()
.unwrap()
.signature
.outputs
.clone()
});
(checked, outputs, failures)
} else if matches!(&call.kind, ast::ExpressionKind::Call(target, _) if target.path().as_deref() == Some("dever.json.decode"))
{
let [field] = variant.fields.as_slice() else {
return Err(Diagnostic::new(
"C005",
"JSON decode capture requires one typed success field",
span,
));
};
if field.range.is_some() {
return Err(Diagnostic::new(
"C008",
"JSON decode capture cannot invent a scalar range; declare constrained record fields",
span,
));
}
let checked = self.decode_json(arguments, Some(&field.kind), call.span, false)?;
let ExpressionKind::Builtin(Builtin::Json(JsonOp::Decode(error)), _) = checked.kind
else {
unreachable!()
};
(
checked,
vec![field.clone()],
BTreeSet::from([Failure::Choice(error, 1)]),
)
} else if let ast::ExpressionKind::Call(target, arguments) = &call.kind
&& let Some(name) = target.path()
&& let Some(checked) = self.database(&name, arguments, call.span, false)?
{
let ExpressionKind::Builtin(
Builtin::Database { error, .. }
| Builtin::Enqueue { error, .. }
| Builtin::JobStates { error, .. },
_,
) = checked.kind
else {
unreachable!()
};
let outputs = vec![Field {
model: None,
name: "value".into(),
kind: checked.value_type.clone(),
range: None,
private: false,
span: call.span,
}];
(
checked,
outputs,
(0..10)
.map(|variant| Failure::Choice(error, variant))
.collect(),
)
} else {
return Err(Diagnostic::new(
"C005",
"result requires a fallible function call",
span,
));
};
if variant.fields.len() != outputs.len()
|| variant.fields.iter().zip(&outputs).any(|(wanted, actual)| {
wanted.kind != actual.kind
|| wanted.range.is_some_and(|required| {
!actual
.guaranteed_range()
.is_some_and(|range| required.contains(range))
})
})
{
return Err(Diagnostic::new(
"C005",
"result success fields must accept the declared call outputs",
span,
));
}
let errors = capture_errors(
variants,
&failures,
*definition,
&self.types.definitions,
span,
)?;
let success = *success;
let call = checked;
Ok(Self::node(
ExpressionKind::Capture(Box::new(Capture {
call,
definition: *definition,
success,
errors,
})),
Type::Named(*definition),
span,
))
}
}
fn capture_errors(
variants: &[Variant],
failures: &BTreeSet<Failure>,
definition: usize,
definitions: &[Definition],
span: Span,
) -> Result<Vec<(Failure, usize, bool)>, Diagnostic> {
let mut errors = Vec::new();
for failure in failures {
let targets = variants
.iter()
.enumerate()
.filter(|(_, variant)| variant.error)
.filter_map(|(index, variant)| {
if matches!(failure, Failure::Api(_))
&& let [field] = variant.fields.as_slice()
&& let Type::Named(origin) = field.kind
&& definitions[origin].name == "dever.api.app.Error"
{
return Some((index, true));
}
if *failure == Failure::Choice(definition, index) {
return Some((index, false));
}
if let (Failure::Choice(origin, _), [field]) = (failure, variant.fields.as_slice())
&& field.kind == Type::Named(*origin)
{
return Some((index, true));
}
None
})
.collect::<Vec<_>>();
let [(index, wrapped)] = targets.as_slice() else {
return Err(Diagnostic::new(
"C005",
"result requires one nominally matching branch for each error",
span,
));
};
errors.push((*failure, *index, *wrapped));
}
Ok(errors)
}
+211
View File
@@ -0,0 +1,211 @@
//! 记录和 choice 按声明字段一次构造;不补缺字段、不推测失败分支。
use super::Checker;
use crate::compiler::model::*;
use crate::syntax::{ast, diagnostic::Diagnostic, source::Span};
impl Checker<'_> {
pub(super) fn variant(
&mut self,
name: &str,
arguments: &[ast::Expression],
expected: Option<&Type>,
span: Span,
) -> Result<Option<Expression>, Diagnostic> {
let Some((definition, variant)) = self.types.variant(name, span.source, expected) else {
return Ok(None);
};
self.types.access(definition, span)?;
let types = self.types;
let Shape::Choice(variants) = &types.definitions[definition].shape else {
unreachable!()
};
let fields = &variants[variant].fields;
if fields.len() != arguments.len() {
return Err(Diagnostic::new(
"C005",
"choice payload argument count differs",
span,
));
}
let values = arguments
.iter()
.zip(fields)
.map(|(value, field)| self.field_value(value, field))
.collect::<Result<_, _>>()?;
Ok(Some(Self::node(
ExpressionKind::Variant(definition, variant, values),
Type::Named(definition),
span,
)))
}
pub(super) fn record(
&mut self,
name: &str,
values: &[(String, ast::Expression)],
span: Span,
) -> Result<Expression, Diagnostic> {
let types = self.types;
let definition = types
.named(name, span.source)
.ok_or_else(|| Diagnostic::new("C004", "unknown record type", span))?;
types.access(definition, span)?;
let Shape::Record(fields) = &types.definitions[definition].shape else {
return Err(Diagnostic::new(
"C005",
"record construction requires a record type",
span,
));
};
for field in fields {
types.field_access(definition, field, span)?;
}
if fields.len() != values.len() {
return Err(Diagnostic::new(
"C005",
"record construction must provide every declared field once",
span,
));
}
let mut seen = vec![false; fields.len()];
let mut checked = Vec::new();
for (name, value) in values {
let field = fields
.iter()
.position(|field| field.name == *name)
.ok_or_else(|| {
Diagnostic::new("C004", format!("unknown field {name}"), value.span)
})?;
if seen[field] {
return Err(Diagnostic::new(
"C005",
"duplicate record field",
value.span,
));
}
seen[field] = true;
checked.push((field, self.field_value(value, &fields[field])?));
}
// 保存源码求值顺序与目标字段位置,不为字段排序改变失败顺序。
Ok(Self::node(
ExpressionKind::Record(definition, checked),
Type::Named(definition),
span,
))
}
pub(super) fn select(
&self,
mut base: Expression,
name: &str,
span: Span,
) -> Result<Expression, Diagnostic> {
let (index, field) = self.member(&base.value_type, name, span)?;
if name == "items"
&& let ExpressionKind::Builtin(Builtin::Database { operation, .. }, _) = &mut base.kind
&& matches!(operation, DatabaseOp::Page { .. })
{
*operation = DatabaseOp::PageItems;
base.value_type = field.kind;
base.span = span;
return Ok(base);
}
let range = field.guaranteed_range();
Ok(Expression {
kind: ExpressionKind::Field(Box::new(base), index),
value_type: field.kind,
range,
known_bool: None,
span,
})
}
// 读取与更新共用字段身份和私有访问检查,内建 MapEntry 只提供 key/value。
pub fn member(
&self,
kind: &Type,
name: &str,
span: Span,
) -> Result<(usize, Field), Diagnostic> {
let fields = match kind {
Type::Named(index) => {
let Shape::Record(fields) = &self.types.definitions[*index].shape else {
return Err(Diagnostic::new(
"C005",
"choice payload must be selected by rule",
span,
));
};
fields
}
Type::Outputs(index) => {
&self.functions[*index]
.as_ref()
.expect("checked callee")
.signature
.outputs
}
Type::Upload => {
let (index, kind) = match name {
"filename" => (0, Type::Text),
"content_type" => (1, Type::Text),
"size" => (2, Type::Int),
_ => return Err(Diagnostic::new("C004", "unknown Upload field", span)),
};
return Ok((
index,
Field {
model: None,
name: name.into(),
kind,
range: None,
private: false,
span,
},
));
}
Type::MapEntry(key, value) => {
let (index, kind) = match name {
"key" => (0, key),
"value" => (1, value),
_ => return Err(Diagnostic::new("C004", "unknown MapEntry field", span)),
};
return Ok((
index,
Field {
model: None,
name: name.into(),
kind: kind.as_ref().clone(),
range: None,
private: false,
span,
},
));
}
Type::Optional(_) => {
return Err(Diagnostic::new(
"C005",
"nullable value must be narrowed before field access",
span,
));
}
_ => {
return Err(Diagnostic::new(
"C005",
"field access requires a record",
span,
));
}
};
let index = fields
.iter()
.position(|field| field.name == name)
.ok_or_else(|| Diagnostic::new("C004", format!("unknown field {name}"), span))?;
let field = &fields[index];
if let Type::Named(definition) = kind {
self.types.field_access(*definition, field, span)?;
}
Ok((index, field.clone()))
}
}
@@ -0,0 +1,146 @@
//! 静态复合键游标;最后追加 id,翻页不依赖 offset 或 count。
use super::*;
impl Checker<'_> {
pub(super) fn model_cursor(
&mut self,
owner: &str,
record: usize,
arguments: &[ast::Expression],
span: Span,
propagate: bool,
) -> Result<Expression, Diagnostic> {
if arguments.len() > 1 {
return Err(Diagnostic::new(
"C005",
"cursor accepts one query block",
span,
));
}
let fields = self.types.definitions[record].columns();
let mut parameters = Vec::new();
let mut relations = Vec::new();
let mut filter = Condition::default();
let mut order = vec![(0, false)];
let mut after = Self::node(
ExpressionKind::Null,
Type::Optional(Box::new(Type::Named(record))),
span,
);
let mut size = Self::node(
ExpressionKind::Number(numeric::Number::Int(20)),
Type::Int,
span,
);
if let Some(block) = arguments.first() {
for (key, value) in entries(block)? {
match key {
"where" => {
filter = self.model_condition(value, record, &mut parameters, true)?
}
"order" => order = query::model_order(value, fields)?,
"with" => relations = self.selected_relations(record, value)?,
"after" => after = self.expression(value, Some(&after.value_type))?,
"size" => size = self.expression(value, Some(&Type::Int))?,
_ => {
return Err(Diagnostic::new(
"C005",
format!("unsupported cursor key {key}"),
value.span,
));
}
}
}
}
if let Some(&(index, _)) = order
.iter()
.find(|&&(i, _)| matches!(fields[i].kind, Type::Optional(_)))
{
return Err(Diagnostic::new(
"C005",
"cursor order requires non-null fields",
fields[index].span,
));
}
if !order.iter().any(|&(i, _)| i == 0) {
order.push((0, false));
}
let mut terms = Vec::new();
let mut equal = Vec::new();
for (position, &(index, ascending)) in order.iter().enumerate() {
let column = quote(&fields[index].name);
let parameter = format!("{}{}", '$', parameters.len() + position + 1);
let comparison = format!("{column} {} {parameter}", if ascending { ">" } else { "<" });
terms.push(format!(
"({})",
equal
.iter()
.cloned()
.chain([comparison])
.collect::<Vec<_>>()
.join(" AND ")
));
equal.push(format!("{column} = {parameter}"));
}
let sorting = order
.iter()
.map(|&(i, asc)| {
format!(
"{} {}",
quote(&fields[i].name),
if asc { "ASC" } else { "DESC" }
)
})
.collect::<Vec<_>>()
.join(",");
let columns = projection(fields);
let table = quote(&self.types.definitions[record].table());
let first = filter.statement(|condition| {
let where_clause = if condition.is_empty() {
String::new()
} else {
format!(" WHERE {condition}")
};
format!(
"SELECT {columns} FROM {table}{where_clause} ORDER BY {sorting} LIMIT ${}",
parameters.len() + 1
)
});
// 有无游标在调用处选择 SQL;把标志放进 OR 会使 SQLite 扫描整段索引。
let matches = terms.join(" OR ");
let sql = filter.statement(|condition| {
let filter = if condition.is_empty() { String::new() } else { format!("({condition}) AND ") };
format!("SELECT {columns} FROM {table} WHERE {filter}({matches}) ORDER BY {sorting} LIMIT ${}", parameters.len() + order.len() + 1)
});
let mut values = vec![
Self::node(first, Type::Text, span),
Self::node(sql, Type::Text, span),
];
values.extend(parameters);
values.extend([after, size]);
let result = self
.types
.named(&format!("{owner}.Cursor"), span.source)
.unwrap();
let error = self
.types
.named("dever.database.Error", span.source)
.unwrap();
if propagate {
self.failures
.extend((0..10).map(|variant| Failure::Choice(error, variant)));
}
Ok(Self::node(
ExpressionKind::Builtin(
Builtin::Database {
relations,
record,
error,
operation: DatabaseOp::Cursor(order),
},
values,
),
Type::Named(result),
span,
))
}
}
@@ -0,0 +1,181 @@
//! 入队返回 Id;载荷失败先传播,队列失败可 result 捕获,执行目标失败不在入队时发生。
use super::*;
impl Checker<'_> {
pub(super) fn enqueue(
&mut self,
method: &str,
arguments: &[ast::Expression],
span: Span,
propagate: bool,
) -> Result<Expression, Diagnostic> {
let module = self.types.module(span.source);
if module.role != Role::App {
return Err(Diagnostic::new("C006", "enqueue belongs in App", span));
}
let target = arguments
.first()
.and_then(|v| v.path())
.ok_or_else(|| Diagnostic::new("C005", "enqueue requires a static job.name", span))?;
let Some(name) = target.strip_prefix("job.") else {
return Err(Diagnostic::new(
"C005",
"enqueue requires a local job.name",
arguments[0].span,
));
};
let identity = format!("{}.{}.job.{name}", module.component, module.domain);
let job = self
.types
.jobs
.iter()
.position(|job| job.name == identity)
.ok_or_else(|| Diagnostic::new("C004", "unknown Job", arguments[0].span))?;
let inputs = &self.types.jobs[job].inputs;
let (mode, values, output) = if method == "enqueueMany" {
let [_, source] = arguments else {
return Err(Diagnostic::new(
"C005",
"enqueueMany requires a Job and one List",
span,
));
};
let (value, fields) = if let [input] = inputs.as_slice() {
let value = self.expression(source, None)?;
let fields = self.submission_fields(&value.value_type, input, source.span)?;
(value, Some(fields))
} else {
(
self.expression(source, Some(&Type::List(Box::new(Type::Text))))?,
None,
)
};
(
Enqueue::Many(fields),
vec![value],
Type::List(Box::new(Type::Id)),
)
} else {
let scheduled = method == "enqueueAt";
if arguments.len() != inputs.len() + 2 + usize::from(scheduled) {
return Err(Diagnostic::new(
"C005",
"enqueue requires job, optional payload, key and optional scheduled time",
span,
));
}
let mut values = Vec::new();
for (argument, input) in arguments[1..].iter().zip(inputs) {
values.push(self.field_value(argument, input)?);
}
values.push(self.expression(&arguments[1 + inputs.len()], Some(&Type::Text))?);
let mode = if scheduled {
values.push(self.expression(arguments.last().unwrap(), Some(&Type::DateTime))?);
Enqueue::Scheduled
} else {
Enqueue::Immediate
};
(mode, values, Type::Id)
};
let error = self
.types
.named("dever.database.Error", span.source)
.unwrap();
if propagate {
self.failures
.extend((0..10).map(|variant| Failure::Choice(error, variant)));
}
Ok(Self::node(
ExpressionKind::Builtin(Builtin::Enqueue { job, error, mode }, values),
output,
span,
))
}
pub(super) fn job_states(
&mut self,
arguments: &[ast::Expression],
span: Span,
propagate: bool,
) -> Result<Expression, Diagnostic> {
if self.types.module(span.source).role != Role::App
|| !self.types.jobs.iter().any(|job| job.database == "default")
{
return Err(Diagnostic::new(
"C006",
"dever.job.states requires an App and a default Job queue",
span,
));
}
let (ids, system) = match arguments {
[ids] => (ids, false),
[ids, scope] if matches!(&scope.kind, ast::ExpressionKind::Literal(ast::Literal::Text(name)) if name == "system") => {
(ids, true)
}
_ => {
return Err(Diagnostic::new(
"C005",
"dever.job.states takes List<Id?> and optionally the literal \"system\"",
span,
));
}
};
let ids = self.expression(
ids,
Some(&Type::List(Box::new(Type::Optional(Box::new(Type::Id))))),
)?;
let error = self
.types
.named("dever.database.Error", span.source)
.unwrap();
if propagate {
self.failures
.extend((0..10).map(|variant| Failure::Choice(error, variant)));
}
Ok(Self::node(
ExpressionKind::Builtin(Builtin::JobStates { error, system }, vec![ids]),
Type::Map(Box::new(Type::Id), Box::new(Type::Text)),
span,
))
}
fn submission_fields(
&self,
kind: &Type,
input: &Field,
span: Span,
) -> Result<(usize, usize), Diagnostic> {
let invalid = || {
Diagnostic::new(
"C005",
"enqueueMany items require key: Text and payload satisfying the Job input type and range",
span,
)
};
let Type::List(item) = kind else {
return Err(invalid());
};
let Type::Named(item) = **item else {
return Err(invalid());
};
let Shape::Record(fields) = &self.types.definitions[item].shape else {
return Err(invalid());
};
let key = fields
.iter()
.position(|f| f.name == "key" && f.kind == Type::Text)
.ok_or_else(invalid)?;
let payload = fields
.iter()
.position(|f| {
f.name == "payload"
&& f.kind == input.kind
&& input.range.is_none_or(|required| {
f.range.is_some_and(|actual| required.contains(actual))
})
})
.ok_or_else(invalid)?;
self.types.field_access(item, &fields[key], span)?;
self.types.field_access(item, &fields[payload], span)?;
Ok((key, payload))
}
}
@@ -0,0 +1,404 @@
//! Model 调用在编译期变成静态 SQL 和具体参数;不生成运行时查询对象。
use super::*;
use crate::compiler::project::Role;
mod cursor;
mod job;
mod native;
mod page;
mod query;
use query::Condition;
mod relation;
mod write;
impl Checker<'_> {
pub(crate) fn model_returning(&self, value: &mut Expression, record: usize) {
let ExpressionKind::Builtin(Builtin::Database { operation, .. }, arguments) =
&mut value.kind
else {
unreachable!()
};
*operation = DatabaseOp::UpdateOne;
let ExpressionKind::Text(sql) = &mut arguments[0].kind else {
unreachable!()
};
let fields = self.types.definitions[record].columns();
sql.push_str(" RETURNING ");
sql.push_str(&projection(fields));
value.value_type = Type::Named(record);
}
pub(super) fn database(
&mut self,
name: &str,
arguments: &[ast::Expression],
span: Span,
propagate: bool,
) -> Result<Option<Expression>, Diagnostic> {
if matches!(name, "enqueue" | "enqueueAt" | "enqueueMany") {
return self.enqueue(name, arguments, span, propagate).map(Some);
}
if name == "dever.job.states" {
return self.job_states(arguments, span, propagate).map(Some);
}
let Some((owner, method)) = name.rsplit_once('.') else {
return Ok(None);
};
let module = self.types.module(span.source);
let id = module.reference(&format!("{owner}.id"));
let identity = id.strip_suffix(".id").unwrap();
let Some((source, record_name)) = self.types.models.get(identity) else {
return Ok(None);
};
let origin = self.types.module(*source);
if !matches!(module.role, Role::App | Role::Test)
|| module.component != origin.component
|| module.domain != origin.domain
{
return Err(Diagnostic::new(
"C006",
"Model operations belong to their owning App",
span,
));
}
let record = self.types.named(record_name, span.source).unwrap();
self.model_operation(identity, record, method, arguments, span, propagate)
.map(Some)
}
// REST 已绑定同领域 Model;共享相同字段校验、SQL 和参数生成。
pub(crate) fn model_operation(
&mut self,
identity: &str,
record: usize,
method: &str,
arguments: &[ast::Expression],
span: Span,
propagate: bool,
) -> Result<Expression, Diagnostic> {
let fields = self.types.definitions[record].columns();
let Some(mut operation) = DatabaseOp::builtin(method) else {
let queries = &self.types.definitions[record].model.as_ref().unwrap().sql;
let index = queries
.iter()
.position(|query| query.name == method)
.ok_or_else(|| Diagnostic::new("C004", "unknown Model operation", span))?;
return self.model_sql(record, index, arguments, span, propagate);
};
match operation {
DatabaseOp::Cursor(_) => {
return self.model_cursor(identity, record, arguments, span, propagate);
}
DatabaseOp::List | DatabaseOp::Page { .. } => {
return self.model_page(identity, record, method, arguments, span, propagate);
}
DatabaseOp::CreateMany | DatabaseOp::Upsert(_) => {
return self.model_write(record, method, arguments, span, propagate);
}
_ => {}
}
let table = self.types.definitions[record].table();
let mut values = Vec::new();
let fail = || Diagnostic::new("C005", "invalid Model operation arguments", span);
let mut relations = Vec::new();
let mut result = Type::Named(record);
let sql = match operation {
DatabaseOp::NotifyChange | DatabaseOp::WaitChange => {
let wait = operation == DatabaseOp::WaitChange;
if arguments.len() != (if wait { 2 } else { 1 }) {
return Err(fail());
}
values.push(self.expression(&arguments[0], Some(&Type::Text))?);
if wait {
values.push(
self.expression(
&arguments[1],
Some(&Type::Optional(Box::new(Type::Text))),
)?,
);
}
result = if wait { Type::Text } else { Type::Unit };
ExpressionKind::Text(table.clone())
}
DatabaseOp::Create => {
let [block] = arguments else {
return Err(fail());
};
let bound =
self.model_input(entries(block)?, block.span, record, &mut values, Some(span))?;
let insert = write::insert(&quote(&table), fields, &bound);
ExpressionKind::Text(format!("{insert} RETURNING {}", projection(fields)))
}
DatabaseOp::Get if matches!(arguments, [id] if !matches!(id.kind, ast::ExpressionKind::Map(_))) =>
{
values.push(self.expression(&arguments[0], Some(&fields[0].kind))?);
let columns = projection(fields);
ExpressionKind::Text(format!(
r#"SELECT {columns} FROM {} WHERE "id" = $1"#,
quote(&table)
))
}
DatabaseOp::Update(_) | DatabaseOp::Delete(_) => {
let count = if matches!(operation, DatabaseOp::Update(_)) {
2
} else {
1
};
if arguments.len() != count {
return Err(fail());
}
let conditional = matches!(arguments[0].kind, ast::ExpressionKind::Map(_));
let filter = if conditional {
self.model_query(arguments.first(), record, &mut values, method)?
.filter
} else {
values.push(self.expression(&arguments[0], Some(&fields[0].kind))?);
Condition::shared("\"id\" = $1".into())
};
if filter.optional {
operation = if matches!(operation, DatabaseOp::Update(_)) {
DatabaseOp::Update(values.len())
} else {
DatabaseOp::Delete(values.len())
};
}
if matches!(operation, DatabaseOp::Update(_)) {
let block = &arguments[1];
let bound =
self.model_input(entries(block)?, block.span, record, &mut values, None)?;
let assignments = write::assignments(fields, &bound);
let returning = if conditional {
result = Type::Int;
String::new()
} else {
operation = DatabaseOp::UpdateOne;
format!(" RETURNING {}", projection(fields))
};
filter.statement(|clause| {
format!(
"UPDATE {} SET {assignments} WHERE {clause}{returning}",
quote(&table)
)
})
} else {
result = Type::Int;
filter
.statement(|clause| format!("DELETE FROM {} WHERE {clause}", quote(&table)))
}
}
DatabaseOp::Get
| DatabaseOp::First
| DatabaseOp::Count { .. }
| DatabaseOp::Exists
| DatabaseOp::Stream => {
if arguments.len() > 1 || (operation == DatabaseOp::Get && arguments.is_empty()) {
return Err(fail());
}
let query = self.model_query(arguments.first(), record, &mut values, method)?;
relations = query.relations;
let order = query.order.as_deref().unwrap_or(query::DEFAULT_ORDER);
let all = query.filter.is_empty();
let filter = query.filter.where_clause();
match operation {
DatabaseOp::Stream => {
result = Type::AsyncStream(Box::new(result));
let columns = projection(fields);
filter.statement(|clause| {
format!(
"SELECT {columns} FROM {}{clause} ORDER BY {order}",
quote(&table)
)
})
}
DatabaseOp::Count { .. } => {
operation = DatabaseOp::Count { all };
result = Type::Int;
filter.statement(|clause| {
format!("SELECT COUNT(*) FROM {}{clause}", quote(&table))
})
}
DatabaseOp::Exists => {
result = Type::Bool;
filter.statement(|clause| {
format!("SELECT EXISTS(SELECT 1 FROM {}{clause})", quote(&table))
})
}
DatabaseOp::Get | DatabaseOp::First => {
if operation == DatabaseOp::First {
result = Type::Optional(Box::new(result));
}
let columns = projection(fields);
filter.statement(|clause| {
format!(
"SELECT {columns} FROM {}{clause} ORDER BY {order} LIMIT 1",
quote(&table)
)
})
}
_ => unreachable!("read operation"),
}
}
DatabaseOp::Sql { .. }
| DatabaseOp::UpdateOne
| DatabaseOp::List
| DatabaseOp::Page { .. }
| DatabaseOp::PageItems
| DatabaseOp::Cursor(_)
| DatabaseOp::CreateMany
| DatabaseOp::Upsert(_) => unreachable!(),
};
let error = self
.types
.named("dever.database.Error", span.source)
.unwrap();
if propagate {
self.failures
.extend((0..10).map(|v| Failure::Choice(error, v)));
}
values.insert(0, Self::node(sql, Type::Text, span));
Ok(Self::node(
ExpressionKind::Builtin(
Builtin::Database {
relations,
record,
error,
operation,
},
values,
),
result,
span,
))
}
fn model_input<'a>(
&mut self,
entries: impl IntoIterator<Item = (&'a str, &'a ast::Expression)>,
span: Span,
record: usize,
values: &mut Vec<Expression>,
created_at: Option<Span>,
) -> Result<Vec<(usize, usize)>, Diagnostic> {
let fields = self.types.definitions[record].columns();
let mut bound = Vec::new();
let mut seen = BTreeSet::new();
for (name, value) in entries {
let Some((index, field)) = fields.iter().enumerate().find(|(_, f)| f.name == name)
else {
return Err(Diagnostic::new(
"C005",
format!("unknown Model field {name}"),
value.span,
));
};
if index < 2 || field.model.as_ref().is_some_and(|m| m.generated) {
return Err(Diagnostic::new(
"C005",
"cannot write a generated Model field",
value.span,
));
}
if !seen.insert(index) {
return Err(Diagnostic::new(
"C005",
"duplicate Model block key",
value.span,
));
}
let value = self.expression(value, Some(&field.kind))?;
values.push(Self::node(
ExpressionKind::Builtin(
Builtin::ModelInput {
write: true,
record,
field: index,
},
vec![value],
),
field.kind.clone(),
span,
));
bound.push((index, values.len()));
}
if let Some(created_at) = created_at {
for (index, field) in fields.iter().enumerate().skip(2) {
if seen.contains(&index) {
continue;
}
let kind = if field.model.as_ref().is_some_and(|m| m.generated) {
ExpressionKind::Builtin(Builtin::ModelUuid, vec![])
} else if let Some(default) = field.model.as_ref().and_then(|m| m.default.as_ref())
{
ExpressionKind::Builtin(
Builtin::ModelInput {
write: true,
record,
field: index,
},
vec![default.clone()],
)
} else if matches!(field.kind, Type::Optional(_)) {
ExpressionKind::Null
} else {
return Err(Diagnostic::new(
"C005",
format!("missing Model field {}", field.name),
span,
));
};
values.push(Self::node(kind, field.kind.clone(), span));
bound.push((index, values.len()));
}
values.push(Self::node(
ExpressionKind::Builtin(Builtin::ModelNow, vec![]),
Type::DateTime,
created_at,
));
bound.push((1, values.len())); // created_at 是第二个内置列。
} else if bound.is_empty() {
return Err(Diagnostic::new(
"C005",
"update requires at least one field",
span,
));
}
Ok(bound)
}
}
fn entries(block: &ast::Expression) -> Result<Vec<(&str, &ast::Expression)>, Diagnostic> {
let ast::ExpressionKind::Map(entries) = &block.kind else {
return Err(Diagnostic::new(
"C005",
"expected a Model field or query block",
block.span,
));
};
let mut names = BTreeSet::new();
entries
.iter()
.map(|(key, value)| {
let name = match &key.kind {
ast::ExpressionKind::Name(name)
| ast::ExpressionKind::Literal(ast::Literal::Text(name)) => name.as_str(),
_ => {
return Err(Diagnostic::new(
"C005",
"Model keys must be field names",
key.span,
));
}
};
if !names.insert(name) {
return Err(Diagnostic::new(
"C005",
"duplicate Model block key",
key.span,
));
}
Ok((name, value))
})
.collect()
}
fn quote(name: &str) -> String {
format!("\"{name}\"")
}
@@ -0,0 +1,49 @@
use super::*;
impl Checker<'_> {
pub(super) fn model_sql(
&mut self,
record: usize,
index: usize,
arguments: &[ast::Expression],
span: Span,
propagate: bool,
) -> Result<Expression, Diagnostic> {
let query = &self.types.definitions[record].model.as_ref().unwrap().sql[index];
if arguments.len() != query.inputs.len() {
return Err(Diagnostic::new(
"C005",
"SQL argument count differs from its declaration",
span,
));
}
let values = arguments
.iter()
.zip(&query.inputs)
.map(|(value, field)| self.field_value(value, field))
.collect::<Result<Vec<_>, _>>()?;
let error = self
.types
.named("dever.database.Error", span.source)
.unwrap();
if propagate {
self.failures
.extend((0..10).map(|variant| Failure::Choice(error, variant)));
}
Ok(Self::node(
ExpressionKind::Builtin(
Builtin::Database {
relations: Vec::new(),
record,
error,
operation: DatabaseOp::Sql {
index,
write: !query.readonly,
},
},
values,
),
query.output.clone(),
span,
))
}
}
@@ -0,0 +1,85 @@
//! 分页保留 count 和具体 Page,分页值仍是类型化 Int 参数。
use super::*;
impl Checker<'_> {
pub(super) fn model_page(
&mut self,
owner: &str,
record: usize,
method: &str,
arguments: &[ast::Expression],
span: Span,
propagate: bool,
) -> Result<Expression, Diagnostic> {
let paged = method == "page";
if arguments.len() > 1 {
return Err(Diagnostic::new("C005", "invalid data read arguments", span));
}
let fields = self.types.definitions[record].columns();
let mut parameters = Vec::new();
let query = self.model_query(arguments.first(), record, &mut parameters, method)?;
let order = query.order.as_deref().unwrap_or(query::DEFAULT_ORDER);
let all = query.filter.is_empty();
let filter = query.filter.where_clause();
let table = self.types.definitions[record].table();
let columns = projection(fields);
let table = quote(&table);
let offset = if paged {
format!(" OFFSET ${}", parameters.len() + 2)
} else {
String::new()
};
let sql = filter.statement(|clause| {
format!(
"SELECT {columns} FROM {table}{clause} ORDER BY {order} LIMIT ${}{offset}",
parameters.len() + 1
)
});
let mut values = vec![Self::node(sql, Type::Text, span)];
if paged {
let count = filter.statement(|clause| format!("SELECT COUNT(*) FROM {table}{clause}"));
values.push(Self::node(count, Type::Text, span));
}
values.extend(parameters);
let integer = |value| {
Self::node(
ExpressionKind::Number(numeric::Number::Int(value)),
Type::Int,
span,
)
};
if paged {
values.push(query.page.unwrap_or_else(|| integer(1)));
}
values.push(query.size.unwrap_or_else(|| integer(20)));
let (operation, result) = if paged {
let page = self
.types
.named(&format!("{owner}.Page"), span.source)
.unwrap();
(DatabaseOp::Page { all }, Type::Named(page))
} else {
(DatabaseOp::List, Type::List(Box::new(Type::Named(record))))
};
let error = self
.types
.named("dever.database.Error", span.source)
.unwrap();
if propagate {
self.failures
.extend((0..10).map(|variant| Failure::Choice(error, variant)));
}
Ok(Self::node(
ExpressionKind::Builtin(
Builtin::Database {
relations: query.relations,
record,
error,
operation,
},
values,
),
result,
span,
))
}
}
@@ -0,0 +1,537 @@
//! 条件结构只在编译期展开,用户值全部参数化;写入不能省略 where。
use super::*;
#[derive(Default)]
pub(super) struct Condition {
pub(super) optional: bool,
postgres: String,
sqlite: Option<String>,
}
impl Condition {
pub(super) fn shared(postgres: String) -> Self {
Self {
postgres,
sqlite: None,
optional: false,
}
}
pub(super) fn is_empty(&self) -> bool {
self.postgres.is_empty()
}
pub(super) fn where_clause(self) -> Self {
if self.is_empty() {
self
} else {
self.map(|sql| format!(" WHERE {sql}"))
}
}
fn map(self, render: impl Fn(&str) -> String) -> Self {
Self {
optional: self.optional,
postgres: render(&self.postgres),
sqlite: self.sqlite.as_deref().map(render),
}
}
fn join(self, operator: &str, other: Self) -> Self {
let render = |left: &str, right: &str| format!("({left} {operator} {right})");
let sqlite = (self.sqlite.is_some() || other.sqlite.is_some()).then(|| {
render(
self.sqlite.as_deref().unwrap_or(&self.postgres),
other.sqlite.as_deref().unwrap_or(&other.postgres),
)
});
Self {
optional: self.optional && other.optional,
postgres: render(&self.postgres, &other.postgres),
sqlite,
}
}
pub(super) fn statement(&self, render: impl Fn(&str) -> String) -> ExpressionKind {
let postgres = render(&self.postgres);
match &self.sqlite {
Some(sqlite) => ExpressionKind::QuerySql {
sqlite: render(sqlite),
postgres,
},
None => ExpressionKind::Text(postgres),
}
}
}
#[derive(Default)]
pub(super) struct Query {
pub filter: Condition,
pub order: Option<String>,
pub relations: Vec<usize>,
pub page: Option<Expression>,
pub size: Option<Expression>,
}
pub(super) const DEFAULT_ORDER: &str = "\"id\" DESC";
impl Checker<'_> {
pub(super) fn model_query(
&mut self,
block: Option<&ast::Expression>,
record: usize,
values: &mut Vec<Expression>,
method: &str,
) -> Result<Query, Diagnostic> {
let mut query = Query::default();
let Some(block) = block else {
return Ok(query);
};
let fields = self.types.definitions[record].columns();
for (key, value) in entries(block)? {
match key {
"where" => query.filter = self.model_condition(value, record, values, true)?,
"with" if matches!(method, "get" | "first" | "list" | "page") => {
query.relations = self.selected_relations(record, value)?
}
"page" if method == "page" => {
query.page = Some(self.expression(value, Some(&Type::Int))?)
}
"size" if method == "page" => {
query.size = Some(self.expression(value, Some(&Type::Int))?)
}
"limit" if method == "list" => {
query.size = Some(self.expression(value, Some(&Type::Int))?)
}
"order" if matches!(method, "get" | "first" | "stream" | "list" | "page") => {
query.order = Some(
model_order(value, fields)?
.iter()
.map(|&(index, ascending)| {
format!(
"{} {}",
quote(&fields[index].name),
if ascending { "ASC" } else { "DESC" }
)
})
.collect::<Vec<_>>()
.join(","),
);
}
_ => {
return Err(Diagnostic::new(
"C005",
format!("unsupported query key {key}"),
value.span,
));
}
}
}
if matches!(method, "get" | "update" | "delete") && query.filter.is_empty() {
return Err(Diagnostic::new(
"C005",
"conditional operation requires where",
block.span,
));
}
Ok(query)
}
pub(super) fn model_condition(
&mut self,
value: &ast::Expression,
record: usize,
values: &mut Vec<Expression>,
absent_matches: bool,
) -> Result<Condition, Diagnostic> {
let fields = self.types.definitions[record].columns();
if let ast::ExpressionKind::Unary(op, inner) = &value.kind
&& op == "not"
{
let condition = self.model_condition(inner, record, values, !absent_matches)?;
return Ok(condition.map(|sql| format!("(NOT ({sql}))")));
}
if let ast::ExpressionKind::Call(target, arguments) = &value.kind {
return self.model_condition_call(
value,
target,
arguments,
record,
values,
absent_matches,
);
}
let ast::ExpressionKind::Binary(op, left, right) = &value.kind else {
return Err(Diagnostic::new(
"C005",
"where requires a Model condition",
value.span,
));
};
if matches!(op.as_str(), "and" | "or") {
let and = op == "and";
let start = values.len() + 1;
let left = self.model_condition(left, record, values, and)?;
let right = self.model_condition(right, record, values, and)?;
let mut group = left.join(if and { "AND" } else { "OR" }, right);
// 整组被省略时,取外层运算的单位值。非空参数的比较保留 SQL 的空值语义。
if group.optional && and != absent_matches {
let missing = (start..=values.len())
.map(|p| format!("${p} IS NULL"))
.collect::<Vec<_>>()
.join(" AND ");
group = group.map(|sql| {
if absent_matches {
format!("({sql} OR ({missing}))")
} else {
format!("({sql} AND NOT ({missing}))")
}
});
}
return Ok(group);
}
let (index, field) = condition_field(left, fields)?;
let column = quote(&field.name);
let token = comparison_token(op, field, value.span)?;
if matches!(right.kind, ast::ExpressionKind::Literal(ast::Literal::Null)) {
if !matches!(field.kind, Type::Optional(_)) || !matches!(op.as_str(), "==" | "!=") {
return Err(Diagnostic::new(
"C005",
"null comparison requires an optional field",
value.span,
));
}
return Ok(Condition::shared(format!(
"{column} IS {}NULL",
if op == "!=" { "NOT " } else { "" }
)));
}
let parameter = self.condition_parameter(
right,
record,
index,
field,
values,
matches!(op.as_str(), "==" | "!="),
)?;
Ok(Condition::shared(format!("{column} {token} ${parameter}")))
}
fn model_condition_call(
&mut self,
source: &ast::Expression,
target: &ast::Expression,
arguments: &[ast::Expression],
record: usize,
values: &mut Vec<Expression>,
absent_matches: bool,
) -> Result<Condition, Diagnostic> {
let fields = self.types.definitions[record].columns();
match (&target.kind, arguments) {
(ast::ExpressionKind::Name(op), [comparison]) if op == "ifSet" => {
let (column, operand, operator) = match &comparison.kind {
ast::ExpressionKind::Binary(op, field, value) => {
(field.as_ref(), value.as_ref(), op.as_str())
}
ast::ExpressionKind::Call(target, args)
if let ast::ExpressionKind::Field(field, method) = &target.kind
&& method == "contains"
&& let [value] = args.as_slice() =>
{
(field.as_ref(), value, "contains")
}
_ => {
return Err(Diagnostic::new(
"C005",
"ifSet requires a comparison or contains",
comparison.span,
));
}
};
let (index, field) = condition_field(column, fields)?;
if operator == "contains" && field.kind != Type::Text {
return Err(Diagnostic::new(
"C005",
"contains requires a non-null Model Text field",
column.span,
));
}
let column = quote(&field.name);
let token = if operator == "contains" {
operator
} else {
comparison_token(operator, field, comparison.span)?
};
let mut field = field.clone();
if !matches!(field.kind, Type::Optional(_)) {
field.kind = Type::Optional(Box::new(field.kind));
}
let p = self.condition_parameter(
operand,
record,
index,
&field,
values,
matches!(operator, "==" | "!="),
)?;
let test = if operator == "contains" {
format!("strpos({column},${p}) > 0")
} else {
format!("{column} {token} ${p}")
};
let sql = if absent_matches {
format!("({test} OR ${p} IS NULL)")
} else {
format!("({test} AND ${p} IS NOT NULL)")
};
Ok(Condition {
optional: true,
..Condition::shared(sql)
})
}
(ast::ExpressionKind::Name(op), [field, list]) if op == "in" => {
let (index, field) = condition_field(field, fields)?;
let ast::ExpressionKind::List(items) = &list.kind else {
let cast = match field.kind {
Type::Int | Type::ModelId(_) => "::bigint",
Type::Text => "",
_ => {
return Err(Diagnostic::new(
"C005",
"runtime in requires a non-null Int, model ID or Text field",
list.span,
));
}
};
let kind = Type::List(Box::new(field.kind.clone()));
let input = self.expression(list, Some(&kind))?;
values.push(Self::node(
ExpressionKind::Builtin(
Builtin::ModelInput {
record,
field: index,
write: false,
},
vec![input],
),
kind,
list.span,
));
let p = values.len();
let column = quote(&field.name);
return Ok(Condition {
optional: false,
postgres: format!(
"{column} IN (SELECT v{cast} FROM jsonb_array_elements_text(${p}::text::jsonb) AS selected(v))"
),
sqlite: Some(format!("{column} IN (SELECT value FROM json_each(${p}))")),
});
};
if !(1..=100).contains(&items.len()) {
return Err(Diagnostic::new(
"C005",
"in requires between 1 and 100 values",
list.span,
));
}
let names = items
.iter()
.map(|item| {
self.condition_parameter(item, record, index, field, values, true)
.map(|p| format!("${p}"))
})
.collect::<Result<Vec<_>, _>>()?;
Ok(Condition::shared(format!(
"{} IN ({})",
quote(&field.name),
names.join(",")
)))
}
(ast::ExpressionKind::Name(op), [column, low, high]) if op == "between" => {
let (index, field) = condition_field(column, fields)?;
let low = self.condition_parameter(low, record, index, field, values, false)?;
let high = self.condition_parameter(high, record, index, field, values, false)?;
Ok(Condition::shared(format!(
"{} BETWEEN ${low} AND ${high}",
quote(&field.name)
)))
}
(ast::ExpressionKind::Name(op), [column, needle])
if matches!(op.as_str(), "startsWith" | "endsWith") =>
{
let (_, field) = condition_field(column, fields)?;
if field.kind != Type::Text
&& !matches!(&field.kind, Type::Optional(inner) if **inner == Type::Text)
{
return Err(Diagnostic::new(
"C005",
"text condition requires a Model Text field",
column.span,
));
}
values.push(self.expression(needle, Some(&Type::Text))?);
let parameter = values.len();
let column = quote(&field.name);
let needle = format!("${parameter}");
let sqlite_column = format!("CAST({column} AS BLOB)");
let sqlite_needle = format!("CAST({needle} AS BLOB)");
let (postgres, sqlite) = if op == "startsWith" {
(
format!("starts_with({column},{needle})"),
format!("instr({sqlite_column},{sqlite_needle}) = 1"),
)
} else {
// SQLite 的 Text length 在 NUL 处停止;按字节比较仍保留完整 UTF-8。
(
format!("right({column},length({needle})) = {needle}"),
format!(
"substr({sqlite_column},length({sqlite_column})-length({sqlite_needle})+1) = {sqlite_needle}"
),
)
};
Ok(Condition {
postgres,
sqlite: Some(sqlite),
optional: false,
})
}
(ast::ExpressionKind::Field(column, method), [needle]) if method == "contains" => {
let (_, field) = condition_field(column, fields)?;
if field.kind != Type::Text {
return Err(Diagnostic::new(
"C005",
"contains requires a non-null Model Text field",
column.span,
));
}
values.push(self.expression(needle, Some(&Type::Text))?);
Ok(Condition::shared(format!(
"strpos({},${}) > 0",
quote(&field.name),
values.len()
)))
}
_ => Err(Diagnostic::new(
"C005",
"invalid Model condition function or arguments",
source.span,
)),
}
}
fn condition_parameter(
&mut self,
source: &ast::Expression,
record: usize,
index: usize,
field: &Field,
values: &mut Vec<Expression>,
equality: bool,
) -> Result<usize, Diagnostic> {
let expression = self.expression(source, Some(&field.kind))?;
let normalize = equality && field.text_normalization().is_some_and(|mode| {
!matches!(expression.kind, ExpressionKind::Variable(i) if self.locals[i].input_contract().is_some_and(|input| input.text == mode))
});
let expression = if normalize || field.model.as_ref().is_some_and(|m| m.decimal.is_some()) {
Self::node(
ExpressionKind::Builtin(
Builtin::ModelInput {
record,
field: index,
write: false,
},
vec![expression],
),
field.kind.clone(),
source.span,
)
} else {
expression
};
values.push(expression);
Ok(values.len())
}
}
fn comparison_token(op: &str, field: &Field, span: Span) -> Result<&'static str, Diagnostic> {
Ok(match op {
"==" if matches!(field.kind, Type::Optional(_)) => "IS NOT DISTINCT FROM",
"!=" if matches!(field.kind, Type::Optional(_)) => "IS DISTINCT FROM",
"==" => "=",
"!=" => "<>",
"<" => "<",
"<=" => "<=",
">" => ">",
">=" => ">=",
_ => {
return Err(Diagnostic::new(
"C005",
"unsupported Model comparison",
span,
));
}
})
}
fn condition_field<'a>(
source: &ast::Expression,
fields: &'a [Field],
) -> Result<(usize, &'a Field), Diagnostic> {
let ast::ExpressionKind::Name(name) = &source.kind else {
return Err(Diagnostic::new(
"C005",
"comparison must start with a Model field",
source.span,
));
};
fields
.iter()
.enumerate()
.find(|(_, field)| &field.name == name)
.ok_or_else(|| {
Diagnostic::new(
"C005",
"comparison must start with a Model field",
source.span,
)
})
}
// 保留排序字段身份,游标检查和 SQL 生成共用,不反解析 SQL 文本。
pub(super) fn model_order(
value: &ast::Expression,
fields: &[Field],
) -> Result<Vec<(usize, bool)>, Diagnostic> {
let items = match &value.kind {
ast::ExpressionKind::List(items) => items.as_slice(),
_ => std::slice::from_ref(value),
};
if items.is_empty() {
return Err(Diagnostic::new("C005", "order cannot be empty", value.span));
}
let mut keys = Vec::new();
for item in items {
let ast::ExpressionKind::Field(base, direction) = &item.kind else {
return Err(Diagnostic::new(
"C005",
"order requires field.asc or field.desc",
item.span,
));
};
let name = base.path().unwrap_or_default();
let Some(index) = fields.iter().position(|field| field.name == name) else {
return Err(Diagnostic::new(
"C005",
"invalid Model order field",
item.span,
));
};
if !matches!(direction.as_str(), "asc" | "desc") || keys.iter().any(|&(i, _)| i == index) {
return Err(Diagnostic::new(
"C005",
"invalid or duplicate Model order field",
item.span,
));
}
keys.push((index, direction == "asc"));
}
Ok(keys)
}
@@ -0,0 +1,46 @@
//! 只对读取操作的 with 参数解析关联字段。
use super::*;
impl Checker<'_> {
pub(super) fn selected_relations(
&self,
record: usize,
value: &ast::Expression,
) -> Result<Vec<usize>, Diagnostic> {
let ast::ExpressionKind::List(selected) = &value.kind else {
return Err(Diagnostic::new(
"C005",
"with requires a direct relation list",
value.span,
));
};
let definition = &self.types.definitions[record];
let Shape::Record(fields) = &definition.shape else {
unreachable!()
};
let model = definition.model.as_ref().unwrap();
let mut relations = Vec::new();
for item in selected {
let ast::ExpressionKind::Name(name) = &item.kind else {
return Err(Diagnostic::new(
"C005",
"with supports one explicit relation layer",
item.span,
));
};
let relation = model
.relations
.iter()
.position(|r| &fields[r.field].name == name)
.ok_or_else(|| Diagnostic::new("C004", "unknown Model relation", item.span))?;
if relations.contains(&relation) {
return Err(Diagnostic::new(
"C005",
"duplicate relation in with",
item.span,
));
}
relations.push(relation);
}
Ok(relations)
}
}
@@ -0,0 +1,157 @@
//! 批量写入复用字段合同;生成一条参数化 SQL,由数据库承担原子性和唯一性。
use super::*;
impl Checker<'_> {
pub(super) fn model_write(
&mut self,
record: usize,
method: &str,
arguments: &[ast::Expression],
span: Span,
propagate: bool,
) -> Result<Expression, Diagnostic> {
let fields = self.types.definitions[record].columns();
let table = quote(&self.types.definitions[record].table());
let mut parameters = Vec::new();
let invalid = |message| Diagnostic::new("C005", message, span);
let (sql, operation, output) = if method == "createMany" {
let [list] = arguments else {
return Err(invalid(
"createMany requires one direct list of field blocks",
));
};
let ast::ExpressionKind::List(rows) = &list.kind else {
return Err(invalid(
"createMany requires one direct list of field blocks",
));
};
let mut tuples = Vec::with_capacity(rows.len());
let mut slots = vec![String::new(); fields.len() - 1];
for row in rows {
let bound =
self.model_input(entries(row)?, row.span, record, &mut parameters, Some(span))?;
// 表达式按源码顺序求值,SQL 的每一行按表列顺序绑定。
for (column, parameter) in bound {
slots[column - 1] = format!("${parameter}");
}
tuples.push(format!("({})", slots.join(",")));
}
let sql = if tuples.is_empty() {
String::new()
} else {
let columns = fields[1..]
.iter()
.map(|f| quote(&f.name))
.collect::<Vec<_>>()
.join(",");
format!(
"INSERT INTO {table} ({columns}) VALUES {}",
tuples.join(",")
)
};
(sql, DatabaseOp::CreateMany, Type::Int)
} else {
let [key, create, update] = arguments else {
return Err(invalid(
"upsert requires unique key, create and update field blocks",
));
};
let keys = entries(key)?;
let positions = keys
.iter()
.map(|(name, _)| fields.iter().position(|f| f.name == *name))
.collect::<Option<Vec<_>>>()
.ok_or_else(|| invalid("unknown upsert key"))?;
let model = self.types.definitions[record].model.as_ref().unwrap();
let unique = positions.len() == 1
&& fields[positions[0]]
.model
.as_ref()
.is_some_and(|m| m.unique)
|| model.indexes.iter().any(|index| {
index.unique
&& index.fields.len() == positions.len()
&& index.fields.iter().all(|f| positions.contains(f))
});
if !unique {
return Err(invalid("upsert key must match a complete unique index"));
}
if keys.iter().any(|(_, value)| {
matches!(value.kind, ast::ExpressionKind::Literal(ast::Literal::Null))
}) {
return Err(invalid("upsert key cannot be null"));
}
let create_fields = entries(create)?;
let bound = self.model_input(
keys.iter().copied().chain(create_fields),
create.span,
record,
&mut parameters,
Some(span),
)?;
let insert = insert(&table, fields, &bound);
let updates = entries(update)?;
let assignments = if updates.is_empty() {
// 空更新仍返回已存在记录,由同一条语句完成冲突处理。
let key = quote(keys[0].0);
format!("{key}=excluded.{key}")
} else {
let bound =
self.model_input(updates, update.span, record, &mut parameters, None)?;
assignments(fields, &bound)
};
let returning = projection(fields);
let sql = format!(
"{insert} ON CONFLICT ({}) DO UPDATE SET {assignments} RETURNING {returning}",
keys.iter()
.map(|(name, _)| quote(name))
.collect::<Vec<_>>()
.join(",")
);
(sql, DatabaseOp::Upsert(keys.len()), Type::Named(record))
};
let error = self
.types
.named("dever.database.Error", span.source)
.unwrap();
if propagate {
self.failures
.extend((0..10).map(|variant| Failure::Choice(error, variant)));
}
parameters.insert(0, Self::node(ExpressionKind::Text(sql), Type::Text, span));
Ok(Self::node(
ExpressionKind::Builtin(
Builtin::Database {
relations: Vec::new(),
record,
error,
operation,
},
parameters,
),
output,
span,
))
}
}
pub(super) fn insert(table: &str, fields: &[Field], bound: &[(usize, usize)]) -> String {
let columns = bound
.iter()
.map(|&(i, _)| quote(&fields[i].name))
.collect::<Vec<_>>()
.join(",");
let parameters = bound
.iter()
.map(|&(_, n)| format!("${n}"))
.collect::<Vec<_>>()
.join(",");
format!("INSERT INTO {table} ({columns}) VALUES ({parameters})")
}
pub(super) fn assignments(fields: &[Field], bound: &[(usize, usize)]) -> String {
bound
.iter()
.map(|&(i, n)| format!(r#""{}"=${n}"#, fields[i].name))
.collect::<Vec<_>>()
.join(",")
}
+325
View File
@@ -0,0 +1,325 @@
//! 先绑定调用和具体值类型,错误集合向调用方传播;没有动态值或备用解析。
use super::Checker;
use crate::compiler::model::*;
use crate::syntax::{ast, diagnostic::Diagnostic};
impl Checker<'_> {
pub(super) fn raw(
&mut self,
expression: &ast::Expression,
expected: Option<&Type>,
) -> Result<Expression, Diagnostic> {
let span = expression.span;
let declared = expected;
let expected = match expected {
Some(Type::Optional(inner)) => Some(inner.as_ref()),
other => other,
};
match &expression.kind {
ast::ExpressionKind::Rule(rule) => {
super::super::program::rule::inline(self, rule, declared, span)
}
ast::ExpressionKind::Loop(l) => {
let kind = declared.ok_or_else(|| {
Diagnostic::new("C005", "inline loop needs a result type here", span)
})?;
let field = Field {
name: String::new(),
kind: kind.clone(),
span,
model: None,
private: false,
range: None,
};
let scope = (
self.names.clone(),
self.ranges.clone(),
self.bools.clone(),
self.variants.clone(),
);
let checked = super::super::program::iteration::check(self, &[field], l)?;
(self.names, self.ranges, self.bools, self.variants) = scope;
Ok(Self::node(
ExpressionKind::Loop(Box::new(checked)),
kind.clone(),
span,
))
}
ast::ExpressionKind::Channel(element, capacity) => {
self.channel_new(element, capacity, span)
}
ast::ExpressionKind::Literal(ast::Literal::Number(text)) => {
let context = match expected {
Some(Type::Optional(inner)) => Some(inner.as_ref()),
other => other,
};
let kind = match context {
Some(Type::Decimal) => Type::Decimal,
Some(Type::Float) => Type::Float,
_ => numeric::Number::literal_type(text),
};
let value = numeric::Number::parse(text, &kind)
.map_err(|message| Diagnostic::new("C008", message, span))?;
Ok(Expression {
kind: ExpressionKind::Number(value),
value_type: kind,
range: Some(numeric::Range::point(value)),
known_bool: None,
span,
})
}
ast::ExpressionKind::Literal(ast::Literal::Text(value)) => Ok(Self::node(
ExpressionKind::Text(value.clone()),
Type::Text,
span,
)),
ast::ExpressionKind::Literal(ast::Literal::Bool(value)) => {
let mut expression = Self::node(ExpressionKind::Bool(*value), Type::Bool, span);
expression.known_bool = Some(*value);
Ok(expression)
}
ast::ExpressionKind::Literal(ast::Literal::Null) => {
Ok(Self::node(ExpressionKind::Null, Type::Null, span))
}
ast::ExpressionKind::Name(name) => {
if let Some(&local) = self.names.get(name) {
return Ok(self.variable(local, span));
}
if let Some(value) = self.setting(name, span)? {
return Ok(value);
}
if let Some(value) = self.constant(name, span)? {
return Ok(value);
}
if let Some(error) = ApiError::parse(name) {
return Ok(Self::node(
ExpressionKind::ApiError(error),
Type::ApiError,
span,
));
}
self.variant(name, &[], expected, span)?.ok_or_else(|| {
Diagnostic::new("C004", format!("unknown or unassigned value {name}"), span)
})
}
ast::ExpressionKind::Field(base, field) => {
if let Some(path) = expression.path()
&& !self.names.contains_key(path.split('.').next().unwrap())
&& let Some(value) = self.setting(&path, span)?
{
return Ok(value);
}
if let Some(path) = expression.path()
&& !self.names.contains_key(path.split('.').next().unwrap())
&& let Some(value) = self.constant(&path, span)?
{
return Ok(value);
}
if let Some(path) = expression.path()
&& let Some(variant) = self.variant(&path, &[], expected, span)?
{
return Ok(variant);
}
let base = self.expression(base, None)?;
self.select(base, field, span)
}
ast::ExpressionKind::Call(target, arguments) => {
self.call_value(target, arguments, declared, span)
}
ast::ExpressionKind::Unary(operator, value) => {
self.unary(operator, value, expected, span)
}
ast::ExpressionKind::Binary(operator, left, right) => {
self.binary(operator, left, right, expected, span)
}
ast::ExpressionKind::Record(name, values) => self.record(name, values, span),
ast::ExpressionKind::List(values) => {
let mut element = match expected {
Some(Type::List(element)) => Some(element.as_ref().clone()),
_ => None,
};
let mut checked = Vec::new();
for value in values {
let value = self.expression(value, element.as_ref())?;
if element.is_none() {
element = Some(value.value_type.clone());
}
checked.push(value);
}
let element = element.ok_or_else(|| {
Diagnostic::new("C005", "empty list requires a declared element type", span)
})?;
self.types.validate(&element, span)?;
Ok(Self::node(
ExpressionKind::List(checked),
Type::List(Box::new(element)),
span,
))
}
ast::ExpressionKind::Map(values) => {
let (mut key, mut value_type) = match expected {
Some(Type::Map(key, value)) => {
(Some(key.as_ref().clone()), Some(value.as_ref().clone()))
}
_ => (None, None),
};
let mut checked = Vec::new();
for (name, value) in values {
let name = self.expression(name, key.as_ref())?;
let value = self.expression(value, value_type.as_ref())?;
if key.is_none() {
key = Some(name.value_type.clone());
value_type = Some(value.value_type.clone());
}
checked.push((name, value));
}
let (Some(key), Some(value)) = (key, value_type) else {
return Err(Diagnostic::new(
"C005",
"empty map requires declared key and value types",
span,
));
};
let kind = Type::Map(Box::new(key), Box::new(value));
self.types.validate(&kind, span)?;
let unique_keys = map_keys(&checked)?;
Ok(Self::node(
ExpressionKind::Map {
entries: checked,
unique_keys,
},
kind,
span,
))
}
}
}
fn call_value(
&mut self,
target: &ast::Expression,
arguments: &[ast::Expression],
declared: Option<&Type>,
span: crate::syntax::source::Span,
) -> Result<Expression, Diagnostic> {
let expected = match declared {
Some(Type::Optional(inner)) => Some(inner.as_ref()),
other => other,
};
if let Some(&edge) = self.calls.by_span.get(&(self.caller, span)) {
let target = self.calls.edges[edge].target;
let mut expression = self.call(target, arguments, span)?;
let function = self.functions[target].as_ref().expect("checked callee");
if function.failure_summary.output.is_none() {
expression.value_type = Type::Never;
}
self.failures.extend(&function.failures);
self.unknown_failures |= function.unknown_failures;
return Ok(expression);
}
let name = target.path().ok_or_else(|| {
Diagnostic::new(
"C004",
"calls require a statically named target",
target.span,
)
})?;
if matches!(
name.as_str(),
"run" | "parallel" | "blocking" | "wait" | "stop" | "timeout" | "race" | "group"
) {
return self.task(&name, arguments, span, true);
}
if name == "result" {
let [call] = arguments else {
return Err(Diagnostic::new("C005", "result requires one call", span));
};
return self.capture(call, expected, span);
}
if matches!(name.as_str(), "send" | "receive" | "close") {
return self.channel_operation(&name, arguments, span);
}
if name == "stream" {
return self.stream(arguments, expected, span);
}
if name == "dever.system.taskTicks" {
return self.ticks(arguments, span);
}
if name == "fail" {
if arguments.len() != 1 {
return Err(Diagnostic::new("C005", "fail requires one error", span));
}
let value = self.expression(&arguments[0], None)?;
let error = self.error(value)?;
return Ok(Self::node(
ExpressionKind::Fail(Box::new(error)),
Type::Never,
span,
));
}
if let Some(value) = self.database(&name, arguments, span, true)? {
return Ok(value);
}
if let Some(value) = self.test_operation(&name, arguments, span)? {
return Ok(value);
}
if let Some(value) = self.request(&name, arguments, span)? {
return Ok(value);
}
if let Some(value) = self.identity(&name, arguments, declared, span)? {
return Ok(value);
}
if let Some(value) = self.authorization(&name, arguments, span)? {
return Ok(value);
}
if let Some(value) = self.session(&name, arguments, span)? {
return Ok(value);
}
if let Some(variant) = self.variant(&name, arguments, expected, span)? {
return Ok(variant);
}
if name == "dever.json.decode" {
self.decode_json(arguments, declared, span, true)
} else {
self.builtin(&name, arguments, expected, span)
}
}
}
#[derive(PartialEq, Eq, Hash)]
enum ConstantKey<'a> {
Bool(bool),
Int(i64),
Text(&'a str),
Variant(usize, usize),
}
fn map_keys(entries: &[(Expression, Expression)]) -> Result<bool, Diagnostic> {
let mut seen = std::collections::HashSet::new();
let mut unique = true;
for (key, _) in entries {
let constant = match &key.kind {
ExpressionKind::Text(value) => Some(ConstantKey::Text(value)),
ExpressionKind::Variant(definition, variant, fields) if fields.is_empty() => {
Some(ConstantKey::Variant(*definition, *variant))
}
_ if key.known_bool.is_some() => Some(ConstantKey::Bool(key.known_bool.unwrap())),
_ => key
.range
.and_then(|range| match (range.minimum, range.maximum) {
(numeric::Number::Int(a), numeric::Number::Int(b)) if a == b => {
Some(ConstantKey::Int(a))
}
_ => None,
}),
};
if let Some(constant) = constant {
if !seen.insert(constant) {
return Err(Diagnostic::new("C005", "duplicate Map key", key.span));
}
} else {
unique = false;
}
}
Ok(unique)
}
+269
View File
@@ -0,0 +1,269 @@
//! 名义 ID 来自调用位置的声明合同;Provider 配置必须与该身份类型一致。
use super::*;
impl Checker<'_> {
pub(super) fn request(
&mut self,
name: &str,
arguments: &[ast::Expression],
span: Span,
) -> Result<Option<Expression>, Diagnostic> {
let operation = match name {
"dever.site.key" => RequestOp::Site,
"dever.api.request.requestId" => RequestOp::RequestId,
"dever.api.request.method" => RequestOp::Method,
"dever.api.request.path" => RequestOp::Path,
"dever.api.request.clientAddress" => RequestOp::ClientAddress,
"dever.api.request.header" => RequestOp::Header,
"dever.api.request.setHeader" => RequestOp::SetHeader,
"dever.api.cookie" => RequestOp::Cookie,
"dever.api.secretCookie" => RequestOp::SecretCookie,
"dever.api.setCookie" => RequestOp::SetCookie,
"dever.api.setSecretCookie" => RequestOp::SetSecretCookie,
_ => return Ok(None),
};
let count = match operation {
RequestOp::Header | RequestOp::Cookie | RequestOp::SecretCookie => 1,
RequestOp::SetHeader => 2,
RequestOp::SetCookie | RequestOp::SetSecretCookie => 3,
_ => 0,
};
if arguments.len() != count {
return Err(Diagnostic::new(
"C005",
"request operation argument count differs",
span,
));
}
let values = arguments
.iter()
.enumerate()
.map(|(index, v)| {
let kind = match index {
1 if operation == RequestOp::SetSecretCookie => Type::Secret,
2 => Type::Named(
self.types
.named("dever.api.CookieOptions", span.source)
.expect("bundled CookieOptions"),
),
_ => Type::Text,
};
self.expression(v, Some(&kind))
})
.collect::<Result<Vec<_>, _>>()?;
if count > 0 {
self.failures.extend([
Failure::Api(ApiError::Invalid),
Failure::Api(ApiError::Forbidden),
]);
}
let kind = match operation {
RequestOp::Header | RequestOp::Cookie => Type::Optional(Box::new(Type::Text)),
RequestOp::SecretCookie => Type::Optional(Box::new(Type::Secret)),
RequestOp::SetHeader | RequestOp::SetCookie | RequestOp::SetSecretCookie => Type::Unit,
_ => Type::Text,
};
Ok(Some(Self::node(
ExpressionKind::Builtin(Builtin::Request(operation), values),
kind,
span,
)))
}
pub(super) fn session(
&mut self,
name: &str,
arguments: &[ast::Expression],
span: Span,
) -> Result<Option<Expression>, Diagnostic> {
let operation = match name {
"dever.auth.issue" => SessionOp::Issue,
"dever.auth.issueCookie" => SessionOp::IssueCookie,
"dever.auth.clearCookie" => SessionOp::ClearCookie,
_ => return Ok(None),
};
let inputs = if operation == SessionOp::ClearCookie {
vec![]
} else {
vec![Type::Text, Type::Text, Type::Optional(Box::new(Type::Text))]
};
if arguments.len() != inputs.len() {
return Err(Diagnostic::new(
"C005",
"session argument count differs",
span,
));
}
let values = arguments
.iter()
.zip(inputs)
.map(|(value, kind)| self.expression(value, Some(&kind)))
.collect::<Result<Vec<_>, _>>()?;
self.authorization_failures(span);
let kind = if operation == SessionOp::Issue {
Type::Secret
} else {
Type::Unit
};
Ok(Some(Self::node(
ExpressionKind::Builtin(Builtin::Session(operation), values),
kind,
span,
)))
}
fn authorization_failures(&mut self, span: Span) {
self.failures.extend(
[
ApiError::Invalid,
ApiError::Unauthorized,
ApiError::Forbidden,
ApiError::NotFound,
ApiError::Conflict,
]
.map(Failure::Api),
);
let error = self
.types
.named("dever.database.Error", span.source)
.expect("authorization database errors");
self.failures
.extend((0..10).map(|variant| Failure::Choice(error, variant)));
}
pub(super) fn authorization(
&mut self,
name: &str,
arguments: &[ast::Expression],
span: Span,
) -> Result<Option<Expression>, Diagnostic> {
use AuthOp::*;
use Type::{Bool, Int, List, Named, Optional, Text, Unit, Uuid};
let named = |name| {
Named(
self.types
.named(name, span.source)
.expect("bundled authorization type"),
)
};
let (operation, inputs, kind) = match name {
"dever.auth.permissions" => (
Permissions,
vec![],
List(Box::new(named("dever.auth.Permission"))),
),
"dever.auth.currentPermissions" => (
CurrentPermissions,
vec![],
List(Box::new(named("dever.auth.Permission"))),
),
"dever.auth.roles" => (Roles, vec![], List(Box::new(named("dever.auth.Role")))),
"dever.auth.role" => (
Role,
vec![Text],
Optional(Box::new(named("dever.auth.Role"))),
),
"dever.auth.userRoles" => (
UserRoles,
vec![Int],
List(Box::new(named("dever.auth.Role"))),
),
"dever.auth.hasProtectedRoles" | "dever.auth.isOwner" => {
(HasProtectedRoles, vec![Int], Bool)
}
"dever.auth.saveRole" => (SaveRole, vec![Text, Text, Bool, List(Box::new(Text))], Unit),
"dever.auth.grantRole" => (GrantRole, vec![Int, Text], Unit),
"dever.auth.revokeRole" => (RevokeRole, vec![Int, Text], Unit),
"dever.auth.disableRole" => (DisableRole, vec![Text], Unit),
"dever.auth.deleteRole" => (DeleteRole, vec![Text], Unit),
"dever.auth.registerCapability" => (RegisterCapability, vec![Uuid], Text),
"dever.auth.removeCapability" => (RemoveCapability, vec![Uuid], Unit),
_ => return Ok(None),
};
if arguments.len() != inputs.len() {
return Err(Diagnostic::new(
"C005",
"authorization argument count differs",
span,
));
}
let values = arguments
.iter()
.zip(inputs)
.enumerate()
.map(|(index, (value, kind))| {
if index == 0 && operation.user_argument() {
let checked = self.expression(value, None)?;
if !matches!(checked.value_type, Type::Int | Type::ModelId(_)) {
return Err(Diagnostic::new(
"C005",
"user reference must be Int or a nominal Model ID",
value.span,
));
}
Ok(checked)
} else {
self.expression(value, Some(&kind))
}
})
.collect::<Result<Vec<_>, _>>()?;
self.authorization_failures(span);
Ok(Some(Self::node(
ExpressionKind::Builtin(Builtin::Authorization(operation), values),
kind,
span,
)))
}
pub(super) fn identity(
&self,
name: &str,
arguments: &[ast::Expression],
expected: Option<&Type>,
span: Span,
) -> Result<Option<Expression>, Diagnostic> {
let operation = match name {
"dever.auth.id" => IdentityOp::Id,
"dever.auth.session" => IdentityOp::Session,
"dever.auth.userId" | "dever.auth.tenantId" => {
let Some(Type::Optional(inner)) = expected else {
return Err(Diagnostic::new(
"C005",
"identity ID requires a declared optional Model ID",
span,
));
};
let Type::ModelId(source) = inner.as_ref() else {
return Err(Diagnostic::new(
"C005",
"identity ID must use a nominal Model ID",
span,
));
};
if name == "dever.auth.userId" {
IdentityOp::User(*source)
} else {
IdentityOp::Tenant(*source)
}
}
_ => return Ok(None),
};
if !arguments.is_empty() {
return Err(Diagnostic::new(
"C005",
"identity reads take no arguments",
span,
));
}
let kind = match operation {
IdentityOp::Id | IdentityOp::Session => Type::Text,
IdentityOp::User(source) | IdentityOp::Tenant(source) => {
Type::Optional(Box::new(Type::ModelId(source)))
}
};
Ok(Some(Self::node(
ExpressionKind::Builtin(Builtin::Identity(operation), vec![]),
kind,
span,
)))
}
}
+236
View File
@@ -0,0 +1,236 @@
//! 共享的具体表达式检查;结果格和普通语句使用同一调用、类型与范围合同。
mod capture;
mod construct;
mod database;
mod expression;
mod identity;
mod numeric;
mod operators;
mod primitive;
pub(super) mod task;
mod testing;
use super::{calls::Calls, types::Types};
use crate::compiler::model::*;
use crate::syntax::{ast, diagnostic::Diagnostic, source::Span};
use std::collections::{BTreeSet, HashMap};
pub(super) struct Checker<'a> {
pub test_settings: bool,
pub setting_references: Vec<(usize, Span)>,
pub allow_settings: bool,
pub constants: &'a super::constants::Constants<'a>,
pub constant_references: Vec<(usize, Span)>,
pub caller: usize,
pub unknown_failures: bool,
pub types: &'a Types<'a>,
pub calls: &'a Calls<'a>,
pub functions: &'a [Option<Function>],
pub locals: Vec<Field>,
pub names: HashMap<String, usize>,
pub ranges: HashMap<usize, numeric::Range>,
pub failures: BTreeSet<Failure>,
pub bools: HashMap<usize, bool>,
pub variants: HashMap<usize, BTreeSet<usize>>,
pub contracts: HashMap<String, Field>,
}
impl Checker<'_> {
pub(super) fn sensitive(&self, kind: &Type) -> bool {
sensitive(kind, &self.types.definitions, |index| {
&self.functions[index]
.as_ref()
.expect("checked callee")
.signature
.outputs
})
}
pub fn expression(
&mut self,
value: &ast::Expression,
expected: Option<&Type>,
) -> Result<Expression, Diagnostic> {
let expression = self.raw(value, expected)?;
match expected {
Some(expected) => Self::coerce(expression, expected),
None => Ok(expression),
}
}
pub fn field_value(
&mut self,
value: &ast::Expression,
field: &Field,
) -> Result<Expression, Diagnostic> {
let expression = self.expression(value, Some(&field.kind))?;
if expression.value_type != Type::Never
&& let Some(required) = field.range
&& !expression
.range
.is_some_and(|actual| required.contains(actual))
{
return Err(Diagnostic::new(
"C008",
format!(
"cannot prove numeric range for {}; narrow it with check or rule",
field.name
),
value.span,
));
}
Ok(expression)
}
pub fn coerce(value: Expression, expected: &Type) -> Result<Expression, Diagnostic> {
if &value.value_type == expected || value.value_type == Type::Never {
return Ok(value);
}
let span = value.span;
let range = value.range;
if value.value_type == Type::Int && *expected == Type::Decimal {
let range = range.map(|range| {
let convert = |number| {
let numeric::Number::Int(value) = number else {
unreachable!()
};
numeric::Number::Decimal(dec::Decimal128::from(value))
};
numeric::Range {
minimum: convert(range.minimum),
maximum: convert(range.maximum),
}
});
return Ok(Expression {
kind: ExpressionKind::DecimalFromInt(Box::new(value)),
value_type: Type::Decimal,
range,
known_bool: None,
span,
});
}
if let Type::Optional(inner) = expected {
if value.value_type == Type::Null {
return Ok(Expression {
kind: ExpressionKind::Null,
value_type: expected.clone(),
range: None,
known_bool: None,
span,
});
}
if !matches!(value.value_type, Type::Optional(_)) {
let value = Self::coerce(value, inner)?;
let range = value.range;
return Ok(Expression {
kind: ExpressionKind::Some(Box::new(value)),
value_type: expected.clone(),
range,
known_bool: None,
span,
});
}
}
Err(Diagnostic::new(
"C005",
format!("expected {expected:?}, got {:?}", value.value_type),
span,
))
}
pub fn error(&mut self, value: Expression) -> Result<Expression, Diagnostic> {
if let Type::Named(definition) = value.value_type
&& !matches!(value.kind, ExpressionKind::Variant(..))
&& let Shape::Choice(variants) = &self.types.definitions[definition].shape
{
let selected = match value.kind {
ExpressionKind::Variable(local) => self.variants.get(&local).cloned(),
_ => None,
}
.unwrap_or_else(|| (0..variants.len()).collect());
if !selected.is_empty() && selected.iter().all(|index| variants[*index].error) {
self.failures.extend(
selected
.into_iter()
.map(|variant| Failure::Choice(definition, variant)),
);
return Ok(value);
}
}
let failure = match value.kind {
ExpressionKind::ApiError(error) => Failure::Api(error),
ExpressionKind::Variant(definition, variant, _) => {
let Shape::Choice(variants) = &self.types.definitions[definition].shape else {
unreachable!()
};
if !variants[variant].error {
return Err(Diagnostic::new(
"C011",
"failure requires an error variant",
value.span,
));
}
Failure::Choice(definition, variant)
}
_ => {
return Err(Diagnostic::new(
"C011",
"failure requires a known error value",
value.span,
));
}
};
self.failures.insert(failure);
Ok(value)
}
pub fn variable(&self, local: usize, span: Span) -> Expression {
let field = &self.locals[local];
Expression {
kind: ExpressionKind::Variable(local),
value_type: field.kind.clone(),
range: self
.ranges
.get(&local)
.copied()
.or_else(|| field.guaranteed_range()),
known_bool: self.bools.get(&local).copied(),
span,
}
}
pub fn bind(
&mut self,
name: String,
value_type: Type,
range: Option<numeric::Range>,
known_bool: Option<bool>,
span: Span,
) -> usize {
let local = self.locals.len();
self.names.insert(name.clone(), local);
if let Some(value) = known_bool {
self.bools.insert(local, value);
}
self.locals.push(Field {
model: None,
name,
kind: value_type,
range,
private: false,
span,
});
local
}
fn node(kind: ExpressionKind, value_type: Type, span: Span) -> Expression {
Expression {
kind,
value_type,
range: None,
known_bool: None,
span,
}
}
}
+193
View File
@@ -0,0 +1,193 @@
//! 区间只用于静态事实;可能溢出时不编造范围,确定故障才在编译期拒绝。
pub(super) use crate::compiler::model::numeric::{Number, Range};
use crate::compiler::model::{Binary, Expression, ExpressionKind};
use crate::syntax::{diagnostic::Diagnostic, source::Span};
pub(super) fn negate(range: Option<Range>, span: Span) -> Result<Option<Range>, Diagnostic> {
let Some(range) = range else { return Ok(None) };
match (range.minimum, range.maximum) {
(Number::Int(minimum), Number::Int(maximum)) => {
integer_range(-(maximum as i128), -(minimum as i128), span).map(Some)
}
(Number::Decimal(minimum), Number::Decimal(maximum)) => {
let mut context = dec::Context::<dec::Decimal128>::default();
Ok(Some(Range {
minimum: Number::Decimal(context.minus(maximum)),
maximum: Number::Decimal(context.minus(minimum)),
}))
}
(Number::Float(_), Number::Float(_)) => Ok(None),
_ => unreachable!("one interval has one numeric type"),
}
}
pub(super) fn calculate(
operation: Binary,
left: Option<Range>,
right: Option<Range>,
span: Span,
) -> Result<Option<Range>, Diagnostic> {
let (Some(left), Some(right)) = (left, right) else {
return Ok(None);
};
if matches!(left.minimum, Number::Float(_)) {
return Ok(None);
}
if let (Number::Int(a), Number::Int(b), Number::Int(c), Number::Int(d)) =
(left.minimum, left.maximum, right.minimum, right.maximum)
{
return integer(operation, a as i128, b as i128, c as i128, d as i128, span).map(Some);
}
let zero = Number::Decimal(dec::Decimal128::ZERO);
if operation == Binary::Divide && right.minimum <= zero && right.maximum >= zero {
return if right.minimum == right.maximum {
Err(fault(span))
} else {
Ok(None)
};
}
let constant = left.minimum == left.maximum && right.minimum == right.maximum;
let mut values = Vec::with_capacity(4);
for left in [left.minimum, left.maximum] {
for right in [right.minimum, right.maximum] {
let Some(value) = apply(operation, left, right) else {
return if constant { Err(fault(span)) } else { Ok(None) };
};
values.push(value);
}
}
values.sort_by(|a, b| a.partial_cmp(b).expect("finite numbers of the same type"));
Ok(Some(Range {
minimum: values[0],
maximum: values[3],
}))
}
// 用宽整数计算数学区间,再取成功结果与 Int 值域的交集;运行故障不会成为成功值。
fn integer_range(minimum: i128, maximum: i128, span: Span) -> Result<Range, Diagnostic> {
let minimum = minimum.max(i64::MIN as i128);
let maximum = maximum.min(i64::MAX as i128);
if minimum > maximum {
return Err(fault(span));
}
Ok(Range {
minimum: Number::Int(minimum as i64),
maximum: Number::Int(maximum as i64),
})
}
fn integer(
operation: Binary,
a: i128,
b: i128,
c: i128,
d: i128,
span: Span,
) -> Result<Range, Diagnostic> {
let (minimum, maximum) = match operation {
Binary::Add => (a + c, b + d),
Binary::Subtract => (a - d, b - c),
Binary::Multiply => {
let values = [a * c, a * d, b * c, b * d];
(*values.iter().min().unwrap(), *values.iter().max().unwrap())
}
Binary::Quotient | Binary::Remainder => {
if c == 0 && d == 0 || a == b && a == i64::MIN as i128 && c == -1 && d == -1 {
return Err(fault(span));
}
if operation == Binary::Remainder {
if a == b && c == d {
(a % c, a % c)
} else {
let magnitude = c.abs().max(d.abs()) - 1;
(a.min(0).max(-magnitude), b.max(0).min(magnitude))
}
} else {
let mut divisors = vec![c, d];
if c <= -1 && d >= -1 {
divisors.push(-1);
}
if c <= 1 && d >= 1 {
divisors.push(1);
}
let values = divisors
.into_iter()
.filter(|value| *value != 0)
.flat_map(|value| [a / value, b / value])
.collect::<Vec<_>>();
(*values.iter().min().unwrap(), *values.iter().max().unwrap())
}
}
_ => unreachable!("checked integer operator"),
};
integer_range(minimum, maximum, span)
}
fn apply(operation: Binary, left: Number, right: Number) -> Option<Number> {
match (left, right) {
(Number::Decimal(left), Number::Decimal(right)) => {
let mut context = dec::Context::<dec::Decimal128>::default();
let value = match operation {
Binary::Add => context.add(left, right),
Binary::Subtract => context.sub(left, right),
Binary::Multiply => context.mul(left, right),
Binary::Divide => context.div(left, right),
_ => unreachable!("checked Decimal operator"),
};
(value.is_finite() && !context.status().invalid_operation())
.then_some(Number::Decimal(value))
}
_ => unreachable!("checked numeric operands"),
}
}
pub(super) fn compare(operation: Binary, left: &Expression, right: &Expression) -> Option<bool> {
if let (Some(left), Some(right)) = (left.known_bool, right.known_bool) {
return Some(ordering(operation, left.cmp(&right)));
}
if let (ExpressionKind::Text(left), ExpressionKind::Text(right)) = (&left.kind, &right.kind) {
return Some(ordering(operation, left.cmp(right)));
}
let (Some(left), Some(right)) = (left.range, right.range) else {
return None;
};
match operation {
Binary::Equal | Binary::NotEqual => {
let equal = if left.minimum == left.maximum && right.minimum == right.maximum {
Some(left.minimum == right.minimum)
} else if left.maximum < right.minimum || right.maximum < left.minimum {
Some(false)
} else {
None
};
equal.map(|equal| equal == (operation == Binary::Equal))
}
Binary::Less if left.maximum < right.minimum => Some(true),
Binary::Less if left.minimum >= right.maximum => Some(false),
Binary::LessEqual if left.maximum <= right.minimum => Some(true),
Binary::LessEqual if left.minimum > right.maximum => Some(false),
Binary::Greater if left.minimum > right.maximum => Some(true),
Binary::Greater if left.maximum <= right.minimum => Some(false),
Binary::GreaterEqual if left.minimum >= right.maximum => Some(true),
Binary::GreaterEqual if left.maximum < right.minimum => Some(false),
_ => None,
}
}
fn ordering(operation: Binary, order: std::cmp::Ordering) -> bool {
use std::cmp::Ordering::*;
match operation {
Binary::Equal => order == Equal,
Binary::NotEqual => order != Equal,
Binary::Less => order == Less,
Binary::LessEqual => order != Greater,
Binary::Greater => order == Greater,
Binary::GreaterEqual => order != Less,
_ => unreachable!("comparison operator"),
}
}
fn fault(span: Span) -> Diagnostic {
Diagnostic::new("C008", "this arithmetic operation always faults", span)
}
+410
View File
@@ -0,0 +1,410 @@
//! 运算符在这里决定具体输入和输出类型,生成器不重新推断数值提升。
use super::{Checker, numeric};
use crate::compiler::model::*;
use crate::syntax::{ast, diagnostic::Diagnostic, source::Span};
impl Checker<'_> {
pub(super) fn unary(
&mut self,
operator: &str,
value: &ast::Expression,
expected: Option<&Type>,
span: Span,
) -> Result<Expression, Diagnostic> {
if operator == "-"
&& let ast::ExpressionKind::Literal(ast::Literal::Number(text)) = &value.kind
{
let kind = match expected {
Some(Type::Decimal) => Type::Decimal,
Some(Type::Float) => Type::Float,
_ => numeric::Number::literal_type(text),
};
let value = numeric::Number::parse(&format!("-{text}"), &kind)
.map_err(|message| Diagnostic::new("C008", message, span))?;
return Ok(Expression {
kind: ExpressionKind::Number(value),
value_type: kind,
range: Some(numeric::Range::point(value)),
known_bool: None,
span,
});
}
let value = self.expression(
value,
if operator == "not" {
Some(&Type::Bool)
} else {
expected
},
)?;
let (operation, range, known_bool) = match (operator, &value.value_type) {
("not", Type::Bool) => (Unary::Not, None, value.known_bool.map(|value| !value)),
("-", Type::Int | Type::Decimal | Type::Float) => {
(Unary::Negate, numeric::negate(value.range, span)?, None)
}
_ => return Err(Diagnostic::new("C005", "invalid unary operand type", span)),
};
let kind = value.value_type.clone();
Ok(Expression {
kind: ExpressionKind::Unary(operation, Box::new(value)),
value_type: kind,
range,
known_bool,
span,
})
}
pub(super) fn binary(
&mut self,
operator: &str,
left: &ast::Expression,
right: &ast::Expression,
expected: Option<&Type>,
span: Span,
) -> Result<Expression, Diagnostic> {
let operation = match operator {
"+" => Binary::Add,
"-" => Binary::Subtract,
"*" => Binary::Multiply,
"/" => Binary::Divide,
"//" => Binary::Quotient,
"%" => Binary::Remainder,
"==" => Binary::Equal,
"!=" => Binary::NotEqual,
"<" => Binary::Less,
"<=" => Binary::LessEqual,
">" => Binary::Greater,
">=" => Binary::GreaterEqual,
"and" => Binary::And,
"or" => Binary::Or,
_ => unreachable!("parsed operator"),
};
let logical = matches!(operation, Binary::And | Binary::Or);
let comparison = matches!(
operation,
Binary::Equal
| Binary::NotEqual
| Binary::Less
| Binary::LessEqual
| Binary::Greater
| Binary::GreaterEqual
);
let context = if logical {
Some(&Type::Bool)
} else if matches!(operation, Binary::Quotient | Binary::Remainder) {
Some(&Type::Int)
} else if comparison {
None
} else {
expected.filter(|kind| matches!(kind, Type::Int | Type::Decimal | Type::Float))
};
let (mut left, mut right) = self.binary_values(comparison, context, left, right)?;
let null_comparison =
matches!(left.kind, ExpressionKind::Null) || matches!(right.kind, ExpressionKind::Null);
if comparison
&& !null_comparison
&& (self.sensitive(&left.value_type) || self.sensitive(&right.value_type))
{
return Err(Diagnostic::new("C005", "Secret cannot be compared", span));
}
if comparison
&& !null_comparison
&& resource(&left.value_type, &self.types.definitions, |index| {
&self.functions[index].as_ref().unwrap().signature.outputs
})
{
return Err(Diagnostic::new(
"C005",
"resource handles cannot be compared",
span,
));
}
let mut known = None;
if matches!(operation, Binary::Equal | Binary::NotEqual) {
if left.value_type == Type::Null && right.value_type == Type::Null {
let mut value = Self::node(
ExpressionKind::Bool(operation == Binary::Equal),
Type::Bool,
span,
);
value.known_bool = Some(operation == Binary::Equal);
return Ok(value);
}
let null =
matches!(left.value_type, Type::Null) || matches!(right.value_type, Type::Null);
let optional = matches!(left.value_type, Type::Optional(_))
|| matches!(right.value_type, Type::Optional(_));
if null && !optional {
known = Some(
(left.value_type == Type::Null && right.value_type == Type::Null)
== (operation == Binary::Equal),
);
}
let common = match (&left.value_type, &right.value_type) {
(Type::Optional(inner), kind) | (kind, Type::Optional(inner))
if **inner == *kind || *kind == Type::Null =>
{
Some(Type::Optional(inner.clone()))
}
(Type::Null, kind) | (kind, Type::Null) if *kind != Type::Null => {
Some(Type::Optional(Box::new(kind.clone())))
}
_ => None,
};
if let Some(kind) = common {
left = Self::coerce(left, &kind)?;
right = Self::coerce(right, &kind)?;
}
}
if matches!(
(&left.value_type, &right.value_type),
(Type::Int, Type::Decimal) | (Type::Decimal, Type::Int)
) || (operation == Binary::Divide
&& left.value_type == Type::Int
&& right.value_type == Type::Int)
{
left = Self::coerce(left, &Type::Decimal)?;
right = Self::coerce(right, &Type::Decimal)?;
}
if left.value_type != right.value_type {
return Err(Diagnostic::new(
"C005",
"binary operands have different types",
span,
));
}
let kind = &left.value_type;
let numeric = matches!(kind, Type::Int | Type::Decimal | Type::Float);
let valid = match operation {
Binary::And | Binary::Or => *kind == Type::Bool,
Binary::Equal | Binary::NotEqual => {
!matches!(kind, Type::Unit | Type::Never | Type::ApiError)
}
Binary::Less | Binary::LessEqual | Binary::Greater | Binary::GreaterEqual => {
numeric
|| matches!(
kind,
Type::Text
| Type::Bool
| Type::ModelId(_)
| Type::DateTime
| Type::Date
| Type::Time
| Type::Duration
)
}
Binary::Quotient | Binary::Remainder => *kind == Type::Int,
Binary::Add => numeric || *kind == Type::Text,
_ => numeric,
};
if !valid {
return Err(Diagnostic::new(
"C005",
"operator is not defined for these operands",
span,
));
}
let value_type = if comparison || logical {
Type::Bool
} else {
kind.clone()
};
let range = if !comparison && !logical && numeric {
numeric::calculate(operation, left.range, right.range, span)?
} else {
None
};
if logical {
known = match (operation, left.known_bool, right.known_bool) {
(Binary::And, Some(false), _) | (Binary::And, _, Some(false)) => Some(false),
(Binary::Or, Some(true), _) | (Binary::Or, _, Some(true)) => Some(true),
(_, Some(left), Some(right)) => Some(if operation == Binary::And {
left && right
} else {
left || right
}),
_ => None,
};
} else if comparison && known.is_none() {
known = numeric::compare(operation, &left, &right);
}
Ok(Expression {
kind: ExpressionKind::Binary(operation, Box::new(left), Box::new(right)),
value_type,
range,
known_bool: known,
span,
})
}
fn binary_values(
&mut self,
comparison: bool,
context: Option<&Type>,
left: &ast::Expression,
right: &ast::Expression,
) -> Result<(Expression, Expression), Diagnostic> {
// 短分支名在左侧时从右侧类型取得上下文;只改变检查顺序,不改变 IR 求值顺序。
let short_left = comparison
&& matches!(&left.kind, ast::ExpressionKind::Name(name)
if name.chars().next().is_some_and(char::is_uppercase)
&& !self.names.contains_key(name));
let checked_right = if short_left {
Some(self.expression(right, None)?)
} else {
None
};
let left = self.expression(
left,
checked_right
.as_ref()
.map(|value| &value.value_type)
.or(context),
)?;
// 已知类型提供 choice 短名的上下文;不同数值类型的提升仍在下方统一决定。
let hint = if comparison
&& !matches!(right.kind, ast::ExpressionKind::Literal(ast::Literal::Null))
&& matches!(left.value_type, Type::Named(_) | Type::Optional(_))
{
Some(&left.value_type)
} else {
context
};
let right = match checked_right {
Some(value) => value,
None => self.expression(right, hint)?,
};
Ok((left, right))
}
pub(super) fn builtin(
&mut self,
name: &str,
arguments: &[ast::Expression],
expected: Option<&Type>,
span: Span,
) -> Result<Expression, Diagnostic> {
if matches!(
name,
"dever.system.timeNow"
| "dever.system.timeSleep"
| "dever.system.timeUnixMillis"
| "dever.system.timeMonotonicNanos"
) {
return self.clock(name, arguments, span);
}
if name.starts_with("dever.system.time") {
return self.calendar(name, arguments, span);
}
if name.starts_with("dever.system.json") {
return self.json(name, arguments, span);
}
if name.starts_with("dever.system.bytes") {
return self.bytes(name, arguments, span);
}
if name.starts_with("dever.system.") {
return self.standard(name, arguments, span);
}
let (operation, count) = match name {
"length" => (Builtin::Length, 1),
"append" => (Builtin::Append, 2),
"get" => (Builtin::Get, 2),
"contains" => (Builtin::Contains, 2),
"put" => (Builtin::Put, 3),
"remove" => (Builtin::Remove, 2),
"entries" => (Builtin::Entries, 1),
_ => {
return Err(Diagnostic::new(
"C004",
format!("unknown call {name}"),
span,
));
}
};
if arguments.len() != count {
return Err(Diagnostic::new(
"C005",
"builtin argument count differs",
span,
));
}
// 返回同种集合的操作沿用调用处合同,空集合无需额外局部标注或包装函数。
let context = expected.filter(|kind| {
matches!(
(&operation, kind),
(Builtin::Append, Type::List(_))
| (Builtin::Put | Builtin::Remove, Type::Map(_, _))
)
});
let collection = self.expression(&arguments[0], context)?;
if operation == Builtin::Contains
&& resource(&collection.value_type, &self.types.definitions, |index| {
&self.functions[index].as_ref().unwrap().signature.outputs
})
{
return Err(Diagnostic::new(
"C005",
"resource handles cannot be compared by contains",
span,
));
}
if operation == Builtin::Contains && self.sensitive(&collection.value_type) {
return Err(Diagnostic::new(
"C005",
"Secret cannot be compared by contains",
span,
));
}
let (kind, argument) = match (&operation, &collection.value_type) {
(Builtin::Length, Type::Text | Type::Bytes | Type::List(_) | Type::Map(_, _)) => {
(Type::Int, None)
}
(Builtin::Append, Type::List(item)) => {
(collection.value_type.clone(), Some(item.as_ref().clone()))
}
(Builtin::Contains, Type::List(item)) => (Type::Bool, Some(item.as_ref().clone())),
(Builtin::Get, Type::List(item)) => (Type::Optional(item.clone()), Some(Type::Int)),
(Builtin::Get, Type::Map(key, value)) => {
(Type::Optional(value.clone()), Some(key.as_ref().clone()))
}
(Builtin::Entries, Type::Map(key, value)) => (
Type::List(Box::new(Type::MapEntry(key.clone(), value.clone()))),
None,
),
(Builtin::Put | Builtin::Remove, Type::Map(key, _)) => {
(collection.value_type.clone(), Some(key.as_ref().clone()))
}
_ => {
return Err(Diagnostic::new(
"C005",
"builtin does not accept this type",
span,
));
}
};
let kind = match kind {
Type::Optional(inner) if matches!(inner.as_ref(), Type::Optional(_)) => *inner,
other => other,
};
let mut values = vec![collection];
if let Some(kind) = argument {
values.push(self.expression(&arguments[1], Some(&kind))?);
}
if operation == Builtin::Put {
let Type::Map(_, value) = &kind else {
unreachable!()
};
values.push(self.expression(&arguments[2], Some(value))?);
}
let length = operation == Builtin::Length;
let mut expression = Self::node(ExpressionKind::Builtin(operation, values), kind, span);
if length {
expression.range = Some(crate::compiler::model::numeric::Range {
minimum: crate::compiler::model::numeric::Number::Int(0),
maximum: crate::compiler::model::numeric::Number::Int(i64::MAX),
});
}
Ok(expression)
}
}
@@ -0,0 +1,64 @@
//! 字节原语只供随包库适配;应用沿用具名库函数及普通错误合同。
use super::*;
impl Checker<'_> {
pub(in crate::compiler::check::value) fn bytes(
&mut self,
name: &str,
arguments: &[ast::Expression],
span: Span,
) -> Result<Expression, Diagnostic> {
if !self.types.module(span.source).bundled_library() {
return Err(Diagnostic::new(
"C003",
"system primitives belong to the bundled library",
span,
));
}
let (operation, inputs, output) = match name {
"dever.system.bytesFromText" => (Builtin::BytesFromText, vec![Type::Text], Type::Bytes),
"dever.system.bytesToText" => (
Builtin::BytesToText,
vec![Type::Bytes],
Type::Named(self.types.named("DecodeResult", span.source).unwrap()),
),
"dever.system.bytesFromBase64" => (
Builtin::BytesFromBase64,
vec![Type::Text],
Type::Named(self.types.named("BufferResult", span.source).unwrap()),
),
"dever.system.bytesFromInts" => (
Builtin::BytesFromInts,
vec![Type::List(Box::new(Type::Int))],
Type::Named(self.types.named("BufferResult", span.source).unwrap()),
),
"dever.system.bytesLength" => (Builtin::Length, vec![Type::Bytes], Type::Int),
"dever.system.bytesAt" => (
Builtin::BytesAt,
vec![Type::Bytes, Type::Int],
Type::Optional(Box::new(Type::Int)),
),
"dever.system.bytesSlice" => (
Builtin::BytesSlice,
vec![Type::Bytes, Type::Int, Type::Int],
Type::Named(self.types.named("BufferResult", span.source).unwrap()),
),
"dever.system.bytesConcat" => (
Builtin::BytesConcat,
vec![Type::Bytes, Type::Bytes],
Type::Bytes,
),
_ => return Err(Diagnostic::new("C004", "unknown bytes primitive", span)),
};
let length = operation == Builtin::Length;
let mut value = self.primitive(operation, arguments, inputs, output, span)?;
if length {
value.range = Some(numeric::Range {
minimum: numeric::Number::Int(0),
maximum: numeric::Number::Int(i64::MAX),
});
}
Ok(value)
}
}
@@ -0,0 +1,63 @@
//! 日历的错误选择由随包 rule 处理;原语只绑定具体输入与返回类型。
use super::*;
impl Checker<'_> {
pub(in crate::compiler::check::value) fn calendar(
&mut self,
name: &str,
arguments: &[ast::Expression],
span: Span,
) -> Result<Expression, Diagnostic> {
if !self.types.module(span.source).bundled_library() {
return Err(Diagnostic::new(
"C003",
"system primitives belong to the bundled library",
span,
));
}
let named = |name| {
Type::Named(
self.types
.named(name, span.source)
.expect("bundled calendar result"),
)
};
use CalendarOp::*;
let (operation, inputs, output) = match name {
"dever.system.timeParseDatetime" => {
(ParseDatetime, vec![Type::Text], named("DateTimeResult"))
}
"dever.system.timeFormatDatetime" => {
(FormatDatetime, vec![Type::DateTime], named("TextResult"))
}
"dever.system.timeParseDate" => (ParseDate, vec![Type::Text], named("DateResult")),
"dever.system.timeFormatDate" => (FormatDate, vec![Type::Date], Type::Text),
"dever.system.timeParseTime" => (ParseTime, vec![Type::Text], named("TimeResult")),
"dever.system.timeFormatTime" => (FormatTime, vec![Type::Time], Type::Text),
"dever.system.timeDuration" => (Duration, vec![Type::Int], Type::Duration),
"dever.system.timeAdd" => (
Add,
vec![Type::DateTime, Type::Duration],
named("DateTimeResult"),
),
"dever.system.timeSubtract" => (
Subtract,
vec![Type::DateTime, Type::Duration],
named("DateTimeResult"),
),
"dever.system.timeDifference" => (
Difference,
vec![Type::DateTime, Type::DateTime],
named("DurationResult"),
),
_ => return Err(Diagnostic::new("C004", "unknown calendar primitive", span)),
};
self.primitive(
Builtin::Calendar(operation),
arguments,
inputs,
output,
span,
)
}
}
@@ -0,0 +1,32 @@
//! 时钟原语只属于随包库;业务仍调用可导航的 flow,效果不靠函数名字猜测。
use super::*;
impl Checker<'_> {
pub(in crate::compiler::check::value) fn clock(
&mut self,
name: &str,
arguments: &[ast::Expression],
span: Span,
) -> Result<Expression, Diagnostic> {
if !self.types.module(span.source).bundled_library() {
return Err(Diagnostic::new(
"C003",
"system primitives belong to the bundled library",
span,
));
}
let (operation, inputs, output) = match name {
"dever.system.timeNow" => (ClockOp::Now, vec![], "DateTimeResult"),
"dever.system.timeSleep" => (ClockOp::Sleep, vec![Type::Int], "SleepResult"),
"dever.system.timeUnixMillis" => (ClockOp::UnixMillis, vec![], "ClockResult"),
"dever.system.timeMonotonicNanos" => (ClockOp::MonotonicNanos, vec![], "ClockResult"),
_ => unreachable!("resolved clock primitive"),
};
let output = Type::Named(
self.types
.named(output, span.source)
.expect("bundled clock result"),
);
self.primitive(Builtin::Clock(operation), arguments, inputs, output, span)
}
}
@@ -0,0 +1,285 @@
//! I/O 操作绑定随包结果类型;资源和系统状态只在运行库持有。
use super::*;
impl Checker<'_> {
pub(super) fn websocket(
&mut self,
name: &str,
arguments: &[ast::Expression],
span: Span,
) -> Result<Expression, Diagnostic> {
use StandardOp::*;
use Type::*;
let named = |name: &str| {
Named(
self.types
.named(name, span.source)
.expect("bundled WebSocket type"),
)
};
let limits = named("dever.websocket.Limits");
let message = named("dever.websocket.Message");
let (operation, inputs, output) = match name {
"dever.system.wsConnect" => (
WsConnect,
vec![Text, Int, Text, limits],
named("dever.websocket.ConnectResult"),
),
"dever.system.wsOpen" => (
WsOpen,
vec![Text, ClientTls, limits],
named("dever.websocket.ConnectResult"),
),
"dever.system.wsAccept" => (
WsAccept,
vec![HttpReply, limits],
named("dever.websocket.ConnectResult"),
),
"dever.system.wsSend" => (
WsSend,
vec![WebSocket, message],
named("dever.io.WriteResult"),
),
"dever.system.wsReceive" => (
WsReceive,
vec![WebSocket],
named("dever.websocket.SystemReceiveResult"),
),
"dever.system.wsMessages" => (
WsMessages,
vec![WebSocket],
AsyncStream(Box::new(named("dever.websocket.MessageEvent"))),
),
"dever.system.wsClose" => (
WsClose,
vec![WebSocket, Int, Text],
named("dever.io.CloseResult"),
),
_ => return Err(Diagnostic::new("C004", "unknown WebSocket primitive", span)),
};
self.primitive(
Builtin::Standard(operation),
arguments,
inputs,
output,
span,
)
}
pub(super) fn http_serve(
&mut self,
tls: bool,
live: bool,
arguments: &[ast::Expression],
span: Span,
) -> Result<Expression, Diagnostic> {
if arguments.len() != 3 + usize::from(tls) + usize::from(live) {
return Err(Diagnostic::new(
"C005",
"HTTP serve argument count differs",
span,
));
}
let edge = self.calls.by_span[&(self.caller, arguments[0].span)];
let target = self.calls.edges[edge].target;
let function = self.functions[target]
.as_ref()
.expect("checked HTTP handler");
if function.effects.identity || function.effects.session || function.effects.request {
return Err(Diagnostic::new(
"C013",
"raw HTTP handlers have no verified API identity or automatic request context",
arguments[0].span,
));
}
if function.effects.blocking || function.effects.output {
return Err(Diagnostic::new(
"C013",
"HTTP handlers cannot block the executor or write stdout",
arguments[0].span,
));
}
let limits = self
.types
.named("dever.http.Limits", span.source)
.expect("bundled HTTP limits");
let result = self
.types
.named("dever.http.ServeResult", span.source)
.expect("bundled HTTP serve result");
let mut inputs = vec![Type::Listener, Type::Named(limits)];
if live {
inputs.push(Type::Named(
self.types
.named("dever.http.LiveLimits", span.source)
.expect("bundled live limits"),
));
}
if tls {
inputs.push(Type::ServerTls);
}
self.primitive(
Builtin::Standard(StandardOp::HttpServe { target, tls, live }),
&arguments[1..],
inputs,
Type::Named(result),
span,
)
}
pub(super) fn io(
&mut self,
name: &str,
arguments: &[ast::Expression],
span: Span,
) -> Result<Expression, Diagnostic> {
use StandardOp::*;
use Type::*;
let (operation, inputs, result) = match name {
"dever.system.fileOpen" => (FileOpen, vec![Text], "OpenResult"),
"dever.system.fileCreate" => (FileCreate, vec![Text], "OpenResult"),
"dever.system.fileRead" => (FileRead, vec![File, Int], "SystemReadResult"),
"dever.system.fileWrite" => (FileWrite, vec![File, Bytes], "WriteResult"),
"dever.system.stdoutPrintln" => (StdoutPrintln, vec![Text], "WriteResult"),
"dever.system.processArguments" => (ProcessArguments, vec![], "ArgumentsResult"),
"dever.system.tlsClient" => (TlsClient, vec![Bytes], "ClientResult"),
"dever.system.tlsServer" => (TlsServer, vec![Bytes, Bytes], "ServerResult"),
"dever.system.httpClient" => {
let limits = self
.types
.named("dever.http.Limits", span.source)
.expect("bundled HTTP limits");
let pool = self
.types
.named("dever.http.PoolLimits", span.source)
.expect("bundled pool limits");
(
StandardOp::HttpClient,
vec![Text, ClientTls, Named(limits), Named(pool)],
"ClientResult",
)
}
"dever.system.httpCloseClient" => (
HttpCloseClient,
vec![Type::HttpClient],
"dever.io.CloseResult",
),
"dever.system.httpSend"
| "dever.system.httpRequest"
| "dever.system.httpOpen"
| "dever.system.httpOpenStream" => {
let streaming = name.ends_with("httpOpenStream");
let request = self
.types
.named(
if streaming {
"dever.http.StreamRequest"
} else {
"dever.http.Request"
},
span.source,
)
.expect("bundled HTTP request");
let limits = self
.types
.named("dever.http.Limits", span.source)
.expect("bundled HTTP limits");
if !name.ends_with("httpSend") {
(
if streaming {
HttpOpenStream
} else if name.ends_with("httpOpen") {
HttpOpen
} else {
HttpRequest
},
vec![Type::HttpClient, Named(request)],
if streaming || name.ends_with("httpOpen") {
"StreamResponseResult"
} else {
"ResponseResult"
},
)
} else {
(
HttpSend,
vec![Text, Int, Named(request), Named(limits)],
"ResponseResult",
)
}
}
"dever.system.httpRespond" => (
HttpRespond,
vec![
HttpReply,
Named(
self.types
.named("dever.http.Response", span.source)
.expect("bundled response"),
),
],
"dever.io.WriteResult",
),
"dever.system.httpStart" | "dever.system.sseStart" => {
let headers = List(Box::new(Named(
self.types
.named("dever.http.Header", span.source)
.expect("bundled header"),
)));
if name.ends_with("sseStart") {
(SseStart, vec![HttpReply, headers], "dever.io.WriteResult")
} else {
(
HttpStart,
vec![HttpReply, Int, headers],
"dever.io.WriteResult",
)
}
}
"dever.system.httpWrite" => (HttpWrite, vec![HttpReply, Bytes], "dever.io.WriteResult"),
"dever.system.httpFinish" => (HttpFinish, vec![HttpReply], "dever.io.WriteResult"),
"dever.system.sseSend" => (
SseSend,
vec![
HttpReply,
Named(
self.types
.named("dever.sse.Event", span.source)
.expect("bundled SSE event"),
),
],
"dever.io.WriteResult",
),
"dever.system.fileChunks" => (FileChunks, vec![File, Int], "ReadStreamResult"),
"dever.system.fileClose" => (FileClose, vec![File], "CloseResult"),
"dever.system.tcpConnect" => (TcpConnect, vec![Text, Int], "ConnectResult"),
"dever.system.tcpConnectTimeout" => {
(TcpConnectTimeout, vec![Text, Int, Int], "ConnectResult")
}
"dever.system.tcpListen" => (TcpListen, vec![Text, Int], "ListenResult"),
"dever.system.tcpAccept" => (TcpAccept, vec![Listener], "ConnectResult"),
"dever.system.tcpPort" => (TcpPort, vec![Listener], "PortResult"),
"dever.system.tcpRead" => (TcpRead, vec![Socket, Int], "dever.io.SystemReadResult"),
"dever.system.tcpWrite" => (TcpWrite, vec![Socket, Bytes], "dever.io.WriteResult"),
"dever.system.tcpTimeout" => (TcpTimeout, vec![Socket, Int], "dever.io.WriteResult"),
"dever.system.tcpClose" => (TcpClose, vec![Socket], "dever.io.CloseResult"),
"dever.system.tcpCloseListener" => {
(TcpCloseListener, vec![Listener], "dever.io.CloseResult")
}
"dever.system.tcpChunks" => (TcpChunks, vec![Socket, Int], "ReadStreamResult"),
"dever.system.tcpConnections" => (TcpConnections, vec![Listener], "ConnectResult"),
_ => return Err(Diagnostic::new("C004", "unknown I/O primitive", span)),
};
let kind = Named(
self.types
.named(result, span.source)
.expect("bundled I/O result"),
);
let kind = if operation == TcpConnections {
AsyncStream(Box::new(kind))
} else {
kind
};
self.primitive(Builtin::Standard(operation), arguments, inputs, kind, span)
}
}
@@ -0,0 +1,138 @@
//! JSON 原语仅做静态适配;错误处理仍由随包库中的普通 rule 承担。
use super::*;
impl Checker<'_> {
pub(in crate::compiler::check::value) fn decode_json(
&mut self,
arguments: &[ast::Expression],
expected: Option<&Type>,
span: Span,
propagate: bool,
) -> Result<Expression, Diagnostic> {
let [argument] = arguments else {
return Err(Diagnostic::new(
"C005",
"dever.json.decode requires one Json argument",
span,
));
};
let kind = expected.ok_or_else(|| {
Diagnostic::new(
"C005",
"dever.json.decode requires a concrete output type",
span,
)
})?;
crate::compiler::check::wire::collect_types(
kind,
&self.types.definitions,
span,
&mut BTreeSet::new(),
)?;
let error = self
.types
.named("dever.json.JsonResult", span.source)
.expect("bundled JSON error");
let value = self.expression(argument, Some(&Type::Json))?;
if propagate {
self.failures.insert(Failure::Choice(error, 1));
}
Ok(Self::node(
ExpressionKind::Builtin(Builtin::Json(JsonOp::Decode(error)), vec![value]),
kind.clone(),
span,
))
}
pub(in crate::compiler::check::value) fn json(
&mut self,
name: &str,
arguments: &[ast::Expression],
span: Span,
) -> Result<Expression, Diagnostic> {
if !self.types.module(span.source).bundled_library() {
return Err(Diagnostic::new(
"C003",
"system primitives belong to the bundled library",
span,
));
}
let named = |name| {
Type::Named(
self.types
.named(name, span.source)
.expect("bundled JSON type"),
)
};
let result = || named("JsonResult");
let (operation, inputs, output) = match name {
"dever.system.jsonKind" => (JsonOp::Kind, vec![Type::Json], named("Kind")),
"dever.system.jsonIsEmptyObject" => {
(JsonOp::IsEmptyObject, vec![Type::Json], Type::Bool)
}
"dever.system.jsonDocument" => (
JsonOp::Document,
vec![Type::Json],
named("dever.json.value.ParseResult"),
),
"dever.system.jsonElementValue" => (
JsonOp::ElementValue,
vec![Type::Json, Type::Int],
Type::Optional(Box::new(Type::Json)),
),
"dever.system.jsonFromText" => (JsonOp::FromText, vec![Type::Text], result()),
"dever.system.jsonToText" => (JsonOp::ToText, vec![Type::Json], Type::Text),
"dever.system.jsonAsText" => (JsonOp::AsText, vec![Type::Json], named("TextResult")),
"dever.system.jsonAsInteger" => {
(JsonOp::AsInteger, vec![Type::Json], named("IntResult"))
}
"dever.system.jsonProperty" => (
JsonOp::Property,
vec![Type::Json, Type::Text],
named("PropertyResult"),
),
"dever.system.jsonSetProperty" => (
JsonOp::SetProperty,
vec![Type::Json, Type::Text, Type::Json],
result(),
),
"dever.system.jsonString" => (JsonOp::String, vec![Type::Text], result()),
"dever.system.jsonInteger" => (JsonOp::Integer, vec![Type::Int], result()),
"dever.system.jsonBoolean" => (JsonOp::Boolean, vec![Type::Bool], result()),
"dever.system.jsonNull" => (JsonOp::Null, vec![], Type::Json),
"dever.system.jsonArray" => (
JsonOp::Array,
vec![Type::List(Box::new(Type::Json))],
result(),
),
"dever.system.jsonObject" => (
JsonOp::Object,
vec![Type::Map(Box::new(Type::Text), Box::new(Type::Json))],
result(),
),
"dever.system.jsonParse" => (
JsonOp::Parse,
vec![Type::Text],
named("dever.json.value.ParseResult"),
),
"dever.system.jsonStringify" => (
JsonOp::Stringify,
vec![named("dever.json.value.Document")],
named("dever.json.value.WriteResult"),
),
"dever.system.jsonDocumentProperty" => (
JsonOp::DocumentProperty,
vec![named("dever.json.value.Document"), Type::Int, Type::Text],
Type::Optional(Box::new(Type::Int)),
),
"dever.system.jsonElement" => (
JsonOp::Element,
vec![named("dever.json.value.Document"), Type::Int, Type::Int],
Type::Optional(Box::new(Type::Int)),
),
_ => return Err(Diagnostic::new("C004", "unknown JSON primitive", span)),
};
self.primitive(Builtin::Json(operation), arguments, inputs, output, span)
}
}
@@ -0,0 +1,39 @@
//! 随包库原语共用输入合同检查;业务代码调用有源码的标准函数。
mod bytes;
mod calendar;
mod clock;
mod io;
mod json;
mod resource;
mod standard;
use super::*;
impl Checker<'_> {
fn primitive(
&mut self,
operation: Builtin,
arguments: &[ast::Expression],
inputs: Vec<Type>,
output: Type,
span: Span,
) -> Result<Expression, Diagnostic> {
if arguments.len() != inputs.len() {
return Err(Diagnostic::new(
"C005",
"builtin argument count differs",
span,
));
}
let values = arguments
.iter()
.zip(inputs)
.map(|(value, kind)| self.expression(value, Some(&kind)))
.collect::<Result<_, _>>()?;
Ok(Self::node(
ExpressionKind::Builtin(operation, values),
output,
span,
))
}
}
@@ -0,0 +1,153 @@
//! 通道和流保留具体元素类型;共享身份与单次消费不转成普通值复制。
use super::*;
impl Checker<'_> {
pub(in crate::compiler::check::value) fn channel_new(
&mut self,
element: &ast::TypeRef,
capacity: &ast::Expression,
span: Span,
) -> Result<Expression, Diagnostic> {
if !element.bounds.is_empty() {
return Err(Diagnostic::new(
"C005",
"numeric constraints belong to a field or parameter",
element.span,
));
}
let element = self.types.reference(element)?;
let kind = Type::Channel(Box::new(element));
self.types.validate(&kind, span)?;
let capacity = self.expression(capacity, Some(&Type::Int))?;
Ok(Self::node(
ExpressionKind::Builtin(Builtin::Channel(ChannelOp::New), vec![capacity]),
kind,
span,
))
}
pub(in crate::compiler::check::value) fn channel_operation(
&mut self,
name: &str,
arguments: &[ast::Expression],
span: Span,
) -> Result<Expression, Diagnostic> {
let count = if name == "send" { 2 } else { 1 };
if arguments.len() != count {
return Err(Diagnostic::new(
"C005",
"invalid channel operation arguments",
span,
));
}
let channel = self.expression(&arguments[0], None)?;
if name == "close" && matches!(channel.value_type, Type::AsyncStream(_) | Type::Stream(_)) {
return Ok(Self::node(
ExpressionKind::Builtin(Builtin::Stream(StreamOp::Close), vec![channel]),
Type::Unit,
span,
));
}
if name == "close" && channel.value_type == Type::Upload {
return Ok(Self::node(
ExpressionKind::Builtin(Builtin::Standard(StandardOp::UploadClose), vec![channel]),
Type::Unit,
span,
));
}
let Type::Channel(element) = &channel.value_type else {
return Err(Diagnostic::new(
"C005",
"operation requires a Channel",
span,
));
};
let (op, kind, value) = match name {
"send" => (
ChannelOp::Send,
Type::Unit,
Some(self.expression(&arguments[1], Some(element))?),
),
"receive" => (
ChannelOp::Receive,
match element.as_ref() {
Type::Optional(_) => element.as_ref().clone(),
_ => Type::Optional(element.clone()),
},
None,
),
"close" => (ChannelOp::Close, Type::Unit, None),
_ => unreachable!("resolved channel operation"),
};
let mut values = vec![channel];
values.extend(value);
Ok(Self::node(
ExpressionKind::Builtin(Builtin::Channel(op), values),
kind,
span,
))
}
pub(in crate::compiler::check::value) fn stream(
&mut self,
arguments: &[ast::Expression],
expected: Option<&Type>,
span: Span,
) -> Result<Expression, Diagnostic> {
let [source] = arguments else {
return Err(Diagnostic::new(
"C005",
"stream requires one List, Bytes or Channel",
span,
));
};
let context = match expected {
Some(Type::AsyncStream(inner))
if matches!(source.kind, ast::ExpressionKind::List(_)) =>
{
Some(Type::List(inner.clone()))
}
_ => None,
};
let value = self.expression(source, context.as_ref())?;
let inner = match &value.value_type {
Type::List(inner) | Type::Channel(inner) => inner.clone(),
Type::Bytes => Box::new(Type::Int),
_ => {
return Err(Diagnostic::new(
"C005",
"stream requires a List, Bytes or Channel",
span,
));
}
};
let kind = Type::AsyncStream(inner);
self.types.validate(&kind, span)?;
Ok(Self::node(
ExpressionKind::Builtin(Builtin::Stream(StreamOp::New), vec![value]),
kind,
span,
))
}
pub(in crate::compiler::check::value) fn ticks(
&mut self,
arguments: &[ast::Expression],
span: Span,
) -> Result<Expression, Diagnostic> {
if !self.types.module(span.source).bundled_library() {
return Err(Diagnostic::new(
"C003",
"system primitives belong to the bundled library",
span,
));
}
self.primitive(
Builtin::Stream(StreamOp::Ticks),
arguments,
vec![Type::Int],
Type::AsyncStream(Box::new(Type::Int)),
span,
)
}
}
@@ -0,0 +1,153 @@
//! 文本和数值库仅绑定具体类型,执行交给 Rust 标准库与已有 Decimal 实现。
use super::*;
impl Checker<'_> {
pub(in crate::compiler::check::value) fn standard(
&mut self,
name: &str,
arguments: &[ast::Expression],
span: Span,
) -> Result<Expression, Diagnostic> {
if !self.types.module(span.source).bundled_library() {
return Err(Diagnostic::new(
"C003",
"system primitives belong to the bundled library",
span,
));
}
use StandardOp::*;
use Type::*;
if name.starts_with("dever.system.ws") {
return self.websocket(name, arguments, span);
}
if matches!(
name,
"dever.system.httpServe"
| "dever.system.httpServeTls"
| "dever.system.httpServeLive"
| "dever.system.httpServeLiveTls"
) {
return self.http_serve(
name.ends_with("Tls"),
name.contains("Live"),
arguments,
span,
);
}
if matches!(
name,
"dever.system.fileOpen"
| "dever.system.fileCreate"
| "dever.system.fileRead"
| "dever.system.fileWrite"
| "dever.system.fileClose"
| "dever.system.fileChunks"
| "dever.system.stdoutPrintln"
| "dever.system.processArguments"
| "dever.system.tlsClient"
| "dever.system.tlsServer"
| "dever.system.httpSend"
| "dever.system.httpClient"
| "dever.system.httpRequest"
| "dever.system.httpOpen"
| "dever.system.httpOpenStream"
| "dever.system.httpCloseClient"
| "dever.system.httpRespond"
| "dever.system.httpStart"
| "dever.system.httpWrite"
| "dever.system.httpFinish"
| "dever.system.sseStart"
| "dever.system.sseSend"
) || name.starts_with("dever.system.tcp")
{
return self.io(name, arguments, span);
}
let (operation, inputs, output) = match name {
"dever.system.uploadPut" | "dever.system.stageBytes" => (
if name.ends_with("stageBytes") {
StageBytes
} else {
UploadPut
},
vec![if name.ends_with("stageBytes") {
Bytes
} else {
Upload
}],
Named(
self.types
.named("PutResult", span.source)
.expect("bundled storage result"),
),
),
"dever.system.tlsSystem" => (TlsSystem, vec![], ClientTls),
"dever.system.cryptoToken"
| "dever.system.cryptoPasswordHash"
| "dever.system.cryptoPasswordVerify" => {
let (operation, inputs, result) = match name {
"dever.system.cryptoToken" => (Token, vec![Int], "TokenResult"),
"dever.system.cryptoPasswordHash" => (PasswordHash, vec![Secret], "HashResult"),
_ => (PasswordVerify, vec![Secret, Text], "VerifyResult"),
};
(
operation,
inputs,
Named(
self.types
.named(result, span.source)
.expect("bundled crypto result"),
),
)
}
"dever.system.cryptoSha256" => (Sha256, vec![Bytes], Bytes),
"dever.system.cryptoHmacSha256" => (HmacSha256, vec![Secret, Bytes], Bytes),
"dever.system.cryptoConstantTimeEq" => (ConstantTimeEq, vec![Bytes, Bytes], Bool),
"dever.system.idFromText" => (IdFromText, vec![Text], Id),
"dever.system.idToText" => (IdToText, vec![Id], Text),
"dever.system.uuidParse" => (UuidParse, vec![Text], Optional(Box::new(Uuid))),
"dever.system.uuidToText" => (UuidToText, vec![Uuid], Text),
"dever.system.textTrim" => (TextTrim, vec![Text], Text),
"dever.system.textLower" => (TextLower, vec![Text], Text),
"dever.system.textUpper" => (TextUpper, vec![Text], Text),
"dever.system.textCodepoint" => (TextCodepoint, vec![Text], Optional(Box::new(Int))),
"dever.system.textFromCodepoint" => {
(TextFromCodepoint, vec![Int], Optional(Box::new(Text)))
}
"dever.system.textAt" => (TextAt, vec![Text, Int], Optional(Box::new(Text))),
"dever.system.textSlice" => (TextSlice, vec![Text, Int, Int], Optional(Box::new(Text))),
"dever.system.textIndexOf" => (TextIndexOf, vec![Text, Text], Optional(Box::new(Int))),
"dever.system.textContains" => (TextContains, vec![Text, Text], Bool),
"dever.system.textStartsWith" => (TextStartsWith, vec![Text, Text], Bool),
"dever.system.textEndsWith" => (TextEndsWith, vec![Text, Text], Bool),
"dever.system.textSplit" => (TextSplit, vec![Text, Text], List(Box::new(Text))),
"dever.system.textReplace" => (TextReplace, vec![Text, Text, Text], Text),
"dever.system.textIsEmpty" => (TextIsEmpty, vec![Text], Bool),
"dever.system.textJoin" => (TextJoin, vec![List(Box::new(Text)), Text], Text),
"dever.system.intParse" => (IntParse, vec![Text], Optional(Box::new(Int))),
"dever.system.intToText" => (IntToText, vec![Int], Text),
"dever.system.floatFromInt" => (FloatFromInt, vec![Int], Float),
"dever.system.floatParse" => (FloatParse, vec![Text], Optional(Box::new(Float))),
"dever.system.floatToText" => (FloatToText, vec![Float], Text),
"dever.system.decimalRound" => (DecimalRound, vec![Decimal, Int], Decimal),
"dever.system.decimalParse" => (DecimalParse, vec![Text], Optional(Box::new(Decimal))),
"dever.system.decimalToText" => (DecimalToText, vec![Decimal], Text),
"dever.system.decimalFromInt" => (DecimalFromInt, vec![Int], Decimal),
"dever.system.floatSqrt" => (FloatSqrt, vec![Float], Float),
"dever.system.floatSin" => (FloatSin, vec![Float], Float),
"dever.system.floatCos" => (FloatCos, vec![Float], Float),
"dever.system.floatLog" => (FloatLog, vec![Float], Float),
"dever.system.floatPow" => (FloatPow, vec![Float, Float], Float),
"dever.system.floatIsNan" => (FloatIsNan, vec![Float], Bool),
"dever.system.floatIsFinite" => (FloatIsFinite, vec![Float], Bool),
"dever.system.floatIsInfinite" => (FloatIsInfinite, vec![Float], Bool),
_ => return Err(Diagnostic::new("C004", "unknown standard primitive", span)),
};
self.primitive(
Builtin::Standard(operation),
arguments,
inputs,
output,
span,
)
}
}
+325
View File
@@ -0,0 +1,325 @@
//! 组合保持静态具名合同;Task/Group 只在 flow 步骤拥有和消费。
use super::Checker;
use crate::compiler::model::*;
use crate::syntax::{ast, diagnostic::Diagnostic, source::Span};
use std::collections::BTreeSet;
mod affine;
pub(crate) use affine::check;
impl Checker<'_> {
pub(super) fn task(
&mut self,
name: &str,
arguments: &[ast::Expression],
span: Span,
propagate: bool,
) -> Result<Expression, Diagnostic> {
let invalid = || Diagnostic::new("C014", "invalid task operation arguments", span);
let (op, values, kind) = match (name, arguments) {
("run", [call]) => {
let (target, values) = self.task_call(call)?;
(TaskOp::Run(target), values, Type::Task(target))
}
("parallel", [call]) => {
let (target, values) = self.task_call(call)?;
if !self.functions[target].as_ref().unwrap().effects.pure() {
return Err(Diagnostic::new(
"C013",
"parallel requires a synchronous pure target",
call.span,
));
}
(TaskOp::Parallel(target), values, self.task_output(target))
}
("blocking", [call]) => {
let (target, values) = self.task_call(call)?;
let function = self.functions[target].as_ref().unwrap();
let effects = function.effects;
// 未绑定 handler 只检查签名;每个实际绑定仍须证明同步阻塞效果。
if !matches!(function.body, Body::Contract)
&& (!effects.blocking || effects.suspends || effects.tasks)
{
return Err(Diagnostic::new(
"C013",
"blocking requires a known synchronous blocking target",
call.span,
));
}
(TaskOp::Blocking(target), values, self.task_output(target))
}
("group", [limit]) => (
TaskOp::Group,
vec![self.expression(limit, Some(&Type::Int))?],
Type::Group(Vec::new()),
),
("run", [group, call]) => {
let mut group = self.expression(group, None)?;
let (Type::Group(targets), ExpressionKind::Variable(local)) =
(&mut group.value_type, &group.kind)
else {
return Err(Diagnostic::new(
"C014",
"run requires a named Group",
group.span,
));
};
let (target, mut values) = self.task_call(call)?;
if !self.functions[target]
.as_ref()
.unwrap()
.signature
.outputs
.is_empty()
{
return Err(Diagnostic::new(
"C014",
"Group members require zero outputs",
call.span,
));
}
if !targets.contains(&target) {
targets.push(target);
}
self.locals[*local].kind = group.value_type.clone();
values.insert(0, group);
(TaskOp::GroupRun(target), values, Type::Unit)
}
("wait" | "stop", [argument]) => {
let task = self.expression(argument, None)?;
match &task.value_type {
Type::Group(_) => (
if name == "wait" {
TaskOp::GroupWait
} else {
TaskOp::GroupStop
},
vec![task],
Type::Unit,
),
Type::Task(target) => {
let target = *target;
if name == "stop"
&& !self.functions[target]
.as_ref()
.unwrap()
.signature
.outputs
.is_empty()
{
return Err(Diagnostic::new(
"C014",
"stop requires a zero-output Task; use wait to receive outputs",
span,
));
}
(
if name == "wait" {
TaskOp::Wait(target)
} else {
TaskOp::Stop(target)
},
vec![task],
self.task_output(target),
)
}
_ => {
return Err(Diagnostic::new(
"C014",
"wait/stop requires a Task or Group",
argument.span,
));
}
}
}
("timeout", [argument, millis, fallback]) => {
let task = self.expression(argument, None)?;
let Type::Task(target) = task.value_type else {
return Err(invalid());
};
let millis = self.expression(millis, Some(&Type::Int))?;
let edge = self.calls.by_span[&(self.caller, fallback.span)];
let fallback_target = self.calls.edges[edge].target;
if !self.functions[fallback_target]
.as_ref()
.unwrap()
.signature
.inputs
.is_empty()
{
return Err(Diagnostic::new(
"C014",
"timeout fallback requires zero inputs",
fallback.span,
));
}
self.task_same_outputs(target, fallback_target, span)?;
(
TaskOp::Timeout {
target,
fallback: fallback_target,
},
vec![task, millis],
self.task_output(target),
)
}
("race", tasks) if tasks.len() >= 2 => {
let values = tasks
.iter()
.map(|v| self.expression(v, None))
.collect::<Result<Vec<_>, _>>()?;
let Type::Task(target) = values[0].value_type else {
return Err(invalid());
};
for task in &values[1..] {
let Type::Task(other) = task.value_type else {
return Err(invalid());
};
self.task_same_outputs(target, other, task.span)?;
}
(TaskOp::Race(target), values, self.task_output(target))
}
_ => return Err(invalid()),
};
Ok(self.task_value(op, values, kind, span, propagate))
}
fn task_value(
&mut self,
op: TaskOp,
values: Vec<Expression>,
kind: Type,
span: Span,
propagate: bool,
) -> Expression {
let targets = op.targets(&values);
if propagate {
for target in &targets {
let function = self.functions[*target].as_ref().unwrap();
self.failures.extend(&function.failures);
self.unknown_failures |= function.unknown_failures;
}
}
let succeeds = |target: &usize| {
self.functions[*target]
.as_ref()
.unwrap()
.failure_summary
.output
.is_some()
};
let can_succeed = match op {
TaskOp::GroupWait => targets.iter().all(succeeds),
TaskOp::Parallel(_)
| TaskOp::Blocking(_)
| TaskOp::Wait(_)
| TaskOp::Timeout { .. }
| TaskOp::Race(_) => targets.iter().any(succeeds),
_ => true,
};
let range = op.output_target().and_then(|target| {
let outputs = &self.functions[target].as_ref().unwrap().signature.outputs;
if let [field] = outputs.as_slice() {
field.guaranteed_range()
} else {
None
}
});
let mut value = Self::node(
ExpressionKind::Builtin(Builtin::Task(op), values),
if can_succeed { kind } else { Type::Never },
span,
);
value.range = range;
value
}
fn task_call(
&mut self,
call: &ast::Expression,
) -> Result<(usize, Vec<Expression>), Diagnostic> {
let error = || {
Diagnostic::new(
"C014",
"task execution requires a named function call",
call.span,
)
};
let ast::ExpressionKind::Call(_, arguments) = &call.kind else {
return Err(error());
};
let edge = self
.calls
.by_span
.get(&(self.caller, call.span))
.ok_or_else(error)?;
let target = self.calls.edges[*edge].target;
let function = self.functions[target]
.as_ref()
.expect("checked task target");
let send = |kind: &Type| {
transferable(kind, &self.types.definitions, |index| {
&self.functions[index].as_ref().unwrap().signature.outputs
})
};
if function
.signature
.inputs
.iter()
.chain(&function.signature.outputs)
.any(|field| !send(&field.kind))
|| function.failures.iter().any(|failure| {
let Failure::Choice(index, variant) = failure else {
return false;
};
let Shape::Choice(variants) = &self.types.definitions[*index].shape else {
unreachable!("checked failure choice")
};
variants[*variant]
.fields
.iter()
.any(|field| !send(&field.kind))
})
{
return Err(Diagnostic::new(
"C014",
"task inputs, outputs and failures cannot contain a synchronous Stream",
call.span,
));
}
let ExpressionKind::Call(_, values) = self.call(target, arguments, call.span)?.kind else {
unreachable!()
};
Ok((target, values))
}
fn task_output(&self, target: usize) -> Type {
match self.functions[target]
.as_ref()
.unwrap()
.signature
.outputs
.as_slice()
{
[] => Type::Unit,
[field] => field.kind.clone(),
_ => Type::Outputs(target),
}
}
fn task_same_outputs(&self, target: usize, other: usize, span: Span) -> Result<(), Diagnostic> {
let a = &self.functions[target].as_ref().unwrap().signature.outputs;
let b = &self.functions[other].as_ref().unwrap().signature.outputs;
if a.len() != b.len()
|| a.iter().zip(b).any(|(a, b)| {
a.name != b.name || a.kind != b.kind || a.guaranteed_range() != b.guaranteed_range()
})
{
return Err(Diagnostic::new(
"C014",
"task alternatives require identical named outputs, types and ranges",
span,
));
}
Ok(())
}
}
@@ -0,0 +1,224 @@
use super::*;
pub(crate) fn check(body: &Body, locals: &[Field], span: Span) -> Result<(), Diagnostic> {
let mut live = BTreeSet::new();
let mut terminated = false;
let mut value = |value: &Expression, flow: bool, binding: Option<usize>| {
let operation = value.operation();
if let ExpressionKind::Builtin(Builtin::Channel(_) | Builtin::Stream(_), arguments) =
&operation.kind
{
if !flow {
return Err(Diagnostic::new(
"C014",
"channel and stream operations require a flow calc step",
value.span,
));
}
for argument in arguments {
plain(argument)?;
}
return Ok(());
}
if let ExpressionKind::Builtin(Builtin::Task(op), arguments) = &operation.kind {
if !flow {
return Err(Diagnostic::new(
"C014",
"task operations require a flow calc step",
value.span,
));
}
match op {
TaskOp::Parallel(_) | TaskOp::Blocking(_) => {
for value in arguments {
plain(value)?;
}
}
TaskOp::Run(_) | TaskOp::Group => {
let local = binding.ok_or_else(|| {
Diagnostic::new("C014", "run/group must bind its resource", value.span)
})?;
live.insert(local);
for value in arguments {
plain(value)?;
}
}
TaskOp::GroupRun(_) => {
resource(&arguments[0], &mut live, false)?;
for value in &arguments[1..] {
plain(value)?;
}
}
TaskOp::Race(_) => {
for value in arguments {
resource(value, &mut live, true)?;
}
}
TaskOp::Wait(_)
| TaskOp::Stop(_)
| TaskOp::GroupWait
| TaskOp::GroupStop
| TaskOp::Timeout { .. } => {
resource(&arguments[0], &mut live, true)?;
for value in &arguments[1..] {
plain(value)?;
}
}
}
} else {
plain(value)?;
}
terminated |= value.value_type == Type::Never;
Ok(())
};
match body {
Body::Statements {
statements, flow, ..
} => {
if let Some(steps) = flow {
let mut start = 0;
while start < steps.len() {
let end = FlowStep::end(steps, start);
let mut groups = BTreeSet::new();
for statement in &statements[start..end] {
let mut duplicate = None;
statement.value().visit(&mut |value| {
if let (Type::Group(_), ExpressionKind::Variable(local)) =
(&value.value_type, &value.kind)
&& !groups.insert(*local)
{
duplicate = Some(value.span);
}
true
});
if let Some(span) = duplicate {
return Err(Diagnostic::new(
"C014",
"a parallel group cannot borrow or consume the same Group twice",
span,
));
}
}
start = end;
}
}
for statement in statements {
let binding = match statement {
Statement::Assign { local, .. } => Some(*local),
_ => None,
};
value(statement.value(), flow.is_some(), binding)?;
match statement {
Statement::Check { error, .. } | Statement::NonNull { error, .. } => {
value(error, false, None)?
}
_ => {}
}
}
}
Body::Rule(rows) => {
for expression in rows.iter().flat_map(|row| &row.results) {
value(expression, false, None)?;
}
}
Body::Loop(iteration) => {
match &iteration.source {
LoopSource::List(v)
| LoopSource::Bytes(v)
| LoopSource::Stream(v)
| LoopSource::SyncStream(v) => value(v, false, None)?,
LoopSource::Range(a, b) => {
value(a, false, None)?;
value(b, false, None)?;
}
LoopSource::Walk { seed, update, .. } => {
value(seed, false, None)?;
value(update, false, None)?;
}
}
for row in &iteration.rows {
if let Some(fold) = &row.fold {
value(&fold.seed, false, None)?;
}
if let Some(v) = &row.value {
value(v, false, None)?;
}
}
}
Body::Contract | Body::Dispatch(_) => {}
}
if !terminated && let Some(local) = live.first() {
let mut error = Diagnostic::new(
"C014",
"Task must be consumed exactly once before normal exit",
span,
);
error
.related
.push((locals[*local].span, "unconsumed Task".into()));
return Err(error);
}
Ok(())
}
fn resource(
value: &Expression,
live: &mut BTreeSet<usize>,
consume: bool,
) -> Result<(), Diagnostic> {
match &value.kind {
ExpressionKind::Variable(local) => {
let valid = if consume {
live.remove(local)
} else {
live.contains(local)
};
if !valid {
return Err(Diagnostic::new(
"C014",
"Task or Group was already consumed",
value.span,
));
}
}
ExpressionKind::Builtin(Builtin::Task(TaskOp::Run(_)), arguments) if consume => {
for value in arguments {
plain(value)?;
}
}
_ => {
return Err(Diagnostic::new(
"C014",
"expected a named resource or nested run call",
value.span,
));
}
}
Ok(())
}
fn plain(value: &Expression) -> Result<(), Diagnostic> {
let mut invalid = None;
value.visit(&mut |child| {
if matches!(child.value_type, Type::Task(_) | Type::Group(_))
|| matches!(
child.kind,
ExpressionKind::Builtin(
Builtin::Task(_) | Builtin::Channel(_) | Builtin::Stream(_),
_
)
)
{
invalid = Some(child.span);
}
invalid.is_none()
});
if let Some(span) = invalid {
return Err(Diagnostic::new(
"C014",
"Task/Group cannot be copied, stored or used in ordinary expressions",
span,
));
}
Ok(())
}
@@ -0,0 +1,113 @@
//! 测试原语只在用例源码中可用;参数使用同一类型、比较与失败义务检查。
use super::*;
use crate::compiler::project::Role;
impl Checker<'_> {
pub(super) fn test_operation(
&mut self,
name: &str,
args: &[ast::Expression],
span: Span,
) -> Result<Option<Expression>, Diagnostic> {
if name == "assertRow" {
return self.assert_row(args, span).map(Some);
}
let operation = match name {
"dever.test.advanceClock" => TestOp::AdvanceClock,
"dever.test.drainJobs" => TestOp::DrainJobs(!self.types.jobs.is_empty()),
"assert" => TestOp::Assert,
"assertEq" => TestOp::AssertEq,
"secret" => TestOp::Secret,
_ => return Ok(None),
};
if self.types.module(span.source).role != Role::Test {
return Err(Diagnostic::new(
"C014",
"test operations are not allowed in production source",
span,
));
}
self.test_settings |= operation == TestOp::DrainJobs(true);
let count = if operation == TestOp::AssertEq { 2 } else { 1 };
if args.len() != count {
return Err(Diagnostic::new(
"C005",
"test operation argument count differs",
span,
));
}
let values = match operation {
TestOp::AdvanceClock | TestOp::DrainJobs(_) => {
vec![self.expression(&args[0], Some(&Type::Int))?]
}
TestOp::AssertRow(_) => unreachable!("checked separately"),
TestOp::Assert => vec![self.expression(&args[0], Some(&Type::Bool))?],
TestOp::AssertEq => {
vec![self.binary("==", &args[0], &args[1], Some(&Type::Bool), span)?]
}
TestOp::Secret => vec![self.expression(&args[0], Some(&Type::Text))?],
};
let kind = if operation == TestOp::Secret {
Type::Secret
} else if matches!(operation, TestOp::DrainJobs(_)) {
Type::Int
} else {
Type::Unit
};
Ok(Some(Self::node(
ExpressionKind::Builtin(Builtin::Test(operation), values),
kind,
span,
)))
}
fn assert_row(
&mut self,
args: &[ast::Expression],
span: Span,
) -> Result<Expression, Diagnostic> {
if self.types.module(span.source).role != Role::Test {
return Err(Diagnostic::new(
"C014",
"test operations are not allowed in production source",
span,
));
}
let [call, row] = args else {
return Err(Diagnostic::new(
"C005",
"assertRow requires a rule call and a row name",
span,
));
};
let ast::ExpressionKind::Literal(ast::Literal::Text(name)) = &row.kind else {
return Err(Diagnostic::new(
"C005",
"assertRow requires a literal row name",
row.span,
));
};
let call = self.expression(call, None)?;
let ExpressionKind::Call(target, _) = &call.kind else {
return Err(Diagnostic::new(
"C005",
"assertRow requires a direct rule call",
call.span,
));
};
let Body::Rule(rows) = &self.functions[*target].as_ref().unwrap().body else {
return Err(Diagnostic::new(
"C005",
"assertRow requires a rule",
call.span,
));
};
let index = rows
.iter()
.position(|r| r.name.as_ref() == Some(name))
.ok_or_else(|| Diagnostic::new("C004", "unknown rule row", row.span))?;
Ok(Self::node(
ExpressionKind::Builtin(Builtin::Test(TestOp::AssertRow(index)), vec![call]),
Type::Unit,
span,
))
}
}
+192
View File
@@ -0,0 +1,192 @@
//! 入口只接受明确的 wire 类型,私有字段和带载荷 choice 不泄露到协议。
use crate::compiler::model::*;
use crate::syntax::{diagnostic::Diagnostic, source::Span};
use std::collections::BTreeSet;
pub fn signature(
signature: &Signature,
definitions: &[Definition],
span: Span,
upload: bool,
) -> Result<(), Diagnostic> {
let mut seen = BTreeSet::new();
for field in signature
.inputs
.iter()
.filter(|f| !upload || f.kind != Type::Upload)
{
collect_types(&field.kind, definitions, span, &mut seen)?;
}
let mut seen = BTreeSet::new();
for field in &signature.outputs {
output(&field.kind, definitions, span, &mut seen)?;
}
Ok(())
}
pub fn collect(
kind: &Type,
program: &Program,
span: Span,
seen: &mut BTreeSet<usize>,
) -> Result<(), Diagnostic> {
collect_types(kind, &program.definitions, span, seen)
}
pub(super) fn collect_types(
kind: &Type,
definitions: &[Definition],
span: Span,
seen: &mut BTreeSet<usize>,
) -> Result<(), Diagnostic> {
types(kind, definitions, span, seen, true)
}
pub(super) fn output(
kind: &Type,
definitions: &[Definition],
span: Span,
seen: &mut BTreeSet<usize>,
) -> Result<(), Diagnostic> {
types(kind, definitions, span, seen, false)
}
fn types(
kind: &Type,
definitions: &[Definition],
span: Span,
seen: &mut BTreeSet<usize>,
allow_secret: bool,
) -> Result<(), Diagnostic> {
// 每个待查类型带上它所在的“记录.字段”,报错时指出具体位置,而不是只指向整个入口。
let mut pending = vec![(kind, None::<String>)];
while let Some((kind, field)) = pending.pop() {
match kind {
Type::Secret if !allow_secret => {
return Err(Diagnostic::new(
"C005",
"Secret cannot be encoded or output",
span,
));
}
Type::Bool
| Type::Int
| Type::Float
| Type::Decimal
| Type::Text
| Type::Json
| Type::Secret
| Type::Uuid
| Type::Id
| Type::ModelId(_)
| Type::DateTime
| Type::Date
| Type::Time
| Type::Duration => {}
Type::List(inner) | Type::Optional(inner) => pending.push((inner, field)),
Type::Named(index) if seen.insert(*index) => match &definitions[*index].shape {
Shape::Record(_) => {
for item in definitions[*index].columns() {
let place = format!("{}.{}", definitions[*index].name, item.name);
if item.private {
return Err(Diagnostic::new(
"C006",
format!("private field `{place}` cannot cross a wire boundary"),
span,
));
}
pending.push((&item.kind, Some(place)));
}
}
Shape::Choice(variants)
if variants
.iter()
.all(|variant| !variant.error && variant.fields.is_empty()) => {}
Shape::Choice(_) => {
let name = &definitions[*index].name;
let place = field.unwrap_or_else(|| name.clone());
let message = if definitions[*index].related {
format!(
"relation `{place}` cannot cross a wire boundary; return an explicit result record for loaded relations"
)
} else {
format!(
"`{place}` is a choice with payload or errors; only payload-free non-error choice can cross a wire boundary"
)
};
return Err(Diagnostic::new("C005", message, span));
}
},
Type::Named(_) => {}
_ => {
return Err(Diagnostic::new(
"C005",
"type cannot cross a wire boundary",
span,
));
}
}
}
Ok(())
}
/// 只证明是否处于协议深度内;更深的可空结构交给单次解码中的真实深度计数。
pub fn shallow(fields: &[Field], program: &Program) -> bool {
let mut pending = fields
.iter()
.map(|field| (&field.kind, 1))
.collect::<Vec<_>>();
let mut visited = vec![0; program.definitions.len()];
while let Some((kind, depth)) = pending.pop() {
match kind {
Type::Json => return false,
Type::Optional(inner) => pending.push((inner, depth)),
Type::List(inner) => {
if depth == 64 {
return false;
}
pending.push((inner, depth + 1));
}
Type::Named(index) if depth > visited[*index] => {
visited[*index] = depth;
if let Shape::Record(_) = &program.definitions[*index].shape {
if depth == 64 {
return false;
}
pending.extend(
program.definitions[*index]
.columns()
.iter()
.map(|field| (&field.kind, depth + 1)),
);
}
}
_ => {}
}
}
true
}
pub fn dynamic(kind: &Type, definitions: &[Definition]) -> bool {
let mut pending = vec![kind];
let mut seen = BTreeSet::new();
while let Some(kind) = pending.pop() {
match kind {
Type::Json => return true,
Type::List(inner) | Type::Optional(inner) => pending.push(inner),
Type::Named(index) if seen.insert(*index) => {
if let Shape::Record(_) = &definitions[*index].shape {
pending.extend(
definitions[*index]
.columns()
.iter()
.map(|field| &field.kind),
);
}
}
_ => {}
}
}
false
}
+194
View File
@@ -0,0 +1,194 @@
//! 客户端只消费已检查的 HTTP 合同;数值精度转换留在协议边界,不重复业务约束。
use crate::compiler::{emit::symbol, model::*};
use serde_json::{Value, json};
use std::{collections::BTreeSet, fmt::Write};
pub fn typescript(program: &Program) -> String {
let mut text = String::from(include_str!("wire.ts"));
let mut pending = BTreeSet::new();
let mut methods = String::new();
for entry in &program.http {
let signature = &program.functions[entry.function].signature;
let mut inputs = signature.inputs.clone();
let detail = entry.rest.as_ref().is_some_and(|r| r.detail);
if let Some(rest) = &entry.rest {
if entry.method == "GET" && !detail {
for field in &mut inputs {
field.kind = Type::Optional(Box::new(field.kind.clone()));
}
}
if let Some((field, _)) = rest.search {
let mut field = program.definitions[rest.record].columns()[field].clone();
field.kind = Type::Optional(Box::new(field.kind));
inputs.push(field);
}
}
let input = fields(&inputs, true, program, &mut pending);
let (output, schema) = if let Some(rest) = &entry.rest {
if entry.method == "DELETE" {
("null".into(), json!("value"))
} else if entry.method == "GET" && !detail {
let row = kind(&Type::Named(rest.record), false, program, &mut pending);
(
format!("{{ items: {row}[]; page: Int; size: Int; total: Int; pages: Int }}"),
json!({"items":[rest.record],"page":"int","size":"int","total":"int","pages":"int"}),
)
} else {
(
kind(&Type::Named(rest.record), false, program, &mut pending),
json!(rest.record),
)
}
} else {
match signature.outputs.as_slice() {
[] => ("null".into(), json!("value")),
[field] => (
kind(&field.kind, false, program, &mut pending),
codec(&field.kind),
),
outputs => (
fields(outputs, false, program, &mut pending),
record(outputs),
),
}
};
let name = format!(
"{} {}{}",
entry.method,
entry.path,
if detail { "/{id}" } else { "" }
);
let id = if detail {
json!(inputs[0].name)
} else {
Value::Null
};
let upload = signature
.inputs
.iter()
.find(|f| f.kind == Type::Upload)
.map(|f| f.name.as_str());
let upload = serde_json::to_string(&upload).unwrap();
writeln!(methods, " {name:?}: (input: {input}, options?: Options): Promise<{output}> => request({:?}, {:?}, input, {schema}, {id}, {upload}, options) as Promise<{output}>,", entry.method, entry.path).unwrap();
}
let mut seen = BTreeSet::new();
let mut codecs = serde_json::Map::new();
while let Some(index) = pending.pop_first() {
if !seen.insert(index) {
continue;
}
let definition = &program.definitions[index];
let name = symbol(&definition.name);
match &definition.shape {
Shape::Record(values) => {
for input in [false, true] {
let body = fields(values, input, program, &mut pending);
writeln!(
text,
"export type {}{name} = {body};",
if input { "Input_" } else { "" }
)
.unwrap();
}
codecs.insert(index.to_string(), record(values));
}
Shape::Choice(variants) => {
let variants = variants
.iter()
.map(|v| format!("{:?}", v.name))
.collect::<Vec<_>>()
.join(" | ");
writeln!(
text,
"export type {name} = {variants};\nexport type Input_{name} = {name};"
)
.unwrap();
codecs.insert(index.to_string(), json!("value"));
}
}
}
writeln!(
text,
"const types: Record<number, Schema> = {};",
Value::Object(codecs)
)
.unwrap();
text.push_str("export function createClient(base: string, defaults: Options = {}) {\n const request = requester(base, defaults);\n return {\n");
text.push_str(&methods);
text.push_str(" };\n}\n");
text
}
fn fields(
values: &[Field],
input: bool,
program: &Program,
pending: &mut BTreeSet<usize>,
) -> String {
let values = values
.iter()
.filter(|f| !f.private)
.map(|field| {
let optional = input
&& (matches!(field.kind, Type::Optional(_))
|| field.model.as_ref().is_some_and(|m| m.default.is_some()));
format!(
"{:?}{}: {}",
field.name,
if optional { "?" } else { "" },
kind(&field.kind, input, program, pending)
)
})
.collect::<Vec<_>>()
.join("; ");
format!("{{ {values} }}")
}
fn kind(value: &Type, input: bool, program: &Program, pending: &mut BTreeSet<usize>) -> String {
match value {
Type::Upload => "Blob".into(),
Type::Bool => "boolean".into(),
Type::Int | Type::Id | Type::ModelId(_) | Type::Duration => "Int".into(),
Type::Float => "number".into(),
Type::Json => "Json".into(),
Type::Text
| Type::Secret
| Type::Decimal
| Type::Uuid
| Type::DateTime
| Type::Date
| Type::Time => "string".into(),
Type::Optional(inner) => format!("({} | null)", kind(inner, input, program, pending)),
Type::List(inner) => format!("Array<{}>", kind(inner, input, program, pending)),
Type::Named(index) => {
pending.insert(*index);
format!(
"{}{}",
if input { "Input_" } else { "" },
symbol(&program.definitions[*index].name)
)
}
_ => unreachable!("checked HTTP wire type"),
}
}
fn record(fields: &[Field]) -> Value {
Value::Object(
fields
.iter()
.filter(|f| !f.private)
.map(|f| (f.name.clone(), codec(&f.kind)))
.collect(),
)
}
fn codec(kind: &Type) -> Value {
match kind {
Type::Int | Type::Id | Type::ModelId(_) | Type::Duration => json!("int"),
Type::Float => json!("float"),
Type::Optional(inner) => codec(inner),
Type::List(inner) => json!([codec(inner)]),
Type::Named(index) => json!(index),
_ => json!("value"),
}
}
+83
View File
@@ -0,0 +1,83 @@
// 由 Dever HTTP 合同生成。要求原生 JSON.rawJSON 和 JSON.parse source;不降级数值精度。
export type Int = number | bigint;
export type RawJson = { readonly rawJSON: string };
export type Json = null | boolean | string | number | bigint | RawJson | Json[] | { [key: string]: Json };
export type Options = Omit<RequestInit, 'method' | 'body'>;
type Schema = 'int' | 'float' | 'value' | number | [Schema] | { [key: string]: Schema };
const exactJSON = JSON as typeof JSON & {
rawJSON(source: string): RawJson;
isRawJSON(value: unknown): value is RawJson;
};
export const rawJson = (source: string): RawJson => exactJSON.rawJSON(source);
export class ApiError extends Error {
readonly status: number;
readonly code: number;
constructor(status: number, code: number, message: string) {
super(message);
this.name = 'ApiError';
this.status = status;
this.code = code;
}
}
function encode(value: unknown): string {
return JSON.stringify(value, (_key, item) => {
if (typeof item === 'bigint') return rawJson(item.toString());
if (typeof item === 'number' && !Number.isFinite(item)) throw new TypeError('non-finite JSON number');
return item;
});
}
function decode(value: any, schema: Schema): any {
if (value === null) return null;
if (typeof schema === 'number') return decode(value, types[schema]);
if (schema === 'value') return value;
if (schema === 'float') return Number(value.rawJSON);
if (schema === 'int') {
const integer = BigInt(value.rawJSON);
const number = Number(integer);
return Number.isSafeInteger(number) ? number : integer;
}
if (Array.isArray(schema)) return value.map((item: unknown) => decode(item, schema[0]));
return Object.fromEntries(Object.entries(schema).map(([key, shape]) => [key, decode(value[key], shape)]));
}
function requester(base: string, defaults: Options) {
// 数字原文由标准 JSON 解析器提供,不在客户端自写 JSON 扫描器。
if (typeof exactJSON.rawJSON !== 'function') throw new Error('client requires JSON.rawJSON');
return async (method: string, path: string, input: Record<string, unknown>, schema: Schema, id: string | null, upload: string | null, options: Options = {}): Promise<unknown> => {
const fields = { ...input };
if (id !== null) {
path += '/' + encodeURIComponent(String(fields[id]));
delete fields[id];
}
const url = new URL(path, base);
const headers = new Headers(defaults.headers);
new Headers(options.headers).forEach((value, key) => headers.set(key, value));
let body: BodyInit | undefined;
if (upload !== null) {
const form = new FormData();
for (const [name, value] of Object.entries(fields)) {
if (value !== undefined && value !== null) form.append(name, name === upload ? value as Blob : String(value));
}
headers.delete('Content-Type');
body = form;
} else if (method === 'GET' || method === 'DELETE') {
for (const [name, value] of Object.entries(fields)) {
if (value !== undefined && value !== null) url.searchParams.set(name, String(value));
}
} else {
headers.set('Content-Type', 'application/json');
body = encode(fields);
}
const response = await fetch(url, { ...defaults, ...options, method, headers, body });
const envelope = JSON.parse(await response.text(), function (_key: string, value: unknown, context?: { source: string }) {
if (typeof value !== 'number') return value;
if (!context) throw new Error('client requires JSON.parse source');
return rawJson(context.source);
});
const code = Number(envelope.code.rawJSON);
if (!response.ok || code !== 0) throw new ApiError(response.status, code, envelope.message);
return decode(envelope.data, schema);
};
}
@@ -0,0 +1,210 @@
//! verify 只绑定已完成调用链检查的 App,默认权限直接调用运行库实时授权。
use super::*;
use crate::compiler::emit::AppendCode;
// 沿真实调用边(包括任务目标)收集名义 ID 合同,在配置绑定处核对 Provider。
pub(in crate::compiler::emit::application) fn identity_verifiers(
program: &Program,
root: usize,
) -> Vec<usize> {
let mut required = BTreeSet::new();
let mut pending = vec![root];
let mut seen = BTreeSet::new();
while let Some(target) = pending.pop() {
if !seen.insert(target) {
continue;
}
let expressions = match &program.functions[target].body {
Body::Statements { statements, .. } => {
statements.iter().map(Statement::value).collect::<Vec<_>>()
}
Body::Rule(rows) => rows.iter().flat_map(|row| &row.results).collect(),
Body::Loop(iteration) => iteration.expressions().collect(),
Body::Contract => Vec::new(),
Body::Dispatch(dispatch) => dispatch.variants.iter().map(|v| &v.call).collect(),
};
for value in expressions {
value.visit(&mut |value| {
match value.kind {
ExpressionKind::Builtin(Builtin::Identity(IdentityOp::User(source)), _) => {
required.insert(("user_id", source));
}
ExpressionKind::Builtin(Builtin::Identity(IdentityOp::Tenant(source)), _) => {
required.insert(("tenant_id", source));
}
ExpressionKind::Builtin(Builtin::Authorization(operation), ref arguments)
if operation.user_argument() =>
{
if let Type::ModelId(source) = arguments[0].value_type {
required.insert(("user_id", source));
}
}
_ => {}
}
true
});
}
pending.extend(
program
.calls
.iter()
.filter(|call| call.caller == target)
.map(|call| call.target),
);
}
verifiers(program)
.iter()
.enumerate()
.filter_map(|(index, (_, function))| {
let Type::Named(output) = function.signature.outputs[0].kind else {
unreachable!()
};
let Shape::Record(fields) = &program.definitions[output].shape else {
unreachable!()
};
required
.iter()
.all(|(name, source)| {
fields.iter().any(|field| {
field.name == *name
&& field.kind == Type::Optional(Box::new(Type::ModelId(*source)))
})
})
.then_some(index)
})
.collect()
}
pub(super) fn verifiers(program: &Program) -> Vec<(usize, &Function)> {
let Some(claims) = program
.definitions
.iter()
.position(|d| d.name == "dever.auth.app.Claims")
else {
return Vec::new();
};
program
.functions
.iter()
.enumerate()
.filter(|(_, f)| {
f.signature.name.split('.').nth(2) == Some("app")
&& f.signature.inputs.len() == 1
&& f.signature.inputs[0].kind == Type::Named(claims)
})
.collect()
}
pub(super) fn emit(program: &Program, decisions: &[Ownership], text: &mut String) {
if program.protected_http() {
owner(program, text);
}
if !program
.http
.iter()
.any(|entry| entry.access != HttpAccess::Public)
{
return;
}
text.append_code(format_args!("async fn api_verify(index:usize,claims:&dever_runtime::auth::Claims,task_scope:&dever_runtime::task::Scope,settings:&Settings{})->Result<dever_runtime::auth::Identity,dever_runtime::auth::Error>{{match index{{",if program.database_operations(){",database:&Databases"}else{""}));
for (index, (target, function)) in verifiers(program).iter().enumerate() {
let Type::Named(claims) = function.signature.inputs[0].kind else {
unreachable!()
};
let Shape::Record(fields) = &program.definitions[claims].shape else {
unreachable!()
};
text.append_code(format_args!(
"{index}=>{{let input={}{{",
symbol(&program.definitions[claims].name)
));
for (i, field) in fields.iter().enumerate() {
text.append_code(format_args!("f{i}:claims.{}.clone(),", field.name));
}
text.push_str("};");
if function.effects.database {
text.push_str("let mut db_context=dever_runtime::database::Context::default();");
}
text.append_code(format_args!(
"let identity={}(",
symbol(&function.signature.name)
));
if function.test_trace {
text.push_str("&mut None,");
}
if function.effects.scope() {
text.push_str("task_scope,");
}
if function.effects.database {
text.push_str("database,&mut db_context,");
}
if function.uses_settings {
text.push_str("settings,");
}
if decisions[*target].parameters[0] != Storage::Owned {
text.push('&');
}
text.push_str("input)");
if function.effects.suspends {
text.push_str(".await");
}
if !function.failures.is_empty() {
text.push_str(".map_err(|error| {let error=api_failure(error);match error.status{401=>dever_runtime::auth::Error::Unauthorized,403=>dever_runtime::auth::Error::Forbidden,_=>dever_runtime::auth::Error::Database(dever_runtime::database::Error::new(dever_runtime::database::Kind::InvalidData,error.reason))}})?");
}
text.push_str(";Ok(dever_runtime::auth::Identity{");
let Type::Named(result) = function.signature.outputs[0].kind else {
unreachable!()
};
let Shape::Record(fields) = &program.definitions[result].shape else {
unreachable!()
};
for (i, field) in fields.iter().enumerate() {
text.append_code(format_args!(
"{}:identity.f{i}{},",
field.name,
if field.name == "id" {
""
} else {
".map(|id|id.0)"
}
));
}
text.push_str("})},");
}
text.push_str("_=>unreachable!(\"validated Provider binding\")}}\n");
}
pub(super) fn entry(entry: &HttpEntry, index: usize, program: &Program, text: &mut String) {
if entry.access == HttpAccess::Public {
return;
}
text.append_code(format_args!("let route=&settings.api.routes[{index}]; let site=&settings.api.sites[&route.site]; let provider=&settings.api.providers[site.auth.as_ref().unwrap()]; let identity=dever_runtime::auth::request::authenticate(&provider.provider,route.cookie.as_deref(),&request,&route.site,false,dever_runtime::value::calendar::DateTime::now().map_err(|error|ApiFailure::new(500,format!(\"{{error:?}}\")))?.millis()/1000,async |claims|api_verify(provider.verify,claims,task_scope,settings{}).await).await?.unwrap();",if program.database_operations(){",database"}else{""}));
if program.database_operations() {
text.push_str("let mut request_database=database.clone();request_database.storage=database.storage.select(task_scope,&identity).await?;let database=&request_database;");
}
if entry.access == HttpAccess::Protected {
text.append_code(format_args!("let permission=format!(\"{}.{{}}.{}\",route.site);let mut access=database.storage.access(&identity,&mut db_context)?;access.authorize(task_scope,database.storage.control(),&permission).await?;",format_args!("{}.{}",entry.component,entry.domain),entry.action));
if !program.jobs.is_empty() {
text.push_str("let mut request_database=database.clone();request_database.execution=dever_runtime::job::Execution::user(&identity,permission);let database=&request_database;");
}
}
}
fn owner(program: &Program, text: &mut String) {
let fields = [
("site", Type::Text),
("user_id", Type::Int),
("tenant", Type::Optional(Box::new(Type::Int))),
]
.into_iter()
.map(|(name, kind)| Field {
model: None,
name: name.into(),
kind,
range: None,
private: false,
span: program.http[0].span,
})
.collect::<Vec<_>>();
text.push_str("struct OwnerArgs {f0:String,f1:i64,f2:Option<i64>}\n");
wire::decode("OwnerArgs", &fields, program, text);
text.append_code(format_args!("fn authorization_owner(input:&str,settings:&Settings)->Result<String,String>{{let args:OwnerArgs=wire::decode(input,true,false)?;if settings.api.sites.get(&args.f0).and_then(|site|site.auth.as_ref()).is_none(){{return Err(\"Owner requires a configured authenticated site\".into());}}wire::task_result(dever_runtime::task::run(database_needs_io(&settings), dever_runtime::task::DEFAULT_CAPACITY,async |scope|{{let database=open_database(settings,scope,false).await.map_err(|e|e.to_string())?;let storage=match args.f2{{Some(id)=>database.storage.select_id(scope,id).await.map_err(|e|e.to_string())?,None=>database.storage}};dever_runtime::auth::initialize_owner(scope,storage.authorization().map_err(|e|e.to_string())?,&args.f0,args.f1).await.map_err(|e|e.to_string())?;wire::response(&())}}).map_err(|e|e.to_string())?)}}\n\n"));
}
@@ -0,0 +1,316 @@
//! HTTP 调用与 CMD 共享参数类型;一次解码后直接调用业务,不再经命令进程或 JSON 中转。
mod auth;
pub(super) mod multipart;
pub(super) mod rest;
use super::*;
use crate::compiler::emit::AppendCode;
pub(super) use auth::identity_verifiers;
pub(super) fn settings(program: &Program, web: bool, assignments: &mut String) {
assignments.push_str("api:{let mut api=config.api.bind(path,&[");
for entry in &program.http {
assignments.append_code(format_args!(
"({:?},{}),",
entry.topic,
entry.access != HttpAccess::Public || program.functions[entry.function].effects.session
));
}
assignments.push_str("],&[");
for (_, function) in auth::verifiers(program) {
assignments.append_code(format_args!(
"{:?},",
function.signature.name.replace(".app.", ".")
));
}
assignments.push_str("])?;");
for (index, entry) in program.http.iter().enumerate() {
if program.functions[entry.function].effects.cookie {
assignments.append_code(format_args!("if api.routes[{index}].cookie.is_none(){{return Err(\"Cookie operations require a configured Provider Cookie\".into());}}"));
}
for function in entry
.functions()
.filter(|f| program.functions[*f].effects.identity)
{
let allowed = identity_verifiers(program, function);
assignments.append_code(format_args!("let provider=&api.providers[api.sites[&api.routes[{index}].site].auth.as_ref().unwrap()]; let allowed:&[usize]=&{allowed:?}; if !allowed.contains(&provider.verify){{return Err({:?}.into());}}", format!("Provider identity types do not match {}", entry.path)));
}
}
if web {
assignments.push_str("api.bind_web(web_assets(),&[");
for entry in &program.http {
assignments.append_code(format_args!(
"({:?},{}),",
entry.path,
entry.rest.as_ref().is_some_and(|r| r.detail)
));
}
assignments.push_str("])?;");
} else {
assignments.push_str("api.bind_web(&[],&[])?;");
}
if program.uses_upload() || program.stages_files() {
assignments.push_str("if api.http.upload.is_none(){return Err(\"Upload requires http.upload configuration\".into());}");
}
assignments.push_str("api},");
}
pub(super) fn emit(program: &Program, decisions: &[Ownership], web: bool, text: &mut String) {
if program.http.is_empty() && !web {
return;
}
text.push_str("use dever_runtime::api::{self,Error as ApiFailure};\n");
let raw = if program.uses_upload() {
",body:api::Body"
} else {
""
};
let fallible =
program.database_operations() || program.functions.iter().any(|f| !f.failures.is_empty());
if fallible {
text.push_str("fn api_failure(error:Failure)->ApiFailure {let status=match &error {Failure::Api(error)=>match error {ApiError::Invalid=>400,ApiError::Unauthorized=>401,ApiError::Forbidden=>403,ApiError::NotFound=>404,ApiError::Conflict=>409,ApiError::TooManyRequests=>429},");
if program.database_operations() {
let definition = program
.definitions
.iter()
.find(|d| d.name == "dever.database.app.Error")
.unwrap();
let name = symbol(&definition.name);
text.append_code(format_args!("Failure::{name}({name}::NotFound(_))=>404,Failure::{name}({name}::Constraint(_))=>409,Failure::{name}({name}::InvalidData(_))=>400,"));
}
text.push_str("_=>500}; ApiFailure::new(status,format!(\"{error:?}\"))}\n");
}
auth::emit(program, decisions, text);
rest::outputs(program, text);
for (index, entry) in program.http.iter().enumerate() {
let function = &program.functions[entry.function];
let name = symbol(&function.signature.name);
let database = if program.database_operations() {
",database:&Databases"
} else {
""
};
let detail = if entry.rest.as_ref().is_some_and(|r| r.detail) {
",id:i64"
} else {
""
};
text.append_code(format_args!("async fn api_{index}(mut request:api::IncomingRequest{raw}, task_scope:&dever_runtime::task::Scope,settings:&Settings,peer:std::net::SocketAddr{database}{detail})->Result<dever_runtime::http::Response,ApiFailure>{{ if !settings.api.accepts({index},&request) {{return Err(ApiFailure::new(404,\"unknown site host\"));}} "));
if program.database_operations() {
text.push_str("let mut db_context=dever_runtime::database::Context::default();");
}
auth::entry(entry, index, program, text);
if function.effects.session {
text.append_code(format_args!("let session=std::sync::Arc::new(api::Session::new(&settings.api,{index},&request,{})?);",entry.access == HttpAccess::Public && function.effects.cookie));
}
if entry
.functions()
.any(|f| program.functions[f].effects.identity)
{
text.push_str("let identity=std::sync::Arc::new(identity);");
}
if function.effects.entry_namespace {
text.append_code(format_args!(
"let entry_namespace=dever_runtime::auth::Namespace{{component:{:?},domain:{:?}}};",
entry.component, entry.domain
));
}
let signature = &function.signature;
let upload = signature.inputs.iter().any(|f| f.kind == Type::Upload);
if program.uses_upload() && !upload {
text.push_str("request.body=api::collect_body(body).await?;");
}
if upload {
multipart::decode(entry, program, text);
} else if entry.rest.is_some() {
rest::decode(entry, program, text);
} else if matches!(entry.method.as_str(), "GET" | "DELETE") {
text.append_code(format_args!("let args:Args_{name}=api::query(&request)?;"));
} else {
let dynamic = signature
.inputs
.iter()
.any(|f| crate::compiler::check::wire::dynamic(&f.kind, &program.definitions));
let sensitive = signature.inputs.iter().any(|f| program.sensitive(&f.kind));
text.append_code(format_args!(
"let args:Args_{name}=api::json(&request,{},{dynamic},{sensitive})?;",
crate::compiler::check::wire::shallow(&signature.inputs, program)
));
}
if entry
.functions()
.any(|f| program.functions[f].effects.request)
{
text.append_code(format_args!("let request_context=std::sync::Arc::new(api::RequestContext::new(request,peer,settings.api.http.limits.header_bytes as usize,&settings.api.routes[{index}]));"));
}
let transaction = function.effects.database_write && !entry.long;
if transaction {
text.push_str("let owner=db_context.enter();");
}
text.push_str("let value=");
if transaction && function.failures.is_empty() {
text.push_str("Ok::<_,Failure>(");
}
rest::call(entry, program, decisions, text);
if transaction && function.failures.is_empty() {
text.push(')');
}
if transaction {
text.push_str("; let value=finish_database(&mut db_context,task_scope,owner,value).await.map_err(api_failure)?");
} else if !function.failures.is_empty() {
text.push_str(".map_err(api_failure)?");
}
text.push_str("; let body=(||->Result<Vec<u8>,String> {");
for (i, field) in signature
.outputs
.iter()
.enumerate()
.filter(|_| entry.rest.is_none())
{
wire::finite(
&field.kind,
&if signature.outputs.len() == 1 {
"value".into()
} else {
format!("value.f{i}")
},
program,
text,
);
}
if entry.rest.is_some() {
rest::response(entry, program, text);
} else if signature
.outputs
.iter()
.any(|f| crate::compiler::check::wire::dynamic(&f.kind, &program.definitions))
{
text.push_str("wire::json::response_body(");
json::response_value(&signature.outputs, &name, program, text);
text.push(')');
} else {
text.push_str("wire::json::response_body(|output| output.value(&value))");
}
text.push_str("})().map_err(ApiFailure::from)?;let mut response=api::response(Ok(body));");
if function.effects.response_headers {
text.push_str("response.headers.extend(request_context.take_headers());");
}
if function.effects.cookie {
text.push_str("response.headers.extend(session.take_headers());");
}
text.push_str("Ok(response) }\n");
}
server(program, web, text);
}
fn server(program: &Program, web: bool, text: &mut String) {
let all = if program.jobs.is_empty() {
""
} else {
",all:bool"
};
text.append_code(format_args!(
"fn run_api(settings:Settings{all})->Result<String,String>{{"
));
if let Some(entry) = program
.http
.iter()
.find(|entry| entry.tenant_model.is_some())
{
text.append_code(format_args!(
"if settings.tenant.is_some(){{return Err({:?}.into());}}",
entry.tenant_error()
));
}
text.push_str("wire::task_result(dever_runtime::task::run(true, dever_runtime::task::DEFAULT_CAPACITY,async |scope| {");
if program.database_setup(web) {
let target = if program.database_operations() {
"let database="
} else {
""
};
text.append_code(format_args!("{target}open_database(&settings,scope,settings.database.create).await.map_err(|e|e.to_string())?;"));
}
if !program.jobs.is_empty() {
text.push_str("let workers=if all{start_workers(scope,&database,&settings).await?}else{Vec::new()};let shutdown_ms=settings.job.shutdown_ms;");
}
text.push_str("let tls=settings.api.tls().map_err(|e|e.to_string())?;let limits=settings.api.http.limits;let http_shutdown=std::time::Duration::from_millis(settings.api.http.shutdown_ms); let listener=dever_runtime::net::listen(&settings.api.http.host,settings.api.http.port,scope).await.map_err(|e|e.to_string())?;");
let scheduled = program.database_operations()
|| program
.http
.iter()
.any(|entry| program.functions[entry.function].effects.scope());
if program.uses_upload() {
text.push_str("let serving=api::serve_upload(scope,&listener,&limits,tls.as_ref(),http_shutdown,move |request,body,request_scope,peer|{let settings=settings.clone();");
} else {
text.append_code(format_args!("let serving=api::serve::<{scheduled},_,_>(scope,&listener,&limits,tls.as_ref(),http_shutdown,move |request,request_scope,peer|{{let settings=settings.clone();"));
}
if program.database_operations() {
text.push_str("let database=database.clone();");
}
text.push_str("async move {let path=request.path(); let result=match (request.method(),path){");
for (index, entry) in program.http.iter().enumerate() {
if entry.rest.is_some() {
continue;
}
text.append_code(format_args!(
"({:?},{:?})=>api_{index}(request{},&request_scope,&settings,peer{}).await,",
entry.method,
entry.path,
if program.uses_upload() { ",body" } else { "" },
if program.database_operations() {
",&database"
} else {
""
}
));
}
rest::routes(program, text);
if web {
text.push_str("_=>settings.api.web_response(&request)");
} else {
text.push_str("_=>Err(ApiFailure::new(404,\"unknown API route\"))");
}
text.push_str(
"}; Ok(match result{Ok(response)=>response,Err(error)=>api::response(Err(error))})}});",
);
if program.jobs.is_empty() {
text.push_str("serving.await");
} else {
text.push_str("api::with_workers(serving,workers,shutdown_ms).await");
}
text.push_str(".and_then(api::Drain::result).map_err(|e|e.to_string())?; Ok::<_,String>(\"API stopped\".into())}).map_err(|e|e.to_string())?)}\n");
}
fn invoke(target: usize, program: &Program, decisions: &[Ownership], text: &mut String) {
let function = &program.functions[target];
text.append_code(format_args!("{}(", symbol(&function.signature.name)));
if function.test_trace {
text.push_str("&mut None,");
}
if function.effects.request {
text.push_str("&request_context,");
}
if function.effects.identity {
text.push_str("&identity,");
}
if function.effects.session {
text.push_str("&session,");
}
if function.effects.entry_namespace {
text.push_str("&entry_namespace,");
}
if function.effects.scope() {
text.push_str("task_scope,");
}
if function.effects.database {
text.push_str("database,&mut db_context,");
}
if function.uses_settings {
text.push_str("settings,");
}
arguments(function, &decisions[target], text);
text.push(')');
if function.effects.suspends {
text.push_str(".await");
}
}
@@ -0,0 +1,58 @@
//! multipart 的文件不参与 Serde;标量继续复用同一具名字段 codec。
use super::*;
use crate::compiler::emit::AppendCode;
pub(in crate::compiler::emit::application) fn arguments(
signature: &Signature,
program: &Program,
text: &mut String,
) {
let fields = signature
.inputs
.iter()
.filter(|f| f.kind != Type::Upload)
.cloned()
.collect::<Vec<_>>();
let name = format!("Fields_{}", symbol(&signature.name));
text.append_code(format_args!("struct {name}{{\n"));
for (i, field) in fields.iter().enumerate() {
text.append_code(format_args!(
"f{i}:{},\n",
types::name(&field.kind, Storage::Owned, program)
));
}
text.push_str("}\n");
wire::decode(&name, &fields, program, text);
}
pub(super) fn decode(entry: &HttpEntry, program: &Program, text: &mut String) {
let signature = &program.functions[entry.function].signature;
let name = symbol(&signature.name);
let file = signature
.inputs
.iter()
.find(|f| f.kind == Type::Upload)
.unwrap();
let fields = signature
.inputs
.iter()
.filter(|f| f.kind != Type::Upload)
.map(|f| f.name.as_str())
.collect::<Vec<_>>();
let tenant = if entry.access == HttpAccess::Public {
"None"
} else {
"identity.tenant()"
};
text.append_code(format_args!("let multipart=dever_runtime::upload::read(&request,body,settings.api.http.upload.as_ref().unwrap(),{tenant},{:?},&{fields:?},task_scope).await?;let fields:Fields_{name}=multipart.fields()?;let args=Args_{name}{{",file.name));
let mut scalar = 0;
for (i, field) in signature.inputs.iter().enumerate() {
if field.kind == Type::Upload {
text.append_code(format_args!("f{i}:multipart.upload,"));
} else {
text.append_code(format_args!("f{i}:fields.f{scalar},"));
scalar += 1;
}
}
text.push_str("};");
}
@@ -0,0 +1,187 @@
//! REST 只增加路径、输入缺省与公开字段投影;数据库函数由普通生成器输出。
use super::*;
use crate::compiler::emit::AppendCode;
pub(in crate::compiler::emit::application) fn arguments(
entry: &HttpEntry,
program: &Program,
text: &mut String,
) {
let rest = entry.rest.as_ref().unwrap();
let function = &program.functions[entry.function];
let name = symbol(&function.signature.name);
let mut fields = function.signature.inputs[usize::from(rest.detail)..].to_vec();
if entry.method == "GET" && !rest.detail {
for field in &mut fields {
field.kind = Type::Optional(Box::new(field.kind.clone()));
}
}
if let Some((position, _)) = rest.search {
let Shape::Record(model) = &program.definitions[rest.record].shape else {
unreachable!()
};
let mut field = model[position].clone();
field.kind = Type::Optional(Box::new(field.kind));
field.range = None;
field.model = None;
fields.push(field);
}
text.append_code(format_args!("struct RestArgs_{name} {{\n"));
for (i, field) in fields.iter().enumerate() {
text.append_code(format_args!(
"f{i}:{},\n",
types::name(&field.kind, Storage::Owned, program)
));
}
text.push_str("}\n");
wire::decode(&format!("RestArgs_{name}"), &fields, program, text);
}
pub(super) fn decode(entry: &HttpEntry, program: &Program, text: &mut String) {
let rest = entry.rest.as_ref().unwrap();
let function = &program.functions[entry.function];
let name = symbol(&function.signature.name);
let fields = &function.signature.inputs[usize::from(rest.detail)..];
text.append_code(format_args!("let input:RestArgs_{name}="));
if matches!(entry.method.as_str(), "GET" | "DELETE") {
text.push_str("api::query(&request)?;");
} else {
text.append_code(format_args!(
"api::json(&request,{},{},false)?;",
crate::compiler::check::wire::shallow(fields, program),
fields
.iter()
.any(|f| crate::compiler::check::wire::dynamic(&f.kind, &program.definitions))
));
}
if rest.search.is_some() {
text.push_str("let rest_search=input.f2;");
}
text.append_code(format_args!("let args=Args_{name}{{"));
if rest.detail {
let Type::ModelId(source) = function.signature.inputs[0].kind else {
unreachable!()
};
text.append_code(format_args!(
"f0:dever_runtime::database::Id::<{source}>(id),"
));
}
if entry.method == "GET" && !rest.detail {
let model = program.definitions[rest.record].model.as_ref().unwrap();
let index = program
.databases()
.iter()
.position(|name| *name == model.database)
.unwrap();
let storage = if model.global {
format!("database.storage.global({index})")
} else {
format!("database.storage.model({index})?")
};
text.append_code(format_args!("f0:input.f0.unwrap_or(1),f1:match input.f1{{Some(size)=>size,None=>{storage}.max_page_size().min(20) as i64}},"));
} else {
for i in 0..fields.len() {
text.append_code(format_args!(
"f{}:input.f{i},",
i + usize::from(rest.detail)
));
}
}
text.push_str("};");
}
pub(super) fn call(
entry: &HttpEntry,
program: &Program,
decisions: &[Ownership],
text: &mut String,
) {
if let Some((_, target)) = entry.rest.as_ref().and_then(|r| r.search) {
text.append_code(format_args!(
"if let Some(search)=rest_search{{let args=Args_{}{{f0:args.f0,f1:args.f1,f2:search}};",
symbol(&program.functions[target].signature.name)
));
invoke(target, program, decisions, text);
text.push_str("}else{");
invoke(entry.function, program, decisions, text);
text.push('}');
} else {
invoke(entry.function, program, decisions, text);
}
}
pub(super) fn outputs(program: &Program, text: &mut String) {
let records = program
.http
.iter()
.filter_map(|e| e.rest.as_ref().map(|r| r.record))
.collect::<BTreeSet<_>>();
for record in records {
let definition = &program.definitions[record];
let fields = definition.columns();
text.append_code(format_args!("fn rest_record_{record}(output:&mut wire::json::Writer,value:&{})->Result<(),String>{{output.object(|output|{{",symbol(&definition.name)));
for (out, (index, field)) in fields
.iter()
.enumerate()
.filter(|(_, f)| !f.private)
.enumerate()
{
wire::finite(&field.kind, &format!("value.f{index}"), program, text);
text.append_code(format_args!(
"output.field({:?},{},|output|",
field.name,
out == 0
));
json::value(&field.kind, &format!("&value.f{index}"), program, text);
text.push_str(")?;");
}
text.push_str("Ok(())})}\n");
}
}
pub(super) fn response(entry: &HttpEntry, _program: &Program, text: &mut String) {
let rest = entry.rest.as_ref().unwrap();
if entry.method == "DELETE" {
text.push_str("wire::json::response_body(|output| output.value(&()))");
return;
}
text.push_str("wire::json::response_body(|output|");
if entry.method == "GET" && !rest.detail {
text.append_code(format_args!("output.object(|output|{{output.field(\"items\",true,|output|output.array(|output|{{for (i,item) in value.f0.iter().enumerate(){{output.element(i==0,|output|rest_record_{}(output,item))?;}}Ok(())}}))?;",rest.record));
for (i, key) in ["page", "size", "total", "pages"].iter().enumerate() {
text.append_code(format_args!(
"output.field({key:?},false,|output|output.value(&value.f{}))?;",
i + 1
));
}
text.push_str("Ok(())})");
} else {
text.append_code(format_args!("rest_record_{}(output,&value)", rest.record));
}
text.push(')');
}
pub(super) fn routes(program: &Program, text: &mut String) {
for (index, entry) in program
.http
.iter()
.enumerate()
.filter(|(_, e)| e.rest.as_ref().is_some_and(|r| !r.detail) && e.method == "GET")
{
let prefix = format!("{}/", entry.path);
text.append_code(format_args!("(_,path) if (path=={:?}||path.starts_with({prefix:?})) && settings.api.accepts({index},&request)=>{{let detail=path!={:?};let id=if detail{{path.strip_prefix({prefix:?}).unwrap().parse::<i64>().ok().filter(|id|*id>0)}}else{{None}};if detail&&id.is_none(){{Err(ApiFailure::new(404,\"invalid REST id\"))}}else{{match(request.method(),detail){{",entry.path,entry.path));
for (i, e) in program
.http
.iter()
.enumerate()
.filter(|(_, e)| e.rest.is_some() && e.path == entry.path)
{
let detail = e.rest.as_ref().unwrap().detail;
text.append_code(format_args!("({:?},{detail})=>api_{i}(request{},&request_scope,&settings,peer,&database{}).await,",
e.method,
if program.uses_upload() {",body"} else {""},
if detail { ",id.unwrap()" } else { "" }));
}
text.push_str("_=>Ok(api::method_not_allowed(if detail{\"GET, PUT, DELETE\"}else{\"GET, POST\"}))}}},");
}
}
Loaded 100 of 816 files, more files were not shown because too many files have changed in this diff. Show more