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
4 changes: 2 additions & 2 deletions .github/workflows/port-docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -380,13 +380,13 @@ jobs:
if: matrix.port == 'ts'
working-directory: port
run: bun install --frozen-lockfile
- if: matrix.port == 'java' || matrix.port == 'kotlin' || matrix.port == 'scala'
- if: matrix.port == 'java' || matrix.port == 'kotlin' || matrix.port == 'scala' || matrix.port == 'clojure'
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6
with:
distribution: temurin
# The repository's Gradle conventions compile and run on JDK 25.
java-version: '25'
- if: matrix.port == 'java' || matrix.port == 'kotlin' || matrix.port == 'scala'
- if: matrix.port == 'java' || matrix.port == 'kotlin' || matrix.port == 'scala' || matrix.port == 'clojure'
uses: gradle/actions/setup-gradle@3f5f9adaf7d9fecd50b5935e54106014257a94e6 # v6.4.0
with:
validate-wrappers: true
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/reusable-deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ jobs:
echo "::error::path-prefix '$p' must be an unrooted path using letters, digits, '.', '_', '-' and '/', without '..'" >&2
exit 1
fi
reserved=(py ruby lua powershell julia elixir ts rs go java kotlin scala csharp fsharp cxx swift manifest _shell)
reserved=(py ruby lua powershell julia elixir ts rs go java clojure kotlin scala csharp fsharp cxx swift manifest _shell)
for r in "${reserved[@]}"; do
if [[ "$p" == "$r" ]]; then
echo "::error::path-prefix '$p' is a bare reserved top-level name — qualify it, e.g. '$r/latest'" >&2
Expand All @@ -153,7 +153,7 @@ jobs:
done
if [[ -n "${PORT_IN:-}" ]]; then
case "$PORT_IN" in
py|ruby|lua|powershell|julia|elixir|ts|rs|go|java|kotlin|scala|csharp|fsharp|cxx|swift) ;;
py|ruby|lua|powershell|julia|elixir|ts|rs|go|java|clojure|kotlin|scala|csharp|fsharp|cxx|swift) ;;
*) echo "::error::unknown port '$PORT_IN'" >&2; exit 1 ;;
esac
if [[ ! "$VERSION_IN" =~ ^[a-zA-Z0-9][a-zA-Z0-9._-]*$ || "$VERSION_IN" == *..* ]]; then
Expand Down
6 changes: 3 additions & 3 deletions notes/adding-a-port.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ and records what it found:
$ node scripts/verify-destinations.mjs
```

The verifier refuses to run, with or without `--check`, if a port in `ports.ts`
has no inventory entry with a published library: the header builds its links
from that entry, so a port without one would offer nothing. A host the
The verifier requires a published library, or a configured but unpublished
library with a public source repository and source installation instructions.
The latter names no registry or API host until those pages exist. A host the
inventory has not named before needs an identity rule in
`scripts/lib/destination-verification.mjs` and its cases in
`scripts/verify-destinations.negative.mjs`; without a rule its destinations are
Expand Down
145 changes: 145 additions & 0 deletions packages/api-model/scripts/export-clojure.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
(ns libtmux.docs.export-clojure
"Build-only export of compiled public namespace and var metadata."
(:require [clojure.java.io :as io]
[clojure.string :as str])
(:import [com.fasterxml.jackson.databind ObjectMapper]
[java.nio.charset StandardCharsets]
[java.nio.file Files]
[java.security MessageDigest]
[java.util HexFormat List]
[java.util.regex Pattern]))

(set! *warn-on-reflection* true)

(def ^:private repo "libtmux/libtmux-java")
(def ^:private exporter-script *file*)

(defn- sha256 [^bytes bytes]
(.formatHex (HexFormat/of) (.digest (MessageDigest/getInstance "SHA-256") bytes)))

(defn- bytes-at [file]
(Files/readAllBytes (.toPath (io/file file))))

(defn- prose [text]
(when (str/blank? text) (throw (ex-info "Public Clojure declaration has no docstring" {})))
(str/replace (str/trim text) #"\n " "\n"))

(defn- tag-text [namespace metadata]
(when-let [tag (:tag metadata)]
(let [resolved (if (class? tag) tag
(when (symbol? tag) (ns-resolve namespace tag)))]
(if (class? resolved) (.getName ^Class resolved) (str tag)))))

(defn- parameters [namespace arguments]
(loop [remaining (seq arguments) variadic? false result []]
(if-let [argument (first remaining)]
(if (= '& argument)
(recur (next remaining) true result)
(recur (next remaining) false
(conj result (cond-> {"name" (if (symbol? argument) (str argument) (pr-str argument))}
variadic? (assoc "variadic" "positional")
(tag-text namespace (meta argument)) (assoc "type" (tag-text namespace (meta argument)))))))
result)))

(defn- signatures [namespace name metadata]
(when-not (seq (:arglists metadata))
(throw (ex-info "Public Clojure var has no callable arities" {:var name})))
(mapv (fn [arguments]
(cond-> {"raw" (pr-str (cons (symbol name) arguments))
"params" (parameters namespace arguments)}
(tag-text namespace metadata) (assoc "returns" (tag-text namespace metadata))))
(:arglists metadata)))

(defn- public-functions [namespace]
(->> (ns-publics namespace)
(keep (fn [[name value]]
(let [metadata (meta value)]
(when (and (:file metadata) (not (:no-doc metadata)))
[(str name) metadata]))))
(sort-by first)))

(defn- source-record [module file revision line]
{"file" (str (get module "path") "/src/main/clojure/" file)
"line" line "repo" repo "revision" revision})

(defn- namespace-line [source namespace]
(let [pattern (re-pattern (str "(?m)^\\(ns\\s+" (Pattern/quote (str namespace)) "(?:\\s|$)"))
matcher (re-matcher pattern source)]
(when-not (.find matcher)
(throw (ex-info "Cannot locate the compiled namespace in source" {:namespace namespace})))
(inc (count (filter #{\newline} (subs source 0 (.start matcher)))))))

(defn- namespace-symbols [root module namespace revision]
(let [file (str (-> (str namespace) (str/replace "." "/") (str/replace "-" "_")) ".clj")
path (str (get module "path") "/src/main/clojure/" file)
^bytes source-bytes (bytes-at (io/file root path))
resource (or (io/resource file) (throw (ex-info "Compiled Clojure source is absent" {:file file})))
loaded-bytes (with-open [stream (io/input-stream resource)] (.readAllBytes stream))
_ (when-not (= (sha256 source-bytes) (sha256 loaded-bytes))
(throw (ex-info "Loaded Clojure resource differs from selected source" {:file path})))
functions (public-functions namespace)
common {"package" (get module "package") "product" "core" "apiScope" "exported"
"namespace" (str namespace) "publicOwner" (str namespace)}]
(when-not (seq functions) (throw (ex-info "Public Clojure namespace has no functions" {:namespace namespace})))
{:input {"path" path "sha256" (sha256 source-bytes)}
:symbols
(into [(merge common {"id" (str namespace) "publicId" (str namespace)
"qualifiedName" (str namespace) "name" (str namespace)
"kind" "module" "modifiers" []
"signatures" [{"raw" (str "(ns " namespace ")") "params" []}]
"docstring" (prose (:doc (meta (the-ns namespace))))
"source" (source-record module file revision
(namespace-line (String. source-bytes StandardCharsets/UTF_8) namespace))})]
(for [[name metadata] functions]
(do
(when-not (and (= file (:file metadata)) (pos-int? (:line metadata)))
(throw (ex-info "Public var source is outside its namespace" {:namespace namespace :var name})))
(merge common {"id" (str namespace "/" name) "publicId" (str namespace "/" name)
"qualifiedName" (str namespace "/" name) "name" name "kind" "function"
"parent" (str namespace)
"modifiers" (cond-> [] (> (count (:arglists metadata)) 1) (conj "overload")
(:macro metadata) (conj "macro")
(:deprecated metadata) (conj "deprecated"))
"signatures" (signatures namespace name metadata)
"docstring" (prose (:doc metadata))
"source" (source-record module file revision (:line metadata))}))))}))

(defn- exporter-provenance []
(let [directory (.getParentFile (io/file exporter-script))
files (mapv (fn [name]
{"path" (str "packages/api-model/scripts/" name)
"sha256" (sha256 (bytes-at (io/file directory name)))})
["export-clojure.clj" "export-clojure.gradle"])
digest (sha256 (.getBytes (str/join "\n" (map #(str (get % "path") ":" (get % "sha256")) files))
StandardCharsets/UTF_8))]
{"name" "clojure-public-var-metadata" "revision" (str "sha256:" digest)
"files" files}))

(defn- -main [root destination revision]
(when-not (re-matches #"[a-f0-9]{40}" revision)
(throw (ex-info "A selected source revision is required" {})))
(let [mapper (ObjectMapper.)
^List modules (.readValue mapper (System/getProperty "libtmux.docs.clojure.modules") List)
namespaces (vec (for [module modules namespace (get module "namespaces")]
[module (symbol namespace)]))]
(when (or (empty? namespaces) (not= (count namespaces) (count (set (map second namespaces)))))
(throw (ex-info "Published Clojure namespaces are absent or duplicated" {})))
(doseq [[_ namespace] namespaces] (require namespace))
(let [exports (mapv (fn [[module namespace]] (namespace-symbols root module namespace revision)) namespaces)
symbols (into [] (mapcat :symbols) exports)
artifact {"schema" "libtmux.clojure-api/1" "port" "clojure" "repo" repo "revision" revision
"compiler" (clojure-version) "extractor" "clojure-public-var-metadata/1"
"sources" (mapv (fn [module]
{"product" "core" "package" (get module "package") "repo" repo
"revision" revision "extractedRevision" revision "version" (get module "version")}) modules)
"nativeProvenance" {"files" (mapv :input exports) "exporter" (exporter-provenance)}
"symbols" symbols}
output (.getAbsoluteFile (io/file destination))]
(when-not (= (count symbols) (count (set (map #(get % "id") symbols))))
(throw (ex-info "Duplicate native Clojure public identity" {})))
(.mkdirs (.getParentFile output))
(spit output (str (.writeValueAsString (.writerWithDefaultPrettyPrinter mapper) artifact) "\n") :encoding "UTF-8")
(binding [*out* *err*]
(println "Clojure" (clojure-version) ": exported" (count symbols) "public declarations")))))

(apply -main *command-line-args*)
57 changes: 57 additions & 0 deletions packages/api-model/scripts/export-clojure.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import groovy.json.JsonOutput
import org.gradle.api.tasks.JavaExec

gradle.projectsEvaluated {
def root = gradle.rootProject
def modules = root.allprojects.findAll { it.plugins.hasPlugin('libtmux.clojure-library') }
.sort { it.path }
if (!modules) return
def scriptPath = root.findProperty('libtmuxClojureExporter')
if (!scriptPath) throw new GradleException('Set libtmuxClojureExporter to export-clojure.clj')
def manifest = modules.collect { module ->
def declared = module.tasks.named('clojureNamespaceLoad', JavaExec).get()
.systemProperties['libtmux.clojure.main-namespaces']
if (!declared) throw new GradleException("Missing public namespaces for ${module.path}")
[path: root.relativePath(module.projectDir), artifact: module.name,
package: "${module.group}:${module.name}", version: module.version.toString(),
namespaces: declared.toString().split(',').toList()]
}
def launcher = modules.first().tasks.named('clojureNamespaceLoad', JavaExec).get().javaLauncher.get()
root.tasks.register('exportClojureApi', JavaExec) {
group = 'documentation'
description = 'Exports public Clojure metadata for the shared documentation model.'
dependsOn(modules.collect { it.tasks.named('classes') })
javaLauncher.set(launcher)
mainClass.set('clojure.main')
classpath = root.files(modules.collect { it.sourceSets.main.runtimeClasspath },
root.project(':libtmux-jackson').configurations.runtimeClasspath)
workingDir(root.projectDir)
def destination = root.file(root.findProperty('libtmuxClojureApiOutput') ?: 'build/docs/clojure-api.json')
def revision = root.findProperty('libtmuxDocsSourceRevision')
if (!(revision ==~ /[a-f0-9]{40}/)) throw new GradleException('Set libtmuxDocsSourceRevision to the selected Git revision')
systemProperty('libtmux.docs.clojure.modules', JsonOutput.toJson(manifest))
jvmArgs('-Xmx384m', '-XX:ActiveProcessorCount=2', '-Dclojure.main.report=stderr')
args(scriptPath, root.projectDir.path, destination.path, revision)
inputs.files(new File(scriptPath), new File(new File(scriptPath).parentFile, 'export-clojure.gradle'))
inputs.property('sourceRevision', revision)
inputs.property('publicModules', JsonOutput.toJson(manifest))
modules.each { inputs.dir(it.file('src/main/clojure')) }
outputs.file(destination)
def errors = new ByteArrayOutputStream()
errorOutput = errors
ignoreExitValue = true
doLast {
def diagnostic = errors.toString('UTF-8')
System.err.print(diagnostic)
def result = executionResult.get()
if (result.exitValue != 0) {
destination.delete()
result.assertNormalExitValue()
}
if (diagnostic =~ /(?m)^(Reflection warning|Performance warning|Boxed math warning)/) {
destination.delete()
throw new GradleException('Clojure API export emitted compiler warnings')
}
}
}
}
7 changes: 6 additions & 1 deletion packages/api-model/src/builtins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,11 @@ export const BUILTINS: Record<string, Record<string, string>> = {
byte: 'https://docs.oracle.com/javase/specs/jls/se21/html/jls-4.html#jls-4.2.1',
void: 'https://docs.oracle.com/javase/specs/jls/se21/html/jls-8.html#jls-8.4.5',
},
clojure: {
// The runtime declaration identifies the Java class; core.async names the library.
ExceptionInfo: 'https://github.com/clojure/clojure/blob/clojure-1.12.6/src/jvm/clojure/lang/ExceptionInfo.java',
'core.async': 'https://github.com/clojure/core.async',
},
// Lua's eight value types share one section of the manual; `integer` is
// the subtype 5.3 added and LuaLS spells separately. `any` is a LuaLS
// annotation type, with no counterpart in the language. LuaLS's `unknown`
Expand Down Expand Up @@ -518,7 +523,7 @@ export const CURATED_BEFORE_INVENTORY: ReadonlySet<string> = new Set(['kotlin',
* "the Java ones" is about the project's wrappers of the Java API and not a switch to Java: its `Vector` is Scala's.
* A sentence that names a language the port does not reach (a Python page on Rust's `Vec`) still decides the name.
*/
export const PLATFORM_REACH: Readonly<Record<string, readonly string[]>> = { kotlin: ['java'], scala: ['java'] }
export const PLATFORM_REACH: Readonly<Record<string, readonly string[]>> = { kotlin: ['java'], scala: ['java'], clojure: ['java'] }

/**
* Names the JDK's inventory holds that Kotlin and Scala prose means another library's by. A Scala sentence's "an Ox
Expand Down
26 changes: 26 additions & 0 deletions packages/api-model/src/concepts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3824,6 +3824,31 @@ for (const [id, binding] of Object.entries(ELIXIR_CONCEPTS)) {
if (binding.note) (concept.notes ??= {}).elixir = binding.note
}
CONCEPTS['list-session-panes']!.absent!.julia = 'Traverse `windows(session)` and `panes(window)` in the captured snapshot. `panes(snapshot)` has server-wide scope.'
const CLOJURE_CONCEPTS: Record<string, { symbol: string; note?: string }> = {
server: { symbol: 'libtmux.core/open!', note: 'Opens a closeable Java server client for an explicit endpoint. Acquisitions return persistent maps with explicit Java references for effects.' },
session: { symbol: 'libtmux.core/sessions!', note: 'Acquires a vector of captured session maps. The session value is a map, not a wrapper class.' },
window: { symbol: 'libtmux.data/windows', note: 'Traverses captured window-placement maps without I/O; the window value is a map with an explicit Java reference for effects.' },
pane: { symbol: 'libtmux.data/panes', note: 'Traverses captured pane maps without I/O. Use keyword lookup for scalar observations and the preserved :tmux/ref for effects.' },
'capture-pane': { symbol: 'libtmux.core/capture!' },
'send-keys': { symbol: 'libtmux.core/send-keys!' },
'split-pane': { symbol: 'libtmux.core/split-pane!' },
'new-session': { symbol: 'libtmux.core/new-session!' },
'new-window': { symbol: 'libtmux.core/new-window!' },
'kill-server': { symbol: 'libtmux.core/kill-server!' },
'list-sessions': { symbol: 'libtmux.core/sessions!', note: 'Acquires a new captured graph and returns its session maps; acquisition failure throws.' },
'list-windows': { symbol: 'libtmux.data/windows', note: 'Traverses one capture locally. It does not issue a list-windows command.' },
'list-panes': { symbol: 'libtmux.data/panes', note: 'Traverses one capture locally. It does not issue a list-panes command.' },
'list-server-windows': { symbol: 'libtmux.core/windows!', note: 'Acquires a new graph and returns its window placements without deduplicating linked windows.' },
'list-server-panes': { symbol: 'libtmux.core/panes!', note: 'Acquires a new graph and returns its pane occurrences.' },
'list-clients': { symbol: 'libtmux.core/clients!' },
snapshot: { symbol: 'libtmux.core/snapshot!', note: 'Acquires a captured graph of persistent values. Retained values do not refresh after mutation or close.' },
}
for (const [id, binding] of Object.entries(CLOJURE_CONCEPTS)) {
const concept = CONCEPTS[id]
if (!concept) throw new Error(`concepts: Clojure maps unknown concept ${id}`)
concept.symbols.clojure = binding.symbol
if (binding.note) (concept.notes ??= {}).clojure = binding.note
}
for (const concept of Object.values(CONCEPTS)) {
concept.absent ??= {}
if (!concept.symbols.powershell) concept.absent.powershell ??= 'No source-verified PowerShell equivalent is recorded for this operation.'
Expand All @@ -3834,6 +3859,7 @@ for (const concept of Object.values(CONCEPTS)) {
if (!concept.symbols.kotlin) concept.absent.kotlin = 'No source-verified Kotlin equivalent is recorded for this operation.'
if (!concept.symbols.scala) concept.absent.scala = 'No source-verified Scala equivalent is recorded for this operation.'
if (!concept.symbols.fsharp) concept.absent.fsharp = 'No source-verified F# equivalent is recorded for this operation.'
if (!concept.symbols.clojure) concept.absent.clojure = 'No source-verified Clojure equivalent is recorded for this operation.'
}

/** Every concept naming this symbol, including concepts sharing an overload group. */
Expand Down
Loading
Loading