Skip to main content

xtask/
editor_contract.rs

1//! The editor contract: the compiler-owned facts a language-client extension
2//! must stay in step with, as one JSON document.
3//!
4//! The VS Code extension keeps a TextMate grammar (it highlights by keyword
5//! list) and declares the custom semantic-token types the server emits. Both
6//! must follow the compiler, and both used to be checked by Rust tests that read
7//! the extension's files from a sibling directory (`legend_drift`, `textmate_keywords`).
8//! That only worked while the extension lived in this repository. This document is the same data,
9//! published: the extension checks itself against the contract of the server
10//! release it pins (see `design/vscode-extension-extraction.md`, ยง4).
11//!
12//! Besides the keywords and legend it carries the two JSON documents the
13//! extension parses and keeps a fixture copy of: `bynk doctor --json` and
14//! `bynk status --json`, as their golden files pin them. The extension checks
15//! its fixtures equal the released ones, so a change to either output shape
16//! fails there instead of surfacing as a runtime parse error in the editor.
17//!
18//! Two forms:
19//! - the **snapshot**, committed at [`SNAPSHOT_PATH`]. It omits the version, so
20//!   a release bump never makes it stale; a change to the keywords or legend
21//!   shows up as a diff in the compiler PR that makes it, which is the signal
22//!   that the extension needs a matching change. `tests/editor_contract.rs`
23//!   fails when it is stale;
24//! - the **release asset** `bynk-editor-contract-<tag>.json`, the snapshot plus
25//!   the release's version ([`render_release`]).
26
27use std::path::Path;
28
29use bynk_syntax::keywords::KEYWORDS;
30use bynk_syntax::semantic_tokens::{
31    STANDARD_MODIFIERS, STANDARD_TYPES, TOKEN_MODIFIERS, TOKEN_TYPES,
32};
33use serde_json::{Value, json};
34
35/// `bynk doctor --json`'s golden, which `bynk/tests/doctor.rs` pins.
36const DOCTOR_GOLDEN: &str = include_str!("../../bynk/tests/golden/doctor.json");
37
38/// `bynk status --json`'s golden, which `bynk/src/migrate.rs` pins.
39const MIGRATE_STATUS_GOLDEN: &str = include_str!("../../bynk/tests/golden/migrate-status.json");
40
41/// Where the snapshot is committed, relative to the repo root.
42pub const SNAPSHOT_PATH: &str = "bynk-lsp/editor-contract.json";
43
44fn custom(names: &[String], standard: &[&str]) -> Vec<String> {
45    names
46        .iter()
47        .filter(|n| !standard.contains(&n.as_str()))
48        .cloned()
49        .collect()
50}
51
52/// The contract without a version.
53pub fn generate() -> Value {
54    let types: Vec<String> = TOKEN_TYPES.iter().map(|t| (*t).to_string()).collect();
55    let modifiers: Vec<String> = TOKEN_MODIFIERS.iter().map(|m| (*m).to_string()).collect();
56    let golden = |name: &str, text: &str| -> Value {
57        serde_json::from_str(text).unwrap_or_else(|e| panic!("the {name} golden is JSON: {e}"))
58    };
59    json!({
60        "goldens": {
61            "doctor": golden("doctor", DOCTOR_GOLDEN),
62            "migrateStatus": golden("migrate-status", MIGRATE_STATUS_GOLDEN),
63        },
64        "reservedKeywords": KEYWORDS.iter().map(|k| k.word).collect::<Vec<_>>(),
65        "semanticTokens": {
66            // Full, in wire order (the legend is append-only).
67            "types": types,
68            "modifiers": modifiers,
69            // The entries the extension must declare in package.json.
70            "customTypes": custom(&types, STANDARD_TYPES),
71            "customModifiers": custom(&modifiers, STANDARD_MODIFIERS),
72        },
73    })
74}
75
76fn pretty(value: &Value) -> String {
77    let mut text = serde_json::to_string_pretty(value).expect("a JSON value serialises");
78    text.push('\n');
79    text
80}
81
82/// The snapshot as committed: pretty-printed, with a trailing newline.
83pub fn render() -> String {
84    pretty(&generate())
85}
86
87/// The release asset: the snapshot plus the release `tag`.
88pub fn render_release(tag: &str) -> String {
89    let Value::Object(mut fields) = generate() else {
90        unreachable!("the contract is an object")
91    };
92    fields.insert("version".into(), json!(tag));
93    pretty(&Value::Object(fields))
94}
95
96/// Write the snapshot to [`SNAPSHOT_PATH`] under `root`.
97pub fn write(root: &Path) -> std::io::Result<()> {
98    std::fs::write(root.join(SNAPSHOT_PATH), render())
99}
100
101#[cfg(test)]
102mod tests {
103    use serde_json::json;
104
105    /// `generate` builds objects with `json!` and relies on `serde_json`'s map
106    /// being key-sorted. A crate anywhere in the workspace build enabling
107    /// `preserve_order` would reorder the snapshot (differently under
108    /// `--workspace` than `-p xtask`); this fails first, naming the cause.
109    #[test]
110    fn serde_json_maps_are_key_sorted() {
111        assert_eq!(json!({"b": 1, "a": 2}).to_string(), r#"{"a":2,"b":1}"#);
112    }
113}