Compare commits
8
Commits
8c50dd202d
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e5c73c647d | ||
|
|
cda32cc260 | ||
|
|
3645a2cc2d | ||
|
|
e50458595b | ||
|
|
6653607ed3 | ||
|
|
e0970acdcc | ||
|
|
e0a9a8efb7 | ||
|
|
848c7f169f |
@@ -9,3 +9,4 @@ site/decodal-site/dist
|
||||
|
||||
# Astro
|
||||
site/decodal-site/.astro
|
||||
site/decodal-site/.wrangler
|
||||
|
||||
Generated
+7
-7
@@ -46,7 +46,7 @@ checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
|
||||
|
||||
[[package]]
|
||||
name = "decodal"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"decodal-derive",
|
||||
"regex",
|
||||
@@ -54,14 +54,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "decodal-cli"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"decodal",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "decodal-derive"
|
||||
version = "0.1.3"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"decodal",
|
||||
"proc-macro2",
|
||||
@@ -71,14 +71,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "decodal-language-service"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"decodal",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "decodal-language-tools"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"decodal",
|
||||
"serde_json",
|
||||
@@ -87,7 +87,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "decodal-lsp"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"decodal",
|
||||
"decodal-language-service",
|
||||
@@ -99,7 +99,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "decodal-wasm"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"decodal",
|
||||
"decodal-language-service",
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ exclude = ["editors/tree-sitter-decodal"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.85"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
@@ -9,7 +9,8 @@ It is designed around a lightweight Rust library:
|
||||
- no filesystem access in the library core
|
||||
- concrete and abstract values with constraints and defaults
|
||||
- asymmetric range refinement with `narrower as wider`
|
||||
- homogeneous associative-array schemas with `{...valueSchema}`
|
||||
- homogeneous associative-array schemas with `{...valueSchema}` and object rest constraints
|
||||
- the safe top range `Unknown`, which remains abstract until refined, defaulted, or supplied concretely
|
||||
- deterministic expression evaluation
|
||||
- optional regex support behind a Cargo feature
|
||||
- browser playground support through WebAssembly
|
||||
@@ -20,16 +21,17 @@ Embedded hosts should depend on `decodal` and provide imports with an `ImportLoa
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
decodal = "0.3.0"
|
||||
decodal = "0.4.0"
|
||||
```
|
||||
|
||||
## Derive support
|
||||
|
||||
For embedded Rust applications, Decodal can generate a schema and typed decoder from a Rust struct with the `derive` feature.
|
||||
Map fields marked with `#[decodal(rest)]` receive additional object fields; `BTreeMap<String, Data>` corresponds to `...Unknown`.
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
decodal = { version = "0.3.0", features = ["derive"] }
|
||||
decodal = { version = "0.4.0", features = ["derive"] }
|
||||
```
|
||||
|
||||
```rust
|
||||
@@ -47,7 +49,7 @@ struct Service {
|
||||
|
||||
The derive implements:
|
||||
|
||||
- `DecodalSchema`, which produces a host schema for `Engine::bind_global`
|
||||
- `DecodalSchema`, which produces a `Value` range for `Engine::bind_global`
|
||||
- `DecodalDecode`, which converts materialized `Data` into the Rust struct
|
||||
|
||||
## CLI
|
||||
@@ -74,9 +76,9 @@ Its library API accepts the same host environment used for production evaluation
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
decodal = "0.3.0"
|
||||
decodal-language-service = "0.3.0"
|
||||
decodal-lsp = "0.3.0"
|
||||
decodal = "0.4.0"
|
||||
decodal-language-service = "0.4.0"
|
||||
decodal-lsp = "0.4.0"
|
||||
```
|
||||
|
||||
Run the default filesystem-backed server from the repository:
|
||||
|
||||
+5
-4
@@ -4,10 +4,10 @@ Run all commands from the repository root. Publishing requires Cargo, npm, and J
|
||||
|
||||
## Versions
|
||||
|
||||
- `decodal-derive`: `0.1.3` (already published)
|
||||
- Other published Rust crates: `0.3.0`
|
||||
- `decodal-wasm` npm/JSR package: `0.2.0`
|
||||
- `decodal-codemirror`: `0.2.0`
|
||||
- `decodal-derive`: `0.2.0`
|
||||
- Other published Rust crates: `0.4.0`
|
||||
- `decodal-wasm` npm/JSR package: `0.3.0`
|
||||
- `decodal-codemirror`: `0.3.0`
|
||||
|
||||
The npm packages advertise the repository's dual `MIT OR Apache-2.0` license.
|
||||
JSR metadata uses the single `MIT` identifier required by its publisher; both license files remain included in every package.
|
||||
@@ -38,6 +38,7 @@ Publish in dependency order. Wait for each crate to become available in the crat
|
||||
Run the corresponding command with `--dry-run` immediately before each real publish.
|
||||
|
||||
```sh
|
||||
cargo publish -p decodal-derive
|
||||
cargo publish -p decodal
|
||||
cargo publish -p decodal-language-service
|
||||
cargo publish -p decodal-language-tools
|
||||
|
||||
@@ -20,4 +20,4 @@ default = []
|
||||
regex = ["decodal/regex"]
|
||||
|
||||
[dependencies]
|
||||
decodal = { version = "0.3.0", path = "../decodal-core" }
|
||||
decodal = { version = "0.4.0", path = "../decodal-core" }
|
||||
|
||||
@@ -5,10 +5,16 @@ use std::{
|
||||
};
|
||||
|
||||
use decodal::{
|
||||
Data, Diagnostic, DiagnosticKind, Engine, ImportLoader, LoadedImport, LoadedSource, SourceId,
|
||||
Span, format_diagnostic_with,
|
||||
Data, Diagnostic, DiagnosticKind, Engine, ImportLoader, LoadedImport, SourceId, Span,
|
||||
format_diagnostic_with,
|
||||
};
|
||||
|
||||
struct SourceInput {
|
||||
key: String,
|
||||
name: String,
|
||||
source: String,
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
@@ -69,7 +75,7 @@ fn materialize_path(path: &str) -> Result<Data, String> {
|
||||
.map_err(|error| engine.format_diagnostic(&error))
|
||||
}
|
||||
|
||||
fn read_root_source(path: &str) -> Result<LoadedSource, Diagnostic> {
|
||||
fn read_root_source(path: &str) -> Result<SourceInput, Diagnostic> {
|
||||
if path == "-" {
|
||||
use std::io::Read;
|
||||
let mut source = String::new();
|
||||
@@ -82,7 +88,7 @@ fn read_root_source(path: &str) -> Result<LoadedSource, Diagnostic> {
|
||||
format!("failed to read stdin: {error}"),
|
||||
)
|
||||
})?;
|
||||
Ok(LoadedSource {
|
||||
Ok(SourceInput {
|
||||
key: String::from("<stdin>"),
|
||||
name: String::from("<stdin>"),
|
||||
source,
|
||||
@@ -112,11 +118,11 @@ impl ImportLoader for FsLoader {
|
||||
} else {
|
||||
PathBuf::from(path)
|
||||
};
|
||||
load_path(&path).map(LoadedImport::Source)
|
||||
load_path(&path).map(|source| LoadedImport::source(source.key, source.name, source.source))
|
||||
}
|
||||
}
|
||||
|
||||
fn load_path(path: &Path) -> Result<LoadedSource, Diagnostic> {
|
||||
fn load_path(path: &Path) -> Result<SourceInput, Diagnostic> {
|
||||
let canonical = path.canonicalize().map_err(|error| {
|
||||
Diagnostic::new(
|
||||
DiagnosticKind::Import,
|
||||
@@ -132,7 +138,7 @@ fn load_path(path: &Path) -> Result<LoadedSource, Diagnostic> {
|
||||
)
|
||||
})?;
|
||||
let key = canonical.to_string_lossy().into_owned();
|
||||
Ok(LoadedSource {
|
||||
Ok(SourceInput {
|
||||
name: key.clone(),
|
||||
key,
|
||||
source,
|
||||
|
||||
@@ -17,5 +17,5 @@ derive = ["dep:decodal-derive"]
|
||||
regex = ["std", "dep:regex"]
|
||||
|
||||
[dependencies]
|
||||
decodal-derive = { version = "0.1.3", path = "../decodal-derive", optional = true }
|
||||
decodal-derive = { version = "0.2.0", path = "../decodal-derive", optional = true }
|
||||
regex = { version = "1.10", default-features = false, features = ["std", "unicode-perl"], optional = true }
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
use decodal::{Data, EmptyLoader, Engine, HostValue};
|
||||
use decodal::{Data, EmptyLoader, Engine, Value};
|
||||
|
||||
fn main() -> decodal::Result<()> {
|
||||
let mut engine = Engine::new(EmptyLoader);
|
||||
|
||||
engine.bind_global(
|
||||
"Service",
|
||||
HostValue::object([
|
||||
("name", HostValue::string_type()),
|
||||
("port", HostValue::int_type().gt(443).default_int(8443)?),
|
||||
("enabled", HostValue::bool_type().default_bool(true)?),
|
||||
Value::object([
|
||||
("name", Value::string_type()),
|
||||
("port", Value::int_type().gt(443).default_int(8443)?),
|
||||
("enabled", Value::bool_type().default_bool(true)?),
|
||||
]),
|
||||
)?;
|
||||
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
use decodal::{
|
||||
Data, Diagnostic, DiagnosticKind, Engine, HostValue, ImportLoader, LoadedImport, Span,
|
||||
};
|
||||
use decodal::{Data, Diagnostic, DiagnosticKind, Engine, ImportLoader, LoadedImport, Span, Value};
|
||||
|
||||
const POST: &str = r#"---
|
||||
title: Hello
|
||||
@@ -33,22 +31,22 @@ impl ImportLoader for ContentLoader {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_markdown(source: &str) -> decodal::Result<HostValue> {
|
||||
fn parse_markdown(source: &str) -> decodal::Result<Value> {
|
||||
let source = source.strip_prefix("---\n").ok_or_else(frontmatter_error)?;
|
||||
let (frontmatter, body) = source.split_once("\n---\n").ok_or_else(frontmatter_error)?;
|
||||
let mut fields = Vec::new();
|
||||
for line in frontmatter.lines() {
|
||||
let (name, value) = line.split_once(':').ok_or_else(frontmatter_error)?;
|
||||
let value = match value.trim() {
|
||||
"true" => HostValue::bool(true),
|
||||
"false" => HostValue::bool(false),
|
||||
value => HostValue::string(value),
|
||||
"true" => Value::bool(true),
|
||||
"false" => Value::bool(false),
|
||||
value => Value::string(value),
|
||||
};
|
||||
fields.push((name.trim(), value));
|
||||
}
|
||||
Ok(HostValue::object([
|
||||
("frontmatter", HostValue::object(fields)),
|
||||
("body", HostValue::string(body)),
|
||||
Ok(Value::object([
|
||||
("frontmatter", Value::object(fields)),
|
||||
("body", Value::string(body)),
|
||||
]))
|
||||
}
|
||||
|
||||
|
||||
@@ -48,7 +48,10 @@ pub struct SpannedExpr {
|
||||
pub enum Expr {
|
||||
Literal(Literal),
|
||||
Ident(String),
|
||||
Object(Vec<Field>),
|
||||
Object {
|
||||
fields: Vec<Field>,
|
||||
rest: Option<ObjectRest>,
|
||||
},
|
||||
Array(Vec<ExprId>),
|
||||
ArrayConstraint {
|
||||
item: ExprId,
|
||||
@@ -116,6 +119,12 @@ pub struct Field {
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ObjectRest {
|
||||
pub value: ExprId,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Param {
|
||||
pub name: String,
|
||||
|
||||
@@ -19,6 +19,10 @@ pub fn normalize_constraints(
|
||||
|
||||
for entry in constraints {
|
||||
match entry.constraint {
|
||||
Constraint::Unknown => rest.push(ConstraintEntry {
|
||||
constraint: Constraint::Unknown,
|
||||
span: entry.span,
|
||||
}),
|
||||
Constraint::Type(next) => match primitive {
|
||||
Some((current, current_span)) if current != next => {
|
||||
return Err(Diagnostic::new(
|
||||
|
||||
+483
-81
@@ -5,14 +5,15 @@ use crate::{
|
||||
ast::{Ast, BinaryOp, CompareOp, Expr, Field, Literal, UnaryOp},
|
||||
constraints::normalize_constraints,
|
||||
diagnostic::{Diagnostic, DiagnosticKind, Result},
|
||||
embedding::HostValue,
|
||||
module::{EmptyLoader, ImportLoader, LoadedImport, LoadedSource, LoadedValue, Module},
|
||||
module::{EmptyLoader, ImportLoader, LoadedImport, Module},
|
||||
parse_source_with_source_id,
|
||||
runtime::{
|
||||
AbstractValue, Binding, ConcreteValue, Constraint, ConstraintEntry, Data, DataField, Env,
|
||||
EnvId, ExprRef, FunctionParam, FunctionValue, LiteralValue, ModuleId, ObjectField,
|
||||
ObjectValue, PrimitiveType, RuntimeValue, Thunk, ThunkId, ThunkKind, ThunkState,
|
||||
ObjectRest as RuntimeObjectRest, ObjectValue, PrimitiveType, RuntimeValue, Thunk, ThunkId,
|
||||
ThunkKind, ThunkState,
|
||||
},
|
||||
value::Value,
|
||||
};
|
||||
|
||||
pub struct Engine<L = EmptyLoader> {
|
||||
@@ -94,8 +95,8 @@ impl<L: ImportLoader> Engine<L> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bind_global(&mut self, name: impl Into<String>, value: HostValue) -> Result<ThunkId> {
|
||||
let value = self.internalize_host_value(value)?;
|
||||
pub fn bind_global(&mut self, name: impl Into<String>, value: Value) -> Result<ThunkId> {
|
||||
let value = self.internalize_value(value)?;
|
||||
let thunk = self.add_value_thunk(value);
|
||||
self.bind(self.prelude_env, name.into(), thunk);
|
||||
Ok(thunk)
|
||||
@@ -280,9 +281,9 @@ impl<L: ImportLoader> Engine<L> {
|
||||
let module = ModuleId(self.modules.len() as u32);
|
||||
let root_env = self.new_env(Some(self.prelude_env));
|
||||
let root_thunk = if source_form == SourceForm::Fields {
|
||||
if let Expr::Object(fields) = ast.get(root).expr.clone() {
|
||||
if let Expr::Object { fields, rest } = ast.get(root).expr.clone() {
|
||||
let object = self
|
||||
.build_object(module, &fields, root_env)
|
||||
.build_object(module, &fields, rest.as_ref(), root_env)
|
||||
.expect("module object construction should not fail for parsed fields");
|
||||
for field in &object.fields {
|
||||
self.bind(root_env, field.name.clone(), field.value);
|
||||
@@ -318,14 +319,14 @@ impl<L: ImportLoader> Engine<L> {
|
||||
let current_key = self.modules[current.0 as usize].key.clone();
|
||||
let loaded = self.loader.load(Some(¤t_key), specifier)?;
|
||||
match loaded {
|
||||
LoadedImport::Source(LoadedSource { key, name, source }) => {
|
||||
LoadedImport::Source { key, name, source } => {
|
||||
if let Some(value) = self.find_imported_value(&key) {
|
||||
return self.force(value);
|
||||
}
|
||||
let module = self.add_source(key, name, &source)?;
|
||||
self.eval_module(module)
|
||||
}
|
||||
LoadedImport::Value(LoadedValue { key, value }) => {
|
||||
LoadedImport::Value { key, value } => {
|
||||
if let Some(module) = self.find_module(&key) {
|
||||
return self.eval_module(module);
|
||||
}
|
||||
@@ -333,7 +334,7 @@ impl<L: ImportLoader> Engine<L> {
|
||||
return self.force(value);
|
||||
}
|
||||
let origin = ImportedValueOrigin::root(key.clone());
|
||||
let value = self.internalize_host_value_with_origin(value, Some(&origin))?;
|
||||
let value = self.internalize_value_with_origin(value, Some(&origin))?;
|
||||
let root = self.add_value_thunk_with_import_origin(value, origin);
|
||||
self.imported_values.push(ImportedValue { key, root });
|
||||
self.force(root)
|
||||
@@ -354,8 +355,8 @@ impl<L: ImportLoader> Engine<L> {
|
||||
match expr {
|
||||
Expr::Literal(literal) => Ok(RuntimeValue::Concrete(literal_to_concrete(literal))),
|
||||
Expr::Ident(name) => self.eval_ident(&name, env, span),
|
||||
Expr::Object(fields) => self
|
||||
.build_object(reference.module, &fields, env)
|
||||
Expr::Object { fields, rest } => self
|
||||
.build_object(reference.module, &fields, rest.as_ref(), env)
|
||||
.map(|object| RuntimeValue::Concrete(ConcreteValue::Object(object))),
|
||||
Expr::Array(items) => {
|
||||
let thunks = items
|
||||
@@ -699,6 +700,15 @@ impl<L: ImportLoader> Engine<L> {
|
||||
}
|
||||
|
||||
fn eval_ident(&mut self, name: &str, env: EnvId, span: Span) -> Result<RuntimeValue> {
|
||||
if name == "Unknown" {
|
||||
return Ok(RuntimeValue::Abstract(AbstractValue {
|
||||
constraints: vec![ConstraintEntry {
|
||||
constraint: Constraint::Unknown,
|
||||
span,
|
||||
}],
|
||||
default: None,
|
||||
}));
|
||||
}
|
||||
if let Some(primitive) = primitive_type(name) {
|
||||
return Ok(RuntimeValue::Abstract(AbstractValue {
|
||||
constraints: vec![ConstraintEntry {
|
||||
@@ -738,9 +748,23 @@ impl<L: ImportLoader> Engine<L> {
|
||||
&mut self,
|
||||
module: ModuleId,
|
||||
fields: &[Field],
|
||||
rest: Option<&crate::ast::ObjectRest>,
|
||||
env: EnvId,
|
||||
) -> Result<ObjectValue> {
|
||||
let mut object = ObjectValue { fields: Vec::new() };
|
||||
let mut object = ObjectValue {
|
||||
fields: Vec::new(),
|
||||
rest: rest.map(|rest| RuntimeObjectRest {
|
||||
value: self.add_expr_thunk_with_span(
|
||||
ExprRef {
|
||||
module,
|
||||
expr: rest.value,
|
||||
},
|
||||
env,
|
||||
rest.span,
|
||||
),
|
||||
span: rest.span,
|
||||
}),
|
||||
};
|
||||
for field in fields {
|
||||
self.insert_field(
|
||||
&mut object,
|
||||
@@ -805,7 +829,10 @@ impl<L: ImportLoader> Engine<L> {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut nested = ObjectValue { fields: Vec::new() };
|
||||
let mut nested = ObjectValue {
|
||||
fields: Vec::new(),
|
||||
rest: None,
|
||||
};
|
||||
self.insert_field(&mut nested, module, &path[1..], expr, env, span)?;
|
||||
object.fields.push(ObjectField {
|
||||
name: name.clone(),
|
||||
@@ -1032,6 +1059,7 @@ impl<L: ImportLoader> Engine<L> {
|
||||
) -> Result<()> {
|
||||
for wider_entry in &wider.constraints {
|
||||
let implied = match &wider_entry.constraint {
|
||||
Constraint::Unknown => true,
|
||||
Constraint::Type(wider_type) => narrower.constraints.iter().any(|entry| {
|
||||
matches!(entry.constraint, Constraint::Type(narrower_type) if narrower_type == *wider_type)
|
||||
}),
|
||||
@@ -1145,11 +1173,20 @@ impl<L: ImportLoader> Engine<L> {
|
||||
));
|
||||
};
|
||||
|
||||
for narrower_field in &narrower.fields {
|
||||
if wider
|
||||
.fields
|
||||
let ObjectValue {
|
||||
fields: narrower_fields,
|
||||
rest: narrower_rest,
|
||||
} = narrower;
|
||||
let ObjectValue {
|
||||
fields: wider_fields,
|
||||
rest: wider_rest,
|
||||
} = wider;
|
||||
|
||||
for narrower_field in &narrower_fields {
|
||||
if wider_fields
|
||||
.iter()
|
||||
.all(|wider_field| wider_field.name != narrower_field.name)
|
||||
&& wider_rest.is_none()
|
||||
{
|
||||
let origin = self.thunk_import_origin(narrower_field.value).cloned();
|
||||
let diagnostic_span = if origin.is_some() {
|
||||
@@ -1172,10 +1209,33 @@ impl<L: ImportLoader> Engine<L> {
|
||||
}
|
||||
}
|
||||
|
||||
let mut refined = ObjectValue { fields: Vec::new() };
|
||||
for wider_field in wider.fields {
|
||||
let Some(narrower_field) = narrower
|
||||
.fields
|
||||
if let Some(narrower_rest) = &narrower_rest
|
||||
&& wider_rest.is_none()
|
||||
{
|
||||
let diagnostic = Diagnostic::new(
|
||||
DiagnosticKind::ConstraintViolation,
|
||||
source_span_or(narrower_rest.span, narrower_diagnostic_span),
|
||||
"left side of `as` permits additional fields but the right side is closed",
|
||||
)
|
||||
.with_label(operation_span, "`as` applied here");
|
||||
let diagnostic = with_source_label(
|
||||
diagnostic,
|
||||
narrower_rest.span,
|
||||
"narrower object rest range declared here",
|
||||
);
|
||||
return Err(with_source_label(
|
||||
diagnostic,
|
||||
wider_span,
|
||||
"closed wider object declared here",
|
||||
));
|
||||
}
|
||||
|
||||
let mut refined = ObjectValue {
|
||||
fields: Vec::new(),
|
||||
rest: None,
|
||||
};
|
||||
for wider_field in wider_fields.iter().cloned() {
|
||||
let Some(narrower_field) = narrower_fields
|
||||
.iter()
|
||||
.find(|narrower_field| narrower_field.name == wider_field.name)
|
||||
else {
|
||||
@@ -1227,6 +1287,82 @@ impl<L: ImportLoader> Engine<L> {
|
||||
span: narrower_field.span,
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(wider_rest) = &wider_rest {
|
||||
let wider_rest_value = self.force(wider_rest.value)?;
|
||||
for narrower_field in narrower_fields.iter().filter(|narrower_field| {
|
||||
wider_fields
|
||||
.iter()
|
||||
.all(|wider_field| wider_field.name != narrower_field.name)
|
||||
}) {
|
||||
let narrower_origin = self.thunk_import_origin(narrower_field.value).cloned();
|
||||
let narrower_value = self.force(narrower_field.value)?;
|
||||
let field_name = narrower_field.name.clone();
|
||||
let narrowed = self
|
||||
.apply_as(
|
||||
narrower_value.clone(),
|
||||
wider_rest_value.clone(),
|
||||
operation_span,
|
||||
narrower_field.span,
|
||||
wider_rest.span,
|
||||
)
|
||||
.map_err(|diagnostic| {
|
||||
let diagnostic = with_source_label(
|
||||
diagnostic,
|
||||
wider_rest.span,
|
||||
"wider object rest range declared here",
|
||||
);
|
||||
if narrower_origin.is_some() {
|
||||
annotate_imported_value(
|
||||
diagnostic,
|
||||
narrower_origin.as_ref(),
|
||||
Some(&narrower_value),
|
||||
)
|
||||
} else {
|
||||
with_source_label(
|
||||
diagnostic,
|
||||
narrower_field.span,
|
||||
format!("additional field `{field_name}` checked here"),
|
||||
)
|
||||
}
|
||||
})?;
|
||||
refined.fields.push(ObjectField {
|
||||
name: field_name,
|
||||
value: self.add_value_thunk_with_span_and_import_origin(
|
||||
narrowed,
|
||||
narrower_field.span,
|
||||
narrower_origin,
|
||||
),
|
||||
span: narrower_field.span,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
refined.rest = match (narrower_rest, wider_rest) {
|
||||
(Some(narrower_rest), Some(wider_rest)) => {
|
||||
let narrower_origin = self.thunk_import_origin(narrower_rest.value).cloned();
|
||||
let narrower_value = self.force(narrower_rest.value)?;
|
||||
let wider_value = self.force(wider_rest.value)?;
|
||||
let narrowed = self.apply_as(
|
||||
narrower_value,
|
||||
wider_value,
|
||||
operation_span,
|
||||
narrower_rest.span,
|
||||
wider_rest.span,
|
||||
)?;
|
||||
Some(RuntimeObjectRest {
|
||||
value: self.add_value_thunk_with_span_and_import_origin(
|
||||
narrowed,
|
||||
narrower_rest.span,
|
||||
narrower_origin,
|
||||
),
|
||||
span: narrower_rest.span,
|
||||
})
|
||||
}
|
||||
(None, Some(wider_rest)) => Some(wider_rest),
|
||||
(None, None) => None,
|
||||
(Some(_), None) => unreachable!("open narrower object was rejected above"),
|
||||
};
|
||||
Ok(RuntimeValue::Concrete(ConcreteValue::Object(refined)))
|
||||
}
|
||||
|
||||
@@ -1321,7 +1457,46 @@ impl<L: ImportLoader> Engine<L> {
|
||||
rhs: ObjectValue,
|
||||
span: Span,
|
||||
) -> Result<RuntimeValue> {
|
||||
for rhs_field in rhs.fields {
|
||||
let lhs_rest = lhs.rest.take();
|
||||
let rhs_rest = rhs.rest;
|
||||
let rhs_field_names = rhs
|
||||
.fields
|
||||
.iter()
|
||||
.map(|field| field.name.clone())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if let Some(rhs_rest) = &rhs_rest {
|
||||
let rhs_rest_value = self.force(rhs_rest.value)?;
|
||||
for lhs_field in lhs
|
||||
.fields
|
||||
.iter_mut()
|
||||
.filter(|field| !rhs_field_names.contains(&field.name))
|
||||
{
|
||||
let lhs_origin = self.thunk_import_origin(lhs_field.value).cloned();
|
||||
let lhs_value = self.force(lhs_field.value)?;
|
||||
let value = self
|
||||
.compose_and(lhs_value.clone(), rhs_rest_value.clone(), span)
|
||||
.map_err(|diagnostic| {
|
||||
let diagnostic = with_source_label(
|
||||
diagnostic,
|
||||
rhs_rest.span,
|
||||
"right object rest constraint declared here",
|
||||
);
|
||||
with_source_label(
|
||||
diagnostic,
|
||||
lhs_field.span,
|
||||
format!("left field `{}` constrained here", lhs_field.name),
|
||||
)
|
||||
})?;
|
||||
lhs_field.value = self.add_value_thunk_with_span_and_import_origin(
|
||||
value,
|
||||
lhs_field.span,
|
||||
lhs_origin,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for mut rhs_field in rhs.fields {
|
||||
if let Some(index) = lhs
|
||||
.fields
|
||||
.iter()
|
||||
@@ -1381,9 +1556,65 @@ impl<L: ImportLoader> Engine<L> {
|
||||
lhs.fields[index].span = rhs_field.span;
|
||||
}
|
||||
} else {
|
||||
if let Some(lhs_rest) = &lhs_rest {
|
||||
let rhs_origin = self.thunk_import_origin(rhs_field.value).cloned();
|
||||
let rhs_value = self.force(rhs_field.value)?;
|
||||
let lhs_rest_value = self.force(lhs_rest.value)?;
|
||||
let value = self.compose_and(rhs_value, lhs_rest_value, span).map_err(
|
||||
|diagnostic| {
|
||||
let diagnostic = with_source_label(
|
||||
diagnostic,
|
||||
lhs_rest.span,
|
||||
"left object rest constraint declared here",
|
||||
);
|
||||
with_source_label(
|
||||
diagnostic,
|
||||
rhs_field.span,
|
||||
format!("right field `{}` constrained here", rhs_field.name),
|
||||
)
|
||||
},
|
||||
)?;
|
||||
rhs_field.value = self.add_value_thunk_with_span_and_import_origin(
|
||||
value,
|
||||
rhs_field.span,
|
||||
rhs_origin,
|
||||
);
|
||||
}
|
||||
lhs.fields.push(rhs_field);
|
||||
}
|
||||
}
|
||||
|
||||
lhs.rest = match (lhs_rest, rhs_rest) {
|
||||
(Some(lhs_rest), Some(rhs_rest)) => {
|
||||
let lhs_origin = self.thunk_import_origin(lhs_rest.value).cloned();
|
||||
let lhs_value = self.force(lhs_rest.value)?;
|
||||
let rhs_value = self.force(rhs_rest.value)?;
|
||||
let value = self
|
||||
.compose_and(lhs_value, rhs_value, span)
|
||||
.map_err(|diagnostic| {
|
||||
let diagnostic = with_source_label(
|
||||
diagnostic,
|
||||
lhs_rest.span,
|
||||
"left object rest constraint declared here",
|
||||
);
|
||||
with_source_label(
|
||||
diagnostic,
|
||||
rhs_rest.span,
|
||||
"right object rest constraint declared here",
|
||||
)
|
||||
})?;
|
||||
Some(RuntimeObjectRest {
|
||||
value: self.add_value_thunk_with_span_and_import_origin(
|
||||
value,
|
||||
rhs_rest.span,
|
||||
lhs_origin,
|
||||
),
|
||||
span: rhs_rest.span,
|
||||
})
|
||||
}
|
||||
(Some(rest), None) | (None, Some(rest)) => Some(rest),
|
||||
(None, None) => None,
|
||||
};
|
||||
Ok(RuntimeValue::Concrete(ConcreteValue::Object(lhs)))
|
||||
}
|
||||
|
||||
@@ -1398,6 +1629,7 @@ impl<L: ImportLoader> Engine<L> {
|
||||
}
|
||||
|
||||
fn patch_objects(&mut self, mut lhs: ObjectValue, rhs: ObjectValue) -> Result<RuntimeValue> {
|
||||
let rhs_rest = rhs.rest;
|
||||
for rhs_field in rhs.fields {
|
||||
if let Some(index) = lhs
|
||||
.fields
|
||||
@@ -1418,6 +1650,9 @@ impl<L: ImportLoader> Engine<L> {
|
||||
lhs.fields.push(rhs_field);
|
||||
}
|
||||
}
|
||||
if rhs_rest.is_some() {
|
||||
lhs.rest = rhs_rest;
|
||||
}
|
||||
Ok(RuntimeValue::Concrete(ConcreteValue::Object(lhs)))
|
||||
}
|
||||
|
||||
@@ -1459,6 +1694,7 @@ impl<L: ImportLoader> Engine<L> {
|
||||
constraint.span
|
||||
};
|
||||
match constraint_value {
|
||||
Constraint::Unknown => Ok(value),
|
||||
Constraint::Type(primitive) => {
|
||||
if value_matches_primitive(&value, *primitive) {
|
||||
Ok(value)
|
||||
@@ -1547,8 +1783,12 @@ impl<L: ImportLoader> Engine<L> {
|
||||
));
|
||||
};
|
||||
let value_schema = self.force(*value_constraint)?;
|
||||
let mut constrained_fields = Vec::with_capacity(object.fields.len());
|
||||
for field in object.fields {
|
||||
let ObjectValue {
|
||||
fields,
|
||||
rest: object_rest,
|
||||
} = object;
|
||||
let mut constrained_fields = Vec::with_capacity(fields.len());
|
||||
for field in fields {
|
||||
let field_span = self.thunk_span(field.value);
|
||||
let field_origin = self.thunk_import_origin(field.value).cloned();
|
||||
let field_value = self.force(field.value)?;
|
||||
@@ -1592,8 +1832,30 @@ impl<L: ImportLoader> Engine<L> {
|
||||
span: field.span,
|
||||
});
|
||||
}
|
||||
let constrained_rest = if let Some(object_rest) = object_rest {
|
||||
let rest_origin = self.thunk_import_origin(object_rest.value).cloned();
|
||||
let rest_value = self.force(object_rest.value)?;
|
||||
let constrained = self.apply_as(
|
||||
rest_value,
|
||||
value_schema,
|
||||
span,
|
||||
object_rest.span,
|
||||
constraint_span,
|
||||
)?;
|
||||
Some(RuntimeObjectRest {
|
||||
value: self.add_value_thunk_with_span_and_import_origin(
|
||||
constrained,
|
||||
object_rest.span,
|
||||
rest_origin,
|
||||
),
|
||||
span: object_rest.span,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(RuntimeValue::Concrete(ConcreteValue::Object(ObjectValue {
|
||||
fields: constrained_fields,
|
||||
rest: constrained_rest,
|
||||
})))
|
||||
}
|
||||
Constraint::Compare(op, expected) => compare_value(&value, *op, expected)
|
||||
@@ -1671,40 +1933,39 @@ impl<L: ImportLoader> Engine<L> {
|
||||
}
|
||||
}
|
||||
|
||||
fn internalize_host_value(&mut self, value: HostValue) -> Result<RuntimeValue> {
|
||||
self.internalize_host_value_with_origin(value, None)
|
||||
fn internalize_value(&mut self, value: Value) -> Result<RuntimeValue> {
|
||||
self.internalize_value_with_origin(value, None)
|
||||
}
|
||||
|
||||
fn internalize_host_value_with_origin(
|
||||
fn internalize_value_with_origin(
|
||||
&mut self,
|
||||
value: HostValue,
|
||||
value: Value,
|
||||
origin: Option<&ImportedValueOrigin>,
|
||||
) -> Result<RuntimeValue> {
|
||||
match value {
|
||||
HostValue::String(value) => Ok(RuntimeValue::Concrete(ConcreteValue::String(value))),
|
||||
HostValue::Int(value) => Ok(RuntimeValue::Concrete(ConcreteValue::Int(value))),
|
||||
HostValue::Float(value) => Ok(RuntimeValue::Concrete(ConcreteValue::Float(value))),
|
||||
HostValue::Bool(value) => Ok(RuntimeValue::Concrete(ConcreteValue::Bool(value))),
|
||||
HostValue::Array(items) => {
|
||||
Value::String(value) => Ok(RuntimeValue::Concrete(ConcreteValue::String(value))),
|
||||
Value::Int(value) => Ok(RuntimeValue::Concrete(ConcreteValue::Int(value))),
|
||||
Value::Float(value) => Ok(RuntimeValue::Concrete(ConcreteValue::Float(value))),
|
||||
Value::Bool(value) => Ok(RuntimeValue::Concrete(ConcreteValue::Bool(value))),
|
||||
Value::Array(items) => {
|
||||
let mut thunks = Vec::new();
|
||||
for (index, item) in items.into_iter().enumerate() {
|
||||
let item_origin = origin.map(|origin| origin.index(index));
|
||||
let value =
|
||||
self.internalize_host_value_with_origin(item, item_origin.as_ref())?;
|
||||
let value = self.internalize_value_with_origin(item, item_origin.as_ref())?;
|
||||
thunks
|
||||
.push(self.add_value_thunk_with_optional_import_origin(value, item_origin));
|
||||
}
|
||||
Ok(RuntimeValue::Concrete(ConcreteValue::Array(thunks)))
|
||||
}
|
||||
HostValue::ArrayConstraint {
|
||||
Value::ArrayRange {
|
||||
item,
|
||||
mut constraints,
|
||||
default,
|
||||
} => {
|
||||
let item = self.internalize_host_value_with_origin(*item, origin)?;
|
||||
let item = self.internalize_value_with_origin(*item, origin)?;
|
||||
let item = self.add_value_thunk_with_optional_import_origin(item, origin.cloned());
|
||||
let default = if let Some(default) = default {
|
||||
let value = self.internalize_host_value_with_origin(*default, origin)?;
|
||||
let value = self.internalize_value_with_origin(*default, origin)?;
|
||||
Some(self.add_value_thunk_with_optional_import_origin(value, origin.cloned()))
|
||||
} else {
|
||||
None
|
||||
@@ -1723,16 +1984,16 @@ impl<L: ImportLoader> Engine<L> {
|
||||
default,
|
||||
}))
|
||||
}
|
||||
HostValue::MapConstraint {
|
||||
Value::MapRange {
|
||||
value,
|
||||
mut constraints,
|
||||
default,
|
||||
} => {
|
||||
let value = self.internalize_host_value_with_origin(*value, origin)?;
|
||||
let value = self.internalize_value_with_origin(*value, origin)?;
|
||||
let value =
|
||||
self.add_value_thunk_with_optional_import_origin(value, origin.cloned());
|
||||
let default = if let Some(default) = default {
|
||||
let value = self.internalize_host_value_with_origin(*default, origin)?;
|
||||
let value = self.internalize_value_with_origin(*default, origin)?;
|
||||
Some(self.add_value_thunk_with_optional_import_origin(value, origin.cloned()))
|
||||
} else {
|
||||
None
|
||||
@@ -1751,8 +2012,11 @@ impl<L: ImportLoader> Engine<L> {
|
||||
default,
|
||||
}))
|
||||
}
|
||||
HostValue::Object(fields) => {
|
||||
let mut object = ObjectValue { fields: Vec::new() };
|
||||
Value::Object { fields, rest } => {
|
||||
let mut object = ObjectValue {
|
||||
fields: Vec::new(),
|
||||
rest: None,
|
||||
};
|
||||
for field in fields {
|
||||
let field_origin = origin.map(|origin| origin.field(field.name.clone()));
|
||||
if object
|
||||
@@ -1763,7 +2027,7 @@ impl<L: ImportLoader> Engine<L> {
|
||||
let diagnostic = Diagnostic::new(
|
||||
DiagnosticKind::Conflict,
|
||||
Span::default(),
|
||||
format!("duplicate host object field `{}`", field.name),
|
||||
format!("duplicate object field `{}`", field.name),
|
||||
);
|
||||
return Err(annotate_imported_value(
|
||||
diagnostic,
|
||||
@@ -1771,8 +2035,8 @@ impl<L: ImportLoader> Engine<L> {
|
||||
None,
|
||||
));
|
||||
}
|
||||
let value = self
|
||||
.internalize_host_value_with_origin(field.value, field_origin.as_ref())?;
|
||||
let value =
|
||||
self.internalize_value_with_origin(field.value, field_origin.as_ref())?;
|
||||
let value =
|
||||
self.add_value_thunk_with_optional_import_origin(value, field_origin);
|
||||
object.fields.push(ObjectField {
|
||||
@@ -1781,14 +2045,22 @@ impl<L: ImportLoader> Engine<L> {
|
||||
span: Span::default(),
|
||||
});
|
||||
}
|
||||
if let Some(rest) = rest {
|
||||
let rest = self.internalize_value_with_origin(*rest, origin)?;
|
||||
object.rest = Some(RuntimeObjectRest {
|
||||
value: self
|
||||
.add_value_thunk_with_optional_import_origin(rest, origin.cloned()),
|
||||
span: Span::default(),
|
||||
});
|
||||
}
|
||||
Ok(RuntimeValue::Concrete(ConcreteValue::Object(object)))
|
||||
}
|
||||
HostValue::Abstract {
|
||||
Value::Range {
|
||||
constraints,
|
||||
default,
|
||||
} => {
|
||||
let default = if let Some(default) = default {
|
||||
let value = self.internalize_host_value_with_origin(*default, origin)?;
|
||||
let value = self.internalize_value_with_origin(*default, origin)?;
|
||||
Some(self.add_value_thunk_with_optional_import_origin(value, origin.cloned()))
|
||||
} else {
|
||||
None
|
||||
@@ -2252,6 +2524,7 @@ fn upper_bound_implies(
|
||||
|
||||
fn constraint_description(constraint: &Constraint) -> String {
|
||||
match constraint {
|
||||
Constraint::Unknown => String::from("the unknown top range"),
|
||||
Constraint::Type(primitive) => format!("type {primitive:?}"),
|
||||
Constraint::ArrayItems(_) => String::from("an array element range"),
|
||||
Constraint::MapValues(_) => String::from("a map value range"),
|
||||
@@ -2590,7 +2863,7 @@ fn concrete_scalar_eq(lhs: &ConcreteValue, rhs: &ConcreteValue) -> bool {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{LoadedSource, parse_source};
|
||||
use crate::parse_source;
|
||||
|
||||
fn eval_data(source: &str) -> Data {
|
||||
let parsed = parse_source(source).unwrap();
|
||||
@@ -2887,6 +3160,29 @@ mod tests {
|
||||
assert!(value.default.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_is_the_unmaterializable_top_range() {
|
||||
assert_eq!(eval_data("42 as Unknown"), Data::Int(42));
|
||||
assert_eq!(eval_data("Unknown default {}"), Data::Object(Vec::new()));
|
||||
|
||||
let parsed = parse_source("Unknown").unwrap();
|
||||
let mut engine = Engine::from_parse(parsed.ast, parsed.root);
|
||||
let value = engine.eval_root().unwrap();
|
||||
let error = engine.materialize(&value).unwrap_err();
|
||||
assert_eq!(error.kind, DiagnosticKind::Materialize);
|
||||
assert!(error.message.contains("unresolved abstract value"));
|
||||
|
||||
let parsed = parse_source("Unknown as Int").unwrap();
|
||||
let mut engine = Engine::from_parse(parsed.ast, parsed.root);
|
||||
let error = engine.eval_root().unwrap_err();
|
||||
assert!(error.message.contains("not known to be narrower"));
|
||||
|
||||
let parsed = parse_source("{...Unknown}").unwrap();
|
||||
let mut engine = Engine::from_parse(parsed.ast, parsed.root);
|
||||
let value = engine.eval_root().unwrap();
|
||||
assert!(engine.materialize(&value).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn abstract_collection_ranges_can_be_proven_narrower() {
|
||||
let parsed = parse_source("[...(Int & > 10)] as [...Int]").unwrap();
|
||||
@@ -2980,6 +3276,100 @@ mod tests {
|
||||
assert_eq!(eval_data("{} as {...String}"), Data::Object(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_rest_constraint_accepts_and_preserves_additional_fields() {
|
||||
let data = eval_data(
|
||||
r#"
|
||||
{
|
||||
hoge = 1;
|
||||
fuga = "two";
|
||||
extra = true;
|
||||
} as {
|
||||
hoge = Int;
|
||||
fuga = String;
|
||||
...Unknown
|
||||
}
|
||||
"#,
|
||||
);
|
||||
assert_eq!(
|
||||
data,
|
||||
Data::Object(vec![
|
||||
DataField {
|
||||
name: String::from("hoge"),
|
||||
value: Data::Int(1),
|
||||
},
|
||||
DataField {
|
||||
name: String::from("fuga"),
|
||||
value: Data::String(String::from("two")),
|
||||
},
|
||||
DataField {
|
||||
name: String::from("extra"),
|
||||
value: Data::Bool(true),
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
eval_data("{ hoge = 1; ...Unknown }"),
|
||||
Data::Object(vec![DataField {
|
||||
name: String::from("hoge"),
|
||||
value: Data::Int(1),
|
||||
}])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_rest_constraint_rejects_invalid_additional_fields() {
|
||||
let parsed =
|
||||
parse_source(r#"{ hoge = 1; extra = "no"; } as { hoge = Int; ...Int }"#).unwrap();
|
||||
let mut engine = Engine::from_parse(parsed.ast, parsed.root);
|
||||
let error = engine.eval_root().unwrap_err();
|
||||
assert_eq!(error.kind, DiagnosticKind::ConstraintViolation);
|
||||
assert!(error.message.contains("expected Int"));
|
||||
assert!(
|
||||
error
|
||||
.labels
|
||||
.iter()
|
||||
.any(|label| label.message.contains("object rest range"))
|
||||
);
|
||||
|
||||
let parsed = parse_source("{ hoge = 1; ...Unknown } as { hoge = Int; }").unwrap();
|
||||
let mut engine = Engine::from_parse(parsed.ast, parsed.root);
|
||||
let error = engine.eval_root().unwrap_err();
|
||||
assert!(error.message.contains("permits additional fields"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_rest_constraints_compose_as_ranges() {
|
||||
assert_eq!(
|
||||
eval_data("{ fixed = 1; ...Unknown } & { additional = 2; ...Unknown }"),
|
||||
Data::Object(vec![
|
||||
DataField {
|
||||
name: String::from("fixed"),
|
||||
value: Data::Int(1),
|
||||
},
|
||||
DataField {
|
||||
name: String::from("additional"),
|
||||
value: Data::Int(2),
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
let parsed =
|
||||
parse_source("{ fixed = Int; ...Int } as { fixed = Unknown; ...Unknown }").unwrap();
|
||||
let mut engine = Engine::from_parse(parsed.ast, parsed.root);
|
||||
assert!(matches!(
|
||||
engine.eval_root().unwrap(),
|
||||
RuntimeValue::Concrete(ConcreteValue::Object(_))
|
||||
));
|
||||
|
||||
let parsed =
|
||||
parse_source("{ fixed = Int; ...Unknown } as { fixed = Unknown; ...Int }").unwrap();
|
||||
let mut engine = Engine::from_parse(parsed.ast, parsed.root);
|
||||
let error = engine.eval_root().unwrap_err();
|
||||
assert!(error.message.contains("not known to be narrower"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_array_primitive_reports_migration() {
|
||||
let parsed = parse_source("Array").unwrap();
|
||||
@@ -3100,11 +3490,11 @@ mod tests {
|
||||
.ok_or_else(|| {
|
||||
Diagnostic::new(DiagnosticKind::Import, Span::default(), "missing source")
|
||||
})?;
|
||||
Ok(LoadedImport::Source(LoadedSource {
|
||||
Ok(LoadedImport::Source {
|
||||
key: specifier.into(),
|
||||
name: specifier.into(),
|
||||
source,
|
||||
}))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3147,7 +3537,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_test_markdown(source: &str) -> Result<HostValue> {
|
||||
fn parse_test_markdown(source: &str) -> Result<Value> {
|
||||
let source = source.strip_prefix("---\n").ok_or_else(|| {
|
||||
Diagnostic::new(
|
||||
DiagnosticKind::Import,
|
||||
@@ -3172,15 +3562,15 @@ mod tests {
|
||||
)
|
||||
})?;
|
||||
let value = match value.trim() {
|
||||
"true" => HostValue::bool(true),
|
||||
"false" => HostValue::bool(false),
|
||||
value => HostValue::string(value.trim_matches('"')),
|
||||
"true" => Value::bool(true),
|
||||
"false" => Value::bool(false),
|
||||
value => Value::string(value.trim_matches('"')),
|
||||
};
|
||||
fields.push((name.trim(), value));
|
||||
}
|
||||
Ok(HostValue::object([
|
||||
("frontmatter", HostValue::object(fields)),
|
||||
("body", HostValue::string(body)),
|
||||
Ok(Value::object([
|
||||
("frontmatter", Value::object(fields)),
|
||||
("body", Value::string(body)),
|
||||
]))
|
||||
}
|
||||
|
||||
@@ -3275,9 +3665,9 @@ mod tests {
|
||||
fn load(&mut self, _current_key: Option<&str>, _specifier: &str) -> Result<LoadedImport> {
|
||||
Ok(LoadedImport::value(
|
||||
"content/navigation.json",
|
||||
HostValue::object([(
|
||||
Value::object([(
|
||||
"items",
|
||||
HostValue::array([HostValue::string("home"), HostValue::int(2)]),
|
||||
Value::array([Value::string("home"), Value::int(2)]),
|
||||
)]),
|
||||
))
|
||||
}
|
||||
@@ -3308,7 +3698,7 @@ mod tests {
|
||||
fn load(&mut self, _current_key: Option<&str>, _specifier: &str) -> Result<LoadedImport> {
|
||||
Ok(LoadedImport::value(
|
||||
"shared-value",
|
||||
HostValue::int_type().default_int(1)?,
|
||||
Value::int_type().default_int(1)?,
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -3351,16 +3741,10 @@ mod tests {
|
||||
engine
|
||||
.bind_global(
|
||||
"Service",
|
||||
HostValue::object([
|
||||
("name", HostValue::string_type()),
|
||||
(
|
||||
"port",
|
||||
HostValue::int_type().gt(443).default_int(8443).unwrap(),
|
||||
),
|
||||
(
|
||||
"enabled",
|
||||
HostValue::bool_type().default_bool(true).unwrap(),
|
||||
),
|
||||
Value::object([
|
||||
("name", Value::string_type()),
|
||||
("port", Value::int_type().gt(443).default_int(8443).unwrap()),
|
||||
("enabled", Value::bool_type().default_bool(true).unwrap()),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
@@ -3385,12 +3769,9 @@ mod tests {
|
||||
engine
|
||||
.bind_global(
|
||||
"Services",
|
||||
HostValue::map_of(HostValue::object([
|
||||
("port", HostValue::int_type()),
|
||||
(
|
||||
"enabled",
|
||||
HostValue::bool_type().default_bool(true).unwrap(),
|
||||
),
|
||||
Value::map_of(Value::object([
|
||||
("port", Value::int_type()),
|
||||
("enabled", Value::bool_type().default_bool(true).unwrap()),
|
||||
])),
|
||||
)
|
||||
.unwrap();
|
||||
@@ -3410,14 +3791,35 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_schema_errors_point_to_the_dcdl_application() {
|
||||
fn host_prelude_provides_object_rest_and_unknown_ranges() {
|
||||
let mut engine = Engine::new(EmptyLoader);
|
||||
engine
|
||||
.bind_global(
|
||||
"Service",
|
||||
HostValue::object([("port", HostValue::int_type())]),
|
||||
"OpenService",
|
||||
Value::object_with_rest([("name", Value::string_type())], Value::unknown()),
|
||||
)
|
||||
.unwrap();
|
||||
let module = engine
|
||||
.add_root_source(
|
||||
"main",
|
||||
"main",
|
||||
r#"{ name = "api"; metadata = { owner = "platform"; }; } as OpenService"#,
|
||||
)
|
||||
.unwrap();
|
||||
let value = engine.eval_module(module).unwrap();
|
||||
let data = engine.materialize(&value).unwrap();
|
||||
let Data::Object(fields) = data else { panic!() };
|
||||
assert_eq!(fields.len(), 2);
|
||||
assert_eq!(fields[0].value, Data::String(String::from("api")));
|
||||
assert!(matches!(fields[1].value, Data::Object(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_schema_errors_point_to_the_dcdl_application() {
|
||||
let mut engine = Engine::new(EmptyLoader);
|
||||
engine
|
||||
.bind_global("Service", Value::object([("port", Value::int_type())]))
|
||||
.unwrap();
|
||||
let module = engine
|
||||
.add_root_source("main", "main", r#"{ port = "not-an-int"; } as Service"#)
|
||||
.unwrap();
|
||||
@@ -3435,7 +3837,7 @@ mod tests {
|
||||
#[test]
|
||||
fn module_binding_shadows_host_prelude() {
|
||||
let mut engine = Engine::new(EmptyLoader);
|
||||
engine.bind_global("Service", HostValue::int(1)).unwrap();
|
||||
engine.bind_global("Service", Value::int(1)).unwrap();
|
||||
let module = engine
|
||||
.add_root_source("main", "main", r#"Service = "local"; result = Service;"#)
|
||||
.unwrap();
|
||||
|
||||
@@ -5,7 +5,6 @@ extern crate alloc;
|
||||
pub mod ast;
|
||||
pub mod constraints;
|
||||
pub mod diagnostic;
|
||||
pub mod embedding;
|
||||
pub mod environment;
|
||||
pub mod eval;
|
||||
mod lexer;
|
||||
@@ -14,29 +13,28 @@ pub mod parser;
|
||||
pub mod runtime;
|
||||
pub mod span;
|
||||
pub mod typed;
|
||||
pub mod value;
|
||||
|
||||
pub use ast::{Ast, BinaryOp, CompareOp, Expr, ExprId, Field, Literal, Param};
|
||||
pub use ast::{Ast, BinaryOp, CompareOp, Expr, ExprId, Field, Literal, ObjectRest, Param};
|
||||
pub use constraints::normalize_constraints;
|
||||
#[cfg(feature = "derive")]
|
||||
pub use decodal_derive::Decodal;
|
||||
pub use diagnostic::{Diagnostic, DiagnosticKind, Result};
|
||||
pub use embedding::{HostField, HostValue};
|
||||
pub use environment::HostEnvironment;
|
||||
pub use eval::{Engine, format_diagnostic_with};
|
||||
pub use lexer::{
|
||||
Token as SyntaxToken, TokenKind as SyntaxTokenKind, tokenize_source,
|
||||
tokenize_source_with_source_id,
|
||||
};
|
||||
pub use module::{
|
||||
EmptyLoader, ImportCandidate, ImportLoader, LoadedImport, LoadedSource, LoadedValue, Module,
|
||||
};
|
||||
pub use module::{EmptyLoader, ImportCandidate, ImportLoader, LoadedImport, Module};
|
||||
pub use parser::{ParseOutput, Parser, SourceForm, parse_source, parse_source_with_source_id};
|
||||
pub use runtime::{Constraint, Data, ExprRef, LiteralValue, ModuleId, PrimitiveType, RuntimeValue};
|
||||
pub use runtime::{Constraint, Data, ExprRef, LiteralValue, ModuleId, PrimitiveType};
|
||||
pub use span::{SourceId, Span};
|
||||
pub use typed::{
|
||||
DecodalDecode, DecodalSchema, DecodeError, DecodeResult, IntoHostValue, data_at_path,
|
||||
DecodalDecode, DecodalRest, DecodalSchema, DecodeError, DecodeResult, IntoValue, data_at_path,
|
||||
decode_path, prefix_decode_error,
|
||||
};
|
||||
pub use value::{Value, ValueField};
|
||||
|
||||
pub fn version() -> &'static str {
|
||||
env!("CARGO_PKG_VERSION")
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use alloc::{string::String, vec::Vec};
|
||||
|
||||
use crate::{
|
||||
Ast, ExprId, HostValue, SourceForm, SourceId,
|
||||
Ast, ExprId, SourceForm, SourceId, Value,
|
||||
runtime::{EnvId, ThunkId},
|
||||
};
|
||||
|
||||
@@ -17,23 +17,18 @@ pub struct Module {
|
||||
pub root_thunk: ThunkId,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LoadedSource {
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub source: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LoadedValue {
|
||||
pub key: String,
|
||||
pub value: HostValue,
|
||||
}
|
||||
|
||||
/// Content resolved by an [`ImportLoader`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum LoadedImport {
|
||||
Source(LoadedSource),
|
||||
Value(LoadedValue),
|
||||
Source {
|
||||
key: String,
|
||||
name: String,
|
||||
source: String,
|
||||
},
|
||||
Value {
|
||||
key: String,
|
||||
value: Value,
|
||||
},
|
||||
}
|
||||
|
||||
/// An import specifier offered by host-owned language tooling.
|
||||
@@ -63,18 +58,18 @@ impl LoadedImport {
|
||||
name: impl Into<String>,
|
||||
source: impl Into<String>,
|
||||
) -> Self {
|
||||
Self::Source(LoadedSource {
|
||||
Self::Source {
|
||||
key: key.into(),
|
||||
name: name.into(),
|
||||
source: source.into(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value(key: impl Into<String>, value: HostValue) -> Self {
|
||||
Self::Value(LoadedValue {
|
||||
pub fn value(key: impl Into<String>, value: Value) -> Self {
|
||||
Self::Value {
|
||||
key: key.into(),
|
||||
value,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,10 @@ use alloc::{string::String, vec::Vec};
|
||||
|
||||
use crate::{
|
||||
SourceId, Span,
|
||||
ast::{Ast, BinaryOp, CompareOp, Expr, ExprId, Field, Literal, MatchArm, Param, UnaryOp},
|
||||
ast::{
|
||||
Ast, BinaryOp, CompareOp, Expr, ExprId, Field, Literal, MatchArm, ObjectRest, Param,
|
||||
UnaryOp,
|
||||
},
|
||||
diagnostic::{Diagnostic, Result},
|
||||
lexer::{Lexer, Token, TokenKind},
|
||||
};
|
||||
@@ -59,7 +62,7 @@ impl Parser {
|
||||
})
|
||||
.unwrap_or_else(|| self.peek().span);
|
||||
(
|
||||
self.ast.push(Expr::Object(fields), span),
|
||||
self.ast.push(Expr::Object { fields, rest: None }, span),
|
||||
SourceForm::Fields,
|
||||
)
|
||||
} else {
|
||||
@@ -338,23 +341,38 @@ impl Parser {
|
||||
|
||||
let mut fields = Vec::new();
|
||||
if self.consume_kind(&TokenKind::RBrace).is_some() {
|
||||
return Ok(self
|
||||
.ast
|
||||
.push(Expr::Object(fields), start_span.join(self.previous_span())));
|
||||
return Ok(self.ast.push(
|
||||
Expr::Object { fields, rest: None },
|
||||
start_span.join(self.previous_span()),
|
||||
));
|
||||
}
|
||||
let mut rest = None;
|
||||
loop {
|
||||
fields.push(self.parse_field()?);
|
||||
if self.consume_kind(&TokenKind::Semicolon).is_some() {
|
||||
if self.consume_kind(&TokenKind::RBrace).is_some() {
|
||||
break;
|
||||
}
|
||||
if let Some(ellipsis) = self.consume_kind(&TokenKind::Ellipsis) {
|
||||
let value = self.parse_expr(0)?;
|
||||
rest = Some(ObjectRest {
|
||||
value,
|
||||
span: ellipsis.join(self.ast.span(value)),
|
||||
});
|
||||
let _ = self.consume_kind(&TokenKind::Semicolon);
|
||||
self.expect_kind(
|
||||
&TokenKind::RBrace,
|
||||
"expected '}' after object rest constraint",
|
||||
)?;
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
self.expect_kind(&TokenKind::RBrace, "expected ';' or '}' after object field")?;
|
||||
break;
|
||||
}
|
||||
let span = start_span.join(self.previous_span());
|
||||
Ok(self.ast.push(Expr::Object(fields), span))
|
||||
Ok(self.ast.push(Expr::Object { fields, rest }, span))
|
||||
}
|
||||
|
||||
fn parse_array_after_lbracket(&mut self, start_span: Span) -> Result<ExprId> {
|
||||
@@ -697,13 +715,16 @@ mod tests {
|
||||
#[test]
|
||||
fn parses_top_level_fields_as_object() {
|
||||
let parsed = parse_source("port = Int & >= 1 default 8080;").unwrap();
|
||||
assert!(matches!(parsed.ast.get(parsed.root).expr, Expr::Object(_)));
|
||||
assert!(matches!(
|
||||
parsed.ast.get(parsed.root).expr,
|
||||
Expr::Object { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_object_dot_field() {
|
||||
let parsed = parse_source("{ feature.enable = false; }").unwrap();
|
||||
let Expr::Object(fields) = &parsed.ast.get(parsed.root).expr else {
|
||||
let Expr::Object { fields, .. } = &parsed.ast.get(parsed.root).expr else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(fields[0].path, ["feature", "enable"]);
|
||||
@@ -726,7 +747,7 @@ mod tests {
|
||||
fn parser_accepts_the_public_lossless_token_stream() {
|
||||
let tokens = crate::tokenize_source("value = (# note\n 1);").unwrap();
|
||||
let parsed = Parser::new(tokens).parse().unwrap();
|
||||
let Expr::Object(fields) = &parsed.ast.get(parsed.root).expr else {
|
||||
let Expr::Object { fields, .. } = &parsed.ast.get(parsed.root).expr else {
|
||||
panic!()
|
||||
};
|
||||
assert!(matches!(
|
||||
@@ -749,6 +770,17 @@ mod tests {
|
||||
assert!(matches!(parsed.ast.get(value).expr, Expr::Ident(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_object_rest_constraint_after_named_fields() {
|
||||
let parsed = parse_source("{ hoge = Int; fuga = String; ...Unknown }").unwrap();
|
||||
let Expr::Object { fields, rest } = &parsed.ast.get(parsed.root).expr else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(fields.len(), 2);
|
||||
let rest = rest.as_ref().expect("object has a rest constraint");
|
||||
assert!(matches!(parsed.ast.get(rest.value).expr, Expr::Ident(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_as_below_composition() {
|
||||
let parsed = parse_source("value & override as Schema").unwrap();
|
||||
|
||||
@@ -11,6 +11,9 @@ pub struct ExprRef {
|
||||
pub expr: ExprId,
|
||||
}
|
||||
|
||||
/// Evaluator-owned representation of a lazy concrete value or unresolved range.
|
||||
///
|
||||
/// Embedders normally construct [`crate::Value`] and consume [`Data`] instead.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum RuntimeValue {
|
||||
Concrete(ConcreteValue),
|
||||
@@ -31,6 +34,13 @@ pub enum ConcreteValue {
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ObjectValue {
|
||||
pub fields: Vec<ObjectField>,
|
||||
pub rest: Option<ObjectRest>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ObjectRest {
|
||||
pub value: ThunkId,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
@@ -67,6 +77,7 @@ pub struct ConstraintEntry {
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Constraint {
|
||||
Unknown,
|
||||
Type(PrimitiveType),
|
||||
ArrayItems(ThunkId),
|
||||
MapValues(ThunkId),
|
||||
@@ -91,6 +102,7 @@ pub enum LiteralValue {
|
||||
Bool(bool),
|
||||
}
|
||||
|
||||
/// Fully materialized Decodal data.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Data {
|
||||
String(String),
|
||||
|
||||
@@ -1,17 +1,24 @@
|
||||
use alloc::{collections::BTreeMap, format, string::String, vec::Vec};
|
||||
|
||||
use crate::{Data, HostValue};
|
||||
use crate::{Data, Value, runtime::DataField};
|
||||
|
||||
pub trait DecodalSchema {
|
||||
fn decodal_schema() -> HostValue;
|
||||
fn decodal_schema() -> Value;
|
||||
}
|
||||
|
||||
pub trait DecodalDecode: Sized {
|
||||
fn decodal_decode(data: &Data) -> DecodeResult<Self>;
|
||||
}
|
||||
|
||||
pub trait IntoHostValue {
|
||||
fn into_host_value(self) -> HostValue;
|
||||
pub trait IntoValue {
|
||||
fn into_value(self) -> Value;
|
||||
}
|
||||
|
||||
/// A map-like receiver for fields not named by a derived struct schema.
|
||||
pub trait DecodalRest: Sized {
|
||||
fn decodal_rest_schema() -> Value;
|
||||
|
||||
fn decodal_decode_rest(data: &Data, known_fields: &[&str]) -> DecodeResult<Self>;
|
||||
}
|
||||
|
||||
pub type DecodeResult<T> = core::result::Result<T, DecodeError>;
|
||||
@@ -80,9 +87,38 @@ fn prefix_error(path: &str, mut error: DecodeError) -> DecodeError {
|
||||
error
|
||||
}
|
||||
|
||||
impl DecodalSchema for Data {
|
||||
fn decodal_schema() -> Value {
|
||||
Value::unknown()
|
||||
}
|
||||
}
|
||||
|
||||
impl DecodalDecode for Data {
|
||||
fn decodal_decode(data: &Data) -> DecodeResult<Self> {
|
||||
Ok(data.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoValue for Data {
|
||||
fn into_value(self) -> Value {
|
||||
match self {
|
||||
Data::String(value) => Value::string(value),
|
||||
Data::Int(value) => Value::int(value),
|
||||
Data::Float(value) => Value::float(value),
|
||||
Data::Bool(value) => Value::bool(value),
|
||||
Data::Array(items) => Value::array(items.into_iter().map(IntoValue::into_value)),
|
||||
Data::Object(fields) => Value::object(
|
||||
fields
|
||||
.into_iter()
|
||||
.map(|field| (field.name, field.value.into_value())),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DecodalSchema for String {
|
||||
fn decodal_schema() -> HostValue {
|
||||
HostValue::string_type()
|
||||
fn decodal_schema() -> Value {
|
||||
Value::string_type()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,15 +131,15 @@ impl DecodalDecode for String {
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoHostValue for String {
|
||||
fn into_host_value(self) -> HostValue {
|
||||
HostValue::string(self)
|
||||
impl IntoValue for String {
|
||||
fn into_value(self) -> Value {
|
||||
Value::string(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoHostValue for &str {
|
||||
fn into_host_value(self) -> HostValue {
|
||||
HostValue::string(self)
|
||||
impl IntoValue for &str {
|
||||
fn into_value(self) -> Value {
|
||||
Value::string(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,8 +147,8 @@ macro_rules! impl_int_decode {
|
||||
($($ty:ty),* $(,)?) => {
|
||||
$(
|
||||
impl DecodalSchema for $ty {
|
||||
fn decodal_schema() -> HostValue {
|
||||
HostValue::int_type()
|
||||
fn decodal_schema() -> Value {
|
||||
Value::int_type()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,9 +162,9 @@ macro_rules! impl_int_decode {
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoHostValue for $ty {
|
||||
fn into_host_value(self) -> HostValue {
|
||||
HostValue::int(self as i64)
|
||||
impl IntoValue for $ty {
|
||||
fn into_value(self) -> Value {
|
||||
Value::int(self as i64)
|
||||
}
|
||||
}
|
||||
)*
|
||||
@@ -138,8 +174,8 @@ macro_rules! impl_int_decode {
|
||||
impl_int_decode!(i8, i16, i32, i64, u8, u16, u32);
|
||||
|
||||
impl DecodalSchema for f64 {
|
||||
fn decodal_schema() -> HostValue {
|
||||
HostValue::float_type()
|
||||
fn decodal_schema() -> Value {
|
||||
Value::float_type()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,15 +189,15 @@ impl DecodalDecode for f64 {
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoHostValue for f64 {
|
||||
fn into_host_value(self) -> HostValue {
|
||||
HostValue::float(self)
|
||||
impl IntoValue for f64 {
|
||||
fn into_value(self) -> Value {
|
||||
Value::float(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl DecodalSchema for f32 {
|
||||
fn decodal_schema() -> HostValue {
|
||||
HostValue::float_type()
|
||||
fn decodal_schema() -> Value {
|
||||
Value::float_type()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,15 +207,15 @@ impl DecodalDecode for f32 {
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoHostValue for f32 {
|
||||
fn into_host_value(self) -> HostValue {
|
||||
HostValue::float(f64::from(self))
|
||||
impl IntoValue for f32 {
|
||||
fn into_value(self) -> Value {
|
||||
Value::float(f64::from(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl DecodalSchema for bool {
|
||||
fn decodal_schema() -> HostValue {
|
||||
HostValue::bool_type()
|
||||
fn decodal_schema() -> Value {
|
||||
Value::bool_type()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,15 +228,15 @@ impl DecodalDecode for bool {
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoHostValue for bool {
|
||||
fn into_host_value(self) -> HostValue {
|
||||
HostValue::bool(self)
|
||||
impl IntoValue for bool {
|
||||
fn into_value(self) -> Value {
|
||||
Value::bool(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: DecodalSchema> DecodalSchema for Vec<T> {
|
||||
fn decodal_schema() -> HostValue {
|
||||
HostValue::array_of(T::decodal_schema())
|
||||
fn decodal_schema() -> Value {
|
||||
Value::array_of(T::decodal_schema())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,15 +256,15 @@ impl<T: DecodalDecode> DecodalDecode for Vec<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: IntoHostValue> IntoHostValue for Vec<T> {
|
||||
fn into_host_value(self) -> HostValue {
|
||||
HostValue::array(self.into_iter().map(IntoHostValue::into_host_value))
|
||||
impl<T: IntoValue> IntoValue for Vec<T> {
|
||||
fn into_value(self) -> Value {
|
||||
Value::array(self.into_iter().map(IntoValue::into_value))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: DecodalSchema> DecodalSchema for BTreeMap<String, T> {
|
||||
fn decodal_schema() -> HostValue {
|
||||
HostValue::map_of(T::decodal_schema())
|
||||
fn decodal_schema() -> Value {
|
||||
Value::map_of(T::decodal_schema())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,19 +284,36 @@ impl<T: DecodalDecode> DecodalDecode for BTreeMap<String, T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: IntoHostValue> IntoHostValue for BTreeMap<String, T> {
|
||||
fn into_host_value(self) -> HostValue {
|
||||
HostValue::object(
|
||||
impl<T: IntoValue> IntoValue for BTreeMap<String, T> {
|
||||
fn into_value(self) -> Value {
|
||||
Value::object(
|
||||
self.into_iter()
|
||||
.map(|(name, value)| (name, value.into_host_value())),
|
||||
.map(|(name, value)| (name, value.into_value())),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: DecodalSchema + DecodalDecode> DecodalRest for BTreeMap<String, T> {
|
||||
fn decodal_rest_schema() -> Value {
|
||||
T::decodal_schema()
|
||||
}
|
||||
|
||||
fn decodal_decode_rest(data: &Data, known_fields: &[&str]) -> DecodeResult<Self> {
|
||||
let Data::Object(fields) = data else {
|
||||
return Err(DecodeError::at_type("", "Object"));
|
||||
};
|
||||
fields
|
||||
.iter()
|
||||
.filter(|field| !known_fields.contains(&field.name.as_str()))
|
||||
.map(decode_rest_field::<T>)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<T: DecodalSchema> DecodalSchema for std::collections::HashMap<String, T> {
|
||||
fn decodal_schema() -> HostValue {
|
||||
HostValue::map_of(T::decodal_schema())
|
||||
fn decodal_schema() -> Value {
|
||||
Value::map_of(T::decodal_schema())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,17 +335,41 @@ impl<T: DecodalDecode> DecodalDecode for std::collections::HashMap<String, T> {
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<T: IntoHostValue> IntoHostValue for std::collections::HashMap<String, T> {
|
||||
fn into_host_value(self) -> HostValue {
|
||||
impl<T: IntoValue> IntoValue for std::collections::HashMap<String, T> {
|
||||
fn into_value(self) -> Value {
|
||||
let mut fields: Vec<_> = self
|
||||
.into_iter()
|
||||
.map(|(name, value)| (name, value.into_host_value()))
|
||||
.map(|(name, value)| (name, value.into_value()))
|
||||
.collect();
|
||||
fields.sort_by(|left, right| left.0.cmp(&right.0));
|
||||
HostValue::object(fields)
|
||||
Value::object(fields)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<T: DecodalSchema + DecodalDecode> DecodalRest for std::collections::HashMap<String, T> {
|
||||
fn decodal_rest_schema() -> Value {
|
||||
T::decodal_schema()
|
||||
}
|
||||
|
||||
fn decodal_decode_rest(data: &Data, known_fields: &[&str]) -> DecodeResult<Self> {
|
||||
let Data::Object(fields) = data else {
|
||||
return Err(DecodeError::at_type("", "Object"));
|
||||
};
|
||||
fields
|
||||
.iter()
|
||||
.filter(|field| !known_fields.contains(&field.name.as_str()))
|
||||
.map(decode_rest_field::<T>)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_rest_field<T: DecodalDecode>(field: &DataField) -> DecodeResult<(String, T)> {
|
||||
T::decodal_decode(&field.value)
|
||||
.map(|value| (field.name.clone(), value))
|
||||
.map_err(|error| prefix_error(&field.name, error))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -302,10 +379,10 @@ mod tests {
|
||||
fn string_maps_expose_map_schemas_and_decode_objects() {
|
||||
assert!(matches!(
|
||||
BTreeMap::<String, i64>::decodal_schema(),
|
||||
HostValue::MapConstraint { value, .. }
|
||||
Value::MapRange { value, .. }
|
||||
if matches!(
|
||||
*value,
|
||||
HostValue::Abstract { ref constraints, .. }
|
||||
Value::Range { ref constraints, .. }
|
||||
if constraints == &[Constraint::Type(PrimitiveType::Int)]
|
||||
)
|
||||
));
|
||||
@@ -317,4 +394,52 @@ mod tests {
|
||||
let decoded = BTreeMap::<String, i64>::decodal_decode(&data).unwrap();
|
||||
assert_eq!(decoded.get("api"), Some(&8080));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_is_the_unknown_schema_and_round_trips_values() {
|
||||
assert!(matches!(
|
||||
Data::decodal_schema(),
|
||||
Value::Range { ref constraints, .. }
|
||||
if constraints == &[Constraint::Unknown]
|
||||
));
|
||||
|
||||
let data = Data::Object(alloc::vec![DataField {
|
||||
name: String::from("nested"),
|
||||
value: Data::Array(alloc::vec![Data::Bool(true), Data::Int(2)]),
|
||||
}]);
|
||||
assert_eq!(Data::decodal_decode(&data).unwrap(), data);
|
||||
assert!(matches!(data.into_value(), Value::Object { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rest_maps_decode_only_fields_outside_the_known_domain() {
|
||||
let data = Data::Object(alloc::vec![
|
||||
DataField {
|
||||
name: String::from("name"),
|
||||
value: Data::String(String::from("api")),
|
||||
},
|
||||
DataField {
|
||||
name: String::from("priority"),
|
||||
value: Data::Int(3),
|
||||
},
|
||||
]);
|
||||
let decoded = BTreeMap::<String, Data>::decodal_decode_rest(&data, &["name"]).unwrap();
|
||||
assert_eq!(decoded.len(), 1);
|
||||
assert_eq!(decoded.get("priority"), Some(&Data::Int(3)));
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[test]
|
||||
fn hash_maps_can_receive_rest_fields() {
|
||||
let data = Data::Object(alloc::vec![DataField {
|
||||
name: String::from("region"),
|
||||
value: Data::String(String::from("ap-northeast-1")),
|
||||
}]);
|
||||
let decoded =
|
||||
std::collections::HashMap::<String, String>::decodal_decode_rest(&data, &[]).unwrap();
|
||||
assert_eq!(
|
||||
decoded.get("region").map(String::as_str),
|
||||
Some("ap-northeast-1")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,37 +3,46 @@ use alloc::{boxed::Box, string::String, vec::Vec};
|
||||
use crate::runtime::{Constraint, LiteralValue, PrimitiveType};
|
||||
use crate::{CompareOp, Diagnostic, DiagnosticKind, Result, Span};
|
||||
|
||||
/// A Decodal value supplied through the embedding API.
|
||||
///
|
||||
/// Unlike [`crate::Data`], a `Value` may contain unresolved ranges and
|
||||
/// defaults. The evaluator converts it into its lazy runtime representation
|
||||
/// when it is bound as a global or returned from an import loader.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum HostValue {
|
||||
pub enum Value {
|
||||
String(String),
|
||||
Int(i64),
|
||||
Float(f64),
|
||||
Bool(bool),
|
||||
Array(Vec<HostValue>),
|
||||
ArrayConstraint {
|
||||
item: Box<HostValue>,
|
||||
Array(Vec<Value>),
|
||||
ArrayRange {
|
||||
item: Box<Value>,
|
||||
constraints: Vec<Constraint>,
|
||||
default: Option<Box<HostValue>>,
|
||||
default: Option<Box<Value>>,
|
||||
},
|
||||
MapConstraint {
|
||||
value: Box<HostValue>,
|
||||
MapRange {
|
||||
value: Box<Value>,
|
||||
constraints: Vec<Constraint>,
|
||||
default: Option<Box<HostValue>>,
|
||||
default: Option<Box<Value>>,
|
||||
},
|
||||
Object(Vec<HostField>),
|
||||
Abstract {
|
||||
Object {
|
||||
fields: Vec<ValueField>,
|
||||
rest: Option<Box<Value>>,
|
||||
},
|
||||
Range {
|
||||
constraints: Vec<Constraint>,
|
||||
default: Option<Box<HostValue>>,
|
||||
default: Option<Box<Value>>,
|
||||
},
|
||||
}
|
||||
|
||||
/// A named field in a [`Value::Object`].
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct HostField {
|
||||
pub struct ValueField {
|
||||
pub name: String,
|
||||
pub value: HostValue,
|
||||
pub value: Value,
|
||||
}
|
||||
|
||||
impl HostValue {
|
||||
impl Value {
|
||||
pub fn string(value: impl Into<String>) -> Self {
|
||||
Self::String(value.into())
|
||||
}
|
||||
@@ -52,65 +61,105 @@ impl HostValue {
|
||||
|
||||
pub fn array<I>(items: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = HostValue>,
|
||||
I: IntoIterator<Item = Value>,
|
||||
{
|
||||
Self::Array(items.into_iter().collect())
|
||||
}
|
||||
|
||||
pub fn object<I, N>(fields: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = (N, HostValue)>,
|
||||
I: IntoIterator<Item = (N, Value)>,
|
||||
N: Into<String>,
|
||||
{
|
||||
Self::Object(
|
||||
fields
|
||||
Self::Object {
|
||||
fields: fields
|
||||
.into_iter()
|
||||
.map(|(name, value)| HostField {
|
||||
.map(|(name, value)| ValueField {
|
||||
name: name.into(),
|
||||
value,
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
rest: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn object_from_paths<I, N>(fields: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = (N, HostValue)>,
|
||||
I: IntoIterator<Item = (N, Value)>,
|
||||
N: Into<String>,
|
||||
{
|
||||
let mut root = Vec::new();
|
||||
for (path, value) in fields {
|
||||
insert_path(&mut root, &path.into(), value);
|
||||
}
|
||||
Self::Object(root)
|
||||
Self::Object {
|
||||
fields: root,
|
||||
rest: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn object_from_paths_with_rest<I, N>(fields: I, rest: Value) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = (N, Value)>,
|
||||
N: Into<String>,
|
||||
{
|
||||
let mut root = Vec::new();
|
||||
for (path, value) in fields {
|
||||
insert_path(&mut root, &path.into(), value);
|
||||
}
|
||||
Self::Object {
|
||||
fields: root,
|
||||
rest: Some(Box::new(rest)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn object_with_rest<I, N>(fields: I, rest: Value) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = (N, Value)>,
|
||||
N: Into<String>,
|
||||
{
|
||||
Self::Object {
|
||||
fields: fields
|
||||
.into_iter()
|
||||
.map(|(name, value)| ValueField {
|
||||
name: name.into(),
|
||||
value,
|
||||
})
|
||||
.collect(),
|
||||
rest: Some(Box::new(rest)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unknown() -> Self {
|
||||
Self::range_with_constraint(Constraint::Unknown)
|
||||
}
|
||||
|
||||
pub fn string_type() -> Self {
|
||||
Self::abstract_with_constraint(Constraint::Type(PrimitiveType::String))
|
||||
Self::range_with_constraint(Constraint::Type(PrimitiveType::String))
|
||||
}
|
||||
|
||||
pub fn int_type() -> Self {
|
||||
Self::abstract_with_constraint(Constraint::Type(PrimitiveType::Int))
|
||||
Self::range_with_constraint(Constraint::Type(PrimitiveType::Int))
|
||||
}
|
||||
|
||||
pub fn float_type() -> Self {
|
||||
Self::abstract_with_constraint(Constraint::Type(PrimitiveType::Float))
|
||||
Self::range_with_constraint(Constraint::Type(PrimitiveType::Float))
|
||||
}
|
||||
|
||||
pub fn bool_type() -> Self {
|
||||
Self::abstract_with_constraint(Constraint::Type(PrimitiveType::Bool))
|
||||
Self::range_with_constraint(Constraint::Type(PrimitiveType::Bool))
|
||||
}
|
||||
|
||||
pub fn array_of(item: HostValue) -> Self {
|
||||
Self::ArrayConstraint {
|
||||
pub fn array_of(item: Value) -> Self {
|
||||
Self::ArrayRange {
|
||||
item: Box::new(item),
|
||||
constraints: Vec::new(),
|
||||
default: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_of(value: HostValue) -> Self {
|
||||
Self::MapConstraint {
|
||||
pub fn map_of(value: Value) -> Self {
|
||||
Self::MapRange {
|
||||
value: Box::new(value),
|
||||
constraints: Vec::new(),
|
||||
default: None,
|
||||
@@ -118,11 +167,11 @@ impl HostValue {
|
||||
}
|
||||
|
||||
pub fn builtin_predicate(name: impl Into<String>) -> Self {
|
||||
Self::abstract_with_constraint(Constraint::BuiltinPredicate(name.into()))
|
||||
Self::range_with_constraint(Constraint::BuiltinPredicate(name.into()))
|
||||
}
|
||||
|
||||
pub fn abstract_with_constraint(constraint: Constraint) -> Self {
|
||||
Self::Abstract {
|
||||
pub fn range_with_constraint(constraint: Constraint) -> Self {
|
||||
Self::Range {
|
||||
constraints: alloc::vec![constraint],
|
||||
default: None,
|
||||
}
|
||||
@@ -130,12 +179,12 @@ impl HostValue {
|
||||
|
||||
pub fn with_constraint(mut self, constraint: Constraint) -> Self {
|
||||
match &mut self {
|
||||
Self::Abstract { constraints, .. } => constraints.push(constraint),
|
||||
Self::ArrayConstraint { constraints, .. } | Self::MapConstraint { constraints, .. } => {
|
||||
Self::Range { constraints, .. } => constraints.push(constraint),
|
||||
Self::ArrayRange { constraints, .. } | Self::MapRange { constraints, .. } => {
|
||||
constraints.push(constraint)
|
||||
}
|
||||
_ => {
|
||||
self = Self::Abstract {
|
||||
self = Self::Range {
|
||||
constraints: alloc::vec![constraint],
|
||||
default: Some(Box::new(self)),
|
||||
};
|
||||
@@ -166,53 +215,53 @@ impl HostValue {
|
||||
))
|
||||
}
|
||||
|
||||
pub fn default(self, value: HostValue) -> Result<Self> {
|
||||
pub fn default(self, value: Value) -> Result<Self> {
|
||||
match self {
|
||||
Self::ArrayConstraint {
|
||||
Self::ArrayRange {
|
||||
item,
|
||||
constraints,
|
||||
default: None,
|
||||
} => Ok(Self::ArrayConstraint {
|
||||
} => Ok(Self::ArrayRange {
|
||||
item,
|
||||
constraints,
|
||||
default: Some(Box::new(value)),
|
||||
}),
|
||||
Self::ArrayConstraint {
|
||||
Self::ArrayRange {
|
||||
default: Some(_), ..
|
||||
} => Err(Diagnostic::new(
|
||||
DiagnosticKind::DefaultConflict,
|
||||
Span::default(),
|
||||
"host value already has a default",
|
||||
"value already has a default",
|
||||
)),
|
||||
Self::MapConstraint {
|
||||
Self::MapRange {
|
||||
value: map_value,
|
||||
constraints,
|
||||
default: None,
|
||||
} => Ok(Self::MapConstraint {
|
||||
} => Ok(Self::MapRange {
|
||||
value: map_value,
|
||||
constraints,
|
||||
default: Some(Box::new(value)),
|
||||
}),
|
||||
Self::MapConstraint {
|
||||
Self::MapRange {
|
||||
default: Some(_), ..
|
||||
} => Err(Diagnostic::new(
|
||||
DiagnosticKind::DefaultConflict,
|
||||
Span::default(),
|
||||
"host value already has a default",
|
||||
"value already has a default",
|
||||
)),
|
||||
Self::Abstract {
|
||||
Self::Range {
|
||||
constraints,
|
||||
default: None,
|
||||
} => Ok(Self::Abstract {
|
||||
} => Ok(Self::Range {
|
||||
constraints,
|
||||
default: Some(Box::new(value)),
|
||||
}),
|
||||
Self::Abstract { .. } => Err(Diagnostic::new(
|
||||
Self::Range { .. } => Err(Diagnostic::new(
|
||||
DiagnosticKind::DefaultConflict,
|
||||
Span::default(),
|
||||
"host value already has a default",
|
||||
"value already has a default",
|
||||
)),
|
||||
concrete => Ok(Self::Abstract {
|
||||
concrete => Ok(Self::Range {
|
||||
constraints: Vec::new(),
|
||||
default: Some(Box::new(concrete)),
|
||||
}),
|
||||
@@ -236,8 +285,8 @@ impl HostValue {
|
||||
}
|
||||
}
|
||||
|
||||
impl HostField {
|
||||
pub fn new(name: impl Into<String>, value: HostValue) -> Self {
|
||||
impl ValueField {
|
||||
pub fn new(name: impl Into<String>, value: Value) -> Self {
|
||||
Self {
|
||||
name: name.into(),
|
||||
value,
|
||||
@@ -245,28 +294,40 @@ impl HostField {
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_path(fields: &mut Vec<HostField>, path: &str, value: HostValue) {
|
||||
fn insert_path(fields: &mut Vec<ValueField>, path: &str, value: Value) {
|
||||
let mut parts = path.splitn(2, '.');
|
||||
let Some(head) = parts.next().filter(|part| !part.is_empty()) else {
|
||||
return;
|
||||
};
|
||||
if let Some(tail) = parts.next() {
|
||||
if let Some(field) = fields.iter_mut().find(|field| field.name == head) {
|
||||
if let HostValue::Object(children) = &mut field.value {
|
||||
if let Value::Object {
|
||||
fields: children, ..
|
||||
} = &mut field.value
|
||||
{
|
||||
insert_path(children, tail, value);
|
||||
} else {
|
||||
let mut children = Vec::new();
|
||||
insert_path(&mut children, tail, value);
|
||||
field.value = HostValue::Object(children);
|
||||
field.value = Value::Object {
|
||||
fields: children,
|
||||
rest: None,
|
||||
};
|
||||
}
|
||||
} else {
|
||||
let mut children = Vec::new();
|
||||
insert_path(&mut children, tail, value);
|
||||
fields.push(HostField::new(head, HostValue::Object(children)));
|
||||
fields.push(ValueField::new(
|
||||
head,
|
||||
Value::Object {
|
||||
fields: children,
|
||||
rest: None,
|
||||
},
|
||||
));
|
||||
}
|
||||
} else if let Some(field) = fields.iter_mut().find(|field| field.name == head) {
|
||||
field.value = value;
|
||||
} else {
|
||||
fields.push(HostField::new(head, value));
|
||||
fields.push(ValueField::new(head, value));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "decodal-derive"
|
||||
version = "0.1.3"
|
||||
version = "0.2.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
@@ -19,4 +19,4 @@ quote = "1"
|
||||
syn = { version = "2", features = ["full"] }
|
||||
|
||||
[dev-dependencies]
|
||||
decodal = { version = "0.3.0", path = "../decodal-core" }
|
||||
decodal = { path = "../decodal-core" }
|
||||
|
||||
@@ -35,12 +35,38 @@ fn expand_decodal(input: DeriveInput) -> Result<TokenStream2> {
|
||||
|
||||
let mut schema_fields = Vec::new();
|
||||
let mut decode_fields = Vec::new();
|
||||
let mut known_field_roots = Vec::new();
|
||||
let mut rest_field = None;
|
||||
|
||||
for field in fields {
|
||||
let ident = field.ident.expect("named field");
|
||||
let ty = field.ty;
|
||||
let attrs = FieldAttrs::from_attrs(&field.attrs, &ident.to_string())?;
|
||||
|
||||
if attrs.rest {
|
||||
if attrs.rename_explicit || attrs.default.is_some() || !attrs.constraints.is_empty() {
|
||||
return Err(syn::Error::new(
|
||||
ident.span(),
|
||||
"`rest` cannot be combined with rename, default, or field constraints",
|
||||
));
|
||||
}
|
||||
if rest_field.is_some() {
|
||||
return Err(syn::Error::new(
|
||||
ident.span(),
|
||||
"Decodal derive supports only one `rest` field",
|
||||
));
|
||||
}
|
||||
rest_field = Some((ident, ty));
|
||||
continue;
|
||||
}
|
||||
|
||||
let path = attrs.rename.clone();
|
||||
known_field_roots.push(
|
||||
path.split('.')
|
||||
.next()
|
||||
.expect("field paths are non-empty")
|
||||
.to_owned(),
|
||||
);
|
||||
let schema_value = schema_expr(&ty, &attrs)?;
|
||||
let decode_value = decode_expr(&ty, &path, &attrs);
|
||||
|
||||
@@ -52,14 +78,40 @@ fn expand_decodal(input: DeriveInput) -> Result<TokenStream2> {
|
||||
});
|
||||
}
|
||||
|
||||
if let Some((ident, ty)) = &rest_field {
|
||||
decode_fields.push(quote! {
|
||||
#ident: <#ty as ::decodal::DecodalRest>::decodal_decode_rest(
|
||||
data,
|
||||
&[#(#known_field_roots),*],
|
||||
)?
|
||||
});
|
||||
}
|
||||
|
||||
let schema_entries = if schema_fields.is_empty() {
|
||||
quote! { ::core::iter::empty::<(&'static str, ::decodal::Value)>() }
|
||||
} else {
|
||||
quote! { [#(#schema_fields),*] }
|
||||
};
|
||||
|
||||
let build_schema = if let Some((_, ty)) = &rest_field {
|
||||
quote! {
|
||||
::decodal::Value::object_from_paths_with_rest(
|
||||
#schema_entries,
|
||||
<#ty as ::decodal::DecodalRest>::decodal_rest_schema(),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
quote! {
|
||||
::decodal::Value::object_from_paths(#schema_entries)
|
||||
}
|
||||
};
|
||||
|
||||
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
|
||||
|
||||
Ok(quote! {
|
||||
impl #impl_generics ::decodal::DecodalSchema for #name #ty_generics #where_clause {
|
||||
fn decodal_schema() -> ::decodal::HostValue {
|
||||
::decodal::HostValue::object_from_paths([
|
||||
#(#schema_fields),*
|
||||
])
|
||||
fn decodal_schema() -> ::decodal::Value {
|
||||
#build_schema
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,6 +128,8 @@ fn expand_decodal(input: DeriveInput) -> Result<TokenStream2> {
|
||||
#[derive(Default)]
|
||||
struct FieldAttrs {
|
||||
rename: String,
|
||||
rename_explicit: bool,
|
||||
rest: bool,
|
||||
default: Option<DefaultAttr>,
|
||||
constraints: Vec<ConstraintAttr>,
|
||||
}
|
||||
@@ -95,6 +149,14 @@ impl FieldAttrs {
|
||||
if meta.path.is_ident("rename") {
|
||||
let value: LitStr = meta.value()?.parse()?;
|
||||
output.rename = value.value();
|
||||
output.rename_explicit = true;
|
||||
return Ok(());
|
||||
}
|
||||
if meta.path.is_ident("rest") {
|
||||
if meta.input.peek(syn::Token![=]) || meta.input.peek(syn::token::Paren) {
|
||||
return Err(meta.error("`rest` does not accept a value"));
|
||||
}
|
||||
output.rest = true;
|
||||
return Ok(());
|
||||
}
|
||||
if meta.path.is_ident("default") {
|
||||
@@ -182,7 +244,7 @@ fn schema_expr(ty: &Type, attrs: &FieldAttrs) -> Result<TokenStream2> {
|
||||
};
|
||||
tokens.extend(quote! {
|
||||
schema = schema
|
||||
.default(::decodal::IntoHostValue::into_host_value(#default_expr))
|
||||
.default(::decodal::IntoValue::into_value(#default_expr))
|
||||
.expect("Decodal derive generated a valid default");
|
||||
});
|
||||
}
|
||||
@@ -210,3 +272,42 @@ fn decode_expr(ty: &Type, path: &str, attrs: &FieldAttrs) -> TokenStream2 {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rejects_multiple_rest_fields() {
|
||||
let input: DeriveInput = syn::parse_quote! {
|
||||
struct Invalid {
|
||||
#[decodal(rest)]
|
||||
first: std::collections::BTreeMap<String, String>,
|
||||
#[decodal(rest)]
|
||||
second: std::collections::BTreeMap<String, String>,
|
||||
}
|
||||
};
|
||||
assert!(
|
||||
expand_decodal(input)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("only one `rest` field")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_rest_field_modifiers() {
|
||||
let input: DeriveInput = syn::parse_quote! {
|
||||
struct Invalid {
|
||||
#[decodal(rest, default)]
|
||||
extra: std::collections::BTreeMap<String, String>,
|
||||
}
|
||||
};
|
||||
assert!(
|
||||
expand_decodal(input)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("cannot be combined")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use decodal::{Data, DecodalDecode, DecodalSchema, EmptyLoader, Engine};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use decodal::{Constraint, Data, DecodalDecode, DecodalSchema, EmptyLoader, Engine, Value};
|
||||
use decodal_derive::Decodal;
|
||||
|
||||
#[derive(Debug, PartialEq, Decodal)]
|
||||
@@ -24,6 +26,28 @@ struct Fleet {
|
||||
workers: Vec<Worker>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Decodal)]
|
||||
struct OpenConfig {
|
||||
name: String,
|
||||
#[decodal(default = true, rename = "feature.enabled")]
|
||||
enabled: bool,
|
||||
#[decodal(rest)]
|
||||
extra: BTreeMap<String, Data>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Decodal)]
|
||||
struct StringLabels {
|
||||
name: String,
|
||||
#[decodal(rest)]
|
||||
labels: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Decodal)]
|
||||
struct OpenBag {
|
||||
#[decodal(rest)]
|
||||
values: BTreeMap<String, Data>,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derives_schema_and_decode() {
|
||||
let mut engine = Engine::new(EmptyLoader);
|
||||
@@ -148,3 +172,97 @@ fn vec_schema_applies_nested_struct_defaults() {
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rest_map_opens_the_derived_object_and_collects_additional_fields() {
|
||||
let schema = OpenConfig::decodal_schema();
|
||||
let Value::Object {
|
||||
fields,
|
||||
rest: Some(rest),
|
||||
} = schema
|
||||
else {
|
||||
panic!("derived schema should have an object rest range")
|
||||
};
|
||||
assert_eq!(fields.len(), 2);
|
||||
assert!(matches!(
|
||||
*rest,
|
||||
Value::Range { ref constraints, .. }
|
||||
if constraints == &[Constraint::Unknown]
|
||||
));
|
||||
|
||||
let mut engine = Engine::new(EmptyLoader);
|
||||
engine
|
||||
.bind_global("OpenConfig", OpenConfig::decodal_schema())
|
||||
.unwrap();
|
||||
let module = engine
|
||||
.add_root_source(
|
||||
"test",
|
||||
"test",
|
||||
r#"
|
||||
{
|
||||
name = "api";
|
||||
plugin = { name = "cache"; };
|
||||
retries = 3;
|
||||
} as OpenConfig
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let value = engine.eval_module(module).unwrap();
|
||||
let data = engine.materialize(&value).unwrap();
|
||||
let config = OpenConfig::decodal_decode(&data).unwrap();
|
||||
|
||||
assert_eq!(config.name, "api");
|
||||
assert!(config.enabled);
|
||||
assert_eq!(config.extra.get("retries"), Some(&Data::Int(3)));
|
||||
assert!(matches!(config.extra.get("plugin"), Some(Data::Object(_))));
|
||||
assert!(!config.extra.contains_key("name"));
|
||||
assert!(!config.extra.contains_key("feature"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_rest_map_constrains_each_additional_field() {
|
||||
let mut engine = Engine::new(EmptyLoader);
|
||||
engine
|
||||
.bind_global("StringLabels", StringLabels::decodal_schema())
|
||||
.unwrap();
|
||||
let module = engine
|
||||
.add_root_source(
|
||||
"test",
|
||||
"test",
|
||||
r#"{ name = "service"; region = "ap-northeast-1"; tier = "edge"; } as StringLabels"#,
|
||||
)
|
||||
.unwrap();
|
||||
let value = engine.eval_module(module).unwrap();
|
||||
let data = engine.materialize(&value).unwrap();
|
||||
let labels = StringLabels::decodal_decode(&data).unwrap();
|
||||
assert_eq!(labels.labels.get("region"), Some(&"ap-northeast-1".into()));
|
||||
assert_eq!(labels.labels.get("tier"), Some(&"edge".into()));
|
||||
|
||||
let module = engine
|
||||
.add_root_source(
|
||||
"invalid",
|
||||
"invalid",
|
||||
r#"{ name = "service"; priority = 1; } as StringLabels"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(engine.eval_module(module).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rest_only_struct_collects_every_field() {
|
||||
let schema = OpenBag::decodal_schema();
|
||||
assert!(matches!(
|
||||
schema,
|
||||
Value::Object {
|
||||
ref fields,
|
||||
rest: Some(_),
|
||||
} if fields.is_empty()
|
||||
));
|
||||
|
||||
let data = Data::Object(vec![decodal::runtime::DataField {
|
||||
name: "answer".into(),
|
||||
value: Data::Int(42),
|
||||
}]);
|
||||
let bag = OpenBag::decodal_decode(&data).unwrap();
|
||||
assert_eq!(bag.values.get("answer"), Some(&Data::Int(42)));
|
||||
}
|
||||
|
||||
@@ -11,4 +11,4 @@ keywords = ["decodal", "lsp", "language-server", "editor"]
|
||||
categories = ["development-tools", "text-editors"]
|
||||
|
||||
[dependencies]
|
||||
decodal = { version = "0.3.0", path = "../decodal-core" }
|
||||
decodal = { version = "0.4.0", path = "../decodal-core" }
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use decodal::{
|
||||
Engine, HostEnvironment, HostValue, ImportLoader, LoadedImport, Result, RuntimeValue,
|
||||
Engine, HostEnvironment, ImportLoader, LoadedImport, Result, Value, runtime::RuntimeValue,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -116,12 +116,12 @@ pub(crate) fn complete<E: HostEnvironment>(
|
||||
let mut loader = environment.create_loader();
|
||||
let loaded = loader.load(Some(key), specifier)?;
|
||||
detail = match &loaded {
|
||||
LoadedImport::Source(source) => source.name.clone(),
|
||||
LoadedImport::Value(value) => value.key.clone(),
|
||||
LoadedImport::Source { name, .. } => name.clone(),
|
||||
LoadedImport::Value { key, .. } => key.clone(),
|
||||
};
|
||||
fields = match loaded {
|
||||
LoadedImport::Source(source) => collect_fields(&tokenize(&source.source)),
|
||||
LoadedImport::Value(value) => fields_from_host_value(&value.value),
|
||||
LoadedImport::Source { source, .. } => collect_fields(&tokenize(&source)),
|
||||
LoadedImport::Value { value, .. } => fields_from_value(&value),
|
||||
};
|
||||
} else if let Some(local) = local_fields.get(root) {
|
||||
fields = local.clone();
|
||||
@@ -229,6 +229,7 @@ fn builtin_items() -> Vec<CompletionItem> {
|
||||
("Int", CompletionKind::Type, "integer constraint", 5),
|
||||
("Float", CompletionKind::Type, "float constraint", 5),
|
||||
("Bool", CompletionKind::Type, "boolean constraint", 5),
|
||||
("Unknown", CompletionKind::Type, "unknown top range", 5),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(label, kind, detail, priority)| CompletionItem {
|
||||
@@ -267,24 +268,24 @@ fn fields_from_runtime<L: ImportLoader>(
|
||||
Ok(tree)
|
||||
}
|
||||
|
||||
fn fields_from_host_value(value: &HostValue) -> FieldTree {
|
||||
fn fields_from_value(value: &Value) -> FieldTree {
|
||||
match value {
|
||||
HostValue::Object(fields) => fields
|
||||
Value::Object { fields, .. } => fields
|
||||
.iter()
|
||||
.map(|field| (field.name.clone(), fields_from_host_value(&field.value)))
|
||||
.map(|field| (field.name.clone(), fields_from_value(&field.value)))
|
||||
.collect(),
|
||||
HostValue::ArrayConstraint {
|
||||
Value::ArrayRange {
|
||||
default: Some(value),
|
||||
..
|
||||
}
|
||||
| HostValue::MapConstraint {
|
||||
| Value::MapRange {
|
||||
default: Some(value),
|
||||
..
|
||||
}
|
||||
| HostValue::Abstract {
|
||||
| Value::Range {
|
||||
default: Some(value),
|
||||
..
|
||||
} => fields_from_host_value(value),
|
||||
} => fields_from_value(value),
|
||||
_ => FieldTree::new(),
|
||||
}
|
||||
}
|
||||
@@ -688,7 +689,7 @@ mod tests {
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use decodal::{
|
||||
Diagnostic, DiagnosticKind, EmptyLoader, HostValue, ImportCandidate, LoadedImport, Span,
|
||||
Diagnostic, DiagnosticKind, EmptyLoader, ImportCandidate, LoadedImport, Span, Value,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
@@ -708,15 +709,15 @@ mod tests {
|
||||
if specifier == "./post.md" {
|
||||
return Ok(LoadedImport::value(
|
||||
"post.md",
|
||||
HostValue::object([
|
||||
Value::object([
|
||||
(
|
||||
"frontmatter",
|
||||
HostValue::object([
|
||||
("title", HostValue::string("Hello")),
|
||||
("draft", HostValue::bool(false)),
|
||||
Value::object([
|
||||
("title", Value::string("Hello")),
|
||||
("draft", Value::bool(false)),
|
||||
]),
|
||||
),
|
||||
("body", HostValue::string("# Hello")),
|
||||
("body", Value::string("# Hello")),
|
||||
]),
|
||||
));
|
||||
}
|
||||
@@ -758,12 +759,9 @@ mod tests {
|
||||
fn configure_engine(&self, engine: &mut Engine<Self::Loader>) -> Result<()> {
|
||||
engine.bind_global(
|
||||
"App",
|
||||
HostValue::object([(
|
||||
Value::object([(
|
||||
"config",
|
||||
HostValue::object([
|
||||
("enabled", HostValue::bool_type()),
|
||||
("port", HostValue::int_type()),
|
||||
]),
|
||||
Value::object([("enabled", Value::bool_type()), ("port", Value::int_type())]),
|
||||
)]),
|
||||
)?;
|
||||
Ok(())
|
||||
@@ -854,6 +852,7 @@ mod tests {
|
||||
.unwrap();
|
||||
let labels = labels(result);
|
||||
assert!(labels.contains(&"String".into()));
|
||||
assert!(labels.contains(&"Unknown".into()));
|
||||
assert!(labels.contains(&"service".into()));
|
||||
assert!(labels.contains(&"value".into()));
|
||||
assert!(labels.contains(&"App".into()));
|
||||
@@ -881,6 +880,10 @@ mod tests {
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(labels(result).contains(&"String".into()));
|
||||
let result = complete(&EmptyEnvironment, "main.dcdl", "Unk", 3, false)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(labels(result).contains(&"Unknown".into()));
|
||||
}
|
||||
|
||||
struct EmptyEnvironment;
|
||||
|
||||
@@ -92,7 +92,7 @@ impl SemanticAnalysis {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use decodal::{
|
||||
Data, Diagnostic, DiagnosticKind, Engine, HostValue, ImportLoader, LoadedImport, Span,
|
||||
Data, Diagnostic, DiagnosticKind, Engine, ImportLoader, LoadedImport, Span, Value,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
@@ -100,11 +100,11 @@ mod tests {
|
||||
const ROOT: &str = r#"Post & import "./post.md""#;
|
||||
|
||||
struct ContentEnvironment {
|
||||
draft: HostValue,
|
||||
draft: Value,
|
||||
}
|
||||
|
||||
struct ContentLoader {
|
||||
draft: HostValue,
|
||||
draft: Value,
|
||||
}
|
||||
|
||||
impl ImportLoader for ContentLoader {
|
||||
@@ -122,15 +122,15 @@ mod tests {
|
||||
}
|
||||
Ok(LoadedImport::value(
|
||||
"content/post.md",
|
||||
HostValue::object([
|
||||
Value::object([
|
||||
(
|
||||
"frontmatter",
|
||||
HostValue::object([
|
||||
("title", HostValue::string("Hello")),
|
||||
Value::object([
|
||||
("title", Value::string("Hello")),
|
||||
("draft", self.draft.clone()),
|
||||
]),
|
||||
),
|
||||
("body", HostValue::string("# Hello")),
|
||||
("body", Value::string("# Hello")),
|
||||
]),
|
||||
))
|
||||
}
|
||||
@@ -148,15 +148,15 @@ mod tests {
|
||||
fn configure_engine(&self, engine: &mut Engine<Self::Loader>) -> decodal::Result<()> {
|
||||
engine.bind_global(
|
||||
"Post",
|
||||
HostValue::object([
|
||||
Value::object([
|
||||
(
|
||||
"frontmatter",
|
||||
HostValue::object([
|
||||
("title", HostValue::string_type()),
|
||||
("draft", HostValue::bool_type()),
|
||||
Value::object([
|
||||
("title", Value::string_type()),
|
||||
("draft", Value::bool_type()),
|
||||
]),
|
||||
),
|
||||
("body", HostValue::string_type()),
|
||||
("body", Value::string_type()),
|
||||
]),
|
||||
)?;
|
||||
Ok(())
|
||||
@@ -173,7 +173,7 @@ mod tests {
|
||||
#[test]
|
||||
fn injected_environment_matches_direct_evaluation() {
|
||||
let environment = ContentEnvironment {
|
||||
draft: HostValue::bool(false),
|
||||
draft: Value::bool(false),
|
||||
};
|
||||
let direct = evaluate_direct(&environment).unwrap();
|
||||
let service = LanguageService::new(&environment);
|
||||
@@ -186,7 +186,7 @@ mod tests {
|
||||
#[test]
|
||||
fn injected_environment_preserves_import_diagnostics() {
|
||||
let service = LanguageService::new(ContentEnvironment {
|
||||
draft: HostValue::string("maybe"),
|
||||
draft: Value::string("maybe"),
|
||||
});
|
||||
let analysis = service.analyze("main.dcdl", "main.dcdl", ROOT);
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ categories = ["development-tools", "text-processing"]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
decodal = { version = "0.3.0", path = "../decodal-core" }
|
||||
decodal = { version = "0.4.0", path = "../decodal-core" }
|
||||
serde_json.workspace = true
|
||||
wasm-bindgen.workspace = true
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use std::{error::Error, fmt};
|
||||
|
||||
use decodal::{
|
||||
Ast, BinaryOp, CompareOp, Expr, ExprId, Field, Param, SourceForm, Span, SyntaxToken,
|
||||
SyntaxTokenKind,
|
||||
Ast, BinaryOp, CompareOp, Expr, ExprId, Field, ObjectRest, Param, SourceForm, Span,
|
||||
SyntaxToken, SyntaxTokenKind,
|
||||
ast::{MatchArm, UnaryOp},
|
||||
parse_source, tokenize_source,
|
||||
};
|
||||
@@ -81,7 +81,7 @@ impl<'a> Formatter<'a> {
|
||||
fn format(&self, root: ExprId, source_form: SourceForm) -> String {
|
||||
let mut out = String::new();
|
||||
if source_form == SourceForm::Fields {
|
||||
let Expr::Object(fields) = &self.ast.get(root).expr else {
|
||||
let Expr::Object { fields, .. } = &self.ast.get(root).expr else {
|
||||
unreachable!("field-form sources parse to an object")
|
||||
};
|
||||
self.write_field_list(&mut out, fields, 0, self.source.len(), 0);
|
||||
@@ -145,7 +145,7 @@ impl<'a> Formatter<'a> {
|
||||
if self.has_comment(node.span)
|
||||
&& !matches!(
|
||||
node.expr,
|
||||
Expr::Object(_) | Expr::Array(_) | Expr::Let { .. } | Expr::Match { .. }
|
||||
Expr::Object { .. } | Expr::Array(_) | Expr::Let { .. } | Expr::Match { .. }
|
||||
)
|
||||
{
|
||||
out.push_str(self.raw(node.span));
|
||||
@@ -162,7 +162,9 @@ impl<'a> Formatter<'a> {
|
||||
Expr::Literal(_) | Expr::Ident(_) | Expr::RegexConstraint(_) | Expr::Wildcard => {
|
||||
out.push_str(self.raw(node.span));
|
||||
}
|
||||
Expr::Object(fields) => self.write_object(out, node.span, fields, indent),
|
||||
Expr::Object { fields, rest } => {
|
||||
self.write_object(out, node.span, fields, rest.as_ref(), indent)
|
||||
}
|
||||
Expr::Array(items) => self.write_array(out, node.span, items, indent),
|
||||
Expr::ArrayConstraint { item } => {
|
||||
out.push_str("[...");
|
||||
@@ -241,15 +243,50 @@ impl<'a> Formatter<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn write_object(&self, out: &mut String, span: Span, fields: &[Field], indent: usize) {
|
||||
fn write_object(
|
||||
&self,
|
||||
out: &mut String,
|
||||
span: Span,
|
||||
fields: &[Field],
|
||||
rest: Option<&ObjectRest>,
|
||||
indent: usize,
|
||||
) {
|
||||
let (start, end) =
|
||||
self.delimited_range(span, SyntaxTokenKind::LBrace, SyntaxTokenKind::RBrace);
|
||||
if fields.is_empty() && !self.has_comment_between(start, end) {
|
||||
if fields.is_empty() && rest.is_none() && !self.has_comment_between(start, end) {
|
||||
out.push_str("{}");
|
||||
return;
|
||||
}
|
||||
out.push_str("{\n");
|
||||
self.write_field_list(out, fields, start, end, indent + INDENT);
|
||||
let field_end = rest.map_or(end, |rest| rest.span.start as usize);
|
||||
self.write_field_list(out, fields, start, field_end, indent + INDENT);
|
||||
if let Some(rest) = rest {
|
||||
write_indent(out, indent + INDENT);
|
||||
out.push_str("...");
|
||||
let value_start = self.ast.span(rest.value).start as usize;
|
||||
let ellipsis = self
|
||||
.tokens_between(rest.span.start as usize, value_start)
|
||||
.find(|token| token.kind == SyntaxTokenKind::Ellipsis)
|
||||
.expect("parsed object rest constraints contain `...`");
|
||||
if self.has_comment_between(ellipsis.span.end as usize, value_start) {
|
||||
self.write_between(
|
||||
out,
|
||||
ellipsis.span.end as usize,
|
||||
value_start,
|
||||
Some(ellipsis.span.end as usize),
|
||||
indent + INDENT,
|
||||
);
|
||||
write_indent(out, indent + INDENT);
|
||||
}
|
||||
self.write_expr(out, rest.value, indent + INDENT, 0);
|
||||
self.write_between(
|
||||
out,
|
||||
rest.span.end as usize,
|
||||
end,
|
||||
Some(rest.span.end as usize),
|
||||
indent + INDENT,
|
||||
);
|
||||
}
|
||||
write_indent(out, indent);
|
||||
out.push('}');
|
||||
}
|
||||
@@ -524,7 +561,7 @@ impl<'a> Formatter<'a> {
|
||||
Expr::As { narrower, wider } => {
|
||||
self.is_inline_expr(*narrower) && self.is_inline_expr(*wider)
|
||||
}
|
||||
Expr::Object(_) | Expr::Let { .. } | Expr::Function { .. } | Expr::Match { .. } => {
|
||||
Expr::Object { .. } | Expr::Let { .. } | Expr::Function { .. } | Expr::Match { .. } => {
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -707,6 +744,17 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_unknown_and_object_rest_constraints() {
|
||||
let source =
|
||||
"value={hoge=Int;fuga=String;# remaining fields\n...# unconstrained\nUnknown};";
|
||||
let formatted = format_source(source).unwrap();
|
||||
assert_eq!(
|
||||
formatted,
|
||||
"value = {\n hoge = Int;\n fuga = String; # remaining fields\n ... # unconstrained\n Unknown\n};\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_regex_and_escaped_strings() {
|
||||
let source = r#"value={pattern=/^api\/.+$/;text="a\n\"b";};"#;
|
||||
|
||||
@@ -11,9 +11,9 @@ keywords = ["decodal", "lsp", "language-server", "editor"]
|
||||
categories = ["development-tools", "text-editors"]
|
||||
|
||||
[dependencies]
|
||||
decodal = { version = "0.3.0", path = "../decodal-core" }
|
||||
decodal-language-service = { version = "0.3.0", path = "../decodal-language-service" }
|
||||
decodal-language-tools = { version = "0.3.0", path = "../decodal-language-tools" }
|
||||
decodal = { version = "0.4.0", path = "../decodal-core" }
|
||||
decodal-language-service = { version = "0.4.0", path = "../decodal-language-service" }
|
||||
decodal-language-tools = { version = "0.4.0", path = "../decodal-language-tools" }
|
||||
lsp-server = "0.10"
|
||||
lsp-types = "0.97"
|
||||
serde_json.workspace = true
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::{
|
||||
|
||||
use decodal::{
|
||||
Diagnostic as DecodalDiagnostic, DiagnosticKind, HostEnvironment, ImportCandidate,
|
||||
ImportLoader, LoadedImport, LoadedSource, SourceId, Span,
|
||||
ImportLoader, LoadedImport, SourceId, Span,
|
||||
};
|
||||
use decodal_language_service::{
|
||||
CompletionKind as ServiceCompletionKind, CompletionResult, LanguageService, SemanticAnalysis,
|
||||
@@ -667,11 +667,11 @@ impl ImportLoader for FileSystemLoader {
|
||||
)
|
||||
})?
|
||||
};
|
||||
Ok(LoadedImport::Source(LoadedSource {
|
||||
Ok(LoadedImport::Source {
|
||||
key: key.clone(),
|
||||
name: key,
|
||||
source,
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
fn complete_import(
|
||||
@@ -743,7 +743,7 @@ mod tests {
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use decodal::{Engine, HostValue};
|
||||
use decodal::{Engine, Value};
|
||||
use lsp_server::RequestId;
|
||||
use serde_json::json;
|
||||
|
||||
@@ -772,12 +772,12 @@ mod tests {
|
||||
.is_some_and(|source| source == "draft: false");
|
||||
Ok(LoadedImport::value(
|
||||
"content/post.md",
|
||||
HostValue::object([(
|
||||
Value::object([(
|
||||
"draft",
|
||||
if draft {
|
||||
HostValue::bool(false)
|
||||
Value::bool(false)
|
||||
} else {
|
||||
HostValue::string("maybe")
|
||||
Value::string("maybe")
|
||||
},
|
||||
)]),
|
||||
))
|
||||
@@ -794,10 +794,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn configure_engine(&self, engine: &mut Engine<Self::Loader>) -> decodal::Result<()> {
|
||||
engine.bind_global(
|
||||
"Post",
|
||||
HostValue::object([("draft", HostValue::bool_type())]),
|
||||
)?;
|
||||
engine.bind_global("Post", Value::object([("draft", Value::bool_type())]))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,8 @@ publish = false
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
decodal = { version = "0.3.0", path = "../decodal-core" }
|
||||
decodal-language-service = { version = "0.3.0", path = "../decodal-language-service" }
|
||||
decodal = { version = "0.4.0", path = "../decodal-core" }
|
||||
decodal-language-service = { version = "0.4.0", path = "../decodal-language-service" }
|
||||
serde_json.workspace = true
|
||||
wasm-bindgen.workspace = true
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ use decodal_language_service::{CompletionKind, LanguageService};
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod host_value;
|
||||
mod value;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod web_environment;
|
||||
|
||||
|
||||
@@ -1,41 +1,41 @@
|
||||
use decodal::{CompareOp, Constraint, HostValue, LiteralValue, PrimitiveType};
|
||||
use serde_json::{Map, Value};
|
||||
use decodal::{CompareOp, Constraint, LiteralValue, PrimitiveType, Value};
|
||||
use serde_json::{Map, Value as JsonValue};
|
||||
|
||||
pub(crate) fn from_json(value: &Value) -> Result<HostValue, String> {
|
||||
pub(crate) fn from_json(value: &JsonValue) -> Result<Value, String> {
|
||||
match value {
|
||||
Value::Null => Err(String::from("null is not a Decodal host value")),
|
||||
Value::Bool(value) => Ok(HostValue::bool(*value)),
|
||||
Value::Number(value) => number(value),
|
||||
Value::String(value) => Ok(HostValue::string(value)),
|
||||
Value::Array(items) => items
|
||||
JsonValue::Null => Err(String::from("null is not a Decodal value")),
|
||||
JsonValue::Bool(value) => Ok(Value::bool(*value)),
|
||||
JsonValue::Number(value) => number(value),
|
||||
JsonValue::String(value) => Ok(Value::string(value)),
|
||||
JsonValue::Array(items) => items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, value)| {
|
||||
from_json(value).map_err(|error| format!("array item {index}: {error}"))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map(HostValue::array),
|
||||
Value::Object(fields) => object(fields),
|
||||
.map(Value::array),
|
||||
JsonValue::Object(fields) => object(fields),
|
||||
}
|
||||
}
|
||||
|
||||
fn number(value: &serde_json::Number) -> Result<HostValue, String> {
|
||||
fn number(value: &serde_json::Number) -> Result<Value, String> {
|
||||
if let Some(value) = value.as_i64() {
|
||||
return Ok(HostValue::int(value));
|
||||
return Ok(Value::int(value));
|
||||
}
|
||||
if let Some(value) = value.as_u64() {
|
||||
return i64::try_from(value)
|
||||
.map(HostValue::int)
|
||||
.map_err(|_| String::from("integer host value is outside the signed 64-bit range"));
|
||||
.map(Value::int)
|
||||
.map_err(|_| String::from("integer value is outside the signed 64-bit range"));
|
||||
}
|
||||
value
|
||||
.as_f64()
|
||||
.filter(|value| value.is_finite())
|
||||
.map(HostValue::float)
|
||||
.ok_or_else(|| String::from("invalid numeric host value"))
|
||||
.map(Value::float)
|
||||
.ok_or_else(|| String::from("invalid numeric value"))
|
||||
}
|
||||
|
||||
fn object(fields: &Map<String, Value>) -> Result<HostValue, String> {
|
||||
fn object(fields: &Map<String, JsonValue>) -> Result<Value, String> {
|
||||
let Some(descriptor) = fields.get("$decodal") else {
|
||||
return fields
|
||||
.iter()
|
||||
@@ -45,7 +45,7 @@ fn object(fields: &Map<String, Value>) -> Result<HostValue, String> {
|
||||
.map_err(|error| format!("field `{name}`: {error}"))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map(HostValue::object);
|
||||
.map(Value::object);
|
||||
};
|
||||
|
||||
let descriptor = descriptor
|
||||
@@ -59,6 +59,14 @@ fn object(fields: &Map<String, Value>) -> Result<HostValue, String> {
|
||||
.map(Box::new);
|
||||
|
||||
match descriptor {
|
||||
"Unknown" => {
|
||||
let mut all_constraints = vec![Constraint::Unknown];
|
||||
all_constraints.extend(constraints);
|
||||
Ok(Value::Range {
|
||||
constraints: all_constraints,
|
||||
default,
|
||||
})
|
||||
}
|
||||
"String" | "Int" | "Float" | "Bool" => {
|
||||
let primitive = match descriptor {
|
||||
"String" => PrimitiveType::String,
|
||||
@@ -69,7 +77,7 @@ fn object(fields: &Map<String, Value>) -> Result<HostValue, String> {
|
||||
};
|
||||
let mut all_constraints = vec![Constraint::Type(primitive)];
|
||||
all_constraints.extend(constraints);
|
||||
Ok(HostValue::Abstract {
|
||||
Ok(Value::Range {
|
||||
constraints: all_constraints,
|
||||
default,
|
||||
})
|
||||
@@ -78,7 +86,7 @@ fn object(fields: &Map<String, Value>) -> Result<HostValue, String> {
|
||||
let item = fields
|
||||
.get("item")
|
||||
.ok_or_else(|| String::from("Array descriptor requires `item`"))?;
|
||||
Ok(HostValue::ArrayConstraint {
|
||||
Ok(Value::ArrayRange {
|
||||
item: Box::new(from_json(item)?),
|
||||
constraints,
|
||||
default,
|
||||
@@ -88,21 +96,49 @@ fn object(fields: &Map<String, Value>) -> Result<HostValue, String> {
|
||||
let value = fields
|
||||
.get("value")
|
||||
.ok_or_else(|| String::from("Map descriptor requires `value`"))?;
|
||||
Ok(HostValue::MapConstraint {
|
||||
Ok(Value::MapRange {
|
||||
value: Box::new(from_json(value)?),
|
||||
constraints,
|
||||
default,
|
||||
})
|
||||
}
|
||||
"Abstract" => Ok(HostValue::Abstract {
|
||||
"Object" => {
|
||||
if !constraints.is_empty() {
|
||||
return Err(String::from(
|
||||
"Object descriptor does not accept `constraints`; constrain its fields or rest range",
|
||||
));
|
||||
}
|
||||
if default.is_some() {
|
||||
return Err(String::from(
|
||||
"Object descriptor does not accept `default`; place defaults on its fields",
|
||||
));
|
||||
}
|
||||
let object_fields = fields
|
||||
.get("fields")
|
||||
.and_then(JsonValue::as_object)
|
||||
.ok_or_else(|| String::from("Object descriptor requires object `fields`"))?;
|
||||
let value_fields = object_fields
|
||||
.iter()
|
||||
.map(|(name, value)| {
|
||||
from_json(value)
|
||||
.map(|value| (name.clone(), value))
|
||||
.map_err(|error| format!("field `{name}`: {error}"))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let rest = fields
|
||||
.get("rest")
|
||||
.ok_or_else(|| String::from("Object descriptor requires `rest`"))?;
|
||||
Ok(Value::object_with_rest(value_fields, from_json(rest)?))
|
||||
}
|
||||
"Range" => Ok(Value::Range {
|
||||
constraints,
|
||||
default,
|
||||
}),
|
||||
name => Err(format!("unknown Decodal host descriptor `{name}`")),
|
||||
name => Err(format!("unknown Decodal value descriptor `{name}`")),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_constraints(value: Option<&Value>) -> Result<Vec<Constraint>, String> {
|
||||
fn parse_constraints(value: Option<&JsonValue>) -> Result<Vec<Constraint>, String> {
|
||||
let Some(value) = value else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
@@ -118,12 +154,13 @@ fn parse_constraints(value: Option<&Value>) -> Result<Vec<Constraint>, String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn parse_constraint(value: &Value) -> Result<Constraint, String> {
|
||||
fn parse_constraint(value: &JsonValue) -> Result<Constraint, String> {
|
||||
let fields = value
|
||||
.as_object()
|
||||
.ok_or_else(|| String::from("constraint must be an object"))?;
|
||||
let kind = required_string(fields, "kind")?;
|
||||
match kind {
|
||||
"unknown" => Ok(Constraint::Unknown),
|
||||
"type" => match required_string(fields, "value")? {
|
||||
"String" => Ok(Constraint::Type(PrimitiveType::String)),
|
||||
"Int" => Ok(Constraint::Type(PrimitiveType::Int)),
|
||||
@@ -154,29 +191,29 @@ fn parse_constraint(value: &Value) -> Result<Constraint, String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn literal(value: &Value) -> Result<LiteralValue, String> {
|
||||
fn literal(value: &JsonValue) -> Result<LiteralValue, String> {
|
||||
match value {
|
||||
Value::String(value) => Ok(LiteralValue::String(value.clone())),
|
||||
Value::Bool(value) => Ok(LiteralValue::Bool(*value)),
|
||||
Value::Number(value) => match number(value)? {
|
||||
HostValue::Int(value) => Ok(LiteralValue::Int(value)),
|
||||
HostValue::Float(value) => Ok(LiteralValue::Float(value)),
|
||||
JsonValue::String(value) => Ok(LiteralValue::String(value.clone())),
|
||||
JsonValue::Bool(value) => Ok(LiteralValue::Bool(*value)),
|
||||
JsonValue::Number(value) => match number(value)? {
|
||||
Value::Int(value) => Ok(LiteralValue::Int(value)),
|
||||
Value::Float(value) => Ok(LiteralValue::Float(value)),
|
||||
_ => unreachable!(),
|
||||
},
|
||||
_ => Err(String::from("comparison value must be a primitive literal")),
|
||||
}
|
||||
}
|
||||
|
||||
fn required_string<'a>(fields: &'a Map<String, Value>, name: &str) -> Result<&'a str, String> {
|
||||
fn required_string<'a>(fields: &'a Map<String, JsonValue>, name: &str) -> Result<&'a str, String> {
|
||||
fields
|
||||
.get(name)
|
||||
.and_then(Value::as_str)
|
||||
.and_then(JsonValue::as_str)
|
||||
.ok_or_else(|| format!("constraint requires string `{name}`"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use decodal::{Constraint, HostValue, LiteralValue, PrimitiveType};
|
||||
use decodal::{Constraint, LiteralValue, PrimitiveType, Value};
|
||||
|
||||
use super::from_json;
|
||||
|
||||
@@ -188,11 +225,11 @@ mod tests {
|
||||
});
|
||||
assert_eq!(
|
||||
from_json(&value).unwrap(),
|
||||
HostValue::object([
|
||||
("body", HostValue::string("# Hello")),
|
||||
Value::object([
|
||||
("body", Value::string("# Hello")),
|
||||
(
|
||||
"frontmatter",
|
||||
HostValue::object([("draft", HostValue::bool(false))]),
|
||||
Value::object([("draft", Value::bool(false))]),
|
||||
),
|
||||
])
|
||||
);
|
||||
@@ -210,8 +247,8 @@ mod tests {
|
||||
});
|
||||
assert_eq!(
|
||||
from_json(&value).unwrap(),
|
||||
HostValue::ArrayConstraint {
|
||||
item: Box::new(HostValue::Abstract {
|
||||
Value::ArrayRange {
|
||||
item: Box::new(Value::Range {
|
||||
constraints: vec![
|
||||
Constraint::Type(PrimitiveType::Int),
|
||||
Constraint::Compare(decodal::CompareOp::Gt, LiteralValue::Int(0)),
|
||||
@@ -219,10 +256,7 @@ mod tests {
|
||||
default: None,
|
||||
}),
|
||||
constraints: Vec::new(),
|
||||
default: Some(Box::new(HostValue::array([
|
||||
HostValue::int(1),
|
||||
HostValue::int(2),
|
||||
]))),
|
||||
default: Some(Box::new(Value::array([Value::int(1), Value::int(2),]))),
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -236,10 +270,41 @@ mod tests {
|
||||
});
|
||||
assert_eq!(
|
||||
from_json(&value).unwrap(),
|
||||
HostValue::MapConstraint {
|
||||
value: Box::new(HostValue::bool_type()),
|
||||
Value::MapRange {
|
||||
value: Box::new(Value::bool_type()),
|
||||
constraints: Vec::new(),
|
||||
default: Some(Box::new(HostValue::object([] as [(&str, HostValue); 0]))),
|
||||
default: Some(Box::new(Value::object([] as [(&str, Value); 0]))),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_unknown_and_open_object_descriptors() {
|
||||
let value = serde_json::json!({
|
||||
"$decodal": "Object",
|
||||
"fields": {
|
||||
"name": { "$decodal": "String" },
|
||||
},
|
||||
"rest": { "$decodal": "Unknown" },
|
||||
});
|
||||
assert_eq!(
|
||||
from_json(&value).unwrap(),
|
||||
Value::object_with_rest([("name", Value::string_type())], Value::unknown(),)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_general_range_descriptors() {
|
||||
let value = serde_json::json!({
|
||||
"$decodal": "Range",
|
||||
"constraints": [{ "kind": "predicate", "value": "available" }],
|
||||
"default": true,
|
||||
});
|
||||
assert_eq!(
|
||||
from_json(&value).unwrap(),
|
||||
Value::Range {
|
||||
constraints: vec![Constraint::BuiltinPredicate("available".into())],
|
||||
default: Some(Box::new(Value::bool(true))),
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use decodal::{
|
||||
Diagnostic, DiagnosticKind, Engine, HostEnvironment, HostValue, ImportCandidate, ImportLoader,
|
||||
LoadedImport, Span,
|
||||
Diagnostic, DiagnosticKind, Engine, HostEnvironment, ImportCandidate, ImportLoader,
|
||||
LoadedImport, Span, Value as DecodalValue,
|
||||
};
|
||||
use js_sys::{Function, Reflect};
|
||||
use serde_json::Value;
|
||||
use wasm_bindgen::{JsCast, JsValue};
|
||||
|
||||
use crate::host_value;
|
||||
use crate::value;
|
||||
|
||||
pub(crate) struct JsEnvironment {
|
||||
globals: BTreeMap<String, HostValue>,
|
||||
globals: BTreeMap<String, DecodalValue>,
|
||||
load_import: Option<Function>,
|
||||
complete_import: Option<Function>,
|
||||
}
|
||||
@@ -37,7 +37,7 @@ impl JsEnvironment {
|
||||
globals
|
||||
.iter()
|
||||
.map(|(name, value)| {
|
||||
host_value::from_json(value)
|
||||
value::from_json(value)
|
||||
.map(|value| (name.clone(), value))
|
||||
.map_err(|error| {
|
||||
JsValue::from_str(&format!("invalid global `{name}`: {error}"))
|
||||
@@ -133,7 +133,7 @@ fn loaded_import(value: &Value) -> Result<LoadedImport, String> {
|
||||
let value = fields
|
||||
.get("value")
|
||||
.ok_or_else(|| String::from("value import requires `value`"))?;
|
||||
let value = host_value::from_json(value)
|
||||
let value = value::from_json(value)
|
||||
.map_err(|error| format!("invalid imported value: {error}"))?;
|
||||
Ok(LoadedImport::value(key, value))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# Developing Decodal
|
||||
|
||||
Development notes live here rather than in the public manual. The manual describes released language behavior and public integration APIs; implementation plans and unresolved design work belong in issues or pull requests.
|
||||
|
||||
## Repository map
|
||||
|
||||
- `crates/decodal-core`: parser, evaluator, public Rust API, and tests.
|
||||
- `crates/decodal-derive`: `Decodal` derive macros.
|
||||
- `crates/decodal-language-service`: host-configurable semantic analysis and completion.
|
||||
- `crates/decodal-language-tools`: source-preserving formatter and tooling.
|
||||
- `crates/decodal-lsp`: LSP transport and document synchronization.
|
||||
- `crates/decodal-wasm`: WebAssembly bindings.
|
||||
- `packages/decodal-wasm`: generated npm and JSR runtime package.
|
||||
- `packages/decodal-codemirror`: CodeMirror language support and formatter WebAssembly.
|
||||
- `editors/lezer-decodal` and `editors/tree-sitter-decodal`: downstream editor grammars.
|
||||
- `site/decodal-site`: documentation site and playground.
|
||||
- `doc/manual/source`: English public manual consumed by the site.
|
||||
- `doc/manual/source/jp`: Japanese translation of the public manual.
|
||||
|
||||
## Runtime architecture
|
||||
|
||||
The host owns I/O. `ImportLoader` turns an import specifier into DCDL source or a structured `Value`, and `HostEnvironment` installs the same loader and globals for production and editor tooling.
|
||||
|
||||
Evaluation proceeds through parse, lazy expression evaluation, and materialization. Object fields, module roots, imports, arguments, and defaults are represented by memoized thunks. A thunk re-entered while it is being evaluated produces a cycle diagnostic.
|
||||
|
||||
Runtime values distinguish concrete values from abstract ranges. Composition and `as` preserve that distinction; materialization selects defaults and rejects unresolved ranges or functions. `Data` is the output-only representation.
|
||||
|
||||
Diagnostics retain Decodal source spans. Structured host values use their stable import key and logical value path rather than synthetic source spans.
|
||||
|
||||
## Checks
|
||||
|
||||
Run the release validation commands documented in [`RELEASING.md`](../../RELEASING.md). For a focused change, run the tests for the affected crate or package first, then the full workspace and site checks before release.
|
||||
|
||||
The documentation site can be checked without regenerating committed WebAssembly artifacts:
|
||||
|
||||
```sh
|
||||
npm --prefix site/decodal-site test
|
||||
npm --prefix site/decodal-site run build
|
||||
```
|
||||
|
||||
Use `npm --prefix site/decodal-site run build:wasm` when Rust bindings or formatter behavior changed.
|
||||
|
||||
## Documentation site delivery
|
||||
|
||||
The canonical site origin is `https://decodal.hareworks.net`, configured through Astro's `site` option. A normal site build generates the sitemap, robots policy, social metadata, structured data, 404 page, and source-backed Markdown endpoints. `/llms.txt` indexes the individual English and Japanese Markdown pages; `/llms-full.txt` and `/ja/llms-full.txt` provide complete manuals. These resources are built directly from `doc/manual/source` and do not use Cloudflare's HTML-to-Markdown conversion.
|
||||
|
||||
Deploy the already prepared site with:
|
||||
|
||||
```sh
|
||||
npm --prefix site/decodal-site run deploy
|
||||
```
|
||||
|
||||
Cloudflare Pages `_redirects` handles legacy paths within the site, but not hostname redirects. In the Cloudflare account, configure a Bulk Redirect from `https://decodal-site.pages.dev/` to `https://decodal.hareworks.net/` with status `301`, subpath matching, path-suffix preservation, and query-string preservation enabled. This prevents the Pages project hostname from becoming a second public origin.
|
||||
|
||||
## Syntax changes
|
||||
|
||||
When syntax changes:
|
||||
|
||||
1. Update the public EBNF in `doc/manual/source/language/grammar.md` and the relevant language page.
|
||||
2. Update the Rust lexer/parser and tests.
|
||||
3. Update the Lezer and Tree-sitter grammars and regenerate their committed outputs.
|
||||
4. Update formatter, playground, and language-service tests as applicable.
|
||||
5. Run the validation commands in `RELEASING.md`.
|
||||
|
||||
The Rust parser is authoritative for evaluation. Lezer and Tree-sitter are downstream editor integrations and are not runtime or formatter dependencies.
|
||||
|
||||
## Releases
|
||||
|
||||
Package versions, validation commands, publish order, and registry commands are maintained only in [`RELEASING.md`](../../RELEASING.md).
|
||||
@@ -1,140 +0,0 @@
|
||||
# Components
|
||||
|
||||
Decodal is split into a small runtime core and separate syntax tooling components.
|
||||
The public surface is intentionally organized by use case: execute Decodal with Rust or WebAssembly, edit Decodal on the Web with Lezer and CodeMirror, and integrate Decodal into general-purpose editors with Tree-sitter.
|
||||
|
||||
## Runtime components
|
||||
|
||||
### Rust crate
|
||||
|
||||
The `decodal` crate is the primary Rust runtime and embedding API.
|
||||
It owns parsing, evaluation, materialization, diagnostics, host-provided values, and schema/decode traits.
|
||||
Rust applications should use this crate when they want to load Decodal source, evaluate it, or embed Decodal into a host program.
|
||||
|
||||
Important paths:
|
||||
|
||||
```text
|
||||
crates/decodal-core/
|
||||
crates/decodal-derive/
|
||||
```
|
||||
|
||||
`decodal-derive` provides optional derive macros for Rust struct integration.
|
||||
It is a companion to the runtime crate rather than an editor or syntax-highlighting component.
|
||||
|
||||
### WebAssembly package
|
||||
|
||||
`decodal-wasm` exposes the runtime to browsers.
|
||||
The documentation site playground uses it to evaluate Decodal entirely in the browser.
|
||||
|
||||
Important paths:
|
||||
|
||||
```text
|
||||
crates/decodal-wasm/
|
||||
packages/decodal-wasm/
|
||||
```
|
||||
|
||||
The npm package is `decodal-wasm`.
|
||||
The JSR package is `@hare/decodal-wasm`.
|
||||
|
||||
The generated files in `packages/decodal-wasm/` are committed so the site can build without requiring every consumer to run `wasm-pack` first.
|
||||
The WebAssembly package is for execution, not syntax highlighting.
|
||||
|
||||
## Language tools
|
||||
|
||||
Semantic editor integration lives in the host-configurable language service crate.
|
||||
It depends only on the runtime and accepts the same `HostEnvironment` implementation used by a production application.
|
||||
The LSP crate adapts that service to the Language Server Protocol over stdin/stdout.
|
||||
It provides full document synchronization, semantic diagnostics, and whole-document formatting.
|
||||
A host-specific LSP binary injects its loader and global schema configuration without reimplementing evaluation rules.
|
||||
|
||||
Important paths:
|
||||
|
||||
```text
|
||||
crates/decodal-language-service/
|
||||
crates/decodal-lsp/
|
||||
```
|
||||
|
||||
The default `decodal-lsp` binary reads Decodal imports from the filesystem.
|
||||
Embedded hosts can call its library entry point with a custom `LspEnvironment` to reuse structured imports and to make unsaved external documents, such as Markdown, visible to the loader.
|
||||
|
||||
Source formatting lives in a separate Rust language tools crate.
|
||||
It uses the canonical Decodal AST together with the runtime lexer's lossless syntax tokens, so native LSP and WebAssembly callers execute the same formatter implementation.
|
||||
|
||||
This component is responsible for operations that must preserve source text details such as comments and whitespace.
|
||||
It is used by the CodeMirror package's bundled formatter WebAssembly and can also be used by an LSP adapter for formatting.
|
||||
It does not depend on Tree-sitter or Lezer.
|
||||
|
||||
Important paths:
|
||||
|
||||
```text
|
||||
crates/decodal-language-tools/
|
||||
```
|
||||
|
||||
The current language tools crate exposes the formatter.
|
||||
|
||||
## Web editor components
|
||||
|
||||
The Web playground editor uses CodeMirror 6 with a generated Lezer parser.
|
||||
Lezer provides syntax highlighting, folding, indentation, and editor syntax tree behavior. The browser formatter command calls the canonical Rust formatter compiled to WebAssembly.
|
||||
|
||||
Important paths:
|
||||
|
||||
```text
|
||||
editors/lezer-decodal/decodal.grammar
|
||||
packages/decodal-codemirror/src/decodal.js
|
||||
packages/decodal-codemirror/src/decodal-parser.js
|
||||
packages/decodal-codemirror/src/decodal-parser.terms.js
|
||||
packages/decodal-codemirror/src/format.js
|
||||
packages/decodal-codemirror/wasm/
|
||||
```
|
||||
|
||||
The npm package is `decodal-codemirror`.
|
||||
The JSR package is `@hare/decodal-codemirror`.
|
||||
|
||||
The Lezer grammar is derived from the canonical grammar documentation, but it is not a literal copy of the EBNF.
|
||||
Precedence and token conflict handling are represented in the Lezer grammar in the form CodeMirror needs.
|
||||
|
||||
## General editor components
|
||||
|
||||
Tree-sitter is the portable editor-integration grammar.
|
||||
Editors such as Zed, Neovim, Helix, and Emacs should consume this component when they need Decodal parsing or highlighting outside the Web playground.
|
||||
|
||||
Important paths:
|
||||
|
||||
```text
|
||||
editors/tree-sitter-decodal/grammar.js
|
||||
editors/tree-sitter-decodal/queries/highlights.scm
|
||||
editors/tree-sitter-decodal/queries/locals.scm
|
||||
editors/tree-sitter-decodal/src/
|
||||
```
|
||||
|
||||
The generated parser sources under `editors/tree-sitter-decodal/src/` are committed so editor integrations can consume the grammar without regenerating it first.
|
||||
|
||||
## Canonical grammar
|
||||
|
||||
The human-readable grammar lives in:
|
||||
|
||||
```text
|
||||
doc/manual/souce/language/grammar.md
|
||||
```
|
||||
|
||||
This EBNF is the language-level reference.
|
||||
The Rust parser, Lezer grammar, and Tree-sitter grammar should be kept aligned with it, but each implementation may encode precedence and recovery behavior in the form required by its parser generator or runtime.
|
||||
|
||||
## Syntax token API
|
||||
|
||||
The `decodal` crate exposes `tokenize_source`, `tokenize_source_with_source_id`, `SyntaxToken`, and `SyntaxTokenKind` for source-preserving tooling.
|
||||
Comments have explicit tokens, while whitespace is represented by gaps between token spans and can be recovered from the original source.
|
||||
The evaluator parser and formatter therefore share one lexical definition without making Tree-sitter an upstream dependency.
|
||||
|
||||
Consumers should otherwise use the component matching their environment:
|
||||
|
||||
- Rust execution and embedding: `decodal`
|
||||
- Browser execution: `decodal-wasm`
|
||||
- Web formatting and editor syntax: canonical formatter / CodeMirror / Lezer
|
||||
- Semantic editor analysis: `decodal-language-service`
|
||||
- Language Server Protocol integration: `decodal-lsp`
|
||||
- Rust formatting: `decodal-language-tools`
|
||||
- General editor syntax: Tree-sitter
|
||||
|
||||
Tree-sitter and Lezer remain downstream editor grammars and are not dependencies of the runtime formatter.
|
||||
@@ -1,143 +0,0 @@
|
||||
# Composition and Materialization
|
||||
|
||||
`&`、`//`、`as`、`default`、materialize は、runtime value の variant に基づいて処理する。
|
||||
|
||||
## `&`
|
||||
|
||||
`&` は制約を保った合成である。
|
||||
|
||||
```text
|
||||
compose_and(a: RuntimeValue, b: RuntimeValue) -> RuntimeValue | Diagnostic
|
||||
```
|
||||
|
||||
基本規則:
|
||||
|
||||
```text
|
||||
Abstract(a) & Abstract(b)
|
||||
-> Abstract {
|
||||
constraints: a.constraints + b.constraints,
|
||||
default: merge_default(a.default, b.default)
|
||||
}
|
||||
|
||||
Abstract(a) & Concrete(v)
|
||||
-> if satisfies(v, a.constraints) then Concrete(v)
|
||||
else constraint diagnostic
|
||||
|
||||
Concrete(v) & Abstract(a)
|
||||
-> if satisfies(v, a.constraints) then Concrete(v)
|
||||
else constraint diagnostic
|
||||
|
||||
Concrete(Object(a)) & Concrete(Object(b))
|
||||
-> Concrete(Object(fieldwise_and(a, b)))
|
||||
|
||||
Concrete(a) & Concrete(b)
|
||||
-> if a == b then Concrete(a)
|
||||
else conflict diagnostic
|
||||
```
|
||||
|
||||
`Abstract & Concrete` が成功した場合、default は消える。
|
||||
明示値があるなら fallback は不要だからである。
|
||||
|
||||
## object の合成
|
||||
|
||||
object は concrete structure だが、field の値は thunk 経由で concrete / abstract のどちらにもなりうる。
|
||||
object 同士の `&` は field ごとに再帰合成する。
|
||||
|
||||
```dcdl
|
||||
MyConfig = {
|
||||
host = String;
|
||||
port = Int default 8080;
|
||||
};
|
||||
|
||||
Config = MyConfig & {
|
||||
host = "localhost";
|
||||
};
|
||||
```
|
||||
|
||||
`host` は `Abstract(String) & Concrete("localhost")` として検証され、成功すれば `Concrete("localhost")` になる。
|
||||
`port` は右辺に明示値がないため、`Abstract(Int, default 8080)` のまま残る。
|
||||
|
||||
## default の合成
|
||||
|
||||
`&` で片方だけが default を持つ場合、その default を保持する。
|
||||
同じ thunk 由来の default 同士は同一 default として保持する。
|
||||
異なる default 同士は conflict とする。
|
||||
|
||||
```text
|
||||
merge_default(None, None) -> None
|
||||
merge_default(Some(a), None) -> Some(a)
|
||||
merge_default(None, Some(b)) -> Some(b)
|
||||
merge_default(Some(a), Some(b)) -> if same(a, b) then Some(a) else conflict
|
||||
```
|
||||
|
||||
`//` では右辺 default が左辺 default を置き換える。
|
||||
|
||||
## `//`
|
||||
|
||||
`//` は右辺優先の deep patch である。
|
||||
|
||||
```text
|
||||
patch(a: RuntimeValue, b: RuntimeValue) -> RuntimeValue
|
||||
```
|
||||
|
||||
基本規則:
|
||||
|
||||
- object / object は field ごとに再帰 patch する。
|
||||
- object / object 以外は右辺で置き換える。
|
||||
- 左辺にしかない field は保持する。
|
||||
- 右辺にしかない field は追加する。
|
||||
- 配列、scalar、function は右辺置換とする。
|
||||
|
||||
`//` は制約を保持するための演算子ではない。
|
||||
対称な制約合成には `&` を使い、左辺が右辺より狭いことを確認しながら合成する場合は `as` を使う。
|
||||
|
||||
## `as`
|
||||
|
||||
`as` は narrower と wider の向きを固定した範囲包含確認と合成である。
|
||||
|
||||
```text
|
||||
apply_as(narrower: RuntimeValue, wider: RuntimeValue)
|
||||
-> RuntimeValue | Diagnostic
|
||||
```
|
||||
|
||||
abstract / abstract では、左辺 constraints が右辺 constraints を包含することを確認し、左辺を結果にする。
|
||||
concrete / abstract では、concrete value が右辺 constraints を満たすことを確認する。
|
||||
|
||||
object / object では右辺を field domain とする。左辺にしかない field は診断し、両側にある field は再帰的に `apply_as` し、右辺にしかない field は thunk を force せずそのまま結果へ残す。
|
||||
この扱いは default の有無に依存しない。default は包含判定の根拠でも `as` の補完値でもなく、後の materialize だけが選択する。
|
||||
|
||||
`ArrayItems(wider)` は concrete array の全要素を、`MapValues(wider)` は concrete object の全 field value を同じ関数で絞り込む。
|
||||
|
||||
## materialize
|
||||
|
||||
materialize は runtime value を出力可能な `Data` に変換する。
|
||||
|
||||
```text
|
||||
materialize(RuntimeValue) -> Data | Diagnostic
|
||||
```
|
||||
|
||||
処理規則:
|
||||
|
||||
```text
|
||||
Concrete(String/Int/Float/Bool) -> Data
|
||||
Concrete(Array(items)) -> each item を force して materialize
|
||||
Concrete(Object(fields)) -> each field を force して materialize
|
||||
Concrete(Function) -> materialize 不能
|
||||
|
||||
Abstract { constraints, default: Some(d) }
|
||||
-> force(d)
|
||||
-> result が constraints を満たすか検証
|
||||
-> materialize(result)
|
||||
|
||||
Abstract { constraints, default: None }
|
||||
-> 未解決 abstract value として diagnostic
|
||||
```
|
||||
|
||||
materialize は default を採用する唯一の段階である。
|
||||
通常評価中に明示値が得られた場合、default は採用されない。
|
||||
|
||||
## Diagnostic context
|
||||
|
||||
Composition and materialization keep source spans for object fields, constraints, defaults, and thunks where possible.
|
||||
When a conflict occurs, the diagnostic should identify the operation span and related participant spans, such as the left field, right field, constraint, or default value.
|
||||
For object materialization errors, diagnostics also include the field path being processed when known.
|
||||
@@ -1,79 +0,0 @@
|
||||
# Diagnostics and Fallback
|
||||
|
||||
エラーは runtime value ではなく diagnostic として扱う。
|
||||
処理系はエラー内容に基づく汎用的な実行時分岐を提供しない。
|
||||
|
||||
## Diagnostic
|
||||
|
||||
```text
|
||||
Diagnostic {
|
||||
kind: DiagnosticKind
|
||||
span: Span
|
||||
message: String
|
||||
labels: Vec<DiagnosticLabel>
|
||||
notes: Vec<String>
|
||||
}
|
||||
|
||||
DiagnosticLabel {
|
||||
span: Span
|
||||
message: String
|
||||
}
|
||||
```
|
||||
|
||||
`span` は primary location を示す。
|
||||
表示時には `Span.source` を source id のまま出すのではなく、可能な限り file path や virtual file name に解決する。
|
||||
`labels` は同じ error に関係する追加 location を示す。
|
||||
`notes` は source location を持たない semantic context を示す。
|
||||
合成や materialize の失敗では、衝突した constraint、value、default、または処理中 field path を label に含める。
|
||||
|
||||
代表的な diagnostic kind:
|
||||
|
||||
- syntax error
|
||||
- unresolved identifier
|
||||
- type mismatch
|
||||
- constraint violation
|
||||
- composition conflict
|
||||
- default conflict
|
||||
- cycle dependency
|
||||
- import failure
|
||||
- match failure
|
||||
- materialization failure
|
||||
|
||||
Structured imports use semantic provenance rather than synthetic source spans.
|
||||
Constraint failures report the imported value's stable key and logical field or array path alongside the source span of the Decodal constraint that rejected it.
|
||||
|
||||
## エラーは値ではない
|
||||
|
||||
評価失敗は `RuntimeValue` ではなく `Diagnostic` を返す。
|
||||
そのため、通常の式はエラー内容に基づいて分岐できない。
|
||||
|
||||
```text
|
||||
Result<RuntimeValue, Diagnostic>
|
||||
```
|
||||
|
||||
これにより、制約違反、未定義識別子、循環依存、import 失敗などが通常値として流れることを避ける。
|
||||
|
||||
## 合成と materialize の diagnostic
|
||||
|
||||
合成や materialize の失敗は、以下を示す。
|
||||
|
||||
1. どの段階で失敗したか: composition、patch、materialization
|
||||
2. どの field path を処理中だったか
|
||||
3. どの constraint、value、default が衝突したか
|
||||
4. なぜ合成または materialize できないか
|
||||
|
||||
例えば default が constraint を満たさない場合は、constraint の位置と default value の位置の両方を label として持つ。
|
||||
object field の合成で concrete value が衝突する場合は、左辺 field と右辺 field の位置を label として持つ。
|
||||
|
||||
## `try / catch` は core に入れない
|
||||
|
||||
汎用 `try / catch` は core に入れない。
|
||||
エラーを制御フローとして扱うと、どの失敗を捕捉できるか、捕捉後の thunk state をどう扱うか、制約違反を握りつぶしてよいか、といった仕様が重くなる。
|
||||
|
||||
fallback は有限で明示的な仕組みに限定する。
|
||||
|
||||
- `default`: 未指定値の fallback。
|
||||
- `match`: 有限 pattern に基づく分岐。
|
||||
|
||||
Decodal は `unknown` / `any` を持たないため、field 不在や未解決 identifier を fallback 可能な通常値として扱わない。
|
||||
それらは diagnostic として報告する。
|
||||
@@ -1,229 +0,0 @@
|
||||
# Embedding API
|
||||
|
||||
Decodal core can be embedded without giving the core crate access to a filesystem.
|
||||
The host supplies imports through `ImportLoader` and may also provide global bindings through the host prelude API.
|
||||
|
||||
## Host prelude
|
||||
|
||||
`Engine` owns a prelude environment.
|
||||
Bindings in this environment are visible from every module loaded by the engine.
|
||||
|
||||
```text
|
||||
prelude env
|
||||
↓
|
||||
module root env
|
||||
↓
|
||||
let / function env
|
||||
```
|
||||
|
||||
Module top-level bindings shadow prelude bindings.
|
||||
Primitive type names such as `String`, `Int`, `Float`, and `Bool` are handled before environment lookup, so they are reserved and cannot be shadowed by host bindings.
|
||||
|
||||
## Global bindings
|
||||
|
||||
The host can bind values before adding or evaluating user sources.
|
||||
|
||||
```rust
|
||||
use decodal::{EmptyLoader, Engine, HostValue};
|
||||
|
||||
let mut engine = Engine::new(EmptyLoader);
|
||||
|
||||
engine.bind_global(
|
||||
"Service",
|
||||
HostValue::object([
|
||||
("name", HostValue::string_type()),
|
||||
("port", HostValue::int_type().gt(443).default_int(8443)?),
|
||||
("enabled", HostValue::bool_type().default_bool(true)?),
|
||||
]),
|
||||
)?;
|
||||
```
|
||||
|
||||
A user source can then refer to `Service` without importing it.
|
||||
|
||||
```dcdl
|
||||
{
|
||||
name = "api";
|
||||
port = 9443;
|
||||
} as Service
|
||||
```
|
||||
|
||||
## HostValue
|
||||
|
||||
`HostValue` is the public builder-facing value representation for embedding.
|
||||
It keeps host code from constructing internal `ThunkId` or `ObjectValue` values directly.
|
||||
|
||||
```text
|
||||
HostValue =
|
||||
String
|
||||
Int
|
||||
Float
|
||||
Bool
|
||||
Array(Vec<HostValue>)
|
||||
ArrayConstraint { item, constraints, default }
|
||||
MapConstraint { value, constraints, default }
|
||||
Object(Vec<HostField>)
|
||||
Abstract { constraints, default }
|
||||
```
|
||||
|
||||
When a host value is bound, the engine internalizes it into `RuntimeValue` and allocates value thunks for object fields, array items, and defaults.
|
||||
|
||||
`HostValue::array_of(item)` builds an array constraint with a required element schema.
|
||||
There is no host API for an unconstrained abstract array.
|
||||
|
||||
`HostValue::map_of(value)` builds a map constraint whose arbitrary object field values must satisfy `value`.
|
||||
`BTreeMap<String, T>` and, with `std`, `HashMap<String, T>` implement `DecodalSchema`, `DecodalDecode`, and `IntoHostValue` using this representation.
|
||||
|
||||
## Abstract host objects
|
||||
|
||||
A host-provided schema object is represented as a concrete object structure whose fields may contain abstract values.
|
||||
|
||||
```rust
|
||||
HostValue::object([
|
||||
("name", HostValue::string_type()),
|
||||
("port", HostValue::int_type().gt(443).default_int(8443)?),
|
||||
])
|
||||
```
|
||||
|
||||
Conceptually this becomes:
|
||||
|
||||
```text
|
||||
Concrete(Object {
|
||||
name -> Thunk(Abstract { constraints: [String], default: none })
|
||||
port -> Thunk(Abstract { constraints: [Int, > 443], default: 8443 })
|
||||
})
|
||||
```
|
||||
|
||||
This matches the runtime model used for Decodal source-defined schema objects.
|
||||
|
||||
## Typed Rust integration
|
||||
|
||||
Hosts can enable the `derive` feature on `decodal` to keep a Rust struct, the Decodal schema, and the decoded result in sync.
|
||||
The derive implements two traits from the `decodal` crate:
|
||||
|
||||
- `DecodalSchema`: builds a `HostValue` schema that can be passed to `Engine::bind_global`.
|
||||
- `DecodalDecode`: decodes materialized `Data` back into the Rust type.
|
||||
|
||||
```rust
|
||||
use decodal::{Decodal, DecodalDecode, DecodalSchema, EmptyLoader, Engine};
|
||||
|
||||
#[derive(Decodal)]
|
||||
struct Service {
|
||||
name: String,
|
||||
|
||||
#[decodal(gt = 443, default = 8443)]
|
||||
port: i64,
|
||||
|
||||
#[decodal(rename = "feature.enable", default = true)]
|
||||
feature_enabled: bool,
|
||||
}
|
||||
|
||||
let mut engine = Engine::new(EmptyLoader);
|
||||
engine.bind_global("Service", Service::decodal_schema())?;
|
||||
|
||||
let value = engine.eval_module(module)?;
|
||||
let data = engine.materialize(&value)?;
|
||||
let service = Service::decodal_decode(&data)?;
|
||||
```
|
||||
|
||||
Supported field attributes are intentionally small:
|
||||
|
||||
- `rename = "path.to.field"`
|
||||
- `default`
|
||||
- `default = value`
|
||||
- numeric constraints: `gt`, `gte`, `lt`, `lte`
|
||||
|
||||
The derive does not add host callbacks or reflection.
|
||||
It only generates schema construction and typed decoding code.
|
||||
|
||||
## ImportLoader and prelude together
|
||||
|
||||
`ImportLoader` and host prelude bindings are independent mechanisms.
|
||||
|
||||
- Use `ImportLoader` when user sources should explicitly import host-provided sources or values.
|
||||
- Use prelude bindings when host-provided schemas or constants should be globally available.
|
||||
|
||||
Both mechanisms share the same runtime evaluator, thunk model, and materialization rules.
|
||||
|
||||
## Shared host environment
|
||||
|
||||
An embedded application can implement `HostEnvironment` to keep loader creation and global binding setup in one place.
|
||||
Both production evaluation and semantic editor tooling create their engines from this environment, preventing the editor from drifting onto a separate validation path.
|
||||
|
||||
```rust
|
||||
use decodal::{Engine, HostEnvironment};
|
||||
|
||||
struct AppEnvironment;
|
||||
|
||||
impl HostEnvironment for AppEnvironment {
|
||||
type Loader = ContentLoader;
|
||||
|
||||
fn create_loader(&self) -> Self::Loader {
|
||||
ContentLoader::new()
|
||||
}
|
||||
|
||||
fn configure_engine(
|
||||
&self,
|
||||
engine: &mut Engine<Self::Loader>,
|
||||
) -> decodal::Result<()> {
|
||||
engine.bind_global("Site", site_schema())?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
let environment = AppEnvironment;
|
||||
let mut engine = environment.create_engine()?;
|
||||
```
|
||||
|
||||
The semantic service accepts the same environment by value:
|
||||
|
||||
```rust
|
||||
use decodal_language_service::LanguageService;
|
||||
|
||||
let service = LanguageService::new(&environment);
|
||||
let analysis = service.analyze("site.dcdl", "site.dcdl", source);
|
||||
```
|
||||
|
||||
Each analysis uses a fresh engine and runs the normal parse, evaluate, and materialize pipeline.
|
||||
An environment may create loaders backed by shared filesystem, database, or editor-overlay state when repeated analysis needs a current workspace snapshot.
|
||||
|
||||
The LSP adapter constructs that environment after receiving the client's initialization parameters:
|
||||
|
||||
```rust
|
||||
use decodal_lsp::{LspEnvironment, run_stdio};
|
||||
|
||||
impl LspEnvironment for AppEnvironment {}
|
||||
|
||||
run_stdio(|initialize| {
|
||||
let _ = initialize;
|
||||
Ok(AppEnvironment)
|
||||
})?;
|
||||
```
|
||||
|
||||
`LspEnvironment` adds document lifecycle hooks on top of `HostEnvironment`.
|
||||
A `run_stdio` environment factory always receives the client's `InitializeParams`; the host decides whether to use its workspace folders, initialization options, and capabilities or ignore them.
|
||||
A host that keeps unsaved buffers in shared state can update them from `open_document`, `change_document`, and `close_document`; every subsequent diagnostic pass creates the normal import loader from that updated environment.
|
||||
Synchronized non-Decodal documents are passed through these hooks but are not evaluated as Decodal roots, so a loader can parse an unsaved Markdown file into `HostValue` and immediately revalidate the open Decodal documents that import it.
|
||||
|
||||
## Structured imports
|
||||
|
||||
`ImportLoader::load` returns either `LoadedImport::Source` or `LoadedImport::Value`.
|
||||
The value variant carries a `HostValue`, allowing a host to parse non-Decodal resources such as Markdown into an application-specific structure.
|
||||
|
||||
```text
|
||||
import "./post.md"
|
||||
-> host parses content
|
||||
-> LoadedImport::Value(
|
||||
{ frontmatter: {...}, body: "..." }
|
||||
)
|
||||
-> Engine internalizes HostValue
|
||||
-> normal composition and materialization
|
||||
```
|
||||
|
||||
The core does not select content types or bundle Markdown/frontmatter parsers.
|
||||
The loader owns path resolution, media or extension dispatch, parsing rules, and parse diagnostics.
|
||||
The stable loader key is also used to cache structured imports.
|
||||
|
||||
When a structured value fails a Decodal constraint, the diagnostic keeps the Decodal constraint span and identifies the host value by its stable import key and logical value path, such as `content/post.md` and `frontmatter.draft`.
|
||||
`HostValue` does not need source spans: syntax diagnostics for the external format remain the loader's responsibility, while cross-value validation reports semantic provenance.
|
||||
|
||||
`load` is the single import hook: loaders dispatch by extension, media type, or another host-defined rule and return the appropriate variant directly.
|
||||
@@ -1,163 +0,0 @@
|
||||
# Execution Pipeline
|
||||
|
||||
処理系は、source を AST に変換し、必要な値だけを AST interpreter で評価する。
|
||||
|
||||
```text
|
||||
source
|
||||
↓
|
||||
lexer / parser
|
||||
↓
|
||||
desugar
|
||||
↓
|
||||
register root module
|
||||
↓
|
||||
demand-driven evaluation
|
||||
├─ force thunk
|
||||
├─ load imported module on demand
|
||||
├─ evaluate expression
|
||||
├─ compose `&`
|
||||
├─ patch `//`
|
||||
└─ validate `as`
|
||||
↓
|
||||
materialize
|
||||
↓
|
||||
data / diagnostics
|
||||
```
|
||||
|
||||
Production applications and semantic language services can construct this pipeline through the same host-defined `HostEnvironment`.
|
||||
The environment creates the `ImportLoader` and installs host globals before the root module is registered.
|
||||
|
||||
## lexer / parser
|
||||
|
||||
lexer / parser は source を AST に変換する。
|
||||
構文エラーはこの段階で diagnostic として報告する。
|
||||
|
||||
AST は arena に格納し、式や pattern は `ExprId`、`PatternId` のような ID で参照する。
|
||||
|
||||
## desugar
|
||||
|
||||
desugar は、意味論を単純にするための表層構文変換を行う。
|
||||
|
||||
例として、dot-path field は nested object に変換できる。
|
||||
|
||||
```dcdl
|
||||
{
|
||||
feature_hoge.enable = false;
|
||||
}
|
||||
```
|
||||
|
||||
```dcdl
|
||||
{
|
||||
feature_hoge = {
|
||||
enable = false;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
この変換により、評価器は object field の再帰構造だけを扱えばよい。
|
||||
|
||||
## module registry
|
||||
|
||||
module registry は、読み込んだ module を loader が返す安定 key で管理する。
|
||||
CLI では canonical path を key とする。
|
||||
組み込み利用では、resource name や static source table の key を使える。
|
||||
|
||||
```text
|
||||
ModuleRegistry:
|
||||
ModuleKey -> ModuleId
|
||||
```
|
||||
|
||||
処理系は、まず root module を parse / desugar して registry に登録する。
|
||||
import 先 module は、この段階で全て読み込む必要はない。
|
||||
|
||||
import expression が評価されたとき、処理系は `ImportLoader::load` に現在の module key と import specifier を渡す。
|
||||
loader は module key、表示名、および DCDL source text または構造化済み `HostValue` を返す。
|
||||
DCDL source の場合、module registry は key が未登録なら対象 module を parse / desugar して登録する。
|
||||
登録された source module は module root thunk を持つ。
|
||||
構造化値の場合、host value を runtime value に internalize した root thunk を key でキャッシュする。
|
||||
同じ key が複数回 import された場合は、同じ source module または structured root thunk を使う。
|
||||
|
||||
つまり source import は module を即時評価しない。
|
||||
module を読み込み、module root を thunk として登録するだけにする。
|
||||
structured import も root value を thunk として保持し、object field や array item の既存 thunk model を利用する。
|
||||
|
||||
AST の `ExprId` は module-local である。
|
||||
そのため runtime が保持する式参照は `ExprRef { module, expr }` として module-qualified にする。
|
||||
|
||||
## demand-driven evaluation
|
||||
|
||||
評価器は、必要になった thunk だけを force する。
|
||||
未参照の field、let binding、import 先の field は評価しない。
|
||||
|
||||
この方式により、module 間に循環 import があっても、実際に force された thunk の依存が循環しない限り評価できる。
|
||||
|
||||
## composition
|
||||
|
||||
composition は、module 全体に後からかける global pass ではない。
|
||||
`&` や `//` の式を評価するときに、demand-driven evaluation の中で呼ばれる演算である。
|
||||
|
||||
```text
|
||||
eval(A & B):
|
||||
a = eval(A)
|
||||
b = eval(B)
|
||||
compose_and(a, b)
|
||||
|
||||
eval(A // B):
|
||||
a = eval(A)
|
||||
b = eval(B)
|
||||
patch(a, b)
|
||||
|
||||
eval(A as S):
|
||||
narrower = eval(A)
|
||||
wider = eval(S)
|
||||
apply_as(narrower, wider)
|
||||
```
|
||||
|
||||
`&` は制約を保った対称な合成を行い、`//` は右辺優先の deep patch を行う。
|
||||
`as` は左辺が右辺より狭いことを再帰的に確認する。左辺で絞られた部分は左辺を使い、右辺だけの部分は abstract のまま保持する。
|
||||
default は `as` では選択せず、materialize まで遅延する。
|
||||
詳細は [Composition and Materialization](./composition-and-materialization.md) に置く。
|
||||
|
||||
## resolver / binder
|
||||
|
||||
resolver / binder は初期実装では必須ではない。
|
||||
評価時に environment lookup を行えば、識別子参照は実装できる。
|
||||
|
||||
ただし、将来的には optional phase として追加できる余地を残す。
|
||||
|
||||
```text
|
||||
source
|
||||
↓
|
||||
lexer / parser
|
||||
↓
|
||||
desugar
|
||||
↓
|
||||
resolver / binder
|
||||
↓
|
||||
register root module
|
||||
↓
|
||||
demand-driven evaluation
|
||||
```
|
||||
|
||||
resolver / binder を追加すると、以下を早期に診断しやすくなる。
|
||||
|
||||
- 未定義識別子
|
||||
- shadowing の扱い
|
||||
- reserved word の扱い
|
||||
- symbol interning
|
||||
- import path の一部静的解決
|
||||
- span 付き diagnostic の精度向上
|
||||
|
||||
ただし、Decodal の制約検証は独立した type checking pass ではなく、`&` の合成時、`as` の適用時、materialize 時に行う。
|
||||
|
||||
## materialize
|
||||
|
||||
通常の評価結果は runtime value であり、抽象値や default を含みうる。
|
||||
外部へ出力するときだけ materialize を行い、出力可能な data に変換する。
|
||||
|
||||
materialize は以下を行う。
|
||||
|
||||
- 必要な thunk を force する。
|
||||
- abstract value の default を必要に応じて force する。
|
||||
- concrete value が constraint を満たすか検証する。
|
||||
- 未解決の abstract value、function value などを diagnostic にする。
|
||||
@@ -1,68 +0,0 @@
|
||||
# Features
|
||||
|
||||
Decodal は embedded use と小さい runtime を優先する。
|
||||
言語機能を追加するときは、値の合成・検証・materialization に直接必要なものを core に残し、重い依存や高度な推論は optional feature または外部 tooling に分ける。
|
||||
|
||||
## Core feature boundary
|
||||
|
||||
Core に入れる機能は、基本的に deterministic な value transformation に限る。
|
||||
|
||||
- arithmetic / logical / comparison operators
|
||||
- array concat
|
||||
- object / constraint composition
|
||||
- asymmetric range refinement and homogeneous map constraints
|
||||
- default materialization
|
||||
- pure function evaluation
|
||||
- host supplied import evaluation
|
||||
|
||||
Core に入れないものは以下である。
|
||||
|
||||
- filesystem / network / environment access
|
||||
- time / random
|
||||
- mutation
|
||||
- reflection or existence probing
|
||||
- arbitrary host function calls
|
||||
- symbolic constraint solving beyond simple normalization
|
||||
|
||||
未解決 identifier や missing field は `unknown` として流れず、diagnostic になる。
|
||||
この方針により、存在チェックや optional chaining のような dynamic object inspection は core language の対象外とする。
|
||||
|
||||
## Constraint reasoning
|
||||
|
||||
Constraint normalization は軽量な範囲に留める。
|
||||
primitive type conflict や明らかな numeric bound conflict は合成時に検出してよい。
|
||||
一方で、symbolic arithmetic、boolean algebra、regex intersection、array length dependent typing のような重い推論は行わない。
|
||||
|
||||
評価済みの concrete value に対する検証は runtime / materialization で行う。
|
||||
静的に完全な型検査フェーズを増やすのではなく、parse、evaluate、compose、materialize の各段階で自然に分かる error を diagnostic として返す。
|
||||
|
||||
## Core defaults
|
||||
|
||||
`decodal` defaults to `std` only.
|
||||
|
||||
```toml
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = []
|
||||
regex = ["std", "dep:regex"]
|
||||
```
|
||||
|
||||
Building `decodal` with `--no-default-features` keeps the core in `no_std + alloc` mode and avoids optional dependencies.
|
||||
|
||||
## Regex
|
||||
|
||||
Regex constraints are implemented behind the `regex` feature.
|
||||
When the feature is disabled, regex constraints parse and compose, but validating a concrete value against them returns an unsupported feature diagnostic.
|
||||
|
||||
```sh
|
||||
cargo run -q -p decodal-cli --features regex -- examples/regex/main.dcdl
|
||||
```
|
||||
|
||||
Regex constraints are accumulated during `&` composition.
|
||||
The implementation does not try to prove whether the intersection of two regex constraints is empty.
|
||||
Concrete strings must match every regex constraint attached to the abstract value.
|
||||
|
||||
## CLI features
|
||||
|
||||
`decodal-cli` exposes a matching `regex` feature that enables `decodal/regex`.
|
||||
The feature is not enabled by default so the default CLI binary remains small.
|
||||
@@ -1,19 +0,0 @@
|
||||
# 処理系設計
|
||||
|
||||
この章では、言語仕様を実装するための処理系モデルを定義する。
|
||||
言語仕様そのものは [Language Specification](../language/index.md) に置き、この章では AST interpreter、遅延評価、thunk、runtime value、materialize の実装方針を扱う。
|
||||
|
||||
## 方針
|
||||
|
||||
初期処理系は AST interpreter として実装する。
|
||||
bytecode VM や JIT ではなく、AST を demand-driven に評価することで、遅延評価、循環参照、`default`、`&`、`//`、`as` の意味論を小さく実装する。
|
||||
|
||||
## 構成
|
||||
|
||||
1. [Execution Pipeline](./execution-pipeline.md)
|
||||
2. [Runtime Model](./runtime-model.md)
|
||||
3. [Thunk and Lazy Evaluation](./thunk-and-lazy-evaluation.md)
|
||||
4. [Composition and Materialization](./composition-and-materialization.md)
|
||||
5. [Diagnostics and Fallback](./diagnostics-and-fallback.md)
|
||||
6. [Embedding API](./embedding-api.md)
|
||||
7. [Features](./features.md)
|
||||
@@ -1,171 +0,0 @@
|
||||
# Runtime Model
|
||||
|
||||
処理系の評価結果は、具体値と抽象値を区別した runtime value として扱う。
|
||||
`value`、`constraints`、`default` を横並びに持つ構造にはしない。
|
||||
|
||||
## RuntimeValue
|
||||
|
||||
```text
|
||||
RuntimeValue =
|
||||
Concrete(ConcreteValue)
|
||||
Abstract(AbstractValue)
|
||||
```
|
||||
|
||||
`Concrete` は明示的な値である。
|
||||
`Abstract` は、まだ具体値に確定していない制約付きの値である。
|
||||
|
||||
Decodal は `unknown`、`any`、`null` のような「存在するが意味が未確定な値」を runtime value として持たない。
|
||||
識別子や field が解決できない場合は、その場で diagnostic になる。
|
||||
未解決値を後続の演算へ流して推論することはしない。
|
||||
|
||||
## ConcreteValue
|
||||
|
||||
```text
|
||||
ConcreteValue =
|
||||
String(String)
|
||||
Int(i64)
|
||||
Float(f64)
|
||||
Bool(bool)
|
||||
Array(Vec<ThunkId>)
|
||||
Object(ObjectValue)
|
||||
Function(FunctionValue)
|
||||
```
|
||||
|
||||
object は concrete structure として扱う。
|
||||
ただし、各 field の中身は concrete value でも abstract value でもよい。
|
||||
|
||||
```text
|
||||
ObjectValue:
|
||||
fields: Map<Symbol, ObjectField>
|
||||
|
||||
ObjectField:
|
||||
value: ThunkId
|
||||
span: Span
|
||||
```
|
||||
|
||||
例えば以下の schema object は、object 自体は concrete だが、field の値は abstract value になる。
|
||||
|
||||
```dcdl
|
||||
MyConfig = {
|
||||
host = String;
|
||||
port = Int default 8080;
|
||||
};
|
||||
```
|
||||
|
||||
概念的には以下である。
|
||||
|
||||
```text
|
||||
Concrete(Object {
|
||||
host -> Thunk(Abstract { constraints: [String], default: none })
|
||||
port -> Thunk(Abstract { constraints: [Int], default: 8080 })
|
||||
})
|
||||
```
|
||||
|
||||
## AbstractValue
|
||||
|
||||
```text
|
||||
AbstractValue {
|
||||
constraints: Vec<ConstraintEntry>
|
||||
default: Option<ThunkId>
|
||||
}
|
||||
|
||||
ConstraintEntry {
|
||||
constraint: Constraint
|
||||
span: Span
|
||||
}
|
||||
```
|
||||
|
||||
`default` は `AbstractValue` にだけ存在する。
|
||||
明示的な concrete value がある場合、default は保持しない。
|
||||
|
||||
```dcdl
|
||||
port = Int default 8080;
|
||||
```
|
||||
|
||||
これは以下の runtime value になる。
|
||||
|
||||
```text
|
||||
Abstract {
|
||||
constraints: [Type(Int)]
|
||||
default: Some(Thunk(8080))
|
||||
}
|
||||
```
|
||||
|
||||
```dcdl
|
||||
port = 8000;
|
||||
```
|
||||
|
||||
これは以下である。
|
||||
|
||||
```text
|
||||
Concrete(Int(8000))
|
||||
```
|
||||
|
||||
## Runtime scope
|
||||
|
||||
Decodal runtime は application runtime ではなく、pure value evaluator である。
|
||||
同じ source、同じ import results、同じ host globals が与えられた場合、評価結果は決定的である。
|
||||
|
||||
runtime が扱う責務は以下に限る。
|
||||
|
||||
- expression を評価する。
|
||||
- thunk を必要に応じて force する。
|
||||
- concrete / abstract value を合成する。
|
||||
- materialize 時に constraint を検証する。
|
||||
|
||||
runtime は filesystem、network、environment variable、time、random、mutation を扱わない。
|
||||
core における import は host supplied source または structured value を受け取る境界であり、filesystem access ではない。
|
||||
|
||||
## Constraint
|
||||
|
||||
constraint は concrete value とは別の型として扱う。
|
||||
|
||||
```text
|
||||
Constraint =
|
||||
Type(PrimitiveType)
|
||||
ArrayItems(ThunkId)
|
||||
MapValues(ThunkId)
|
||||
Compare(Op, Literal)
|
||||
Regex(Pattern)
|
||||
BuiltinPredicate(Symbol)
|
||||
ObjectConstraint(...)
|
||||
```
|
||||
|
||||
`ArrayItems` は配列そのものの型と、すべての要素へ合成する schema thunk を表す。
|
||||
配列用の primitive type は持たず、抽象配列には必ず要素制約が必要である。
|
||||
|
||||
`MapValues` は object の key 集合を制限せず、すべての field value へ適用する schema thunk を表す。
|
||||
連想配列は materialize 後も `Data::Object` になり、別の data variant は持たない。
|
||||
|
||||
初期実装では、object の形は主に `Concrete(Object)` の field に `Abstract` を置くことで表現する。
|
||||
object 全体にかかる constraint は必要になった時点で追加する。
|
||||
|
||||
## Data
|
||||
|
||||
materialize 後の出力可能な値は runtime value とは別型にする。
|
||||
|
||||
```text
|
||||
Data =
|
||||
String(String)
|
||||
Int(i64)
|
||||
Float(f64)
|
||||
Bool(bool)
|
||||
Array(Vec<Data>)
|
||||
Object(Map<Symbol, Data>)
|
||||
```
|
||||
|
||||
`Function`、未解決の `Abstract`、未評価の thunk は `Data` にはならない。
|
||||
|
||||
## 命名
|
||||
|
||||
実装内部では `RuntimeValue` を短く `Value` と呼んでもよい。
|
||||
ただし、materialize 後の出力値とは区別する。
|
||||
|
||||
推奨する区別:
|
||||
|
||||
```text
|
||||
RuntimeValue / Value 言語内部の評価結果。Abstract を含む。
|
||||
ConcreteValue 明示的な具体値。
|
||||
AbstractValue constraint と default を持つ抽象値。
|
||||
Data 外部へ出力可能な最終データ。
|
||||
```
|
||||
@@ -1,88 +0,0 @@
|
||||
# Thunk and Lazy Evaluation
|
||||
|
||||
thunk は、まだ評価していない式をあとで評価できるように包んだ遅延計算である。
|
||||
この処理系では、循環検出と memoize の単位として thunk を使う。
|
||||
|
||||
## Thunk
|
||||
|
||||
```text
|
||||
Thunk {
|
||||
expr: ExprRef
|
||||
env: EnvId
|
||||
state: ThunkState
|
||||
}
|
||||
|
||||
ExprRef {
|
||||
module: ModuleId
|
||||
expr: ExprId
|
||||
}
|
||||
|
||||
ThunkState =
|
||||
Unevaluated
|
||||
Evaluating
|
||||
Evaluated(RuntimeValue)
|
||||
Error(Diagnostic)
|
||||
```
|
||||
|
||||
`expr` は評価対象の AST node を module-qualified に指す。
|
||||
`ExprId` は module-local な ID なので、runtime では `ModuleId` と組み合わせた `ExprRef` を保持する。
|
||||
`env` は、その式を評価するときに使う lexical environment を指す。
|
||||
|
||||
式だけではなく environment も保持するのは、遅延評価された式が定義時の名前解決文脈を必要とするためである。
|
||||
|
||||
## force
|
||||
|
||||
thunk を評価する操作を force と呼ぶ。
|
||||
|
||||
```text
|
||||
force(thunk):
|
||||
Unevaluated -> Evaluating -> Evaluated(value)
|
||||
Evaluated(value) -> value
|
||||
Evaluating -> cycle diagnostic
|
||||
Error(diagnostic) -> diagnostic
|
||||
```
|
||||
|
||||
一度 `Evaluated` になった thunk は memoize される。
|
||||
同じ thunk を複数回 force しても、式は一度だけ評価される。
|
||||
|
||||
## 循環検出
|
||||
|
||||
評価中の thunk を再度 force しようとした場合は循環依存である。
|
||||
|
||||
```dcdl
|
||||
{
|
||||
a = b;
|
||||
b = a;
|
||||
}
|
||||
```
|
||||
|
||||
`a` を force すると、`a -> b -> a` と戻る。
|
||||
このとき `a` は `Evaluating` なので cycle diagnostic を返す。
|
||||
|
||||
## 遅延評価の単位
|
||||
|
||||
thunk は主に以下に使う。
|
||||
|
||||
- module root
|
||||
- object field
|
||||
- let binding
|
||||
- function argument
|
||||
- default expression
|
||||
|
||||
object は field ごとに thunk を持つ。
|
||||
そのため、object の一部だけが必要な場合、他の field は評価されない。
|
||||
|
||||
## module import
|
||||
|
||||
import は module を登録するが、module 全体を即時評価しない。
|
||||
module root や field は thunk として保持され、参照されたときだけ force される。
|
||||
|
||||
これにより、module 間に循環 import があっても、force された thunk の依存が循環しなければ評価できる。
|
||||
|
||||
## function call
|
||||
|
||||
関数引数は thunk として関数の environment に束縛する。
|
||||
関数本体で引数が参照されたときだけ force する。
|
||||
|
||||
関数呼び出し結果そのものはグローバルには memoize しない。
|
||||
field に束縛された関数呼び出し結果は、その field thunk の評価結果として memoize される。
|
||||
@@ -1,242 +0,0 @@
|
||||
# Development
|
||||
|
||||
This document describes the development workflow for Decodal itself.
|
||||
|
||||
## Rust checks
|
||||
|
||||
Run the normal Rust checks from the repository root.
|
||||
|
||||
```sh
|
||||
cargo fmt --check
|
||||
cargo test
|
||||
cargo check -p decodal --no-default-features
|
||||
nix flake check
|
||||
```
|
||||
|
||||
Run the default stdio language server with:
|
||||
|
||||
```sh
|
||||
cargo run -q -p decodal-lsp
|
||||
```
|
||||
|
||||
The protocol integration tests use an in-memory LSP connection and can be run independently:
|
||||
|
||||
```sh
|
||||
cargo test -p decodal-lsp
|
||||
```
|
||||
|
||||
Regex support is optional and should be tested explicitly when touched.
|
||||
|
||||
```sh
|
||||
cargo test -p decodal --features regex
|
||||
cargo run -q -p decodal-cli --features regex -- examples/regex/main.dcdl
|
||||
```
|
||||
|
||||
## crates.io release
|
||||
|
||||
The crates.io release contains `decodal`, `decodal-derive`, `decodal-language-service`, `decodal-language-tools`, and `decodal-lsp`.
|
||||
`decodal-cli` and the Rust source crate `decodal-wasm` remain repository-only packages.
|
||||
The generated WebAssembly package under `packages/decodal-wasm/` is published to npm and JSR.
|
||||
The CodeMirror package bundles the generated formatter WebAssembly from `decodal-language-tools`.
|
||||
The project is dual licensed as `MIT OR Apache-2.0`.
|
||||
|
||||
The authoritative validation commands, dependency order, and publish commands are maintained in `RELEASING.md` at the repository root.
|
||||
|
||||
## Web site and playground
|
||||
|
||||
The Astro documentation site and browser playground are kept in:
|
||||
|
||||
```text
|
||||
site/decodal-site/
|
||||
```
|
||||
|
||||
The site imports Markdown files from `doc/manual/souce/` and renders them as mdBook-style pages.
|
||||
The playground loads `decodal-wasm` for evaluation and `decodal-codemirror` for editor features and source formatting.
|
||||
|
||||
Important files:
|
||||
|
||||
```text
|
||||
site/decodal-site/src/pages/docs/[...slug].astro
|
||||
site/decodal-site/src/pages/playground.astro
|
||||
site/decodal-site/src/scripts/playground.js
|
||||
site/decodal-site/src/scripts/playground-examples.js
|
||||
site/decodal-site/src/layouts/ManualLayout.astro
|
||||
site/decodal-site/src/lib/docs.js
|
||||
site/decodal-site/src/lib/highlight.js
|
||||
packages/decodal-codemirror/src/decodal.js
|
||||
packages/decodal-codemirror/src/decodal-parser.js
|
||||
packages/decodal-wasm/decodal_wasm.js
|
||||
packages/decodal-wasm/decodal_wasm_bg.wasm
|
||||
packages/decodal-codemirror/wasm/decodal_language_tools.js
|
||||
packages/decodal-codemirror/wasm/decodal_language_tools_bg.wasm
|
||||
crates/decodal-wasm/src/lib.rs
|
||||
crates/decodal-language-tools/src/lib.rs
|
||||
```
|
||||
|
||||
Build the WebAssembly packages before building the site:
|
||||
|
||||
```sh
|
||||
cd site/decodal-site
|
||||
npm install
|
||||
npm run build:wasm
|
||||
npm run build
|
||||
```
|
||||
|
||||
`npm run build:wasm` builds both generated WebAssembly packages.
|
||||
`npm run build:wasm:runtime` writes generated runtime files into `packages/decodal-wasm/`.
|
||||
`npm run build:wasm:formatter` writes generated formatter files into `packages/decodal-codemirror/wasm/`.
|
||||
`npm run build` builds only the static site from the current package files.
|
||||
Use `npm run build:all` to regenerate both WebAssembly packages and then build the static site in one command.
|
||||
|
||||
These generated files are committed so the site can be built without requiring every consumer to regenerate the wasm packages first.
|
||||
|
||||
Publish the generated WebAssembly package from its package directory:
|
||||
|
||||
```sh
|
||||
cd packages/decodal-wasm
|
||||
npm publish
|
||||
npx jsr publish
|
||||
```
|
||||
|
||||
Run dry-runs first when preparing a release:
|
||||
|
||||
```sh
|
||||
npm pack --dry-run
|
||||
npx jsr publish --dry-run
|
||||
```
|
||||
|
||||
The npm package name is `decodal-wasm`.
|
||||
The JSR package name is `@hare/decodal-wasm`.
|
||||
The npm package advertises `MIT OR Apache-2.0`; JSR metadata uses `MIT` because its publisher requires a single recognized license identifier. Both license files are included in the package.
|
||||
|
||||
The playground editor uses the `decodal-codemirror` package with the generated Lezer parser in `packages/decodal-codemirror/src/decodal-parser.js`.
|
||||
The canonical grammar is documented in `doc/manual/souce/language/grammar.md`; regenerate the Lezer parser when that grammar or `editors/lezer-decodal/decodal.grammar` changes.
|
||||
|
||||
Publish the CodeMirror package from its package directory:
|
||||
|
||||
```sh
|
||||
cd packages/decodal-codemirror
|
||||
npm install
|
||||
npm publish
|
||||
npx jsr publish
|
||||
```
|
||||
|
||||
Run dry-runs first when preparing a release:
|
||||
|
||||
```sh
|
||||
npm install
|
||||
npm pack --dry-run
|
||||
npx jsr publish --dry-run
|
||||
```
|
||||
|
||||
The npm package name is `decodal-codemirror`.
|
||||
The JSR package name is `@hare/decodal-codemirror`.
|
||||
As with `decodal-wasm`, JSR metadata uses `MIT` while both the MIT and Apache-2.0 license files remain included.
|
||||
|
||||
The documentation build still uses the lightweight JavaScript fallback highlighter so Astro can render Markdown without initializing WASM at build time.
|
||||
|
||||
To run the site locally:
|
||||
|
||||
```sh
|
||||
cd site/decodal-site
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Deploy the static site to Cloudflare Pages with Wrangler direct upload:
|
||||
|
||||
```sh
|
||||
cd site/decodal-site
|
||||
npm run deploy
|
||||
```
|
||||
|
||||
The deploy script runs `npm run build` and then uploads `dist/` to the Pages project named `decodal-site` on branch `master`.
|
||||
Cloudflare Pages treats this as production when the project production branch is `master`.
|
||||
Use `CLOUDFLARE_PROJECT_NAME` when deploying to a differently named Pages project.
|
||||
|
||||
```sh
|
||||
CLOUDFLARE_PROJECT_NAME=my-pages-project npm run deploy
|
||||
```
|
||||
|
||||
If the committed WASM package must be regenerated before deploy, use:
|
||||
|
||||
```sh
|
||||
npm run deploy:all
|
||||
```
|
||||
|
||||
## Tree-sitter grammar
|
||||
|
||||
The Tree-sitter grammar is kept in:
|
||||
|
||||
```text
|
||||
editors/tree-sitter-decodal/
|
||||
```
|
||||
|
||||
Important files:
|
||||
|
||||
```text
|
||||
editors/tree-sitter-decodal/grammar.js
|
||||
editors/tree-sitter-decodal/queries/highlights.scm
|
||||
editors/tree-sitter-decodal/queries/locals.scm
|
||||
editors/tree-sitter-decodal/corpus/basic.txt
|
||||
```
|
||||
|
||||
The grammar is intended to be portable across editors such as Zed, Neovim, Helix, and Emacs.
|
||||
Zed support should consume this grammar rather than relying on a TextMate grammar.
|
||||
|
||||
## Tree-sitter commands
|
||||
|
||||
From the grammar directory:
|
||||
|
||||
```sh
|
||||
cd editors/tree-sitter-decodal
|
||||
npm install
|
||||
npx tree-sitter generate
|
||||
npx tree-sitter test
|
||||
```
|
||||
|
||||
To inspect a parse tree:
|
||||
|
||||
```sh
|
||||
npx tree-sitter parse ../../examples/advanced/main.dcdl
|
||||
```
|
||||
|
||||
The generated parser files under `editors/tree-sitter-decodal/src/` are committed so editor integrations can consume the grammar without regenerating it first.
|
||||
`node_modules/` is ignored and must not be committed.
|
||||
|
||||
## Updating the grammar
|
||||
|
||||
When the Decodal syntax changes:
|
||||
|
||||
1. Update the canonical EBNF in `doc/manual/souce/language/grammar.md`.
|
||||
2. Update the Rust parser/lexer as needed.
|
||||
3. Update `editors/tree-sitter-decodal/grammar.js` and run `npx tree-sitter generate` / `npx tree-sitter test`.
|
||||
4. Update `editors/lezer-decodal/decodal.grammar` and regenerate the CodeMirror parser:
|
||||
|
||||
```sh
|
||||
cd site/decodal-site
|
||||
npx lezer-generator ../../editors/lezer-decodal/decodal.grammar -o ../../packages/decodal-codemirror/src/decodal-parser.js
|
||||
```
|
||||
|
||||
5. Add or update corpus/tests/examples.
|
||||
6. Run Rust and site checks from the repository root.
|
||||
|
||||
## Development shell
|
||||
|
||||
The Nix development shell includes Rust tooling, Node.js, Tree-sitter CLI tooling, and wasm-pack tooling.
|
||||
|
||||
```sh
|
||||
nix develop
|
||||
```
|
||||
|
||||
The shell provides:
|
||||
|
||||
- `cargo`
|
||||
- `rustc`
|
||||
- `rustfmt`
|
||||
- `clippy`
|
||||
- `node`
|
||||
- `npm`
|
||||
- `wasm-pack`
|
||||
- `lld`
|
||||
- `tree-sitter`
|
||||
- `nixfmt`
|
||||
@@ -1,49 +0,0 @@
|
||||
# Decodal Manual
|
||||
|
||||
このディレクトリには、Decodal のマニュアル文書を置く。
|
||||
Decodal は Deferred Constraint Data Language、略称 DCDL のプロジェクト名である。
|
||||
|
||||
## 目次
|
||||
|
||||
1. [Introduction](./introduction.md)
|
||||
2. [Components](./components.md)
|
||||
3. [Language Specification](./language/index.md)
|
||||
1. [Lexical Structure and Syntax](./language/syntax.md)
|
||||
2. [Value](./language/value/index.md)
|
||||
1. [String](./language/value/string.md)
|
||||
2. [Int](./language/value/int.md)
|
||||
3. [Float](./language/value/float.md)
|
||||
4. [Bool](./language/value/bool.md)
|
||||
3. [Expression](./language/expression/index.md)
|
||||
1. [Literal](./language/expression/literal.md)
|
||||
2. [Identifier](./language/expression/identifier.md)
|
||||
3. [Path Reference](./language/expression/path-reference.md)
|
||||
4. [Object](./language/expression/object.md)
|
||||
5. [Array](./language/expression/array.md)
|
||||
6. [Function](./language/expression/function.md)
|
||||
7. [Function Call](./language/expression/function-call.md)
|
||||
8. [Let](./language/expression/let.md)
|
||||
9. [Match](./language/expression/match.md)
|
||||
10. [Import](./language/expression/import.md)
|
||||
11. [Composition](./language/expression/composition.md)
|
||||
12. [Range Refinement](./language/expression/ascription.md)
|
||||
13. [Default](./language/expression/default.md)
|
||||
14. [String Interpolation](./language/expression/string-interpolation.md)
|
||||
4. [Constraints and Defaults](./language/constraints-and-defaults.md)
|
||||
5. [Composition Operators](./language/operators.md)
|
||||
6. [Functions](./language/functions.md)
|
||||
7. [Modules and Imports](./language/modules-and-imports.md)
|
||||
8. [Evaluation Semantics](./language/evaluation.md)
|
||||
9. [Materialization and Errors](./language/materialization-and-errors.md)
|
||||
10. [Naming Conventions](./language/naming.md)
|
||||
11. [Examples](./language/examples.md)
|
||||
4. [Implementation Design](./design/index.md)
|
||||
1. [Execution Pipeline](./design/execution-pipeline.md)
|
||||
2. [Runtime Model](./design/runtime-model.md)
|
||||
3. [Thunk and Lazy Evaluation](./design/thunk-and-lazy-evaluation.md)
|
||||
4. [Composition and Materialization](./design/composition-and-materialization.md)
|
||||
5. [Diagnostics and Fallback](./design/diagnostics-and-fallback.md)
|
||||
6. [Embedding API](./design/embedding-api.md)
|
||||
7. [Features](./design/features.md)
|
||||
5. [Development](./development.md)
|
||||
6. [Open Issues](./open-issues.md)
|
||||
@@ -1,94 +0,0 @@
|
||||
# Introduction
|
||||
|
||||
このマニュアルは、Decodal の目的、設計方針、言語仕様をまとめる。
|
||||
Decodal は **Deferred Constraint Data Language**、略称 **DCDL** のプロジェクト名である。
|
||||
ファイル拡張子は `.dcdl` とする。
|
||||
|
||||
Decodal は、設定値・スキーマ・制約・派生設定を同じ式体系で扱い、組み込み環境でも実装しやすい小さな言語核を提供することを目指す。
|
||||
|
||||
## 目的
|
||||
|
||||
一般的な設定ファイルでは、値の記述、スキーマ定義、デフォルト値、派生設定、バリデーションが別々の仕組みとして扱われやすい。
|
||||
この言語では、それらを単一の式体系に寄せる。
|
||||
|
||||
例えば、以下のように制約と値を同じ構文で合成できる。
|
||||
|
||||
```dcdl
|
||||
Port = Int & >= 1 & <= 65535;
|
||||
NarrowedPort = Port & > 443;
|
||||
|
||||
MyConfig = {
|
||||
host = String;
|
||||
port = NarrowedPort default 8080;
|
||||
};
|
||||
|
||||
Config = MyConfig & {
|
||||
host = "127.0.0.1";
|
||||
port = 8000;
|
||||
};
|
||||
```
|
||||
|
||||
`MyConfig` は設定の形と制約を表し、`Config` はそこへ具体値を合成した設定を表す。
|
||||
具体値は対応する制約を満たす必要がある。
|
||||
|
||||
## 設計目標
|
||||
|
||||
- データ記述とスキーマ記述を同じ構文で表現できる。
|
||||
- 制約を `&` で合成し、値が制約を満たすか検証できる。
|
||||
- 設定値やスキーマを `//` で構造的に patch できる。
|
||||
- `default` により、最終評価時の fallback 値を定義できる。
|
||||
- フィールド単位の遅延評価により、未使用値の評価を避ける。
|
||||
- import 循環があっても、必要なフィールド依存が循環していなければ評価できる。
|
||||
- 処理系を組み込み向けに小さく保てるよう、意味論を明示的かつ決定的にする。
|
||||
|
||||
## 非目標
|
||||
|
||||
初期仕様では以下を必須にしない。
|
||||
|
||||
- 高度な型推論。
|
||||
- match の完全な網羅性検査。
|
||||
- 到達不能分岐の静的検査。
|
||||
- 任意の関数呼び出し結果のグローバル memoize。
|
||||
- 正規表現エンジンの必須搭載。
|
||||
- 汎用 `try / catch` の core 搭載。
|
||||
- 完全なプログラミング言語としての汎用性。
|
||||
|
||||
## 中心概念
|
||||
|
||||
この言語の中心概念は以下である。
|
||||
|
||||
- 値と制約を同じ式として扱う。
|
||||
- `&` で制約を保った合成を行う。
|
||||
- `//` で右辺優先の構造的 patch を行う。
|
||||
- `default` は制約ではなく、最終評価時の fallback として扱う。
|
||||
- フィールド単位で遅延評価する。
|
||||
- import 循環は、実際に必要なフィールド依存が循環しない限り許容する。
|
||||
|
||||
## 組み込み向けの方針
|
||||
|
||||
この言語は、汎用プログラミング言語を目指すものではない。
|
||||
主対象は、設定、スキーマ、制約、派生データの記述である。
|
||||
|
||||
そのため、言語核は「値・制約・構造の合成」と「遅延評価」に寄せる。
|
||||
便利な機能であっても、実装サイズ・評価モデル・エラー決定性を大きく複雑にするものは optional feature または将来拡張として扱う。
|
||||
|
||||
## ドキュメント構成
|
||||
|
||||
言語仕様の解説は [Language Specification](./language/index.md) にまとめる。
|
||||
`language/` 配下には、構文、値、式、制約、演算子、評価意味論など、言語仕様そのものの説明だけを置く。
|
||||
|
||||
処理系の設計は [Implementation Design](./design/index.md) にまとめる。
|
||||
ここでは、AST interpreter、runtime value、thunk、合成処理、materialize、diagnostic の扱いを説明する。
|
||||
|
||||
主な章は以下である。
|
||||
|
||||
- [Value](./language/value/index.md): `String`、`Int`、`Float`、`Bool` などの値・プリミティブ制約。
|
||||
- [Expression](./language/expression/index.md): literal、object、array、function、let、match、import などの式。
|
||||
- [Constraints and Defaults](./language/constraints-and-defaults.md): 制約と `default` の意味。
|
||||
- [Composition Operators](./language/operators.md): `&` と `//` の意味。
|
||||
- [Evaluation Semantics](./language/evaluation.md): 遅延評価、thunk、循環検出。
|
||||
- [Materialization and Errors](./language/materialization-and-errors.md): 最終評価とエラー分類。
|
||||
- [Runtime Model](./design/runtime-model.md): concrete value と abstract value の内部表現。
|
||||
- [Thunk and Lazy Evaluation](./design/thunk-and-lazy-evaluation.md): 遅延計算と循環検出の処理系モデル。
|
||||
|
||||
未確定事項は [Open Issues](./open-issues.md) に集約する。
|
||||
@@ -1,227 +0,0 @@
|
||||
# 制約と default
|
||||
|
||||
この章では、制約と `default` の意味を定義する。
|
||||
|
||||
## 制約
|
||||
|
||||
制約は、値が満たすべき条件を表す。
|
||||
|
||||
```dcdl
|
||||
Int
|
||||
String
|
||||
>= 1
|
||||
<= 65535
|
||||
/Hello! .*/
|
||||
```
|
||||
|
||||
制約は `&` により合成できる。
|
||||
|
||||
```dcdl
|
||||
Port = Int & >= 1 & <= 65535;
|
||||
NarrowedPort = Port & > 443;
|
||||
```
|
||||
|
||||
制約合成の意味は、すべての制約を同時に満たすことである。
|
||||
|
||||
```text
|
||||
A & B = A と B の両方を満たす値または制約
|
||||
```
|
||||
|
||||
矛盾する制約はエラーになる。
|
||||
|
||||
```dcdl
|
||||
Int & String # エラー
|
||||
> 10 & < 5 # エラー
|
||||
Int & > 10 & < 11 # エラー。整数値の候補が存在しない
|
||||
```
|
||||
|
||||
## 制約の正規化
|
||||
|
||||
`&` によって abstract value 同士を合成した場合、処理系は軽量に判定できる制約を正規化する。
|
||||
|
||||
正規化対象:
|
||||
|
||||
- primitive type 制約。
|
||||
- 数値比較制約。
|
||||
|
||||
primitive type 制約は、異なる型が同時に要求された場合 conflict になる。
|
||||
|
||||
```dcdl
|
||||
Int & Float
|
||||
Int & String
|
||||
```
|
||||
|
||||
数値比較制約は上下限として正規化される。
|
||||
|
||||
```dcdl
|
||||
Int & >= 1 & <= 65535 & > 443
|
||||
```
|
||||
|
||||
これは概念的に以下へ正規化される。
|
||||
|
||||
```text
|
||||
Type(Int)
|
||||
> 443
|
||||
<= 65535
|
||||
```
|
||||
|
||||
上下限の交差が空であれば conflict になる。
|
||||
`Int` 制約がある場合は、整数候補が存在するかも判定する。
|
||||
|
||||
```dcdl
|
||||
> 10 & < 5 # conflict
|
||||
Int & > 10 & < 11 # conflict
|
||||
Int & >= 10 & <= 10 # OK
|
||||
```
|
||||
|
||||
`Int` の比較制約は整数リテラルを使う。
|
||||
`Float` の比較制約は整数リテラルまたは浮動小数リテラルを使える。
|
||||
|
||||
## 組み込み制約
|
||||
|
||||
最小の組み込み制約は以下である。
|
||||
|
||||
```dcdl
|
||||
String
|
||||
Int
|
||||
Float
|
||||
Bool
|
||||
```
|
||||
|
||||
追加の述語制約はライブラリまたは組み込みとして提供できる。
|
||||
|
||||
```dcdl
|
||||
IPv4Address
|
||||
```
|
||||
|
||||
## 正規表現制約
|
||||
|
||||
正規表現リテラルは文字列制約として使える。
|
||||
|
||||
```dcdl
|
||||
Host = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
|
||||
```
|
||||
|
||||
正規表現制約は積み重ね可能である。
|
||||
複数の正規表現制約が同じ abstract value に付与された場合、具体文字列はすべての正規表現制約に一致しなければならない。
|
||||
|
||||
```dcdl
|
||||
String & /^a/ & /z$/
|
||||
```
|
||||
|
||||
処理系は、正規表現制約同士の交差が空であるかを合成時に判定する必要はない。
|
||||
つまり、以下は合成時には conflict にならず、具体値検証時に失敗する。
|
||||
|
||||
```dcdl
|
||||
String & /^a$/ & /^b$/
|
||||
```
|
||||
|
||||
正規表現エンジンは optional feature にできる。
|
||||
正規表現 feature が無効な処理系では、正規表現制約の検証は unsupported feature diagnostic になる。
|
||||
軽量実装では代表的な制約を組み込み述語として提供してもよい。
|
||||
|
||||
```dcdl
|
||||
Host = IPv4Address;
|
||||
```
|
||||
|
||||
## 配列制約
|
||||
|
||||
配列制約には要素制約が必須であり、`[...T]` と書く。
|
||||
|
||||
```dcdl
|
||||
Names = [...String];
|
||||
PositiveInts = [...(Int & > 0)];
|
||||
```
|
||||
|
||||
複数の配列制約を `&` で合成した場合、各 concrete 要素をすべての要素 range で絞り込む。
|
||||
要素が object range の場合、右辺にしかない field は default の有無にかかわらず abstract のまま各要素へ残る。
|
||||
左辺にしかない field は右辺の field domain 外なのでエラーになる。
|
||||
要素制約のない `Array` primitive type は存在しない。
|
||||
|
||||
## 連想配列制約
|
||||
|
||||
連想配列制約は `{...T}` と書き、object の任意の field value を `T` に対して絞り込む。
|
||||
|
||||
```dcdl
|
||||
Services = {...{
|
||||
port = Int;
|
||||
enabled = Bool default true;
|
||||
}};
|
||||
```
|
||||
|
||||
key は schema で列挙せず、空 object も許容する。
|
||||
固定 object field と任意 key の value constraint を混在させる構文は現在サポートしない。
|
||||
|
||||
## default
|
||||
|
||||
`default` は制約ではない。
|
||||
`default` は、最終評価時に明示値が存在しない場合だけ使われる fallback 値である。
|
||||
|
||||
```dcdl
|
||||
port = NarrowedPort default 8080;
|
||||
```
|
||||
|
||||
これは概念的には以下を表す。
|
||||
|
||||
```text
|
||||
Abstract {
|
||||
constraints: [NarrowedPort]
|
||||
default: 8080
|
||||
}
|
||||
```
|
||||
|
||||
明示値が合成された場合、`default` は採用されない。
|
||||
|
||||
```dcdl
|
||||
MyConfig = {
|
||||
port = NarrowedPort default 8080;
|
||||
};
|
||||
|
||||
Config = MyConfig & {
|
||||
port = 8000;
|
||||
};
|
||||
```
|
||||
|
||||
この場合、最終値は `8000` である。
|
||||
`8080` は評価されない、または評価されても採用されない。
|
||||
|
||||
明示値がない場合、最終 materialize 時に `default` が採用される。
|
||||
採用された default 値は、同じフィールドに定義された制約を満たす必要がある。
|
||||
|
||||
```text
|
||||
Abstract {
|
||||
constraints: [NarrowedPort]
|
||||
default: 8080
|
||||
}
|
||||
|
||||
finalize => 8080 が NarrowedPort を満たせば成功
|
||||
```
|
||||
|
||||
## default の内部表現
|
||||
|
||||
`default` は abstract value に付随する fallback thunk として保持できる。
|
||||
これにより、default 値自体も必要になるまで評価しない。
|
||||
|
||||
```text
|
||||
RuntimeValue =
|
||||
Concrete(ConcreteValue)
|
||||
Abstract {
|
||||
constraints: Vec<Constraint>
|
||||
default: Option<Thunk>
|
||||
}
|
||||
```
|
||||
|
||||
明示値は `Concrete` として表現し、`default` を保持しない。
|
||||
`Abstract & Concrete` が成功した場合、制約検証後に `Concrete` になり、default は消える。
|
||||
|
||||
## default の合成
|
||||
|
||||
`default` の合成規則は以下である。
|
||||
|
||||
- `&` で片方だけが default を持つ場合、その default を保持する。
|
||||
- `&` で両方が異なる default を持つ場合、conflict になる。
|
||||
- `Abstract & Concrete` が成功した場合、結果は concrete value になり default は消える。
|
||||
- `//` では右辺が左辺を置き換える。object/object の場合は field ごとに再帰 patch されるため、右辺 field の default が左辺 field の default を置き換える。
|
||||
|
||||
`default` thunk は materialize 時に必要になった時点で評価する。
|
||||
評価された default value は、同じ abstract value に残っている制約を満たす必要がある。
|
||||
@@ -1,78 +0,0 @@
|
||||
# 遅延評価
|
||||
|
||||
この言語はフィールド単位で遅延評価する。
|
||||
|
||||
## 基本方針
|
||||
|
||||
```dcdl
|
||||
{
|
||||
schema = {
|
||||
hoge = String;
|
||||
};
|
||||
|
||||
result = expensive(schema);
|
||||
}
|
||||
```
|
||||
|
||||
`schema` のみが必要な場合、`result` は評価されない。
|
||||
|
||||
## thunk
|
||||
|
||||
各フィールドや let 束縛は thunk として保持できる。
|
||||
|
||||
```text
|
||||
Thunk {
|
||||
expr: ExprId
|
||||
env: EnvRef
|
||||
state: Unevaluated | Evaluating | Evaluated(Value) | Error
|
||||
}
|
||||
```
|
||||
|
||||
評価済み thunk は memoize する。
|
||||
同じフィールドを複数回参照しても、評価は一度だけでよい。
|
||||
|
||||
## 評価状態
|
||||
|
||||
thunk は以下の状態を持つ。
|
||||
|
||||
```text
|
||||
Unevaluated 未評価
|
||||
Evaluating 評価中
|
||||
Evaluated 評価済み
|
||||
Error 評価失敗
|
||||
```
|
||||
|
||||
`Evaluating` の thunk を再度評価しようとした場合、循環依存として扱う。
|
||||
|
||||
## 循環検出
|
||||
|
||||
```dcdl
|
||||
{
|
||||
a = b + 1;
|
||||
b = a + 1;
|
||||
}
|
||||
```
|
||||
|
||||
この場合、`a` または `b` を評価すると循環エラーになる。
|
||||
|
||||
一方、同じモジュール内または import 間に循環があっても、評価対象のフィールドが循環していなければ成功する。
|
||||
|
||||
## 評価と materialize の分離
|
||||
|
||||
通常の評価では、制約や default を含む中間値が残ることがある。
|
||||
外部へデータとして出力する段階で materialize を行う。
|
||||
|
||||
この分離により、以下が可能になる。
|
||||
|
||||
- スキーマを値として扱う。
|
||||
- default を必要になるまで評価しない。
|
||||
- import されたモジュールの未使用フィールドを評価しない。
|
||||
- 制約だけのフィールドを中間状態として保持する。
|
||||
|
||||
## 関数呼び出しとの関係
|
||||
|
||||
関数引数は thunk として渡せる。
|
||||
関数本体内で引数が参照されたときに評価する。
|
||||
|
||||
関数呼び出し結果そのものはグローバルには memoize しない。
|
||||
ただし、フィールドに束縛された呼び出し結果は、そのフィールド thunk の評価結果として memoize される。
|
||||
@@ -1,15 +0,0 @@
|
||||
# Default Expression
|
||||
|
||||
`default` expression は、明示値が存在しない場合に materialize 時に採用される fallback を指定する。
|
||||
|
||||
```dcdl
|
||||
port = Int default 8080;
|
||||
```
|
||||
|
||||
`default` は制約ではない。
|
||||
詳細は [制約と default](../constraints-and-defaults.md) に置く。
|
||||
|
||||
## 評価
|
||||
|
||||
fallback 値は thunk として保持できる。
|
||||
明示値がある場合、default は採用されない。
|
||||
@@ -1,14 +0,0 @@
|
||||
# Identifier Expression
|
||||
|
||||
identifier expression は、現在の環境に束縛された名前を参照する式である。
|
||||
|
||||
```dcdl
|
||||
Port
|
||||
MyConfig
|
||||
mkConfig
|
||||
```
|
||||
|
||||
## 評価
|
||||
|
||||
識別子は、対応する束縛の thunk を参照する。
|
||||
束縛が存在しない場合は未定義識別子エラーになる。
|
||||
@@ -1,15 +0,0 @@
|
||||
# Import Expression
|
||||
|
||||
import expression は、外部ファイルを読み込み、そのファイルの評価結果を返す。
|
||||
|
||||
```dcdl
|
||||
import ./config.n
|
||||
import "./config.n"
|
||||
```
|
||||
|
||||
import 仕様の詳細は [モジュールと import](../modules-and-imports.md) に置く。
|
||||
|
||||
## 評価
|
||||
|
||||
import 先はモジュール単位で読み込まれる。
|
||||
ただし、各 field は thunk として保持され、必要になるまで評価されない。
|
||||
@@ -1,16 +0,0 @@
|
||||
# Let Expression
|
||||
|
||||
let expression は、ローカル束縛を作る。
|
||||
|
||||
```dcdl
|
||||
let
|
||||
base = 8000;
|
||||
offset = 80;
|
||||
in
|
||||
base + offset
|
||||
```
|
||||
|
||||
## 評価
|
||||
|
||||
let 束縛は thunk として保持される。
|
||||
参照されない束縛は評価されない。
|
||||
@@ -1,8 +0,0 @@
|
||||
# String Interpolation
|
||||
|
||||
文字列補間は初期実装には含めない。
|
||||
|
||||
Decodal の string literal は、現時点では literal text として扱う。
|
||||
式を埋め込む構文は定義しない。
|
||||
|
||||
必要になった場合は、文字列連結や明示的な formatting function として別途設計する。
|
||||
@@ -1,59 +0,0 @@
|
||||
# 関数
|
||||
|
||||
関数は構造を受け取り、構造を返す式として扱う。
|
||||
|
||||
## 構文
|
||||
|
||||
```dcdl
|
||||
(value: Int) => value + 1
|
||||
```
|
||||
|
||||
関数呼び出しは通常の呼び出し構文で行う。
|
||||
|
||||
```dcdl
|
||||
let
|
||||
increment = (value: Int) => value + 1;
|
||||
in
|
||||
increment(41)
|
||||
```
|
||||
|
||||
複数引数も指定できる。
|
||||
|
||||
```dcdl
|
||||
(input_a: { hoge = Int & >= 0; }, input_b: { fuga = Int; }) =>
|
||||
{
|
||||
hoge = input_a.hoge;
|
||||
fuga = input_b.fuga;
|
||||
}
|
||||
```
|
||||
|
||||
## 関数の意味
|
||||
|
||||
関数は runtime value として扱えるが、最終データとして materialize することはできない。
|
||||
未適用の関数値が materialize 対象に残っている場合は diagnostic になる。
|
||||
|
||||
関数値は opaque であり、関数値同士の等価性は提供しない。
|
||||
`&` で関数値同士を合成すると conflict になる。
|
||||
|
||||
## 評価方針
|
||||
|
||||
関数は以下の方針で評価する。
|
||||
|
||||
- 関数は純粋である。
|
||||
- 関数はレキシカルスコープを持つ。
|
||||
- 関数は定義時の環境を参照として保持する。
|
||||
- 引数は thunk として渡され、必要になるまで評価されない。
|
||||
- parameter range がある引数は、force 時に `as` と同じ範囲包含・絞り込み規則で合成される。
|
||||
- 関数呼び出し結果そのものはグローバルには memoize しない。
|
||||
- フィールドに束縛された関数呼び出し結果は、そのフィールド thunk の評価結果として memoize される。
|
||||
- 再帰的な依存は thunk cycle として diagnostic になる。
|
||||
|
||||
関数値の内部モデル例:
|
||||
|
||||
```text
|
||||
Function {
|
||||
params: Vec<Param>
|
||||
body: ExprId
|
||||
env: EnvRef
|
||||
}
|
||||
```
|
||||
@@ -1,12 +0,0 @@
|
||||
# 言語仕様
|
||||
|
||||
このディレクトリは、Decodal / DCDL の仕様本文を章ごとに分割して管理する。
|
||||
|
||||
目次はマニュアル直下の [Manual Index](../index.md) に集約する。
|
||||
このファイルは `Language Specification` 章の入口としてだけ使う。
|
||||
|
||||
## Language
|
||||
|
||||
言語仕様は、構文、値、式、制約、合成演算子、関数、モジュール、評価意味論、materialize、エラーを定義する。
|
||||
|
||||
詳細な章構成と各ファイルへのリンクは [Manual Index](../index.md) を参照する。
|
||||
@@ -1,99 +0,0 @@
|
||||
# materialize とエラー
|
||||
|
||||
通常の評価では、制約や default を含む中間値が残ることがある。
|
||||
外部へデータとして出力する段階では、materialize を行う。
|
||||
|
||||
## materialize の責務
|
||||
|
||||
materialize は以下を行う。
|
||||
|
||||
- 必要なフィールドを評価する。
|
||||
- 明示値がない abstract value に default を適用する。
|
||||
- 採用された値が制約を満たすか検証する。
|
||||
- default を持たない未解決の abstract value をエラーにする。
|
||||
- 未適用の関数など、データとして出力できない値をエラーにする。
|
||||
|
||||
## 例
|
||||
|
||||
```dcdl
|
||||
MyConfig = {
|
||||
host = String;
|
||||
port = Int default 8080;
|
||||
};
|
||||
```
|
||||
|
||||
`MyConfig` を materialize すると、`host` は具体値も default もないためエラーになる。
|
||||
`port` は `8080` が採用される。
|
||||
|
||||
```dcdl
|
||||
Config = MyConfig & {
|
||||
host = "localhost";
|
||||
};
|
||||
```
|
||||
|
||||
`Config` を materialize すると以下になる。
|
||||
|
||||
```dcdl
|
||||
{
|
||||
host = "localhost";
|
||||
port = 8080;
|
||||
}
|
||||
```
|
||||
|
||||
## default の適用
|
||||
|
||||
`default` は materialize 時にのみ fallback として採用される。
|
||||
|
||||
```text
|
||||
Abstract {
|
||||
constraints: [Int]
|
||||
default: 8080
|
||||
}
|
||||
```
|
||||
|
||||
この abstract value を materialize すると、`8080` が採用され、`Int` を満たすか検証される。
|
||||
|
||||
明示値がある場合、default は採用しない。
|
||||
明示値は concrete value として表現され、default を保持しない。
|
||||
|
||||
```text
|
||||
Concrete(Int(9000))
|
||||
```
|
||||
|
||||
この値の最終値は `9000` である。
|
||||
|
||||
## エラー分類
|
||||
|
||||
代表的なエラー:
|
||||
|
||||
- 構文エラー
|
||||
- 未定義識別子
|
||||
- 型不一致
|
||||
- 制約違反
|
||||
- `&` の conflict
|
||||
- `default` の conflict
|
||||
- 循環依存
|
||||
- import 失敗
|
||||
- match の非網羅による失敗
|
||||
- materialize 不能な値の出力
|
||||
|
||||
## match の失敗
|
||||
|
||||
`match` に fallback 分岐がなく、どの分岐にも一致しなかった場合はエラーになる。
|
||||
|
||||
```dcdl
|
||||
match value {
|
||||
>= 10: "large";
|
||||
}
|
||||
```
|
||||
|
||||
`value` が `10` 未満であれば失敗する。
|
||||
|
||||
## エラーは値ではない
|
||||
|
||||
エラーは runtime value ではなく diagnostic として扱う。
|
||||
通常の式はエラー内容に基づいて分岐できない。
|
||||
|
||||
汎用 `try / catch` は core には含めない。
|
||||
fallback は `default` と `match` で表現する。
|
||||
optional import や optional field access は core には含めない。
|
||||
@@ -1,159 +0,0 @@
|
||||
# モジュールと import
|
||||
|
||||
`import` は外部ファイルを読み込み、そのファイルの評価結果を返す。
|
||||
|
||||
## 構文
|
||||
|
||||
```dcdl
|
||||
import "./config.dcdl"
|
||||
```
|
||||
|
||||
import specifier は文字列リテラルとする。
|
||||
パスリテラル構文は採用しない。
|
||||
|
||||
## モジュール
|
||||
|
||||
import 先はモジュール単位で読み込まれる。
|
||||
ただし、モジュール全体を即時評価する必要はない。
|
||||
各フィールドは thunk として保持され、必要になったときだけ評価される。
|
||||
|
||||
top-level に field 定義列を書いた module は、recursive module scope を作る。
|
||||
つまり、top-level field は同じ module の他の top-level field から識別子として参照できる。
|
||||
|
||||
```dcdl
|
||||
schema = {
|
||||
hoge = String;
|
||||
};
|
||||
|
||||
result = schema;
|
||||
```
|
||||
|
||||
この場合、`result` の右辺の `schema` は同じ module の top-level field `schema` を参照する。
|
||||
通常の object literal 内の field は、その object 内の sibling field を暗黙には識別子として参照できない。
|
||||
object 内の値を参照する場合は、外側で束縛された値や明示的な path reference を使う。
|
||||
|
||||
## ImportLoader
|
||||
|
||||
`import` specifier の解決は処理系 core ではなく host 側の `ImportLoader` が行う。
|
||||
CLI では、specifier を現在の module path からの相対 path として解決する。
|
||||
組み込み利用では、resource table や static source map など、filesystem 以外の loader を使える。
|
||||
|
||||
module cache の key は loader が返す安定 key を使う。
|
||||
CLI では canonical path を key とする。
|
||||
|
||||
### 構造化 import
|
||||
|
||||
`ImportLoader::load` は DCDL source または host が構築した `HostValue` を import 結果として返す。
|
||||
Markdown、JSON、TOML などの解釈規則は core に固定せず、loader がファイル種別を判定して構造化する。
|
||||
|
||||
```rust
|
||||
use decodal::{HostValue, ImportLoader, LoadedImport};
|
||||
|
||||
struct ContentLoader;
|
||||
|
||||
impl ImportLoader for ContentLoader {
|
||||
fn load(
|
||||
&mut self,
|
||||
current_key: Option<&str>,
|
||||
specifier: &str,
|
||||
) -> decodal::Result<LoadedImport> {
|
||||
if specifier.ends_with(".md") {
|
||||
let markdown = read_content(current_key, specifier)?;
|
||||
let parsed = parse_frontmatter(&markdown)?;
|
||||
return Ok(LoadedImport::value(
|
||||
parsed.key,
|
||||
HostValue::object([
|
||||
("frontmatter", parsed.frontmatter),
|
||||
("body", HostValue::string(parsed.body)),
|
||||
]),
|
||||
));
|
||||
}
|
||||
|
||||
let source = read_dcdl(current_key, specifier)?;
|
||||
Ok(LoadedImport::source(
|
||||
source.key,
|
||||
specifier,
|
||||
source.text,
|
||||
))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`read_content` と `parse_frontmatter` は host 独自の処理であり、Decodal core は Markdown や YAML parser に依存しない。
|
||||
上の loader を使うと、DCDL 側から次のように扱える。
|
||||
|
||||
```dcdl
|
||||
Post = {
|
||||
frontmatter = {
|
||||
title = String;
|
||||
draft = Bool default false;
|
||||
};
|
||||
body = String;
|
||||
};
|
||||
|
||||
post = Post & import "./hello.md";
|
||||
title = post.frontmatter.title;
|
||||
body = post.body;
|
||||
```
|
||||
|
||||
`LoadedImport::Value` は通常の concrete runtime value に internalize される。
|
||||
そのため、path reference、object composition、constraint validation、materialize は source 由来の値と同じ規則を使う。
|
||||
安定した `key` が同じ構造化 import は、engine 内で同じ値としてキャッシュされる。
|
||||
|
||||
`load` が唯一の import hook である。
|
||||
loader は拡張子、media type、または host 独自の規則で振り分け、対応する `LoadedImport` variant を直接返す。
|
||||
|
||||
## 循環 import
|
||||
|
||||
モジュール間に循環参照があっても、必要なフィールドの依存関係が循環していなければ評価できる。
|
||||
|
||||
例:
|
||||
|
||||
```dcdl
|
||||
# main.dcdl
|
||||
{
|
||||
schema = {
|
||||
hoge = String;
|
||||
};
|
||||
|
||||
result = (import "./func.dcdl")(schema);
|
||||
}
|
||||
```
|
||||
|
||||
```dcdl
|
||||
# func.dcdl
|
||||
(input: (import "./main.dcdl").schema) =>
|
||||
{
|
||||
# ...
|
||||
}
|
||||
```
|
||||
|
||||
`func.dcdl` は `main.dcdl` を import しているが、参照しているのは `main.schema` である。
|
||||
`main.schema` が `main.result` に依存していなければ、この循環 import は成立する。
|
||||
|
||||
## import の評価単位
|
||||
|
||||
実装上は、以下の単位で管理するのが自然である。
|
||||
|
||||
```text
|
||||
Module main
|
||||
schema -> thunk
|
||||
result -> thunk
|
||||
|
||||
Module func
|
||||
root -> thunk
|
||||
```
|
||||
|
||||
各 thunk は一度だけ評価して memoize する。
|
||||
評価中に同じ thunk へ戻った場合は循環依存としてエラーにする。
|
||||
|
||||
## import 失敗
|
||||
|
||||
以下は import 失敗として扱う。
|
||||
|
||||
- ファイルが存在しない。
|
||||
- ファイルが読めない。
|
||||
- import 先の構文解析に失敗する。
|
||||
- import 先の評価で必要な値がエラーになる。
|
||||
- host による非 DCDL content の読み込みまたは構造化に失敗する。
|
||||
- 実装が禁止する import 循環に該当する。
|
||||
@@ -1,27 +0,0 @@
|
||||
# 命名規約
|
||||
|
||||
具体値と抽象値がグラデーションになるため、大文字・小文字による厳密な意味分けは設けない。
|
||||
|
||||
ただし、読みやすさのために慣習を定める。
|
||||
|
||||
## 推奨規約
|
||||
|
||||
- object 値: `lower_snake`
|
||||
- 関数: `lowerCamel`
|
||||
- 組み込み型・抽象的な制約名: `UpperCamel`
|
||||
|
||||
例:
|
||||
|
||||
```dcdl
|
||||
IPv4Address
|
||||
MyConfig
|
||||
new_config
|
||||
mkConfig
|
||||
```
|
||||
|
||||
## 厳密な規則にしない理由
|
||||
|
||||
この言語では、値・制約・スキーマ・派生設定が同じ式体系に乗る。
|
||||
そのため、ある名前が「具体値」か「抽象的な制約」かは文脈によってグラデーションになる。
|
||||
|
||||
大文字なら型、小文字なら値、のような厳密な規則を設けると、実際の利用に対して過剰に硬くなる可能性がある。
|
||||
@@ -1,23 +0,0 @@
|
||||
# 未確定事項
|
||||
|
||||
今後決める必要がある事項を管理する。
|
||||
実装または仕様方針が固まった項目は、該当する仕様ファイルへ反映してここから外す。
|
||||
|
||||
## Materialize target and host projection
|
||||
|
||||
Decodal の評価結果は、制約・default・関数値を含む中間値になり得る。
|
||||
そのため、Decodal 単独で常に「最終成果物」を一意に決めるのではなく、host 側が期待する型や出力形式を与えて materialize / decode する経路を明確にする必要がある。
|
||||
|
||||
決めること:
|
||||
|
||||
- Rust API で評価結果の field/path を選択して decode / materialize できるようにするか。
|
||||
- `decodal-derive` の struct schema と評価結果を合成して decode する経路を、主要な materialize path として位置づけるか。
|
||||
- CLI / WASM では target path を指定して JSON-compatible value へ materialize する形にするか。
|
||||
- 制約や関数値が残った値を出力したい場合、materialize ではなく inspect/debug API として分けるか。
|
||||
|
||||
現時点の案:
|
||||
|
||||
- Rust では `evaluate -> select field/path -> expected schema と合成 -> decode` を主経路にする。
|
||||
- CLI / WASM では、明示された target path または module 全体を JSON-compatible value として materialize する。
|
||||
- materialize できない unresolved abstract value、default のない制約値、関数値は diagnostic にする。
|
||||
- Decodal 言語内には materialize 構文を追加せず、host API / CLI / WASM の責務として扱う。
|
||||
@@ -0,0 +1,81 @@
|
||||
# Packages and Integrations
|
||||
|
||||
Decodal provides separate packages for execution, host embedding, language services, and editor integration.
|
||||
|
||||
## Rust
|
||||
|
||||
### `decodal`
|
||||
|
||||
The runtime and embedding API for Rust applications.
|
||||
It handles parsing, evaluation, and materialization of source; host globals; and imports containing either source or structured values.
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
decodal = "0.4"
|
||||
```
|
||||
|
||||
Enable the `derive` feature to generate a Decodal schema and decoder from a Rust struct.
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
decodal = { version = "0.4", features = ["derive"] }
|
||||
```
|
||||
|
||||
Enable the `regex` feature to validate regular-expression constraints.
|
||||
This feature requires `std`.
|
||||
|
||||
### `decodal-language-service`
|
||||
|
||||
Provides transport-independent semantic evaluation and completion.
|
||||
It accepts an application's `HostEnvironment` directly, allowing production and editor evaluation to share global bindings and import rules.
|
||||
|
||||
### `decodal-lsp`
|
||||
|
||||
Connects the language service to the Language Server Protocol.
|
||||
In addition to a stdio server, it exposes a library API that constructs an application-specific environment from the client's `InitializeParams`.
|
||||
|
||||
### `decodal-language-tools`
|
||||
|
||||
Provides shared tools for source text, including the formatter.
|
||||
The Rust, LSP, and WebAssembly integrations all use the same formatter implementation.
|
||||
|
||||
## JavaScript and WebAssembly
|
||||
|
||||
### `decodal-wasm`
|
||||
|
||||
Provides the evaluator and language service for browsers and other WebAssembly runtimes.
|
||||
|
||||
```sh
|
||||
npm install decodal-wasm
|
||||
```
|
||||
|
||||
It is also published on JSR as `@hare/decodal-wasm`.
|
||||
Pass `globals`, `loadImport`, and `completeImport` to `DecodalLanguageService` so JavaScript-owned environments are shared by evaluation and completion.
|
||||
|
||||
### `decodal-codemirror`
|
||||
|
||||
Language support for CodeMirror 6.
|
||||
It provides syntax highlighting, folding, indentation, and integration with the Decodal formatter.
|
||||
|
||||
```sh
|
||||
npm install decodal-codemirror
|
||||
```
|
||||
|
||||
It is also published on JSR as `@hare/decodal-codemirror`.
|
||||
Combine it with the `decodal-wasm` language service when semantic evaluation and completion are required.
|
||||
|
||||
## Editor syntax
|
||||
|
||||
The Tree-sitter grammar is an integration for parsing and highlighting in editors that use Tree-sitter.
|
||||
Tree-sitter is not required by the Decodal runtime, formatter, or LSP.
|
||||
|
||||
Choose packages according to the integration you need:
|
||||
|
||||
- Execution and embedding in Rust: `decodal`
|
||||
- Execution and semantic tooling in a browser: `decodal-wasm`
|
||||
- CodeMirror 6: `decodal-codemirror`
|
||||
- Transport-independent Rust language service: `decodal-language-service`
|
||||
- General editor clients: `decodal-lsp`
|
||||
- Syntax grammar for editors that use Tree-sitter: the Tree-sitter integration
|
||||
|
||||
See [Embedding](./embedding.md) for concrete environment setup.
|
||||
@@ -0,0 +1,193 @@
|
||||
# Embedding
|
||||
|
||||
The Decodal runtime does not read filesystems, networks, or environment variables directly.
|
||||
The host injects global bindings and import resolution, then receives the evaluation result as `Data` or an application type.
|
||||
|
||||
## Rust runtime
|
||||
|
||||
`Engine` owns an `ImportLoader` and global bindings.
|
||||
Use `EmptyLoader` for source that does not require external resources.
|
||||
|
||||
```rust
|
||||
use decodal::{EmptyLoader, Engine, Value};
|
||||
|
||||
let mut engine = Engine::new(EmptyLoader);
|
||||
engine.bind_global(
|
||||
"Service",
|
||||
Value::object([
|
||||
("name", Value::string_type()),
|
||||
("port", Value::int_type().gt(443).default_int(8443)?),
|
||||
("enabled", Value::bool_type().default_bool(true)?),
|
||||
]),
|
||||
)?;
|
||||
|
||||
let module = engine.add_root_source(
|
||||
"service.dcdl",
|
||||
"service.dcdl",
|
||||
r#"{ name = "api"; port = 9443; } as Service"#,
|
||||
)?;
|
||||
let value = engine.eval_module(module)?;
|
||||
let data = engine.materialize(&value)?;
|
||||
```
|
||||
|
||||
`Value` is the public type for both concrete values and host-defined ranges.
|
||||
Its main constructors are:
|
||||
|
||||
- `Value::string`, `int`, `float`, `bool`, `array`, and `object`: concrete values.
|
||||
- `Value::string_type`, `int_type`, `float_type`, and `bool_type`: primitive ranges.
|
||||
- `Value::unknown`: the top range, `Unknown`.
|
||||
- `Value::array_of`: an array range that applies one range to every element.
|
||||
- `Value::map_of`: an associative-array range that applies one range to every field value.
|
||||
- `Value::object_with_rest`: an object with named fields and a range for remaining fields.
|
||||
|
||||
## Typed Rust integration
|
||||
|
||||
The `Decodal` derive from the `derive` feature generates `DecodalSchema` and `DecodalDecode` implementations from a Rust struct.
|
||||
|
||||
```rust
|
||||
use decodal::{Decodal, DecodalDecode, DecodalSchema};
|
||||
|
||||
#[derive(Decodal)]
|
||||
struct Service {
|
||||
name: String,
|
||||
|
||||
#[decodal(gt = 443, default = 8443)]
|
||||
port: i64,
|
||||
|
||||
#[decodal(rename = "feature.enable", default = true)]
|
||||
feature_enabled: bool,
|
||||
}
|
||||
```
|
||||
|
||||
`DecodalSchema::decodal_schema()` returns a `Value` suitable for `Engine::bind_global`.
|
||||
Materialized `Data` can be converted to a Rust type with `DecodalDecode::decodal_decode`.
|
||||
|
||||
For a struct that accepts additional fields, mark a map field with `#[decodal(rest)]`.
|
||||
|
||||
```rust
|
||||
use std::collections::BTreeMap;
|
||||
use decodal::{Data, Decodal};
|
||||
|
||||
#[derive(Decodal)]
|
||||
struct OpenConfig {
|
||||
enabled: bool,
|
||||
|
||||
#[decodal(rest)]
|
||||
extra: BTreeMap<String, Data>,
|
||||
}
|
||||
```
|
||||
|
||||
`BTreeMap<String, Data>` corresponds to `...Unknown`, while `BTreeMap<String, String>` corresponds to `...String`.
|
||||
Named fields are excluded from the rest map.
|
||||
Only one `#[decodal(rest)]` field is allowed per struct, and it cannot be combined with `rename`, `default`, or field constraints.
|
||||
|
||||
## Imports
|
||||
|
||||
`ImportLoader::load` returns either `LoadedImport::Source` or `LoadedImport::Value`.
|
||||
The host controls specifier resolution, reading from the filesystem or other storage, and content-type detection.
|
||||
|
||||
`LoadedImport::Source` supplies DCDL source.
|
||||
`LoadedImport::Value` is intended for structured host-defined representations of formats such as Markdown, JSON, and TOML.
|
||||
|
||||
```text
|
||||
import "./post.md"
|
||||
-> host reads and parses Markdown
|
||||
-> LoadedImport::Value {
|
||||
key: "content/post.md",
|
||||
value: { frontmatter: {...}, body: "..." }
|
||||
}
|
||||
-> normal Decodal validation and materialization
|
||||
```
|
||||
|
||||
A stable `key` identifies an import and supplies diagnostic provenance.
|
||||
If a structured value violates a Decodal constraint, the diagnostic identifies the import key, logical value path, and source span of the violated DCDL constraint.
|
||||
The loader reports parse errors and positions in the external format itself.
|
||||
|
||||
## Shared host environment
|
||||
|
||||
`HostEnvironment` combines loader construction and global-binding setup.
|
||||
Passing the same environment to the runtime, language service, and LSP keeps runtime and editor evaluation rules aligned.
|
||||
|
||||
```rust
|
||||
use decodal::{Engine, HostEnvironment};
|
||||
|
||||
struct AppEnvironment;
|
||||
|
||||
impl HostEnvironment for AppEnvironment {
|
||||
type Loader = ContentLoader;
|
||||
|
||||
fn create_loader(&self) -> Self::Loader {
|
||||
ContentLoader::new()
|
||||
}
|
||||
|
||||
fn configure_engine(
|
||||
&self,
|
||||
engine: &mut Engine<Self::Loader>,
|
||||
) -> decodal::Result<()> {
|
||||
engine.bind_global("Site", site_schema())?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Construct transport-independent tooling with `decodal_language_service::LanguageService::new(&environment)`.
|
||||
For LSP integration, implement `decodal_lsp::LspEnvironment` and start the server from an environment factory.
|
||||
|
||||
```rust
|
||||
use decodal_lsp::{LspEnvironment, run_stdio};
|
||||
|
||||
impl LspEnvironment for AppEnvironment {}
|
||||
|
||||
run_stdio(|initialize| {
|
||||
let _ = initialize;
|
||||
Ok(AppEnvironment)
|
||||
})?;
|
||||
```
|
||||
|
||||
The factory receives the client's `InitializeParams` once, before the server responds with its capabilities.
|
||||
Use the `LspEnvironment` document lifecycle hooks to reflect unsaved DCDL, Markdown, and other resources in a host-owned overlay.
|
||||
|
||||
## JavaScript and browser environments
|
||||
|
||||
The `DecodalLanguageService` in `decodal-wasm` does not assume a filesystem or virtual project.
|
||||
JavaScript supplies `globals`, `loadImport`, and `completeImport`.
|
||||
|
||||
```js
|
||||
import init, { DecodalLanguageService } from 'decodal-wasm';
|
||||
|
||||
await init();
|
||||
|
||||
const files = {
|
||||
'schema.dcdl': 'Server = { port = Int; };',
|
||||
};
|
||||
|
||||
const service = new DecodalLanguageService({
|
||||
globals: {
|
||||
App: {
|
||||
enabled: { $decodal: 'Bool', default: true },
|
||||
},
|
||||
},
|
||||
loadImport(_currentKey, specifier) {
|
||||
const key = specifier.replace(/^\.\//, '');
|
||||
return { kind: 'source', key, name: key, source: files[key] };
|
||||
},
|
||||
completeImport() {
|
||||
return ['./schema.dcdl'];
|
||||
},
|
||||
});
|
||||
|
||||
const result = service.evaluate('main.dcdl', 'main.dcdl', 'App');
|
||||
```
|
||||
|
||||
JavaScript primitives, arrays, and plain objects become concrete values.
|
||||
Use `$decodal` descriptors for ranges:
|
||||
|
||||
- `{ $decodal: 'String' | 'Int' | 'Float' | 'Bool' }`
|
||||
- `{ $decodal: 'Unknown' }`
|
||||
- `{ $decodal: 'Array', item }`
|
||||
- `{ $decodal: 'Map', value }`
|
||||
- `{ $decodal: 'Object', fields, rest }`
|
||||
- `{ $decodal: 'Range', constraints, default }`
|
||||
|
||||
Import callbacks are synchronous.
|
||||
Preload or cache asynchronous inputs such as network resources before evaluation.
|
||||
@@ -0,0 +1,42 @@
|
||||
# Decodal Manual
|
||||
|
||||
This manual describes the Decodal language and the public APIs for embedding it in applications.
|
||||
Decodal is the project name for the Deferred Constraint Data Language, abbreviated DCDL.
|
||||
|
||||
## Contents
|
||||
|
||||
1. [Introduction](./introduction.md)
|
||||
2. [Language Specification](./language/index.md)
|
||||
1. [Lexical Structure and Syntax](./language/syntax.md)
|
||||
2. [Grammar](./language/grammar.md)
|
||||
3. [Value](./language/value/index.md)
|
||||
1. [String](./language/value/string.md)
|
||||
2. [Int](./language/value/int.md)
|
||||
3. [Float](./language/value/float.md)
|
||||
4. [Bool](./language/value/bool.md)
|
||||
4. [Expression](./language/expression/index.md)
|
||||
1. [Literal](./language/expression/literal.md)
|
||||
2. [Identifier](./language/expression/identifier.md)
|
||||
3. [Path Reference](./language/expression/path-reference.md)
|
||||
4. [Object](./language/expression/object.md)
|
||||
5. [Array](./language/expression/array.md)
|
||||
6. [Function](./language/expression/function.md)
|
||||
7. [Function Call](./language/expression/function-call.md)
|
||||
8. [Let](./language/expression/let.md)
|
||||
9. [Match](./language/expression/match.md)
|
||||
10. [Import](./language/expression/import.md)
|
||||
11. [Composition](./language/expression/composition.md)
|
||||
12. [Range Refinement](./language/expression/ascription.md)
|
||||
13. [Default](./language/expression/default.md)
|
||||
14. [Arithmetic](./language/expression/arithmetic.md)
|
||||
15. [Logical and Comparison](./language/expression/logical-and-comparison.md)
|
||||
5. [Constraints and Defaults](./language/constraints-and-defaults.md)
|
||||
6. [Operators](./language/operators.md)
|
||||
7. [Functions](./language/functions.md)
|
||||
8. [Modules and Imports](./language/modules-and-imports.md)
|
||||
9. [Evaluation Semantics](./language/evaluation.md)
|
||||
10. [Materialization and Errors](./language/materialization-and-errors.md)
|
||||
11. [Naming](./language/naming.md)
|
||||
12. [Examples](./language/examples.md)
|
||||
3. [Embedding](./embedding.md)
|
||||
4. [Packages and Integrations](./components.md)
|
||||
@@ -0,0 +1,54 @@
|
||||
# Introduction
|
||||
|
||||
Decodal is the **Deferred Constraint Data Language**, abbreviated **DCDL**.
|
||||
Its source files use the `.dcdl` extension.
|
||||
|
||||
Decodal is a language for describing configuration values, schemas, constraints, and derived configuration in one expression system, producing validated structured data.
|
||||
|
||||
## Purpose
|
||||
|
||||
In conventional configuration systems, values, schemas, defaults, derived settings, and validation are often handled by separate mechanisms.
|
||||
Decodal treats them as composable expressions.
|
||||
|
||||
```dcdl
|
||||
Port = Int & >= 1 & <= 65535;
|
||||
|
||||
Service = {
|
||||
host = String;
|
||||
port = Port default 8080;
|
||||
};
|
||||
|
||||
Config = {
|
||||
host = "127.0.0.1";
|
||||
port = 8000;
|
||||
} as Service;
|
||||
```
|
||||
|
||||
`Service` describes a range of accepted values.
|
||||
Each value in `Config` is validated against `Service`, while ranges that exist only in `Service` remain abstract in the result.
|
||||
During materialization, explicit values take precedence and `default` supplies values for ranges that remain unspecified.
|
||||
|
||||
## Core concepts
|
||||
|
||||
- Values and constraints are expressions that can be referenced and composed in the same way.
|
||||
- `&` performs symmetric composition and preserves constraints from both sides.
|
||||
- `as` verifies that the left side is more specific and narrower than the right side, then combines them.
|
||||
- `//` performs a right-biased structural patch, including overrides.
|
||||
- `default` is not a constraint. It is a fallback selected only during materialization.
|
||||
- Object fields, function arguments, and imports are evaluated when they are needed.
|
||||
- `Unknown` is the top range that accepts any concrete value, but it cannot be materialized while it remains abstract.
|
||||
|
||||
## Scope
|
||||
|
||||
Decodal is specialized for describing configuration, schemas, constraints, and derived data.
|
||||
General-purpose state mutation, time, randomness, network access, and `try / catch` for treating errors as values are not language features.
|
||||
The host provides filesystem and external-format access. Given the same source, import results, and global bindings, Decodal evaluation is deterministic.
|
||||
|
||||
Regular-expression constraints depend on the runtime's `regex` feature.
|
||||
Decodal does not provide advanced type inference, exhaustiveness checking for `match`, or static detection of unreachable branches.
|
||||
|
||||
## Continue reading
|
||||
|
||||
- [Language Specification](./language/index.md): syntax, values, expressions, constraints, evaluation, and materialization.
|
||||
- [Embedding](./embedding.md): Rust and JavaScript execution, host environments, structured imports, and language services.
|
||||
- [Packages and Integrations](./components.md): crates and JavaScript packages for each use case.
|
||||
@@ -0,0 +1,81 @@
|
||||
# Packages and Integrations
|
||||
|
||||
Decodal は実行、ホスト組み込み、言語サービス、エディタ統合を用途別の package として提供する。
|
||||
|
||||
## Rust
|
||||
|
||||
### `decodal`
|
||||
|
||||
Rust アプリケーション向けの runtime と embedding API である。
|
||||
source の parse・evaluate・materialize、host global、source または structured value の import を扱う。
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
decodal = "0.4"
|
||||
```
|
||||
|
||||
Rust struct から Decodal schema と decoder を生成する場合は `derive` feature を有効にする。
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
decodal = { version = "0.4", features = ["derive"] }
|
||||
```
|
||||
|
||||
正規表現制約を検証する場合は `regex` feature を有効にする。
|
||||
この feature は `std` を必要とする。
|
||||
|
||||
### `decodal-language-service`
|
||||
|
||||
transport に依存しない semantic evaluation と completion を提供する。
|
||||
アプリケーションの `HostEnvironment` をそのまま受け取るため、本番評価と編集時評価で global bindings と import 規則を共有できる。
|
||||
|
||||
### `decodal-lsp`
|
||||
|
||||
language service を Language Server Protocol に接続する。
|
||||
stdio server のほか、client の `InitializeParams` からアプリケーション固有の environment を構築する library API を提供する。
|
||||
|
||||
### `decodal-language-tools`
|
||||
|
||||
source formatter など、source text を扱う共通ツールを提供する。
|
||||
formatter は Rust、LSP、WebAssembly の各統合から同じ実装を利用できる。
|
||||
|
||||
## JavaScript and WebAssembly
|
||||
|
||||
### `decodal-wasm`
|
||||
|
||||
browser と WebAssembly 対応 runtime 向けの evaluator と language service である。
|
||||
|
||||
```sh
|
||||
npm install decodal-wasm
|
||||
```
|
||||
|
||||
JSR では `@hare/decodal-wasm` として提供される。
|
||||
`DecodalLanguageService` に `globals`、`loadImport`、`completeImport` を渡すことで、JavaScript が所有する environment を評価と補完で共有できる。
|
||||
|
||||
### `decodal-codemirror`
|
||||
|
||||
CodeMirror 6 向けの language support である。
|
||||
syntax highlighting、folding、indentation、Decodal formatter との統合を提供する。
|
||||
|
||||
```sh
|
||||
npm install decodal-codemirror
|
||||
```
|
||||
|
||||
JSR では `@hare/decodal-codemirror` として提供される。
|
||||
semantic evaluation と completion が必要な場合は `decodal-wasm` の language service と組み合わせる。
|
||||
|
||||
## Editor syntax
|
||||
|
||||
Tree-sitter grammar は、Tree-sitter を採用するエディタで構文解析と highlighting を行うための統合である。
|
||||
Decodal runtime、formatter、LSP の利用には Tree-sitter は必要ない。
|
||||
|
||||
用途ごとの選択は次の通りである。
|
||||
|
||||
- Rust での実行と組み込み: `decodal`
|
||||
- browser での実行と semantic tooling: `decodal-wasm`
|
||||
- CodeMirror 6: `decodal-codemirror`
|
||||
- transport 非依存の Rust language service: `decodal-language-service`
|
||||
- 一般的な editor client: `decodal-lsp`
|
||||
- Tree-sitter 採用 editor の syntax grammar: Tree-sitter integration
|
||||
|
||||
具体的な environment の構築方法は [Embedding](./embedding.md) を参照する。
|
||||
@@ -0,0 +1,193 @@
|
||||
# Embedding
|
||||
|
||||
Decodal runtime は filesystem、network、environment variable を直接読み込まない。
|
||||
ホストは global bindings と import の解決方法を注入し、評価結果を `Data` または application type として受け取る。
|
||||
|
||||
## Rust runtime
|
||||
|
||||
`Engine` は `ImportLoader` と global bindings を持つ。
|
||||
外部 resource を必要としない source には `EmptyLoader` を使える。
|
||||
|
||||
```rust
|
||||
use decodal::{EmptyLoader, Engine, Value};
|
||||
|
||||
let mut engine = Engine::new(EmptyLoader);
|
||||
engine.bind_global(
|
||||
"Service",
|
||||
Value::object([
|
||||
("name", Value::string_type()),
|
||||
("port", Value::int_type().gt(443).default_int(8443)?),
|
||||
("enabled", Value::bool_type().default_bool(true)?),
|
||||
]),
|
||||
)?;
|
||||
|
||||
let module = engine.add_root_source(
|
||||
"service.dcdl",
|
||||
"service.dcdl",
|
||||
r#"{ name = "api"; port = 9443; } as Service"#,
|
||||
)?;
|
||||
let value = engine.eval_module(module)?;
|
||||
let data = engine.materialize(&value)?;
|
||||
```
|
||||
|
||||
`Value` は concrete value と host-defined range の両方を表す公開型である。
|
||||
主な constructor は次の通りである。
|
||||
|
||||
- `Value::string`、`int`、`float`、`bool`、`array`、`object`: concrete value。
|
||||
- `Value::string_type`、`int_type`、`float_type`、`bool_type`: primitive range。
|
||||
- `Value::unknown`: 最上位 range `Unknown`。
|
||||
- `Value::array_of`: 全要素へ同じ range を適用する array range。
|
||||
- `Value::map_of`: 全 field value へ同じ range を適用する associative-array range。
|
||||
- `Value::object_with_rest`: named fields と残りの field range を持つ object。
|
||||
|
||||
## Typed Rust integration
|
||||
|
||||
`derive` feature の `Decodal` derive は、Rust struct から `DecodalSchema` と `DecodalDecode` を生成する。
|
||||
|
||||
```rust
|
||||
use decodal::{Decodal, DecodalDecode, DecodalSchema};
|
||||
|
||||
#[derive(Decodal)]
|
||||
struct Service {
|
||||
name: String,
|
||||
|
||||
#[decodal(gt = 443, default = 8443)]
|
||||
port: i64,
|
||||
|
||||
#[decodal(rename = "feature.enable", default = true)]
|
||||
feature_enabled: bool,
|
||||
}
|
||||
```
|
||||
|
||||
`DecodalSchema::decodal_schema()` は `Engine::bind_global` に渡せる `Value` を返す。
|
||||
materialize 済みの `Data` は `DecodalDecode::decodal_decode` で Rust type に変換できる。
|
||||
|
||||
追加 field を受け取る struct では、map field に `#[decodal(rest)]` を付ける。
|
||||
|
||||
```rust
|
||||
use std::collections::BTreeMap;
|
||||
use decodal::{Data, Decodal};
|
||||
|
||||
#[derive(Decodal)]
|
||||
struct OpenConfig {
|
||||
enabled: bool,
|
||||
|
||||
#[decodal(rest)]
|
||||
extra: BTreeMap<String, Data>,
|
||||
}
|
||||
```
|
||||
|
||||
`BTreeMap<String, Data>` は `...Unknown`、`BTreeMap<String, String>` は `...String` に対応する。
|
||||
named fields は rest map から除外される。
|
||||
`#[decodal(rest)]` は struct ごとに1つだけ指定でき、`rename`、`default`、field constraints とは併用できない。
|
||||
|
||||
## Imports
|
||||
|
||||
`ImportLoader::load` は `LoadedImport::Source` または `LoadedImport::Value` を返す。
|
||||
ホストは specifier の解決、filesystem や他の storage からの読み込み、content type の判定をすべて管理する。
|
||||
|
||||
`LoadedImport::Source` は DCDL source を返す。
|
||||
`LoadedImport::Value` は Markdown、JSON、TOML などをホスト独自の規則で構造化して返す用途に使える。
|
||||
|
||||
```text
|
||||
import "./post.md"
|
||||
-> host reads and parses Markdown
|
||||
-> LoadedImport::Value {
|
||||
key: "content/post.md",
|
||||
value: { frontmatter: {...}, body: "..." }
|
||||
}
|
||||
-> normal Decodal validation and materialization
|
||||
```
|
||||
|
||||
stable `key` は import の同一性と diagnostic の provenance に使われる。
|
||||
構造化した値が Decodal constraint に違反した場合、diagnostic は import key と logical value path、および違反した DCDL constraint の source span を示す。
|
||||
外部形式そのものの parse error と位置情報は loader が報告する。
|
||||
|
||||
## Shared host environment
|
||||
|
||||
`HostEnvironment` は loader の作成と global binding の設定を1つにまとめる。
|
||||
同じ environment を runtime、language service、LSP へ渡すことで、実行時と編集時の評価規則を一致させられる。
|
||||
|
||||
```rust
|
||||
use decodal::{Engine, HostEnvironment};
|
||||
|
||||
struct AppEnvironment;
|
||||
|
||||
impl HostEnvironment for AppEnvironment {
|
||||
type Loader = ContentLoader;
|
||||
|
||||
fn create_loader(&self) -> Self::Loader {
|
||||
ContentLoader::new()
|
||||
}
|
||||
|
||||
fn configure_engine(
|
||||
&self,
|
||||
engine: &mut Engine<Self::Loader>,
|
||||
) -> decodal::Result<()> {
|
||||
engine.bind_global("Site", site_schema())?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
transport 非依存の tooling は `decodal_language_service::LanguageService::new(&environment)` で構築する。
|
||||
LSP integration では `decodal_lsp::LspEnvironment` を実装し、environment factory から server を起動する。
|
||||
|
||||
```rust
|
||||
use decodal_lsp::{LspEnvironment, run_stdio};
|
||||
|
||||
impl LspEnvironment for AppEnvironment {}
|
||||
|
||||
run_stdio(|initialize| {
|
||||
let _ = initialize;
|
||||
Ok(AppEnvironment)
|
||||
})?;
|
||||
```
|
||||
|
||||
factory は server capability の応答前に client の `InitializeParams` を一度受け取る。
|
||||
`LspEnvironment` の document lifecycle hooks を使うと、未保存の DCDL、Markdown、その他の resource を host-owned overlay に反映できる。
|
||||
|
||||
## JavaScript and browser environments
|
||||
|
||||
`decodal-wasm` の `DecodalLanguageService` は filesystem や仮想 project を仮定しない。
|
||||
JavaScript 側が `globals`、`loadImport`、`completeImport` を提供する。
|
||||
|
||||
```js
|
||||
import init, { DecodalLanguageService } from 'decodal-wasm';
|
||||
|
||||
await init();
|
||||
|
||||
const files = {
|
||||
'schema.dcdl': 'Server = { port = Int; };',
|
||||
};
|
||||
|
||||
const service = new DecodalLanguageService({
|
||||
globals: {
|
||||
App: {
|
||||
enabled: { $decodal: 'Bool', default: true },
|
||||
},
|
||||
},
|
||||
loadImport(_currentKey, specifier) {
|
||||
const key = specifier.replace(/^\.\//, '');
|
||||
return { kind: 'source', key, name: key, source: files[key] };
|
||||
},
|
||||
completeImport() {
|
||||
return ['./schema.dcdl'];
|
||||
},
|
||||
});
|
||||
|
||||
const result = service.evaluate('main.dcdl', 'main.dcdl', 'App');
|
||||
```
|
||||
|
||||
JavaScript の primitive、array、plain object は concrete value になる。
|
||||
range は `$decodal` descriptor で指定する。
|
||||
|
||||
- `{ $decodal: 'String' | 'Int' | 'Float' | 'Bool' }`
|
||||
- `{ $decodal: 'Unknown' }`
|
||||
- `{ $decodal: 'Array', item }`
|
||||
- `{ $decodal: 'Map', value }`
|
||||
- `{ $decodal: 'Object', fields, rest }`
|
||||
- `{ $decodal: 'Range', constraints, default }`
|
||||
|
||||
import callbacks は同期 API である。
|
||||
network resource などの非同期入力は、評価の前に preload または cache しておく。
|
||||
@@ -0,0 +1,42 @@
|
||||
# Decodal Manual
|
||||
|
||||
このマニュアルでは、Decodal の言語仕様と、アプリケーションへ組み込むための公開 API を説明する。
|
||||
Decodal は Deferred Constraint Data Language、略称 DCDL のプロジェクト名である。
|
||||
|
||||
## 目次
|
||||
|
||||
1. [Introduction](./introduction.md)
|
||||
2. [Language Specification](./language/index.md)
|
||||
1. [Lexical Structure and Syntax](./language/syntax.md)
|
||||
2. [Grammar](./language/grammar.md)
|
||||
3. [Value](./language/value/index.md)
|
||||
1. [String](./language/value/string.md)
|
||||
2. [Int](./language/value/int.md)
|
||||
3. [Float](./language/value/float.md)
|
||||
4. [Bool](./language/value/bool.md)
|
||||
4. [Expression](./language/expression/index.md)
|
||||
1. [Literal](./language/expression/literal.md)
|
||||
2. [Identifier](./language/expression/identifier.md)
|
||||
3. [Path Reference](./language/expression/path-reference.md)
|
||||
4. [Object](./language/expression/object.md)
|
||||
5. [Array](./language/expression/array.md)
|
||||
6. [Function](./language/expression/function.md)
|
||||
7. [Function Call](./language/expression/function-call.md)
|
||||
8. [Let](./language/expression/let.md)
|
||||
9. [Match](./language/expression/match.md)
|
||||
10. [Import](./language/expression/import.md)
|
||||
11. [Composition](./language/expression/composition.md)
|
||||
12. [Range Refinement](./language/expression/ascription.md)
|
||||
13. [Default](./language/expression/default.md)
|
||||
14. [Arithmetic](./language/expression/arithmetic.md)
|
||||
15. [Logical and Comparison](./language/expression/logical-and-comparison.md)
|
||||
5. [Constraints and Defaults](./language/constraints-and-defaults.md)
|
||||
6. [Operators](./language/operators.md)
|
||||
7. [Functions](./language/functions.md)
|
||||
8. [Modules and Imports](./language/modules-and-imports.md)
|
||||
9. [Evaluation Semantics](./language/evaluation.md)
|
||||
10. [Materialization and Errors](./language/materialization-and-errors.md)
|
||||
11. [Naming](./language/naming.md)
|
||||
12. [Examples](./language/examples.md)
|
||||
3. [Embedding](./embedding.md)
|
||||
4. [Packages and Integrations](./components.md)
|
||||
@@ -0,0 +1,54 @@
|
||||
# Introduction
|
||||
|
||||
Decodal は **Deferred Constraint Data Language**、略称 **DCDL** である。
|
||||
ファイル拡張子には `.dcdl` を使う。
|
||||
|
||||
Decodal は、設定値・スキーマ・制約・派生設定を同じ式体系で記述し、検証済みの構造化データを得るための言語である。
|
||||
|
||||
## 目的
|
||||
|
||||
一般的な設定システムでは、値、スキーマ、デフォルト値、派生設定、バリデーションが別々の仕組みになりやすい。
|
||||
Decodal では、それらを合成可能な式として扱う。
|
||||
|
||||
```dcdl
|
||||
Port = Int & >= 1 & <= 65535;
|
||||
|
||||
Service = {
|
||||
host = String;
|
||||
port = Port default 8080;
|
||||
};
|
||||
|
||||
Config = {
|
||||
host = "127.0.0.1";
|
||||
port = 8000;
|
||||
} as Service;
|
||||
```
|
||||
|
||||
`Service` は許容する値の範囲を表す。
|
||||
`Config` の各値は `Service` によって検証され、`Service` にだけ存在する範囲は抽象的なまま結果へ残る。
|
||||
materialize 時には明示値が優先され、値がない範囲には `default` が使われる。
|
||||
|
||||
## 中心概念
|
||||
|
||||
- 値と制約は同じ式として参照・合成できる。
|
||||
- `&` は両辺の制約を保つ対称な合成を行う。
|
||||
- `as` は左辺が右辺より具体的で狭いことを検証しながら合成する。
|
||||
- `//` は右辺優先の構造的な patch を行う。
|
||||
- `default` は制約ではなく、materialize 時にだけ選ばれる fallback である。
|
||||
- object field、関数引数、import は必要になった時点で評価される。
|
||||
- `Unknown` は任意の具体値を受け入れる最上位 range だが、抽象的なまま materialize はできない。
|
||||
|
||||
## 適用範囲
|
||||
|
||||
Decodal は、設定、スキーマ、制約、派生データの記述に特化している。
|
||||
汎用的な状態変更、時刻・乱数・ネットワークアクセス、例外を値として捕捉する `try / catch` は言語機能に含まれない。
|
||||
filesystem や外部形式の読み込みはホストが提供し、Decodal の評価は同じ source・import 結果・global bindings に対して決定的に動作する。
|
||||
|
||||
正規表現制約は利用する runtime の `regex` feature に依存する。
|
||||
高度な型推論、match の網羅性検査、到達不能分岐の静的検査は提供しない。
|
||||
|
||||
## 次に読む章
|
||||
|
||||
- [Language Specification](./language/index.md): 構文、値、式、制約、評価、materialization。
|
||||
- [Embedding](./embedding.md): Rust・JavaScript からの実行、host environment、structured import、language service。
|
||||
- [Packages and Integrations](./components.md): 用途ごとに選ぶ crate と JavaScript package。
|
||||
@@ -0,0 +1,163 @@
|
||||
# 制約と default
|
||||
|
||||
constraint は、値が満たすべき範囲を表す。
|
||||
|
||||
```dcdl
|
||||
Int
|
||||
String
|
||||
>= 1
|
||||
<= 65535
|
||||
/Hello! .*/
|
||||
```
|
||||
|
||||
constraint は `&` で合成できる。
|
||||
|
||||
```dcdl
|
||||
Port = Int & >= 1 & <= 65535;
|
||||
NarrowedPort = Port & > 443;
|
||||
```
|
||||
|
||||
合成結果は両辺を同時に満たす範囲になる。
|
||||
両立しない constraint は conflict になる。
|
||||
|
||||
```dcdl
|
||||
Int & String # conflict
|
||||
> 10 & < 5 # conflict
|
||||
Int & > 10 & < 11 # conflict: integer candidate does not exist
|
||||
```
|
||||
|
||||
## Primitive and comparison constraints
|
||||
|
||||
組み込みの primitive range は次の通りである。
|
||||
|
||||
```dcdl
|
||||
String
|
||||
Int
|
||||
Float
|
||||
Bool
|
||||
```
|
||||
|
||||
異なる primitive type を `&` で合成すると conflict になる。
|
||||
数値比較 constraint は上下限として合成され、空の範囲になる場合は conflict になる。
|
||||
|
||||
```dcdl
|
||||
Int & >= 1 & <= 65535 & > 443
|
||||
```
|
||||
|
||||
`Int` の比較 constraint は integer literal を使う。
|
||||
`Float` の比較 constraint は integer または float literal を使える。
|
||||
|
||||
## Unknown
|
||||
|
||||
`Unknown` はすべての Decodal value を含む最上位 range である。
|
||||
検査を無効化して具体値の情報を消す `Any` ではなく、値の範囲がまだ絞られていないことを表す。
|
||||
|
||||
```dcdl
|
||||
Int & Unknown # Int
|
||||
42 as Unknown # 42
|
||||
Unknown as Int # conflict
|
||||
```
|
||||
|
||||
`Unknown` 自体は concrete value を持たないため materialize できない。
|
||||
concrete value で絞り込むか `default` を指定する必要がある。
|
||||
|
||||
```dcdl
|
||||
Unknown default {}
|
||||
```
|
||||
|
||||
## Regex constraints
|
||||
|
||||
regex literal は string constraint である。
|
||||
|
||||
```dcdl
|
||||
Host = /^api-[0-9]+$/;
|
||||
```
|
||||
|
||||
複数の regex constraint を合成した場合、concrete string はすべてに一致する必要がある。
|
||||
|
||||
```dcdl
|
||||
String & /^a/ & /z$/
|
||||
```
|
||||
|
||||
regex constraint 同士の交差は合成時には判定されない。
|
||||
そのため、次の範囲は合成時には conflict にならず、concrete value の検証時に失敗する。
|
||||
|
||||
```dcdl
|
||||
String & /^a$/ & /^b$/
|
||||
```
|
||||
|
||||
Rust runtime では regex engine を `regex` feature で有効にする。
|
||||
feature が無効な場合、regex constraint の concrete value 検証は unsupported feature diagnostic になる。
|
||||
|
||||
## Array constraints
|
||||
|
||||
array constraint は `[...T]` と書き、すべての要素へ `T` を適用する。
|
||||
要素 constraint は必須である。
|
||||
|
||||
```dcdl
|
||||
Names = [...String];
|
||||
PositiveInts = [...(Int & > 0)];
|
||||
```
|
||||
|
||||
concrete array と合成した場合、各要素は `T` に対して `as` と同じ規則で絞り込まれる。
|
||||
空 array は任意の array constraint を満たす。
|
||||
|
||||
要素 constraint が object range の場合、右辺にだけある field は abstract のまま各要素へ残る。
|
||||
左辺にしかない field は右辺の field domain 外なので conflict になる。
|
||||
|
||||
## Associative-array and object rest constraints
|
||||
|
||||
associative-array constraint は `{...T}` と書き、object の任意の field value へ `T` を適用する。
|
||||
|
||||
```dcdl
|
||||
Services = {...{
|
||||
port = Int;
|
||||
enabled = Bool default true;
|
||||
}};
|
||||
```
|
||||
|
||||
key は列挙されず、空 object も許容される。
|
||||
named field を持つ object の末尾へ `...T` を書くと、列挙されていない field だけに `T` を適用できる。
|
||||
|
||||
```dcdl
|
||||
{
|
||||
enabled = Bool default true;
|
||||
...Unknown
|
||||
}
|
||||
```
|
||||
|
||||
rest constraint は field を生成しない。
|
||||
実在する追加 field の検証にだけ使われる。
|
||||
|
||||
## default
|
||||
|
||||
`default` は constraint ではない。
|
||||
materialize 時に concrete value がない場合だけ使われる fallback である。
|
||||
|
||||
```dcdl
|
||||
Port = Int & >= 1 & <= 65535;
|
||||
|
||||
Service = {
|
||||
port = Port default 8080;
|
||||
};
|
||||
```
|
||||
|
||||
明示値が合成された場合は明示値が使われ、`default` は評価されない。
|
||||
|
||||
```dcdl
|
||||
Config = {
|
||||
port = 9000;
|
||||
} as Service;
|
||||
```
|
||||
|
||||
明示値がない場合、materialize 時に `8080` が採用され、`Port` を満たすか検証される。
|
||||
|
||||
## default composition
|
||||
|
||||
- `&` で片方だけが `default` を持つ場合、その `default` は保持される。
|
||||
- `&` で両辺が異なる `default` を持つ場合は conflict になる。
|
||||
- constraint と concrete value の `&` が成功した場合、結果は concrete value になり `default` は残らない。
|
||||
- `//` は右辺優先なので、同じ field では右辺の値または `default` が左辺を置き換える。
|
||||
- `as` は右辺の `default` を左辺へ注入しない。ただし右辺にだけ存在する field は、その field が持つ `default` とともに abstract なまま結果へ残る。
|
||||
|
||||
`default` expression は materialize 時に必要になった時点で評価され、同じ range の constraint を満たす必要がある。
|
||||
@@ -0,0 +1,48 @@
|
||||
# 遅延評価
|
||||
|
||||
Decodal は値を必要になった時点で評価する。
|
||||
|
||||
## 遅延評価される値
|
||||
|
||||
次の値は参照または materialize されるまで評価されない。
|
||||
|
||||
- module の root と top-level field
|
||||
- object field
|
||||
- `let` binding
|
||||
- function argument
|
||||
- `default` expression
|
||||
- import 先の値
|
||||
|
||||
同じ binding を複数回参照した場合、その評価結果は再利用される。
|
||||
このため、未参照の field や function argument にある失敗は、値が必要になるまで発生しない。
|
||||
|
||||
```dcdl
|
||||
let
|
||||
safe = 42;
|
||||
unused = missing_name;
|
||||
in
|
||||
safe
|
||||
```
|
||||
|
||||
この式は `unused` を参照しないため `42` になる。
|
||||
|
||||
## 循環検出
|
||||
|
||||
評価中の値が自身へ再び依存した場合は cycle diagnostic になる。
|
||||
|
||||
```dcdl
|
||||
{
|
||||
a = b + 1;
|
||||
b = a + 1;
|
||||
}
|
||||
```
|
||||
|
||||
module や import の参照関係自体が循環していても、実際に評価される field の依存関係が循環していなければ評価できる。
|
||||
|
||||
## 評価と materialize
|
||||
|
||||
通常の評価結果には、constraint、`Unknown`、`default`、function などの abstract value が残り得る。
|
||||
外部へ concrete data として取り出すときに materialize を行う。
|
||||
|
||||
この分離により、schema を値として合成し、必要な field だけを評価し、`default` の選択を出力時まで遅らせられる。
|
||||
詳細は [materialize とエラー](./materialization-and-errors.md) を参照する。
|
||||
@@ -1,11 +1,11 @@
|
||||
# 例
|
||||
|
||||
この章には、仕様を説明するための例を置く。
|
||||
この章では、Decodal の主要な記法を組み合わせた例を示す。
|
||||
|
||||
## 基本的な設定スキーマ
|
||||
|
||||
```dcdl
|
||||
Host = IPv4Address;
|
||||
Host = String;
|
||||
|
||||
Port = Int & >= 1 & <= 65535;
|
||||
NarrowedPort = Port & > 443;
|
||||
@@ -144,23 +144,23 @@ Patched = Base // {
|
||||
## 循環 import
|
||||
|
||||
```dcdl
|
||||
# main.n
|
||||
# main.dcdl
|
||||
{
|
||||
schema = {
|
||||
hoge = String;
|
||||
};
|
||||
|
||||
result = (import ./func.n)(schema);
|
||||
result = (import "./func.dcdl")(schema);
|
||||
}
|
||||
```
|
||||
|
||||
```dcdl
|
||||
# func.n
|
||||
(input: (import ./main.n).schema) =>
|
||||
# func.dcdl
|
||||
(input: (import "./main.dcdl").schema) =>
|
||||
{
|
||||
# ...
|
||||
}
|
||||
```
|
||||
|
||||
`func.n` は `main.n` を import しているが、参照しているのは `main.schema` である。
|
||||
`func.dcdl` は `main.dcdl` を import しているが、参照しているのは `main.schema` である。
|
||||
`main.schema` が `main.result` に依存していなければ、この循環 import は成立する。
|
||||
@@ -0,0 +1,43 @@
|
||||
# 算術式
|
||||
|
||||
Decodal は具体的な数値に対する算術演算をサポートする。
|
||||
|
||||
```dcdl
|
||||
{
|
||||
workers = 2 + 2;
|
||||
timeout = 30.0 / 2;
|
||||
port = 8000 + 80;
|
||||
negative = -1;
|
||||
}
|
||||
```
|
||||
|
||||
## 演算子
|
||||
|
||||
- `+`: 加算
|
||||
- `-`: 減算
|
||||
- `*`: 乗算
|
||||
- `/`: 除算
|
||||
- 単項 `-`: 符号反転
|
||||
|
||||
`*` と `/` は `+` と `-` より高い優先順位を持つ。
|
||||
括弧を使ってグループ化を明示できる。
|
||||
|
||||
```dcdl
|
||||
2 + 3 * 4 # 14
|
||||
(2 + 3) * 4 # 20
|
||||
```
|
||||
|
||||
## 数値の扱い
|
||||
|
||||
算術演算には具体的な `Int` または `Float` の operand が必要である。
|
||||
`Int + Int`、`Int - Int`、`Int * Int` は、overflow が発生しない場合に `Int` を返す。
|
||||
`Int` と `Float` が混在する演算は `Float` を返す。
|
||||
除算は常に `Float` を返す。
|
||||
|
||||
ゼロ除算と整数 overflow は評価エラーになる。
|
||||
|
||||
算術式は、default や数値制約を含め、具体的な数値式が必要な任意の場所で使える。
|
||||
|
||||
```dcdl
|
||||
port = Int & > 4000 + 42 default 8080;
|
||||
```
|
||||
+1
-1
@@ -49,7 +49,7 @@ object の要素 range では左辺にしかない field がエラーになり
|
||||
要素制約のない抽象配列型は提供しない。
|
||||
旧来の `Array` primitive type は使用できず、`[...T]` の `T` は必須である。
|
||||
`[String]` は配列制約ではなく、未解決の `String` 制約を 1 要素に持つ concrete array になる。
|
||||
長さ制約、位置別の tuple 制約、unique 制約は現在サポートしない。
|
||||
配列制約は要素範囲だけを表す。長さ制約、位置別の tuple 制約、unique 制約は持たない。
|
||||
|
||||
## Array concat
|
||||
|
||||
+1
-1
@@ -60,7 +60,7 @@ primitive constraint や合成 constraint は通常どおり値を検証する
|
||||
右辺が concrete scalar または array literal の場合は、左辺も同じ値または同じ長さ・要素構造である必要がある。
|
||||
function は右辺の範囲として使用できない。
|
||||
|
||||
左辺は concrete value に限らない。処理系が包含を確認できる constraint 同士であれば abstract value も使用できる。primitive type、numeric bound、同一 regex / predicate、array/map の要素範囲は包含確認の対象になる。
|
||||
左辺は concrete value に限らない。包含関係を判定できる constraint 同士であれば abstract value も使用できる。primitive type、numeric bound、同一 regex / predicate、array/map の要素範囲は包含確認の対象になる。
|
||||
|
||||
関数 parameter の `name: range` も、引数が force された時点で `as` と同じ絞り込み規則を使う。
|
||||
|
||||
+1
-1
@@ -24,4 +24,4 @@ Patched = Base // {
|
||||
};
|
||||
```
|
||||
|
||||
詳細は [合成演算子](../operators.md) に置く。
|
||||
詳細は [合成演算子](../operators.md) を参照する。
|
||||
@@ -0,0 +1,15 @@
|
||||
# Default Expression
|
||||
|
||||
`default` expression は、明示値が存在しない場合に materialize 時に採用される fallback を指定する。
|
||||
|
||||
```dcdl
|
||||
port = Int default 8080;
|
||||
```
|
||||
|
||||
`default` は制約ではない。
|
||||
詳細は [制約と default](../constraints-and-defaults.md) を参照する。
|
||||
|
||||
## 評価
|
||||
|
||||
fallback expression は materialize 時に必要になった場合だけ評価される。
|
||||
明示値がある場合、`default` は評価も採用もされない。
|
||||
+2
-5
@@ -8,10 +8,7 @@ increment(41)
|
||||
|
||||
## 評価
|
||||
|
||||
引数は thunk として渡せる。
|
||||
関数本体内で引数が参照されたときに評価する。
|
||||
引数は関数本体から参照された時点で評価される。
|
||||
同じ引数を複数回参照した場合は評価結果が再利用される。
|
||||
parameter に range が指定されている場合、引数は `narrower as wider` と同じ規則で絞り込まれる。
|
||||
parameter 側だけにある field は abstract のまま残り、default はこの時点では選択されない。
|
||||
|
||||
関数呼び出し結果そのものはグローバルには memoize しない。
|
||||
フィールドに束縛された呼び出し結果は、そのフィールド thunk の評価結果として memoize される。
|
||||
+2
-2
@@ -6,9 +6,9 @@ function expression は、引数を受け取り式を返す値である。
|
||||
(value: Int) => value + 1
|
||||
```
|
||||
|
||||
関数仕様の詳細は [関数](../functions.md) に置く。
|
||||
関数仕様の詳細は [関数](../functions.md) を参照する。
|
||||
|
||||
## 評価
|
||||
|
||||
関数は定義時の環境を参照として保持する。
|
||||
関数は定義された lexical scope の bindings を参照する。
|
||||
関数本体は、関数値の生成時ではなく呼び出し時に評価される。
|
||||
@@ -0,0 +1,14 @@
|
||||
# Identifier Expression
|
||||
|
||||
identifier expression は、lexical scope に束縛された名前を参照する式である。
|
||||
|
||||
```dcdl
|
||||
Port
|
||||
MyConfig
|
||||
mkConfig
|
||||
```
|
||||
|
||||
## 評価
|
||||
|
||||
識別子は対応する binding の値を必要になった時点で評価する。
|
||||
束縛が存在しない場合は未定義識別子エラーになる。
|
||||
@@ -0,0 +1,14 @@
|
||||
# Import Expression
|
||||
|
||||
import expression は、ホストが解決した DCDL module または structured value を返す。
|
||||
|
||||
```dcdl
|
||||
import "./config.dcdl"
|
||||
```
|
||||
|
||||
specifier は string literal であり、path や resource name としての解釈はホストが定義する。
|
||||
詳しくは [モジュールと import](../modules-and-imports.md) を参照する。
|
||||
|
||||
## 評価
|
||||
|
||||
import 先は遅延評価され、参照されない field は評価されない。
|
||||
+1
-2
@@ -20,8 +20,7 @@ Expr
|
||||
├─ import
|
||||
├─ composition
|
||||
├─ range refinement (`as`)
|
||||
├─ default
|
||||
└─ string interpolation
|
||||
└─ default
|
||||
```
|
||||
|
||||
各式の個別仕様へのリンクは [Manual Index](../../index.md) に集約する。
|
||||
@@ -0,0 +1,16 @@
|
||||
# Let Expression
|
||||
|
||||
let expression は、ローカル束縛を作る。
|
||||
|
||||
```dcdl
|
||||
let
|
||||
base = 8000;
|
||||
offset = 80;
|
||||
in
|
||||
base + offset
|
||||
```
|
||||
|
||||
## 評価
|
||||
|
||||
binding は参照された時点で評価される。
|
||||
参照されない binding は評価されず、同じ binding を複数回参照した場合は評価結果が再利用される。
|
||||
@@ -0,0 +1,41 @@
|
||||
# 論理式と比較式
|
||||
|
||||
Decodal は具体的な `Bool` に対する論理演算と、具体的な scalar value に対する比較をサポートする。
|
||||
|
||||
```dcdl
|
||||
{
|
||||
is_prod = env == "prod";
|
||||
high_port = port > 9000;
|
||||
enabled = is_prod && high_port;
|
||||
disabled = !enabled;
|
||||
}
|
||||
```
|
||||
|
||||
## 論理演算子
|
||||
|
||||
- `!expr` は具体的な `Bool` を反転する。
|
||||
- `lhs && rhs` は論理積を返す。
|
||||
- `lhs || rhs` は論理和を返す。
|
||||
|
||||
`&&` と `||` は短絡評価され、右辺は必要な場合にだけ評価される。
|
||||
論理演算の operand は具体的な `Bool` へ評価される必要がある。
|
||||
|
||||
## 比較演算子
|
||||
|
||||
- `==`
|
||||
- `!=`
|
||||
- `<`
|
||||
- `<=`
|
||||
- `>`
|
||||
- `>=`
|
||||
|
||||
`==` と `!=` は、`String`、`Bool`、`Int`、`Float` の具体的な scalar value を比較する。
|
||||
`Int` と `Float` は数値として相互に比較できる。
|
||||
|
||||
順序比較演算子 `<`、`<=`、`>`、`>=` は、具体的な数値だけを比較する。
|
||||
これらは `> 443` のような prefix comparison constraint とは別のものである。
|
||||
|
||||
```dcdl
|
||||
port = Int & > 443 default 9443;
|
||||
is_high = port > 9000;
|
||||
```
|
||||
+24
-2
@@ -50,7 +50,7 @@ Services = {...{
|
||||
```
|
||||
|
||||
`{...T}` は key の集合を固定せず、すべての value が `T` を満たす object を表す。
|
||||
空 object も許容される。runtime と materialize 後の表現は通常の object と共通であり、別の map value variant は持たない。
|
||||
空 object も許容される。materialize 後は named fields を持つ object と同じ object data になる。
|
||||
|
||||
```dcdl
|
||||
services = {
|
||||
@@ -63,4 +63,26 @@ services = {
|
||||
右辺にしかない field は default の有無にかかわらず abstract のまま残る。
|
||||
host から渡した object は識別子構文に収まらない文字列 key も保持できるが、DCDL source の object field name は通常の識別子に限られる。
|
||||
|
||||
固定 field と任意 key を一つの object schema に混在させる rest-field 構文は、現在サポートしない。
|
||||
## Object rest constraint
|
||||
|
||||
固定 field と任意 key の value range は、一つの object に混在できる。
|
||||
|
||||
```dcdl
|
||||
OpenConfig = {
|
||||
enabled = Bool default true;
|
||||
...Unknown
|
||||
};
|
||||
```
|
||||
|
||||
`...T` は明示されていない残余 field にだけ適用する。明示 field にはそれぞれの field range を適用し、rest range を重ねて適用しない。
|
||||
rest constraint は field を生成せず、materialize 時には実際に存在する追加 field だけを出力する。
|
||||
|
||||
```dcdl
|
||||
{
|
||||
enabled = false;
|
||||
plugin = { name = "cache"; };
|
||||
} as OpenConfig
|
||||
```
|
||||
|
||||
`...T` は object の末尾に一つだけ書ける。省略した object は閉じており、`as` の左辺に未宣言 field があればエラーになる。
|
||||
named field を持たない `{...T}` は abstract な map constraint であり、単独で materialize するには `default` または concrete value が必要になる。
|
||||
+1
-1
@@ -13,4 +13,4 @@ config.feature_hoge.enable
|
||||
参照先 field は必要になるまで評価されない。
|
||||
|
||||
存在しない field への参照は diagnostic になる。
|
||||
Decodal は unknown / Any のような値を伝播せず、field の有無を曖昧にしない。
|
||||
明示的な `Unknown` range は存在しないfieldを表さないため、fieldの有無を曖昧にはしない。
|
||||
@@ -0,0 +1,41 @@
|
||||
# 関数
|
||||
|
||||
関数は値を受け取り、値を返す純粋な式である。
|
||||
|
||||
## 構文
|
||||
|
||||
```dcdl
|
||||
(value: Int) => value + 1
|
||||
```
|
||||
|
||||
関数呼び出しは通常の呼び出し構文で行う。
|
||||
|
||||
```dcdl
|
||||
let
|
||||
increment = (value: Int) => value + 1;
|
||||
in
|
||||
increment(41)
|
||||
```
|
||||
|
||||
複数の parameter を指定できる。
|
||||
|
||||
```dcdl
|
||||
(input_a: { hoge = Int & >= 0; }, input_b: { fuga = Int; }) =>
|
||||
{
|
||||
hoge = input_a.hoge;
|
||||
fuga = input_b.fuga;
|
||||
}
|
||||
```
|
||||
|
||||
parameter range は省略できる。
|
||||
range がある場合、引数は参照された時点で `as` と同じ規則によって検証・絞り込みされる。
|
||||
|
||||
## Scope and evaluation
|
||||
|
||||
関数は lexical scope を持ち、定義された場所の bindings を参照する。
|
||||
引数は遅延評価され、関数本体から参照されない引数は評価されない。
|
||||
再帰的な field または argument の依存は cycle diagnostic になる。
|
||||
|
||||
関数は中間値として参照・呼び出しできるが、data として materialize できない。
|
||||
未適用の関数が materialize 対象に残っている場合は diagnostic になる。
|
||||
関数値同士の等価性は定義されず、`&` で関数値同士を合成すると conflict になる。
|
||||
@@ -0,0 +1,113 @@
|
||||
# 文法
|
||||
|
||||
このページでは、Decodal ソーステキストの文法を定義する。
|
||||
|
||||
## 字句文法
|
||||
|
||||
```ebnf
|
||||
source_character = ? any Unicode scalar value ? ;
|
||||
newline = "\n" | "\r\n" | "\r" ;
|
||||
space = " " | "\t" | newline ;
|
||||
comment = "#" , { ? any character except newline ? } ;
|
||||
|
||||
digit = "0" … "9" ;
|
||||
letter = "A" … "Z" | "a" … "z" ;
|
||||
identifier = letter , { letter | digit | "_" } ;
|
||||
|
||||
integer = digit , { digit } ;
|
||||
float = digit , { digit } , "." , digit , { digit } ;
|
||||
|
||||
string = '"' , { string_character | escape } , '"' ;
|
||||
string_character = ? any character except '"', "\\", or newline ? ;
|
||||
escape = "\\" , source_character ;
|
||||
|
||||
regex = "/" , regex_character , { regex_character } , "/" ;
|
||||
regex_character = escape | ? any character except "/", "\\", or newline ? ;
|
||||
```
|
||||
|
||||
空白とコメントは token を区切り、それ以外では parser に無視される。
|
||||
|
||||
## 構文文法
|
||||
|
||||
```ebnf
|
||||
module = { statement } ;
|
||||
statement = field_definition , [ ";" ]
|
||||
| expression , [ ";" ] ;
|
||||
|
||||
expression = as_expression ;
|
||||
|
||||
as_expression = default_expression , { "as" , default_expression } ;
|
||||
default_expression = patch_expression , [ "default" , default_expression ] ;
|
||||
patch_expression = compose_expression , { "//" , compose_expression } ;
|
||||
compose_expression = logical_or_expression , { "&" , logical_or_expression } ;
|
||||
|
||||
logical_or_expression = logical_and_expression , { "||" , logical_and_expression } ;
|
||||
logical_and_expression = comparison_expression , { "&&" , comparison_expression } ;
|
||||
comparison_expression = concat_expression , [ comparison_operator , concat_expression ] ;
|
||||
concat_expression = additive_expression , { "++" , additive_expression } ;
|
||||
additive_expression = multiplicative_expression , { ( "+" | "-" ) , multiplicative_expression } ;
|
||||
multiplicative_expression = unary_expression , { ( "*" | "/" ) , unary_expression } ;
|
||||
|
||||
unary_expression = [ "!" | "-" ] , postfix_expression ;
|
||||
postfix_expression = primary_expression , { call_suffix | path_suffix } ;
|
||||
call_suffix = "(" , [ argument_list ] , ")" ;
|
||||
path_suffix = "." , identifier ;
|
||||
|
||||
primary_expression = literal
|
||||
| identifier
|
||||
| comparison_constraint
|
||||
| map_constraint
|
||||
| object
|
||||
| array_constraint
|
||||
| array
|
||||
| let_expression
|
||||
| function_expression
|
||||
| match_expression
|
||||
| import_expression
|
||||
| "(" , expression , ")" ;
|
||||
|
||||
literal = string | integer | float | "true" | "false" | regex ;
|
||||
comparison_operator = "==" | "!=" | "<" | "<=" | ">" | ">=" ;
|
||||
comparison_constraint = ( "<" | "<=" | ">" | ">=" ) , expression ;
|
||||
|
||||
object = "{" , [ field_definition , { ";" , field_definition }
|
||||
, [ ";" , object_rest ] , [ ";" ] ] , "}" ;
|
||||
object_rest = "..." , expression ;
|
||||
map_constraint = "{" , "..." , expression , "}" ;
|
||||
field_definition = field_path , "=" , expression ;
|
||||
field_path = identifier , { "." , identifier } ;
|
||||
|
||||
array = "[" , [ expression , { "," , expression } , [ "," ] ] , "]" ;
|
||||
array_constraint = "[" , "..." , expression , [ "," ] , "]" ;
|
||||
|
||||
let_expression = "let" , { field_definition , ";" } , "in" , expression ;
|
||||
function_expression = "(" , [ parameter_list ] , ")" , "=>" , expression ;
|
||||
parameter_list = parameter , { "," , parameter } , [ "," ] ;
|
||||
parameter = identifier , [ ":" , expression ] ;
|
||||
|
||||
match_expression = "match" , expression , "{" , [ match_arm , { ";" , match_arm } , [ ";" ] ] , "}" ;
|
||||
match_arm = pattern , ":" , expression ;
|
||||
pattern = "_" | expression ;
|
||||
|
||||
import_expression = "import" , string ;
|
||||
argument_list = expression , { "," , expression } , [ "," ] ;
|
||||
```
|
||||
|
||||
## 優先順位
|
||||
|
||||
優先順位は高い順に以下の通りである。
|
||||
|
||||
1. 関数呼び出しとフィールドのパス参照
|
||||
2. 単項 `!` と `-`
|
||||
3. `*` と `/`
|
||||
4. `+` と `-`
|
||||
5. `++`
|
||||
6. `==`、`!=`、`<`、`<=`、`>`、`>=`
|
||||
7. `&&`
|
||||
8. `||`
|
||||
9. `&`
|
||||
10. `//`
|
||||
11. `default`
|
||||
12. `as`
|
||||
|
||||
二項演算子は左結合だが、`default` だけは右結合である。
|
||||
@@ -0,0 +1,12 @@
|
||||
# 言語仕様
|
||||
|
||||
この章では、Decodal source の構文と評価結果を決める規則を説明する。
|
||||
|
||||
- syntax と grammar
|
||||
- primitive、object、array、function
|
||||
- constraint、`Unknown`、`default`
|
||||
- `&`、`//`、`as` とその他の operators
|
||||
- module、import、lazy evaluation
|
||||
- materialization と diagnostics
|
||||
|
||||
章の一覧は [Manual Index](../index.md) を参照する。
|
||||
@@ -0,0 +1,73 @@
|
||||
# materialize とエラー
|
||||
|
||||
通常の評価結果には constraint、`default`、function などが残り得る。
|
||||
materialize は評価結果を外部へ渡せる concrete data に変換する。
|
||||
|
||||
## materialize の規則
|
||||
|
||||
materialize は次の処理を行う。
|
||||
|
||||
- 必要な field を評価する。
|
||||
- 明示値のない abstract range に `default` を適用する。
|
||||
- concrete value と採用した `default` が constraint を満たすか検証する。
|
||||
- `default` のない `Unknown` や他の未解決 range を拒否する。
|
||||
- 未適用の function など、data に変換できない値を拒否する。
|
||||
|
||||
```dcdl
|
||||
Service = {
|
||||
host = String;
|
||||
port = Int default 8080;
|
||||
};
|
||||
```
|
||||
|
||||
`Service` をそのまま materialize すると、`host` に concrete value も `default` もないため失敗する。
|
||||
|
||||
```dcdl
|
||||
Config = {
|
||||
host = "localhost";
|
||||
} as Service;
|
||||
```
|
||||
|
||||
`Config` を materialize すると次の data になる。
|
||||
|
||||
```dcdl
|
||||
{
|
||||
host = "localhost";
|
||||
port = 8080;
|
||||
}
|
||||
```
|
||||
|
||||
明示値がある field では `default` は採用されない。
|
||||
|
||||
## Diagnostics
|
||||
|
||||
エラーは通常の値ではなく diagnostic として返される。
|
||||
式は diagnostic の種類や内容に基づいて分岐できない。
|
||||
|
||||
代表的な diagnostic は次の通りである。
|
||||
|
||||
- syntax error
|
||||
- unresolved identifier または field
|
||||
- type mismatch と constraint violation
|
||||
- `&` または `default` の conflict
|
||||
- cycle dependency
|
||||
- import failure
|
||||
- match failure
|
||||
- materialization failure
|
||||
|
||||
diagnostic は問題のある DCDL source span を示す。
|
||||
複数の式が conflict した場合は、関係する field、constraint、value、`default` の位置も示される。
|
||||
structured import の値に source span がない場合は、host が返した stable key と logical value path が示される。
|
||||
|
||||
## Fallback
|
||||
|
||||
`match` に fallback arm がなく、どの arm にも一致しない場合は diagnostic になる。
|
||||
|
||||
```dcdl
|
||||
match value {
|
||||
>= 10: "large";
|
||||
}
|
||||
```
|
||||
|
||||
Decodal は diagnostic を捕捉する汎用 `try / catch`、optional import、optional field access を提供しない。
|
||||
値がない場合の fallback は `default`、有限の値分岐は `match` で表現する。
|
||||
@@ -0,0 +1,88 @@
|
||||
# モジュールと import
|
||||
|
||||
`import` はホストが解決した DCDL module または structured value を返す。
|
||||
|
||||
## 構文
|
||||
|
||||
```dcdl
|
||||
import "./config.dcdl"
|
||||
```
|
||||
|
||||
import specifier は string literal である。
|
||||
specifier が path、URL、resource name のどれを表すかはホストが決める。
|
||||
|
||||
## モジュール
|
||||
|
||||
top-level に field 定義列を書いた module は recursive module scope を作る。
|
||||
top-level field は同じ module の他の top-level field から identifier として参照できる。
|
||||
|
||||
```dcdl
|
||||
schema = {
|
||||
name = String;
|
||||
};
|
||||
|
||||
result = schema;
|
||||
```
|
||||
|
||||
通常の object literal の field は sibling field を identifier として暗黙参照しない。
|
||||
object 内の値を参照する場合は、外側で束縛された値または明示的な path reference を使う。
|
||||
|
||||
module とその field は遅延評価される。
|
||||
import した module の未参照 field は評価されない。
|
||||
|
||||
## Host-defined resolution
|
||||
|
||||
Decodal は import specifier に対する filesystem や network の規則を定義しない。
|
||||
ホストが import 元の module と specifier を受け取り、次のどちらかを返す。
|
||||
|
||||
- DCDL source
|
||||
- ホストが構築した structured value
|
||||
|
||||
後者を使うと、Markdown、JSON、TOML などをホスト独自の規則で構造化し、通常の Decodal value として扱える。
|
||||
|
||||
```dcdl
|
||||
Post = {
|
||||
frontmatter = {
|
||||
title = String;
|
||||
draft = Bool default false;
|
||||
};
|
||||
body = String;
|
||||
};
|
||||
|
||||
post = (import "./hello.md") as Post;
|
||||
```
|
||||
|
||||
structured value も path reference、composition、constraint validation、materialization では DCDL source 由来の値と同じ規則に従う。
|
||||
loader API と diagnostic provenance は [Embedding](../embedding.md#imports) を参照する。
|
||||
|
||||
## 循環 import
|
||||
|
||||
module 間に循環参照があっても、実際に評価される field の依存関係が循環していなければ成功する。
|
||||
|
||||
```dcdl
|
||||
# main.dcdl
|
||||
schema = {
|
||||
name = String;
|
||||
};
|
||||
|
||||
result = (import "./func.dcdl")(schema);
|
||||
```
|
||||
|
||||
```dcdl
|
||||
# func.dcdl
|
||||
(input: (import "./main.dcdl").schema) => input
|
||||
```
|
||||
|
||||
この例で `func.dcdl` は `main.dcdl` を import するが、参照する `schema` は `result` に依存しないため評価できる。
|
||||
評価中の同じ field へ再び到達した場合は循環依存の diagnostic になる。
|
||||
|
||||
## import の失敗
|
||||
|
||||
次の状態は import failure になる。
|
||||
|
||||
- ホストが specifier を解決できない。
|
||||
- resource を読み込めない。
|
||||
- DCDL source の構文解析に失敗する。
|
||||
- 必要な import 先の値を評価できない。
|
||||
- structured value の読み込みまたは変換に失敗する。
|
||||
- 評価対象の依存関係が循環する。
|
||||
@@ -0,0 +1,17 @@
|
||||
# 命名規約
|
||||
|
||||
identifier の大文字・小文字に言語上の意味はない。
|
||||
値、constraint、schema、派生設定はいずれも同じ式として扱われる。
|
||||
|
||||
読みやすさのため、次の命名を推奨する。
|
||||
|
||||
- object value: `lower_snake`
|
||||
- function: `lowerCamel`
|
||||
- primitive、schema、抽象的な constraint: `UpperCamel`
|
||||
|
||||
```dcdl
|
||||
Port = Int & >= 1;
|
||||
Service = { port = Port; };
|
||||
service = { port = 8080; } as Service;
|
||||
mkService = (port: Port) => { port = port; };
|
||||
```
|
||||
@@ -58,7 +58,7 @@ host = "127.0.0.1"; # trailing comment
|
||||
## 識別子
|
||||
|
||||
識別子は ASCII 英字で始まり、ASCII 英数字または `_` を続けられる。
|
||||
慣習としては `lower_snake`、`lowerCamel`、`UpperCamel` を使える想定とする。
|
||||
命名規則には `lower_snake`、`lowerCamel`、`UpperCamel` を使用できる。
|
||||
|
||||
```dcdl
|
||||
my_config
|
||||
+2
-1
@@ -12,7 +12,8 @@ enable = Bool default true;
|
||||
tags = [...String];
|
||||
```
|
||||
|
||||
現在の primitive type は `String`、`Int`、`Float`、`Bool` である。
|
||||
primitive type は `String`、`Int`、`Float`、`Bool` である。
|
||||
`Unknown` はprimitive typeではなく、すべてのDecodal値を含む最上位の抽象rangeである。具体値またはdefaultがない `Unknown` はmaterializeできない。
|
||||
配列は primitive type ではなく、必須の要素制約を持つ `[...T]` で表現する。
|
||||
各型の個別仕様へのリンクは [Manual Index](../../index.md) に集約する。
|
||||
|
||||
+9
@@ -2,6 +2,15 @@
|
||||
|
||||
`String` は文字列値を表す primitive type constraint である。
|
||||
|
||||
文字列リテラルは `"` で囲む。
|
||||
|
||||
```dcdl
|
||||
"hello"
|
||||
"line 1\nline 2"
|
||||
```
|
||||
|
||||
文字列内の `$` や `{}` に特別な意味はなく、文字列補間は行わない。
|
||||
|
||||
## 例
|
||||
|
||||
```dcdl
|
||||
@@ -0,0 +1,163 @@
|
||||
# Constraints and Defaults
|
||||
|
||||
A constraint describes a range that a value must satisfy.
|
||||
|
||||
```dcdl
|
||||
Int
|
||||
String
|
||||
>= 1
|
||||
<= 65535
|
||||
/Hello! .*/
|
||||
```
|
||||
|
||||
Constraints can be composed with `&`.
|
||||
|
||||
```dcdl
|
||||
Port = Int & >= 1 & <= 65535;
|
||||
NarrowedPort = Port & > 443;
|
||||
```
|
||||
|
||||
The result is the range that satisfies both sides.
|
||||
Incompatible constraints produce a conflict.
|
||||
|
||||
```dcdl
|
||||
Int & String # conflict
|
||||
> 10 & < 5 # conflict
|
||||
Int & > 10 & < 11 # conflict: integer candidate does not exist
|
||||
```
|
||||
|
||||
## Primitive and comparison constraints
|
||||
|
||||
The built-in primitive ranges are:
|
||||
|
||||
```dcdl
|
||||
String
|
||||
Int
|
||||
Float
|
||||
Bool
|
||||
```
|
||||
|
||||
Composing different primitive types with `&` produces a conflict.
|
||||
Numeric comparison constraints combine as bounds and conflict if they form an empty range.
|
||||
|
||||
```dcdl
|
||||
Int & >= 1 & <= 65535 & > 443
|
||||
```
|
||||
|
||||
Comparison constraints for `Int` use integer literals.
|
||||
Comparison constraints for `Float` may use either integer or float literals.
|
||||
|
||||
## Unknown
|
||||
|
||||
`Unknown` is the top range containing every Decodal value.
|
||||
It is not an `Any` that disables checking and erases concrete information; it means that the value's range has not yet been narrowed.
|
||||
|
||||
```dcdl
|
||||
Int & Unknown # Int
|
||||
42 as Unknown # 42
|
||||
Unknown as Int # conflict
|
||||
```
|
||||
|
||||
`Unknown` has no concrete value of its own and therefore cannot be materialized.
|
||||
It must be narrowed by a concrete value or given a `default`.
|
||||
|
||||
```dcdl
|
||||
Unknown default {}
|
||||
```
|
||||
|
||||
## Regex constraints
|
||||
|
||||
A regex literal is a string constraint.
|
||||
|
||||
```dcdl
|
||||
Host = /^api-[0-9]+$/;
|
||||
```
|
||||
|
||||
When several regex constraints are composed, a concrete string must match all of them.
|
||||
|
||||
```dcdl
|
||||
String & /^a/ & /z$/
|
||||
```
|
||||
|
||||
The intersection of regex constraints is not determined during composition.
|
||||
The following range therefore does not conflict when composed, but fails when a concrete value is validated.
|
||||
|
||||
```dcdl
|
||||
String & /^a$/ & /^b$/
|
||||
```
|
||||
|
||||
In the Rust runtime, enable the regex engine with the `regex` feature.
|
||||
Without that feature, validating a regex constraint against a concrete value produces an unsupported-feature diagnostic.
|
||||
|
||||
## Array constraints
|
||||
|
||||
Write an array constraint as `[...T]`; it applies `T` to every element.
|
||||
The element constraint is required.
|
||||
|
||||
```dcdl
|
||||
Names = [...String];
|
||||
PositiveInts = [...(Int & > 0)];
|
||||
```
|
||||
|
||||
When composed with a concrete array, each element is refined against `T` using the same rules as `as`.
|
||||
An empty array satisfies every array constraint.
|
||||
|
||||
If the element constraint is an object range, fields present only on the right remain abstract in every element.
|
||||
A field present only on the left is outside the right-hand field domain and produces a conflict.
|
||||
|
||||
## Associative-array and object rest constraints
|
||||
|
||||
Write an associative-array constraint as `{...T}`; it applies `T` to every field value in an object.
|
||||
|
||||
```dcdl
|
||||
Services = {...{
|
||||
port = Int;
|
||||
enabled = Bool default true;
|
||||
}};
|
||||
```
|
||||
|
||||
Keys are not enumerated, and an empty object is allowed.
|
||||
Writing `...T` at the end of an object with named fields applies `T` only to fields that were not named explicitly.
|
||||
|
||||
```dcdl
|
||||
{
|
||||
enabled = Bool default true;
|
||||
...Unknown
|
||||
}
|
||||
```
|
||||
|
||||
A rest constraint does not generate fields.
|
||||
It only validates additional fields that actually exist.
|
||||
|
||||
## default
|
||||
|
||||
`default` is not a constraint.
|
||||
It is a fallback used only when no concrete value exists during materialization.
|
||||
|
||||
```dcdl
|
||||
Port = Int & >= 1 & <= 65535;
|
||||
|
||||
Service = {
|
||||
port = Port default 8080;
|
||||
};
|
||||
```
|
||||
|
||||
When an explicit value has been composed into the range, that value is used and `default` is not evaluated.
|
||||
|
||||
```dcdl
|
||||
Config = {
|
||||
port = 9000;
|
||||
} as Service;
|
||||
```
|
||||
|
||||
Without an explicit value, materialization selects `8080` and verifies that it satisfies `Port`.
|
||||
|
||||
## Default composition
|
||||
|
||||
- If only one side of `&` has a `default`, that `default` is preserved.
|
||||
- If both sides of `&` have different defaults, they conflict.
|
||||
- If `&` between a constraint and a concrete value succeeds, the result is concrete and does not retain the `default`.
|
||||
- Because `//` is right-biased, the right-hand value or `default` replaces the left-hand one for the same field.
|
||||
- `as` does not inject a right-hand `default` into the left side. A field that exists only on the right, however, remains abstract in the result together with its `default`.
|
||||
|
||||
A `default` expression is evaluated when materialization requires it and must satisfy the constraints of the same range.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user