Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,15 @@ eyre = "0.6.8"
# needs real I/O (git fetch, filesystem), so it's off by default for
# `comline-core`'s wasm32 consumers (the playground editor, the language
# server); the CLI is the one consumer that actually runs `comline build`.
comline-core = { git = "https://github.com/ComlineProject/core", rev = "a5d6f8597c8c2f4ac44ae9feabfdfbb4bb671e82", features = ["deps"] }
comline-core = { git = "https://github.com/ComlineProject/core", rev = "2ba38df6f16759aae83f1b295621691d84e8c332", features = ["deps"] }
# All three pinned to revs that agree on one `comline-codegen`, and bumped
# together: comline-rust and comline-typescript's codegen crates consume
# `comline-codegen`'s types, so the rev below must be byte-identical to the
# one *they* pin - Cargo only unifies a git dependency across identical rev
# strings, and two copies of `GenRequest` are two incompatible types.
comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "9b101080133da8f26747c1322dd8959e6cd973ff" }
comline-codegen-rust = { git = "https://github.com/ComlineProject/comline-rust", rev = "562084f595a8f529210f0169c4e3f6855cfdd8c3", optional = true }
comline-codegen-typescript = { git = "https://github.com/ComlineProject/comline-typescript", rev = "a5a8800dd1c3d245ae53e7862b4ee218f36eadfd", optional = true }
comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "dfd3bdbc9933ac87e880efa86455f8da84a05120" }
comline-codegen-rust = { git = "https://github.com/ComlineProject/comline-rust", rev = "e1a290f154387d9e32cb2d35b0ed522ef9f88d52", optional = true }
comline-codegen-typescript = { git = "https://github.com/ComlineProject/comline-typescript", rev = "72da96a6f55d4598355973d0fccc33480af00c64", optional = true }

[features]
# Which language generators are compiled in. Drop one to shed its whole
Expand Down
22 changes: 16 additions & 6 deletions src/commands/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use std::path::{Path, PathBuf};

use comline_codegen::{features, GenRequest, Mode, PackageMeta, Registry, Resolved, Unresolved};
use comline_core::package::build::{self, cas::ObjectStore};
use comline_core::package::config::ir::frozen::FrozenUnit as ConfigUnit;
use comline_core::package::config::ir::frozen::{self, FrozenUnit as ConfigUnit};
use comline_core::schema::idl::constants::SCHEMA_EXTENSION;
use comline_core::schema::ir::frozen::unit::{schema_namespace_as_path, FrozenUnit};
use miette::{miette, IntoDiagnostic, Result, WrapErr};
Expand Down Expand Up @@ -60,6 +60,9 @@ pub fn run(
struct GenVersion {
package_version: String,
schemas: Vec<(String, Vec<FrozenUnit>)>, // (namespace path, frozen units)
/// The version's own `wire.format`: a built version keeps the format it
/// was built with.
wire_format: String,
}

fn generate_once(work_dir: &Path, overrides: &Overrides, dry_run: bool, list: bool) -> Result<()> {
Expand Down Expand Up @@ -179,7 +182,7 @@ fn generate_once(work_dir: &Path, overrides: &Overrides, dry_run: bool, list: bo
}
let (generator, ext) = (resolved.generator.generate, resolved.generator.ext);

let versions = expand_versions(&t.versions, work_dir, &live_schemas)?;
let versions = expand_versions(&t.versions, work_dir, &live_schemas, config_units)?;
if mode == Mode::Lib && versions.len() > 1 {
return Err(miette!(
"target `{}`: `lib` mode does not support multiple package versions yet",
Expand Down Expand Up @@ -221,7 +224,7 @@ fn generate_once(work_dir: &Path, overrides: &Overrides, dry_run: bool, list: bo
},
},
lang_version: t.lang_version.clone(),
default_framing: t.default_framing.clone(),
wire_format: gv.wire_format.clone(),
external_std: t.external_std,
async_api: t.async_api,
validate_on_decode: t.validate_on_decode,
Expand Down Expand Up @@ -336,6 +339,7 @@ fn expand_versions(
spec: &VersionSpec,
work_dir: &Path,
live: &[(String, Vec<FrozenUnit>)],
live_config: &[ConfigUnit],
) -> Result<Vec<GenVersion>> {
match spec {
VersionSpec::Latest => {
Expand All @@ -346,6 +350,7 @@ fn expand_versions(
Ok(vec![GenVersion {
package_version,
schemas: live.to_vec(),
wire_format: frozen::wire_format(live_config).to_string(),
}])
}
VersionSpec::All => {
Expand Down Expand Up @@ -391,14 +396,19 @@ fn gen_version_from_commit(
(ns, units)
})
.collect();
let config = history::load_config(store, commit)?;
Ok(GenVersion {
package_version: version.to_owned(),
schemas,
wire_format: frozen::wire_format(&config).to_string(),
})
}

/// `async = true` changes only protocols on a connection; with none, the
/// output is the same as without it, which looks like the setting did nothing.
/// Every protocol is on one by default, so that's a package whose protocols
/// are all lockstep: on the `datagram` framing, or on JSON-RPC with none of
/// them client-provided.
fn warn_async_unused(language: &str, request: &GenRequest) {
if !request.async_api {
return;
Expand All @@ -409,9 +419,9 @@ fn warn_async_unused(language: &str, request: &GenRequest) {
}
ui::warn(format!(
"`{language}`: `async = true`, but no protocol runs on a connection, so the output \
is the same as without it - a protocol is on one with `@provider = Client` or \
`Multiple`, a `datagram@2` framing, or JSON-RPC once any of the package's JSON-RPC \
protocols is client-provided"
is the same as without it - every protocol here is lockstep: on the `datagram` \
framing (the default, `datagram@2`, is a connection), or on JSON-RPC with none of \
the package's JSON-RPC protocols client-provided"
));
}

Expand Down
4 changes: 3 additions & 1 deletion src/commands/new.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ const COMLINE_TOML: &str = "\
# mode = \"code\" # code (loose source) | lib (a buildable package); dylib not built yet
# external_std = false # reference `comline_std` rather than inlining std; defaults on in `lib`
# package_versions = \"latest\" # latest | all | [\"0.3.0\", \"0.4.0\"]
# default_framing = \"jsonrpc\" # wire framing for protocols with no `@framing` (else datagram)
# validate_on_decode = \"off\" # run `@validators` while decoding: off | collect | first
# async = false # protocols on a connection get async handlers and senders
#
Expand Down Expand Up @@ -137,6 +136,9 @@ code_generation = {{
{language} = {{}}
}}
}}

// The wire both ends speak; these are the defaults.
// wire = {{ format = \"packed@1\" framing = \"datagram@2\" }}
"
)
}
Expand Down
128 changes: 42 additions & 86 deletions src/gen_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use comline_codegen::validation::ValidateOnDecode;
use comline_codegen::versions::LangVersion;
use comline_core::schema::idl::annotations;
use comline_core::utils::templating::recurse_render;
use comline_core::utils::text::closest;
use miette::{miette, IntoDiagnostic, Result, WrapErr};
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -105,10 +104,8 @@ pub struct Generate {
pub mode: Option<String>,
/// Version selection shared by every target unless overridden.
pub package_versions: Option<VersionSpec>,
/// Fallback wire framing for protocols that do not pick one with `@framing`,
/// shared by every target unless overridden. One of `@framing`'s accepted
/// spellings (`"jsonrpc"`, `"datagram"`, …), folded onto its canonical
/// form; an unknown one is an error.
/// Moved to config.idp's `wire = { framing = "..." }`: the framing is part
/// of the schema, which both ends must agree on. Read only to say so.
pub default_framing: Option<String>,
/// `true`: reference `comline_std` as its own crate instead of inlining
/// it, shared by every target unless overridden. Only a generator that
Expand Down Expand Up @@ -221,8 +218,6 @@ pub struct ResolvedTarget {
pub layout: String,
pub mode: String,
pub versions: VersionSpec,
/// Fallback framing handed to the generator; `None` ⇒ its built-in default.
pub default_framing: Option<String>,
/// `lib` mode only — see [`Target::flatten`].
pub flatten: bool,
/// See [`Generate::external_std`].
Expand Down Expand Up @@ -304,6 +299,12 @@ pub fn resolve(
work_dir: &Path,
ov: &Overrides,
) -> Result<Vec<ResolvedTarget>> {
let moved = std::iter::once(&cfg.generate.default_framing)
.chain(cfg.generate.targets.iter().map(|t| &t.default_framing));
if let Some(written) = moved.flatten().next() {
return Err(moved_default_framing(written));
}

let declares = |language: &str| {
declared
.iter()
Expand Down Expand Up @@ -527,24 +528,13 @@ pub fn resolve(
.or_else(|| cfg.generate.package_versions.clone())
.unwrap_or_default();

// `[[target]]` wins over `[generate]`; `None` at both ⇒ the generator's
// built-in default. No flag / env override — schema-shaping config, not
// a per-run knob.
let default_framing = t
.default_framing
.as_deref()
.or(cfg.generate.default_framing.as_deref())
.map(|written| canonical_framing(written, &t.language))
.transpose()?;

resolved.push(ResolvedTarget {
language: t.language.clone(),
lang_version,
out: work_dir.join(out),
layout,
mode,
versions,
default_framing,
flatten: t.flatten,
external_std,
validate_on_decode,
Expand All @@ -555,27 +545,16 @@ pub fn resolve(
Ok(resolved)
}

/// Fold a `default_framing` onto the canonical spelling `@framing` uses, the
/// same table core checks `@framing` against. An unknown name is an error:
/// each generator falls back to datagram for a name it doesn't recognise, so
/// a typo would otherwise generate the wrong framing and only surface as a
/// refused handshake.
fn canonical_framing(written: &str, language: &str) -> Result<String> {
if let Some(canonical) = annotations::canonical_value("framing", written) {
return Ok(canonical.to_string());
}
let spellings = annotations::value_spellings("framing");
let hint = closest(written, spellings.iter().copied())
.map(|s| format!(" - did you mean `{s}`?"))
.unwrap_or_default();
Err(miette!(
"`default_framing = \"{written}\"` for target `{language}` - expected one of {}{hint}",
spellings
.iter()
.map(|n| format!("`{n}`"))
.collect::<Vec<_>>()
.join(", ")
))
/// `default_framing` left `comline.toml`: the framing is part of the schema,
/// which both ends of a connection must agree on, so the package declares it.
fn moved_default_framing(written: &str) -> miette::Report {
let framing = annotations::canonical_value("framing", written).unwrap_or(written);
miette!(
"`default_framing` moved from {FILE_NAME} to config.idp\n \
help: drop it here, and declare the package's framing in config.idp:\n \
wire = {{ framing = \"{framing}\" }}\n \
Protocols with no `@framing` default to `datagram@2` without it."
)
}

#[cfg(test)]
Expand Down Expand Up @@ -745,29 +724,6 @@ mod tests {
assert_eq!(resolved[0].out, Path::new("/x/here"));
}

#[test]
fn default_framing_section_reaches_a_declared_target() {
let cfg = parse("[generate]\ndefault_framing = \"jsonrpc\"\n");
let declared = [DeclaredLang {
language: "rust".into(),
lang_version: "1.80".into(),
}];
let resolved = resolve(&cfg, &declared, Path::new("/x"), &Overrides::default()).unwrap();
assert_eq!(resolved[0].default_framing.as_deref(), Some("jsonrpc"));
}

#[test]
fn target_default_framing_wins_over_section() {
let cfg = parse(
"[generate]\ndefault_framing = \"jsonrpc\"\n\n\
[[generate.target]]\nlanguage = \"rust\"\nlang_version = \"1.85.0\"\n\
default_framing = \"datagram\"\n",
);
let declared = [];
let resolved = resolve(&cfg, &declared, Path::new("/x"), &Overrides::default()).unwrap();
assert_eq!(resolved[0].default_framing.as_deref(), Some("datagram"));
}

/// `lib` writes the package manifest, so the generator can add
/// `comline_std` to it; `code` emits loose files with nowhere to put a
/// dependency, so inlining stays the honest default there.
Expand Down Expand Up @@ -850,17 +806,6 @@ mod tests {
assert!(message.contains("never lower it"), "{message}");
}

#[test]
fn default_framing_absent_is_none() {
let cfg = parse("[generate]\n");
let declared = [DeclaredLang {
language: "rust".into(),
lang_version: "1.80".into(),
}];
let resolved = resolve(&cfg, &declared, Path::new("/x"), &Overrides::default()).unwrap();
assert_eq!(resolved[0].default_framing, None);
}

#[test]
fn flatten_defaults_to_false_and_is_target_only() {
let cfg = parse(
Expand Down Expand Up @@ -990,26 +935,37 @@ mod tests {
}

#[test]
fn default_framing_is_folded_onto_its_canonical_spelling() {
let cfg = parse(
"[generate]\ndefault_framing = \"json-rpc\"\n\n\
[[generate.target]]\nlanguage = \"rust\"\nlang_version = \"1.85.0\"\n",
fn default_framing_says_it_moved_to_config_idp() {
let cfg = parse("[generate]\ndefault_framing = \"json-rpc\"\n");
let declared = [DeclaredLang {
language: "rust".into(),
lang_version: "1.80".into(),
}];
let error = resolve(&cfg, &declared, Path::new("/x"), &Overrides::default()).unwrap_err();
let message = error.to_string();
assert!(
message.contains("moved from comline.toml to config.idp"),
"{message}"
);
// The hint is ready to paste, in the canonical spelling.
assert!(
message.contains("wire = { framing = \"jsonrpc\" }"),
"{message}"
);
let resolved = resolve(&cfg, &[], Path::new("/x"), &Overrides::default()).unwrap();
assert_eq!(resolved[0].default_framing.as_deref(), Some("jsonrpc"));
}

#[test]
fn an_unknown_default_framing_names_the_accepted_values_and_a_near_miss() {
fn a_target_default_framing_says_it_moved_too() {
let cfg = parse(
"[generate]\ndefault_framing = \"jsonrcp\"\n\n\
[[generate.target]]\nlanguage = \"rust\"\nlang_version = \"1.85.0\"\n",
"[[generate.target]]\nlanguage = \"rust\"\nlang_version = \"1.85.0\"\n\
default_framing = \"datagram\"\n",
);
let error = resolve(&cfg, &[], Path::new("/x"), &Overrides::default()).unwrap_err();
assert_eq!(
error.to_string(),
"`default_framing = \"jsonrcp\"` for target `rust` - expected one of `jsonrpc`, \
`datagram`, `datagram@2` - did you mean `jsonrpc`?"
assert!(
error
.to_string()
.contains("wire = { framing = \"datagram\" }"),
"{error}"
);
}

Expand Down
Loading
Loading