67 Commits
Author SHA1 Message Date
waozi d27ad25cfc Reset to version 0.1.0 for the Zi-focused extension 2026-12-06 12:21:51 -03:00
waozi 571f6dbf2c Refocus the extension on the new Zi runtime
- Zi: Build / Run / Web Preview drive the zi CLI (tao in older trees) on
  ziran.toml or tao.toml manifests, with compiler errors in Problems
- Zi Module editor for .zx images: id, kind, version, sha256, imports,
  exports parsed from the module prefix, never fake text
- Import completions from the project manifest module ids
- Remove the old Ziran compiler surfaces: .zi grammar and snippets, .zir
  viewer, ziran check diagnostics, api symbols, run targets, C/Go
  conversion and native inspectors, Kryon preview, TS plugin, Wine/adb/wasm
- Tests: manifest-keyed unit suite for the viewer parser and activation
2026-12-06 12:11:24 -03:00
waozi 2e6ff5462e Use declared TypeScript contexts for Inspect conversion 2026-12-03 05:02:02 -03:00
waozi cb06e01764 Select native TypeScript bindings by checked project context 2026-12-03 00:25:38 -03:00
waozi 6baa709f45 Keep native project Run compiler inspection available 2026-12-02 22:05:42 -03:00
waozi 3423d65d28 Read current converter receipts in Run pipelines 2026-12-02 21:46:01 -03:00
waozi 771332f14a Surface TS binding failures and add an explicit refresh 2026-12-02 14:24:23 -03:00
waozi 9ffb4e34b3 Surface binding refresh failures on native runs in the Run pane 2026-12-02 08:28:28 -03:00
waozi 874e01a2f7 Resolve native TS imports on open and native runs, and name the target TS 2026-12-02 07:58:10 -03:00
waozi 0aebcc4ed7 Run the project-declared native app from the editor play action 2026-12-02 07:33:33 -03:00
waozi e795d212f9 Show TypeScript conversion stages and target in VS Code 2026-11-30 19:47:57 -03:00
waozi 80005abb13 Inspect Kryon apps through their own profile bindings 2026-11-30 18:15:04 -03:00
waozi 7dd0fe963f Serve Kryon previews from persistent project origins 2026-11-30 13:54:36 -03:00
waozi b8ba182d82 Inspect C and Go converter pipelines in Run 2026-11-30 06:27:25 -03:00
waozi df36044cc6 Revert "Run host-bound packages through their workspace task"
This reverts commit c10612795e.
2026-11-30 05:56:31 -03:00
waozi c10612795e Run host-bound packages through their workspace task
A package whose #foreign host capabilities come from its application
cannot run as a standalone native program; zx2native stops at the first
missing capability. ziran.runTasks maps workspace globs to the task that
builds and starts that host, so Run starts it instead, and a missing task
is reported by name.
2026-11-30 04:43:37 -03:00
waozi 76a07546ab Document current TSX application preview routes 2026-11-28 09:56:17 -03:00
waozi 568dbeeed5 Declare the preview fixture entry module root 2026-11-28 09:40:20 -03:00
waozi 26bf07e3de Generate native TypeScript bindings on explicit editor checks 2026-11-27 09:41:18 -03:00
waozi 9c34866c1d Resolve native bindings through the stock TypeScript server 2026-11-27 08:14:06 -03:00
waozi 635de9a96f Run explicitly exported program entries by their declared names 2026-11-27 08:03:41 -03:00
waozi 6d9be7844b Keep native compiler analysis off the editing path 2026-11-27 06:53:57 -03:00
waozi 192fff9b86 Support native TSX editing and binary pipeline inspection 2026-11-27 05:43:20 -03:00
waozi 80fa347024 Group internal modules by their owning package 2026-11-26 02:13:33 -03:00
waozi b47e9e2e62 Show all target files in a persistent explorer tree 2026-11-26 01:54:53 -03:00
waozi b7cef6ace4 Inspect target-specific dependencies and deploy Windows native hosts 2026-11-26 01:09:03 -03:00
waozi 69524923ce Use import names throughout compiler-backed views 2026-11-25 19:13:06 -03:00
waozi ace798f63d Run Kryon UI programs through the normal main path
The Run pane no longer diverts kryon/app programs to a notice: main is the only program entry, so a main-bearing file bundles and runs like any other. Fixtures and browser tests drop the #program_export marker or move to main + App.Run; the preview fixture uses the current App.Frame API.
2026-11-25 05:56:46 -03:00
waozi 8259ce596f Show imported dependencies in the Source stage dropdown
The Source stage now resolves every imported module the ZIR stage lists: the checked build writes build/.ziran/module-map.tsv, which names the file behind each std and package import, so kryon/geometry or std/text appears in the Source dropdown under its own name and loads only when picked. When the check fails, the program and its own modules are still parsed for imports so the dropdown keeps the dependencies it can find.
2026-11-24 21:43:26 -03:00
waozi b86b59457b Compact the extension README and add AGENTS.md 2026-11-22 15:01:22 -03:00
waozi 74e7b20258 Give a real project its folder settings back after the preview browser test
Picking the Wasm platform saves ziran.previewPlatform in the folder's
.vscode/settings.json, so a run against a real checkout left Kryon's folder
on Wasm. The test now restores the file it found, or removes the one it
made.
2026-11-16 14:00:02 -03:00
waozi 689c349e10 Run Wasm's Open in window in the page through Kryon's ZX canvas player
On the Wasm platform Open in window ran the program's .wasm in Node, which
has no host for a Kryon program's capabilities. It now runs the program's
ZX in the page, in the frame the web preview uses: a canvas profile with
codegen = "zx" (a single-file preview's own project gains `wasm`) builds
Kryon's canvas player around the bundle, which lowers it to Wasm in the
page and runs main with the page's canvas as its window. A project with no
such profile names what its page needs. The platform is chosen before
anything is built, so the Wasm page builds no native bundle.

The preview tests build a fake page and check the missing-profile message;
the browser test selects Wasm, checks Native's WAT and that window.zi's page
fills its canvas with the frame colour.
2026-11-16 13:57:58 -03:00
waozi 4b981fbc54 Open in window runs the executable the Binary tab shows
On Linux x86-64 Open in window ran `zi2zx run --backend native`, which
never consults the host registry, so a Kryon program such as
examples/window.zi stopped at "missing host capability". Every platform now
runs the build its Binary tab shows: zx2native's executable on Linux x86-64,
which links window.zi's capabilities from Kryon's registered desktop host
library and opens its window, Wine or a device elsewhere. A capability no
registered library provides still shows zx2native's named gap.

The preview tests run a fake executable from a fake zx2native and check the
gap; the browser test checks one 320x160 "Window" and Native's Assembly of
the linked executable, and takes ZIRAN_PREVIEW_COMMAND to pick a toolchain.
2026-11-16 13:31:24 -03:00
waoziandClaude Opus 5.5 907d5653e1 Keep the page still when a Targets view shows a shorter block
A viewport of padding under the open Targets section, so switching tabs or
views no longer pulls the page up. The Run pane browser test scrolls the view
tabs to the top over C's Assembly, switches to Source and checks the position.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 11:34:29 -03:00
waoziandClaude Opus 5.5 30615d3dbd Add a Platform dropdown: analyze and run Native on every platform the toolchain lists
The Platform dropdown beside the target checkboxes lists every row of
`ziran capabilities --json`, checked against zx2native's own --target,
--platform and --emit choices and a probe of each row, plus Wasm from
zx2wasm. A refused row is disabled with its gap by name; Windows x86-64
lights up once zx2native accepts --platform windows. The choice is saved to
ziran.previewPlatform (now resource-scoped, like previewTargets, which VS
Code refused to write to folder settings).

Native ends in the platform's output: Assembly and Binary of the ELF or PE,
or WAT and Binary for Wasm; the shared stages are unchanged. PE files list
their DOS header and stub, PE headers, sections and imports, name calls
through the import table, and Hide PE parts leaves only the program's code.
AArch64 and ARM disassemble with a cross objdump or the NDK's llvm-objdump.

Run and Open in window run the platform's own way: Linux x86-64 directly,
Windows under Wine in a private prefix with WINEDEBUG=-all, ARM on a device
through adb (ziran.adbCommands, such as `ssh user@host adb`), Wasm in Node.
One process, no fallback, and a missing route is named.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 03:01:48 -03:00
waoziandClaude Sonnet 5.5 9eca22b3eb Highlight Source from the Ziran grammar; one stage table for every target; native Open in window
Source and dependency sources are colored with the extension's TextMate grammar.
Tabs come from one table: Source, ZIR, LIR, Optimized, ZX, then the target's output; C and
Go stop after ZIR. Source and ZIR get the file dropdown. Open in window runs the
ZX bundle natively with no fallback. The preview follows the active .zi editor and its
live frame has no padding and a transparent page.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-16 00:46:59 -03:00
waozi ffbdc20b2b Show the whole ELF in Assembly and Binary; full pipeline for every target
Native's Assembly was empty: Ziran's direct ELFs carry no section headers,
so objdump -d found nothing to disassemble. Assembly now lists the ELF
header, the program headers and every region of the file in order, with
code disassembled by objdump at its load address under <module:function>
labels from the native map, and data as bytes. Hide ELF parts leaves only
the program's own functions. A linear pass that runs past padding is
re-decoded at the map's boundaries and branch targets.

Binary, and the ZX, C, Go and WebAssembly bytes, show the whole file with
each region under a label row; the same toggle keeps only code and data.

Every target shows Source, LIR, Optimized and ZX, built once and shared,
then its own output. The ZIR tab, the view descriptions and the generated
comment headers are gone.

The Kryon preview shows these targets under its live window instead of an
Inspect Targets button, and Open in window runs a Kryon program's C
executable as one owned window again.
2026-11-15 21:23:29 -03:00
waozi 05cc99700a Run browser tests in the installed Code fork
Microsoft VS Code was replaced by the waozixyz/code VSCodium fork, which ships
this extension built in. The browser tests launch its editor binary when it is
installed and fall back to /usr/share/code/code.
2026-11-15 21:22:24 -03:00
waozi 7d8c05af48 Show only a program's own code; drop the preview's new window
The Kryon preview keeps its embedded live window and loses Open in New
Window and the raw Kryon-profile Generated C and ZIR dumps. Inspect
Targets opens the normal C, Go, ZIR, WebAssembly and Native tabs.

Generated views show the program's own modules first: for window.zi,
C Source opens window.c instead of the 139 Kryon desktop-host files.
Other modules are listed under Dependencies and are read, compiled to
assembly or inspected only on request. A failed target reads as one
line with the full output collapsed.

Native runs through zi2zx and zx2native, naming a missing tool, with
zi2asm kept only as a fallback until the rename lands everywhere.
2026-11-14 18:56:16 -03:00
waozi 3d51ab48e2 Show every target tab as soon as a run starts
The Run pane built C, Go, WebAssembly and Native in parallel but posted
them only after the slowest finished, so only the ZIR tab was visible for a
long time. Each enabled target now has its tab at once, marked as building
and still showing its last output, and fills in when its own build ends.
2026-11-14 16:32:17 -03:00
waozi cf93f3943b Run Kryon programs as a live preview with a real window on request
A .zi file that imports kryon/app and declares main opens its own window. Run
now shows it live in the Kryon preview instead of the portable Run pane, which
has no window host and could only print main's failure status, 1. The preview
keeps an extension-owned project for the file and builds its main through the
Kryon tool's canvas profile.

Open in New Window builds the C-generated executable and runs it as one owned
process that opens the program's real window. Its stdout, stderr and exit
status are shown separately; reopening replaces the process, and closing the
preview or VS Code ends it.

Inspect Targets opens the Run pane's C, Go, WebAssembly and Native views for
such a program, with a note in place of a portable run.

A project bundle now runs with ziran run --project, so the toolchain that
wrote it also reads it, and a ZIR version mismatch names the ziran and zi2zx
paths in use.
2026-11-13 21:11:15 -03:00
waozi 2207ccd865 Name the Native stages ZIR and Binary
ZIR is always type-checked, so the Native view, the .zir editor and the
docs drop the Checked prefix. The final Native stage is Binary, matching
C, Go and WebAssembly; it still shows the ELF lowered from ZX, starting at
main, with its ELF header toggle.
2026-11-13 19:48:04 -03:00
waozi 3ca95ac909 Unify Native inspection through verified ZX instructions 2026-11-13 18:14:17 -03:00
waozi f7fe2c9b30 Reduce unit test suite duplication 2026-11-13 14:57:54 -03:00
waozi fb95178645 Show executable code first in binary views 2026-11-13 14:09:46 -03:00
waoziandClaude Opus 5.5 3688f31785 Inspect C, Go, ZX and native target output in the Run pane
Add source, assembly and paged hex binary views per target, explain
files without main instead of failing on a missing bundle entry, and
resolve kryon/<package> and aliased imports through the import map.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 00:17:09 -03:00
waozi 4e1202dfbe Offer only the current Ziran native targets 2026-10-31 02:46:30 -03:00
waozi b788d17a48 Release Ziran editor support for ZX portable executables 2026-10-23 19:20:33 -03:00
waozi 5c53e295be Use .zx portable executables in Ziran editor support 2026-10-23 18:55:42 -03:00
waozi eb0dcb5413 Show declaration references and guard compiler quick fixes 2026-10-03 01:08:24 -03:00
waozi 3c45c1c67f Complete, hover, and go to the program's declarations
Completion and Go to Definition covered only import paths, and hovering
showed nothing. The extension now runs `ziran api --json` for the file's
program (with --project inside a package) and uses what it declares:

- completion offers every procedure, type, constant, and global with its
  signature;
- hovering a name shows its declaration and the // comment above it;
- Go to Definition opens the declaring line, preferring the file's own
  module over an import of the same name.

Results are cached per document version. tests/symbols.test.mjs covers
reading api output, name lookup, the name under the cursor, and doc
comments.
2026-09-30 06:49:32 -03:00
waozi f41098b7c6 Check Ziran packages with --project and follow package-qualified imports
A file inside a ziran.toml package is checked with `ziran check
--project`, so its Git dependencies are part of the check. Go to
Definition and import completion read the module map that check writes:
#import "kryon/Widgets" opens that dependency's export, std/text the
pinned standard library, and a short name resolves the way the compiler
resolves it.
2026-09-29 19:53:25 -03:00
waozi 872d62e6e1 Show Python in the generated code tabs
The Run pane builds ziran build --target=py alongside C, C++, 9c, Go,
and Rust, highlights its output, and offers it in ziran.previewTargets.
2026-09-28 17:21:16 -03:00
waozi 28d6b7f941 Give .zi, .zir, and .zib files the Ziran icon
Source files show the Ziran Z logo, checked modules a blue variant, and
bundles a brown one. The extension uses the logo as its own icon.
2026-09-28 11:57:41 -03:00
waozi 2ab50616bf List 9c right after C++ in the generated code tabs 2026-09-28 11:18:50 -03:00
waozi 3932dde4cc Make the Run pane follow the focused file
One Run pane shows whichever .zi file has focus: switching editors
retargets it, and Run from another file reuses it.
2026-09-28 11:16:09 -03:00
waozi 0608354071 Put generated code and .zir under the Run output
The Run pane now holds, like the Kryon preview, the program output
window, highlighted generated code for each target, and the inspected
checked .zir. The separate generated code tab and command are gone.
2026-09-28 02:44:11 -03:00
waozi 46eddfca56 Show Ziran runs in a pane beside the source
Run opens a webview like the Kryon preview: program output in a window,
run time, build and runtime errors, rerun on save, and a link to the
generated code preview. Runs stop after 10 seconds.
2026-09-28 02:36:13 -03:00
waozi 490f642a2a Fix extension activation
A stray async before a comment made extension.cjs throw on load, so no
command was registered. A test now activates the extension against a
fake vscode module and checks every contributed command is registered.
2026-09-28 02:33:18 -03:00
waozi e84cb6efc9 Run .zi files from the editor
The play button and a Run link above main bundle the file's main and run
it on the portable runtime in a Ziran terminal. Kryon projects keep their
Kryon preview button.
2026-09-28 02:31:34 -03:00
waozi f2219c8580 Release 0.5.0 2026-09-28 02:26:35 -03:00
waozi a9e60efac6 Highlight // and /* */ comments
Apostrophes inside comments no longer start a string that swallows the
following code, block comments nest, and Toggle Comment uses //.
The repository link points at ziranlang/ziran-vscode.
2026-09-28 02:26:35 -03:00
waozi 4766f7295c Check files and preview generated code without Kryon
A single .zi file now works on its own: opening or saving it runs
ziran check and reports errors in Problems, and imports resolve from its
directory and the Ziran checkout's std.

Ziran: Preview Generated Code shows the C, C++, Go, Rust, and Plan 9 C
that ziran build produces for the file, one tab per target. Its checkboxes
choose the targets and save them to ziran.previewTargets.

The Kryon preview button and command now appear only in projects with a
kryon.toml. ziran.command replaces ziran.inspectorCommand and serves
checking, the target preview, and .zir browsing.
2026-09-28 02:24:37 -03:00
waozi 968eb989ca Render project preview canvas and browse checked modules 2026-09-25 13:27:04 -03:00
waozi 8c85576568 Expose Run Kryon controls in editor and status bar 2026-09-25 13:17:26 -03:00
waozi 4d20b2f770 Add live Kryon project preview to VS Code 2026-09-25 13:12:18 -03:00
waozi ecffbf8734 Make VS Code extension support Ziran modules 2026-09-24 17:50:25 -03:00
19 changed files with 863 additions and 246 deletions

No files matched your search

+6 -6
View File
@@ -27,11 +27,11 @@ jobs:
- run: npm ci
- run: npm test
- run: npm run package
- run: unzip -t kryon-language-*.vsix
- run: unzip -t ziran-language-*.vsix
- uses: actions/upload-artifact@v6
with:
name: kryon-language-vsix
path: kryon-language-*.vsix
name: ziran-language-vsix
path: ziran-language-*.vsix
if-no-files-found: error
release:
@@ -44,14 +44,14 @@ jobs:
- uses: actions/checkout@v7
- uses: actions/download-artifact@v6
with:
name: kryon-language-vsix
name: ziran-language-vsix
path: dist
- name: Publish release
env:
GH_TOKEN: ${{ github.token }}
run: |
version=$(node -p "require('./package.json').version")
gh release create "v${version}" dist/kryon-language-*.vsix \
gh release create "v${version}" dist/ziran-language-*.vsix \
--target "$GITHUB_SHA" \
--title "Kryon Language v${version}" \
--title "Ziran Language v${version}" \
--generate-notes
+1
View File
@@ -1,2 +1,3 @@
node_modules/
*.vsix
tests/.runtime-*/
+1
View File
@@ -0,0 +1 @@
install-links=true
+5 -1
View File
@@ -1,7 +1,11 @@
node_modules/**
scripts/**
tests/**
.github/**
.gitignore
*.vsix
package-lock.json
update_version.sh
TODO.md
.npmrc
DONE.md
backup/**
+41
View File
@@ -0,0 +1,41 @@
# AGENTS.md — Zi Language for VS Code
Editor support for the new Zi runtime (the `tao` checkout, command `zi`,
manifests `ziran.toml`/`tao.toml`, `.zx` module images). Build, run and web
preview drive the `zi` CLI; the compiler's output stays the source of truth.
Published as the `ziran-language` extension (.vsix on GitHub Releases).
Version lives in `package.json` and is bumped with `./update_version.sh`.
## Layout map (question -> file)
| Question | File |
|---|---|
| Activation, commands, settings, completions? | `extension.cjs` |
| Manifest and CLI discovery? | `nearestManifest`, `workspaceManifests`, `ziCommand` in `extension.cjs` |
| Build diagnostics parsing? | `collectDiagnostics` in `extension.cjs` |
| Web preview server? | `serveDirectory`, `showPreview` in `extension.cjs` |
| `.zx` module image parsing and viewer? | `tao-module.cjs` |
| Icons? | `icons/` (`extension.png`, `zx.svg`) |
| Tests? | `tests/*.test.mjs` |
## Commands (from package.json)
```sh
npm ci # install dependencies pinned by package-lock.json
npm test # unit suite: node --test tests/*.test.mjs
npm run package # vsce package
```
## Dependency pins
Runtime: `@iarna/toml`. Dev: `@vscode/vsce`. Engine: VS Code `^1.80.0`.
Exact versions are pinned by `package-lock.json`; install only with `npm ci`.
## Notes
- CLI discovery: `zi.command` setting; else a checkout's `build/zi`
(`build/tao` in older trees) above the manifest or beside the workspace;
else `~/.local/bin/zi`; else `PATH`.
- Release: GitHub Actions uploads a VSIX from every build; maintainers publish
with the workflow's **Run workflow** button and **Publish GitHub Release**.
- Install locally: `code --install-extension ziran-language-*.vsix`.
+85
View File
@@ -0,0 +1,85 @@
# Changes
## 0.1.0
- Refocus the extension on the new Zi runtime. The `zi` command (named `tao`
in older trees) builds `ziran.toml` (or `tao.toml`) projects; **Zi: Build**
reports compiler `path:line` errors in Problems, **Zi: Run** opens the native
window from a terminal, and **Zi: Web Preview** builds and serves the
zi2web output in a browser.
- New Zi Module editor for `.zx` images: reads the module prefix of app and
library images and lists id, kind, version, sha256, imports and exports.
- Import completions suggest the module ids declared by the project manifest.
- Removed the old Ziran compiler surfaces: `.zi` grammar and snippets, the
`.zir` viewer, `ziran check` diagnostics, `ziran api` symbols, run-pane
targets, C/Go conversion and native inspectors, the Kryon preview, the TS
bindings plugin, and the Wine/adb/wasm runners.
## 0.7.1
- Run portable programs as `.zx` files and show the portable file icon for `.zx`.
- Keep `.zi` for source files and `.zir` for checked intermediate modules.
## 0.7.0
- Complete the procedures, types, constants, and globals a file's program declares, with their signatures, as reported by `ziran api`.
- Show a declaration and the comment above it when hovering a name.
- Go to Definition opens the declaration of a procedure, type, constant, or global, not only of an imported module.
## 0.6.3
- Show Python, from `ziran build --target=py`, as a tab in the Run pane's generated code, with highlighting and a checkbox in `ziran.previewTargets`.
## 0.6.2
- Show the Ziran logo as the file icon for `.zi` sources, with blue and brown variants for checked `.zir` modules and `.zib` bundles, and as the extension icon.
## 0.6.1
- Show Plan 9 C as 9c, right after C++, in the generated code tabs.
- The Run pane follows the focused `.zi` file: switching files shows and runs the new one.
## 0.6.0
- Show generated code and the checked `.zir` directly under the program output in the Run pane, like the Kryon preview, instead of in a separate tab.
- Highlight C, C++, Go, Rust, Plan 9 C, and inspected `.zir` in the Run pane.
## 0.5.3
- Show a run's output in a Run pane beside the source, like the Kryon preview, and rerun it on save.
## 0.5.2
- Fix the extension failing to start in 0.5.0 and 0.5.1, which left Run, the generated code preview, checking, and import completion unavailable.
## 0.5.1
- Run any `.zi` file with a `main` procedure from the ▶ button in the editor title bar or the **▶ Run** link above `main`. Output appears in a Ziran terminal.
## 0.5.0
- Check `.zi` files on open and save, with errors in the Problems panel.
- Work with a single `.zi` file: imports resolve from its folder and Ziran's standard modules, without a Kryon project.
- Preview the C, C++, Go, Rust, and Plan 9 C generated for a file with **Ziran: Preview Generated Code**, and choose which targets it shows.
- Show the Kryon preview button only in projects with a `kryon.toml`.
- Use one `ziran.command` setting for checking, previews, and `.zir` browsing.
## 0.4.1
- Highlight `//` and `/* */` comments correctly, including apostrophes in comments.
- Use Ziran's comment syntax when toggling comments in the editor.
## 0.4.0
- Open `.zir` files as readable, searchable modules with an outline and hex view.
- Show rendered terminal frames in a canvas window beside source files.
## 0.3.1
- Show a Run Kryon button in the status bar and above Ziran source in Kryon projects.
## 0.3.0
- Preview Kryon projects beside Ziran source in VS Code.
- Reload the preview when project source or configuration changes.
- Inspect the generated C and checked `.zir` modules for the current preview.
+46 -20
View File
@@ -1,27 +1,53 @@
# Kryon Language for VS Code
# Zi Language for VS Code
Syntax highlighting, brackets, comments, and indentation for `.kry` files.
Editor support for the new Zi runtime (the `tao` tree): `ziran.toml` projects,
TypeScript/TSX sources, `.zx` module images, and the `zi` command line.
VS Code keeps its built-in TypeScript language for `.ts`/`.tsx`; this extension
adds the parts the compiler owns instead.
## Install
## Commands
Download the `.vsix` from the [latest GitHub Release](https://github.com/kryonlabs/kryon-vscode/releases/latest), then run:
All commands look for the nearest `ziran.toml` (or `tao.toml`) above the active
file, then across the workspace, and ask which project to use when several
exist.
- **Zi: Build** runs `zi build <manifest>` and reports compiler errors
(`path:line: message`) in Problems.
- **Zi: Run** runs `zi run <manifest>` in a terminal; the native window opens
from that terminal.
- **Zi: Web Preview** runs `zi web <manifest>`, serves the generated
`build/web` folder on a local port, and opens it in the Simple Browser
(falls back to the system browser when Simple Browser is unavailable).
The ▶ button in the editor title bar runs the project of the open manifest.
## Zi Module editor
Opening any `.zx` image shows what the module actually contains: its id, kind
(app or library), image version, size, sha256, and the module prefix's imports
(with their kind: app, library or wildcard) and exports (with arity,
visibility and code size). The editor never invents text for binary content.
## Import completions
Inside a project, extension-less imports such as `import { twice } from
"ziran/math"` complete the module ids declared by the project manifest.
## Settings
- `zi.command`: path to the `zi` command. Empty finds a checkout's
`build/zi` (or `build/tao` in older trees) above the manifest or beside the
workspace, then `~/.local/bin/zi`, then `PATH`.
## Development
```sh
code --install-extension kryon-language-*.vsix
npm ci # install dependencies pinned by package-lock.json
npm test # unit suite: node --test tests/*.test.mjs
npm run package # vsce package
```
You can also use **Extensions: Install from VSIX...** in VS Code. Reload the
window after installing. New `.kry` tabs will open in Kryon mode automatically.
If an existing tab still says Plain Text in the status bar, use **Change Language
Mode** and select **Kryon**.
## Build
```sh
npm ci
npm run package
```
GitHub Actions uploads a VSIX from every build. Maintainers can use the
workflow's **Run workflow** button with **Publish GitHub Release** enabled to
publish the package version as a public release.
Version lives in `package.json` and is bumped with `./update_version.sh`.
Release: GitHub Actions uploads a VSIX from every build; maintainers publish
with the workflow's **Run workflow** button and **Publish GitHub Release**.
Install locally: `code --install-extension ziran-language-*.vsix`.
+260
View File
@@ -0,0 +1,260 @@
const { execFile } = require('node:child_process');
const fs = require('node:fs');
const fsp = require('node:fs/promises');
const http = require('node:http');
const os = require('node:os');
const path = require('node:path');
const { parse } = require('@iarna/toml');
const vscode = require('vscode');
const { registerModuleViewer } = require('./tao-module.cjs');
const MANIFESTS = ['ziran.toml', 'tao.toml'];
const BINARIES = ['zi', 'tao'];
function quote(value) { return `'${value.replace(/'/g, `'\''`)}'`; }
function executable(file) {
try { fs.accessSync(file, fs.constants.X_OK); return fs.statSync(file).isFile(); }
catch { return false; }
}
// The zi CLI lives in a checkout's build directory; older trees name the
// binary tao during the zi rename.
async function ziCommand(manifest) {
const configured = vscode.workspace.getConfiguration('zi').get('command', '');
if (configured) return configured;
const bases = [];
if (manifest) {
let dir = path.dirname(manifest);
for (;;) {
bases.push(path.join(dir, 'build'), path.join(dir, '..', 'tao', 'build'), path.join(dir, '..', 'zi', 'build'));
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
}
for (const folder of vscode.workspace.workspaceFolders || []) {
const root = folder.uri.fsPath;
bases.push(path.join(root, 'build'), path.join(root, '..', 'tao', 'build'), path.join(root, '..', 'zi', 'build'));
}
bases.push(path.join(os.homedir(), '.local', 'bin'));
for (const base of bases) {
for (const name of BINARIES) {
const candidate = path.join(base, name);
if (executable(candidate)) return candidate;
}
}
return 'zi';
}
async function nearestManifest(fromFile) {
let dir = path.dirname(fromFile);
for (;;) {
for (const name of MANIFESTS) {
const candidate = path.join(dir, name);
if (fs.existsSync(candidate)) return candidate;
}
const parent = path.dirname(dir);
if (parent === dir) return null;
dir = parent;
}
}
async function workspaceManifests() {
const found = [];
const walk = async (dir, depth) => {
if (depth > 4) return;
let entries;
try { entries = await fsp.readdir(dir, { withFileTypes: true }); }
catch { return; }
for (const entry of entries) {
if (entry.isFile() && MANIFESTS.includes(entry.name)) found.push(path.join(dir, entry.name));
else if (entry.isDirectory() && !['.git', 'build', 'dist', 'node_modules', 'backup', 'work'].includes(entry.name)) {
await walk(path.join(dir, entry.name), depth + 1);
}
}
};
for (const folder of vscode.workspace.workspaceFolders || []) {
await walk(folder.uri.fsPath, 0);
}
return [...new Set(found)];
}
async function currentManifest() {
const active = vscode.window.activeTextEditor;
if (active) {
const manifest = await nearestManifest(active.document.uri.fsPath);
if (manifest) return manifest;
}
const manifests = await workspaceManifests();
if (manifests.length === 0) return null;
if (manifests.length === 1) return manifests[0];
return await vscode.window.showQuickPick(manifests, { placeHolder: 'Select a Ziran project manifest' }) || null;
}
function runCommand(command, args, cwd) {
return new Promise((resolve) => {
execFile(command, args, { cwd, maxBuffer: 8 * 1024 * 1024 }, (error, stdout, stderr) => {
const code = error && typeof error.code === 'number' ? error.code : error ? 1 : 0;
resolve({ code, stdout, stderr });
});
});
}
// Compiler errors arrive as "path:line: message" on stderr.
function collectDiagnostics(output, manifestDir, collection) {
const byFile = new Map();
for (const raw of output.split('\n')) {
const match = /^(.+?):([0-9]+): (.+)$/.exec(raw.trim());
if (!match) continue;
const file = path.isAbsolute(match[1]) ? match[1] : path.join(manifestDir, match[1]);
const line = Math.max(0, parseInt(match[2], 10) - 1);
const diagnostic = new vscode.Diagnostic(new vscode.Range(line, 0, line, 240), match[3],
vscode.DiagnosticSeverity.Error);
diagnostic.source = 'zi';
const list = byFile.get(file) || [];
list.push(diagnostic);
byFile.set(file, list);
}
collection.clear();
for (const [file, list] of byFile) collection.set(vscode.Uri.file(file), list);
return byFile.size;
}
const MIME = {
'.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json',
'.png': 'image/png', '.svg': 'image/svg+xml', '.wasm': 'application/wasm', '.map': 'application/json',
};
function serveDirectory(root) {
return new Promise((resolve, reject) => {
const server = http.createServer((request, response) => {
const requestPath = decodeURIComponent((request.url || '/').split('?')[0]);
const relative = path.normalize(requestPath).replace(/^([.][.][/\\])+/, '');
let file = path.join(root, relative);
if (!file.startsWith(root)) {
response.writeHead(403);
response.end();
return;
}
fs.stat(file, (error, stat) => {
if (!error && stat.isDirectory()) file = path.join(file, 'index.html');
fs.readFile(file, (readError, body) => {
if (readError) {
response.writeHead(404);
response.end('not found');
return;
}
response.writeHead(200, { 'content-type': MIME[path.extname(file)] || 'application/octet-stream' });
response.end(body);
});
});
});
server.on('error', reject);
server.listen(0, '127.0.0.1', () => resolve(server));
});
}
async function showPreview(url) {
const simpleBrowser = vscode.extensions.getExtension && vscode.extensions.getExtension('vscode.simple-browser');
if (simpleBrowser) {
await simpleBrowser.activate();
await vscode.commands.executeCommand('simpleBrowser.show', url);
} else {
await vscode.env.openExternal(vscode.Uri.parse(url));
}
}
function activate(context) {
const channel = vscode.window.createOutputChannel('Zi');
const diagnostics = vscode.languages.createDiagnosticCollection('zi-build');
let previewServer = null;
context.subscriptions.push(channel, diagnostics, { dispose() { if (previewServer) previewServer.close(); } });
registerModuleViewer(context);
workspaceManifests().then((manifests) => {
if (manifests.length) void vscode.commands.executeCommand('setContext', 'zi.project', true);
});
const command = async () => {
const manifest = await currentManifest();
if (!manifest) {
await vscode.window.showErrorMessage('No Ziran project found. Open a file inside a folder with a ziran.toml manifest.');
return null;
}
return { manifest, dir: path.dirname(manifest), zi: await ziCommand(manifest) };
};
context.subscriptions.push(vscode.commands.registerCommand('zi.build', async () => {
const project = await command();
if (!project) return;
channel.appendLine(`$ ${project.zi} build ${project.manifest}`);
const result = await runCommand(project.zi, ['build', project.manifest], project.dir);
channel.append(result.stdout);
channel.append(result.stderr);
const failures = collectDiagnostics(result.stderr, project.dir, diagnostics);
if (result.code === 0) {
await vscode.window.showInformationMessage('Zi build finished (build/graph.json).');
} else {
await vscode.window.showErrorMessage(failures
? 'Zi build failed. See Problems for compiler errors.'
: 'Zi build failed. See the Zi output channel for details.');
}
}));
context.subscriptions.push(vscode.commands.registerCommand('zi.run', async () => {
const project = await command();
if (!project) return;
const terminal = vscode.window.createTerminal({ name: 'Zi', cwd: project.dir });
terminal.show();
terminal.sendText(`${quote(project.zi)} run ${quote(project.manifest)}`);
}));
context.subscriptions.push(vscode.commands.registerCommand('zi.web', async () => {
const project = await command();
if (!project) return;
channel.appendLine(`$ ${project.zi} web ${project.manifest}`);
const result = await runCommand(project.zi, ['web', project.manifest], project.dir);
channel.append(result.stdout);
channel.append(result.stderr);
if (result.code !== 0) {
await vscode.window.showErrorMessage('Zi web build failed. See the Zi output channel for details.');
return;
}
const webRoot = path.join(project.dir, 'build', 'web');
try {
await fsp.access(path.join(webRoot, 'index.html'));
} catch {
await vscode.window.showErrorMessage(`The Zi web build produced no index.html under ${webRoot}.`);
return;
}
if (previewServer) previewServer.close();
previewServer = await serveDirectory(webRoot);
const port = previewServer.address().port;
await showPreview(`http://127.0.0.1:${port}/`);
}));
context.subscriptions.push(vscode.languages.registerCompletionItemProvider(['typescript', 'typescriptreact'], {
async provideCompletionItems(document, position) {
const manifest = await nearestManifest(document.uri.fsPath);
if (!manifest) return null;
const prefix = document.lineAt(position.line).text.slice(0, position.character);
const typed = /['"]([A-Za-z0-9_./-]*)$/.exec(prefix);
if (!typed || !/\b(?:from|import)\b/.test(prefix.slice(0, typed.index))) return null;
let config;
try { config = parse(await fsp.readFile(manifest, 'utf8')); }
catch { return null; }
const ids = new Set(Object.keys(config.modules || {}));
if (config.app && config.app.id) ids.add(config.app.id);
return [...ids].filter((id) => id.startsWith(typed[1])).map((id) => {
const item = new vscode.CompletionItem(id, vscode.CompletionItemKind.Module);
item.range = new vscode.Range(position.translate(0, -typed[1].length), position);
return item;
});
},
}));
}
function deactivate() {}
module.exports = { activate, deactivate };
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="10" fill="#8a5a2b"/><path d="M18 17h29v6L26 42h21v6H17v-6l21-19H18z" fill="#fffdf7"/></svg>

After

Width:  |  Height:  |  Size: 185 B

-26
View File
@@ -1,26 +0,0 @@
{
"comments": {
"lineComment": "#"
},
"brackets": [
["{", "}"],
["[", "]"],
["(", ")"]
],
"autoClosingPairs": [
{"open": "{", "close": "}"},
{"open": "[", "close": "]"},
{"open": "(", "close": ")"},
{"open": "\"", "close": "\"", "notIn": ["string"]}
],
"surroundingPairs": [
["{", "}"],
["[", "]"],
["(", ")"],
["\"", "\""]
],
"indentationRules": {
"increaseIndentPattern": "\\{[^}]*$",
"decreaseIndentPattern": "^\\s*\\}"
}
}
+14 -21
View File
@@ -1,17 +1,18 @@
{
"name": "kryon-language",
"version": "0.1.2",
"name": "ziran-language",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kryon-language",
"version": "0.1.2",
"name": "ziran-language",
"version": "0.1.0",
"license": "MIT",
"dependencies": {
"@iarna/toml": "^2.2.5"
},
"devDependencies": {
"@vscode/vsce": "^3.6.0",
"vscode-oniguruma": "^2.0.1",
"vscode-textmate": "^9.3.2"
"@vscode/vsce": "^3.6.0"
},
"engines": {
"vscode": "^1.80.0"
@@ -238,6 +239,12 @@
"node": ">=6.9.0"
}
},
"node_modules/@iarna/toml": {
"version": "2.2.5",
"resolved": "https://registry.npmjs.org/@iarna/toml/-/toml-2.2.5.tgz",
"integrity": "sha512-trnsAYxU3xnS1gPHPyU961coFyLkh4gAD/0zQ5mymY4yOZ+CYvsPqUbOFSw0aDM4y0tV7tiFxL/1XfXPNC6IPg==",
"license": "ISC"
},
"node_modules/@nodelib/fs.scandir": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@@ -3720,20 +3727,6 @@
"url": "https://bevry.me/fund"
}
},
"node_modules/vscode-oniguruma": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/vscode-oniguruma/-/vscode-oniguruma-2.0.1.tgz",
"integrity": "sha512-poJU8iHIWnC3vgphJnrLZyI3YdqRlR27xzqDmpPXYzA93R4Gk8z7T6oqDzDoHjoikA2aS82crdXFkjELCdJsjQ==",
"dev": true,
"license": "MIT"
},
"node_modules/vscode-textmate": {
"version": "9.3.2",
"resolved": "https://registry.npmjs.org/vscode-textmate/-/vscode-textmate-9.3.2.tgz",
"integrity": "sha512-n2uGbUcrjhUEBH16uGA0TvUfhWwliFZ1e3+pTjrkim1Mt7ydB41lV08aUvsi70OlzDWp6X7Bx3w/x3fAXIsN0Q==",
"dev": true,
"license": "MIT"
},
"node_modules/whatwg-encoding": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz",
+90 -23
View File
@@ -1,13 +1,14 @@
{
"name": "kryon-language",
"displayName": "Kryon Language",
"description": "Syntax highlighting and editor behavior for Kryon .kry files",
"version": "0.1.2",
"name": "ziran-language",
"displayName": "Zi Language",
"description": "Zi language support for Ziran projects: manifest builds, run, web preview, and .zx module inspection",
"version": "0.1.0",
"publisher": "kryonlabs",
"license": "MIT",
"icon": "icons/extension.png",
"repository": {
"type": "git",
"url": "https://github.com/kryonlabs/kryon-vscode.git"
"url": "https://github.com/ziranlang/ziran-vscode.git"
},
"engines": {
"vscode": "^1.80.0"
@@ -15,35 +16,101 @@
"categories": [
"Programming Languages"
],
"main": "./extension.cjs",
"activationEvents": [
"workspaceContains:**/ziran.toml",
"workspaceContains:**/tao.toml",
"onCommand:zi.build",
"onCommand:zi.run",
"onCommand:zi.web",
"onCustomEditor:zi.moduleViewer"
],
"contributes": {
"languages": [
"customEditors": [
{
"id": "kryon",
"aliases": [
"Kryon",
"kry"
"viewType": "zi.moduleViewer",
"displayName": "Zi Module",
"selector": [
{
"filenamePattern": "*.zx"
}
],
"extensions": [
".kry"
],
"configuration": "./language-configuration.json"
"priority": "default"
}
],
"grammars": [
"languages": [
{
"language": "kryon",
"scopeName": "source.kryon",
"path": "./syntaxes/kryon.tmLanguage.json"
"id": "zi-bundle",
"aliases": [
"Zi Module"
],
"extensions": [
".zx"
],
"icon": {
"light": "./icons/zx.svg",
"dark": "./icons/zx.svg"
}
}
]
],
"commands": [
{
"command": "zi.build",
"title": "Zi: Build"
},
{
"command": "zi.run",
"title": "Zi: Run",
"icon": "$(play)"
},
{
"command": "zi.web",
"title": "Zi: Web Preview",
"icon": "$(browser)"
}
],
"menus": {
"editor/title": [
{
"command": "zi.run",
"when": "resourceFilename == ziran.toml || resourceFilename == tao.toml",
"group": "navigation@0"
}
]
},
"commandPalette": [
{
"command": "zi.build",
"when": "zi.project"
},
{
"command": "zi.run",
"when": "zi.project"
},
{
"command": "zi.web",
"when": "zi.project"
}
],
"configuration": {
"title": "Zi",
"properties": {
"zi.command": {
"type": "string",
"default": "",
"description": "Path to the zi command used to build, run, and preview projects. Empty finds a checkout's build/zi (build/tao in older trees) above the manifest or beside the workspace, then ~/.local/bin/zi, then PATH."
}
}
}
},
"scripts": {
"test": "node --test tests/*.test.mjs",
"package": "vsce package --no-dependencies"
"package": "vsce package"
},
"devDependencies": {
"@vscode/vsce": "^3.6.0",
"vscode-oniguruma": "^2.0.1",
"vscode-textmate": "^9.3.2"
"@vscode/vsce": "^3.6.0"
},
"dependencies": {
"@iarna/toml": "^2.2.5"
}
}
-98
View File
@@ -1,98 +0,0 @@
{
"name": "Kryon",
"scopeName": "source.kryon",
"patterns": [
{"include": "#strings"},
{"include": "#directives"},
{"include": "#comments"},
{"include": "#declarations"},
{"include": "#types"},
{"include": "#numbers"},
{"include": "#keywords"},
{"include": "#operators"}
],
"repository": {
"strings": {
"patterns": [
{
"name": "string.quoted.double.kryon",
"begin": "\"",
"end": "\"",
"patterns": [{"name": "constant.character.escape.kryon", "match": "\\\\(?:[0-7]{1,3}|x[0-9a-fA-F]+|[\\\\\"'abfnrtv0])"}]
},
{
"name": "string.quoted.single.kryon",
"begin": "'",
"end": "'",
"patterns": [{"name": "constant.character.escape.kryon", "match": "\\\\(?:[0-7]{1,3}|x[0-9a-fA-F]+|[\\\\\"'abfnrtv0])"}]
}
]
},
"directives": {
"patterns": [
{
"name": "meta.preprocessor.kryon",
"match": "(?<!\\S)(#)(import|module|style|else_if|elif|if|else|endif|enum|assert|include)\\b",
"captures": {
"1": {"name": "punctuation.definition.directive.kryon"},
"2": {"name": "keyword.control.directive.kryon"}
}
},
{
"name": "storage.modifier.kryon",
"match": "#(?:private|export|extern|ui|slot|type|intrinsic|host|global|defined|const|attr)\\b"
}
]
},
"comments": {
"patterns": [
{"name": "comment.line.number-sign.kryon", "match": "#.*$"},
{"name": "comment.line.double-slash.kryon", "match": "//.*$"},
{"name": "comment.block.kryon", "begin": "/\\*", "end": "\\*/"}
]
},
"declarations": {
"patterns": [
{
"match": "\\b([A-Za-z_][A-Za-z_0-9]*)(\\s*)(::)(?=\\s*(?:\\(|struct\\b|enum\\b|union\\b|#import\\b))",
"captures": {
"1": {"name": "entity.name.function.kryon"},
"3": {"name": "keyword.operator.declaration.kryon"}
}
},
{
"match": "\\b([A-Za-z_][A-Za-z_0-9]*)(\\s*)(::)",
"captures": {
"1": {"name": "entity.name.constant.kryon"},
"3": {"name": "keyword.operator.declaration.kryon"}
}
},
{"name": "entity.name.function.call.kryon", "match": "\\b[A-Za-z_][A-Za-z_0-9]*(?=\\s*\\()"}
]
},
"types": {
"patterns": [
{"name": "storage.type.kryon", "match": "\\b(?:bool|char|int|float|double|void|size_t|i8|i16|i32|i64|u8|u16|u32|u64|f32|f64|string)\\b"},
{"name": "storage.type.definition.kryon", "match": "\\b(?:struct|enum|union|state)\\b"},
{"name": "entity.name.type.kryon", "match": "\\b[A-Z][A-Za-z_0-9]*\\b"}
]
},
"numbers": {
"patterns": [
{"name": "constant.numeric.kryon", "match": "\\b(?:0[xX][0-9a-fA-F]+|0[bB][01]+|[0-9]+(?:\\.[0-9]*)?(?:[eE][+-]?[0-9]+)?)(?:[uUlLfF]*)\\b"}
]
},
"keywords": {
"patterns": [
{"name": "keyword.control.kryon", "match": "\\b(?:if|else|for|while|switch|case|default|break|continue|return|defer|goto|in)\\b"},
{"name": "storage.modifier.kryon", "match": "\\b(?:const|static|extern|inline|unused)\\b"},
{"name": "constant.language.kryon", "match": "\\b(?:true|false|nil|NULL)\\b"}
]
},
"operators": {
"patterns": [
{"name": "keyword.operator.kryon", "match": "(?:::|:=|->|==|!=|<=|>=|&&|\\|\\||[+*/%=!<>?:&|^-])"}
]
}
}
}
+122
View File
@@ -0,0 +1,122 @@
const { createHash } = require('node:crypto');
const RECORD = { APP_ID: 0x0b, IMPORT: 0x0c, EXPORT: 0x0d, END: 0xff };
const KINDS = { TAO1: 'app', AO01: 'library' };
function u16(data, at) { return data[at] | (data[at + 1] << 8); }
function readString(data, at) {
const length = u16(data, at);
if (at + 2 + length > data.length) throw new Error('truncated string record');
return [data.slice(at + 2, at + 2 + length).toString('utf8'), at + 2 + length];
}
// Zi module images share one module prefix in both kinds. Apps ("TAO1")
// continue with view and state records; libraries ("AO01") end at REC_END.
function parseModuleImage(buffer) {
const data = Buffer.from(buffer);
if (data.length < 9) throw new Error('truncated module image');
const magic = data.slice(0, 4).toString('latin1');
const kind = KINDS[magic];
if (!kind) throw new Error(`not a Zi module image (magic ${JSON.stringify(magic)})`);
const version = data[4];
const expectedVersion = kind === 'app' ? 3 : 1;
if (version !== expectedVersion) throw new Error(`unsupported ${kind} image version ${version}`);
let at = 8;
if (data[at] !== RECORD.APP_ID) throw new Error('image does not start with a module record');
at += 1;
let id;
[id, at] = readString(data, at);
const imports = [];
const exports = [];
while (at < data.length) {
const tag = data[at];
if (tag === RECORD.IMPORT) {
at += 1;
const appFlag = data[at];
at += 1;
let name;
let importId;
[name, at] = readString(data, at);
[importId, at] = readString(data, at);
const importKind = appFlag === 0 ? 'library' : appFlag === 1 ? 'app' : 'wildcard';
imports.push({ name, id: importId, kind: importKind });
} else if (tag === RECORD.EXPORT) {
at += 1;
let name;
[name, at] = readString(data, at);
const isPublic = data[at] === 1;
at += 1;
const arity = data[at];
at += 1;
const codeLength = u16(data, at);
at += 2;
if (at + codeLength > data.length) throw new Error('truncated export record');
at += codeLength;
exports.push({ name, public: isPublic, arity, bytes: codeLength });
} else break;
}
const info = { kind, version, id, imports, exports, size: data.length };
if (kind === 'library') {
if (at + 1 !== data.length || data[at] !== RECORD.END) {
info.trailing = data.length - at;
}
} else {
info.views = data.length - at;
}
info.sha256 = createHash('sha256').update(data).digest('hex');
return info;
}
function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
function moduleHtml(info) {
const importRows = info.imports.map((entry) =>
`<tr><td><code>${escapeHtml(entry.name)}</code></td><td><code>${escapeHtml(entry.id)}</code></td><td>${escapeHtml(entry.kind)}</td></tr>`).join('');
const exportRows = info.exports.map((entry) =>
`<tr><td><code>${escapeHtml(entry.name)}</code></td><td>${entry.arity}</td><td>${entry.public ? 'public' : 'local'}</td><td>${entry.bytes}</td></tr>`).join('');
const trailing = info.trailing === undefined ? '' :
`<p class="warn">${info.trailing} unexpected trailing bytes after the module prefix</p>`;
return `<!DOCTYPE html>
<html><head><meta charset="utf-8"><style>
body { font-family: var(--vscode-editor-font-family); margin: 12px; color: var(--vscode-editor-foreground); }
h1 { font-size: 1.2em; } h2 { font-size: 1em; }
table { border-collapse: collapse; margin: 6px 0; }
td, th { border: 1px solid var(--vscode-panel-border); padding: 2px 8px; text-align: left; }
.warn { color: var(--vscode-errorForeground); }
.hash { opacity: 0.8; font-size: 0.85em; }
</style></head><body>
<h1>${escapeHtml(info.id)}</h1>
<p>${escapeHtml(info.kind)} image, version ${info.version}, ${info.size} bytes</p>
<p class="hash">sha256 ${escapeHtml(info.sha256)}</p>
${trailing}
<h2>Imports (${info.imports.length})</h2>
${info.imports.length ? `<table><tr><th>name</th><th>module</th><th>kind</th></tr>${importRows}</table>` : '<p>none</p>'}
<h2>Exports (${info.exports.length})</h2>
${info.exports.length ? `<table><tr><th>name</th><th>arity</th><th>visibility</th><th>code bytes</th></tr>${exportRows}</table>` : '<p>none</p>'}
</body></html>`;
}
function registerModuleViewer(context) {
const vscode = require('vscode');
const provider = {
openCustomDocument(uri) { return { uri, dispose() {} }; },
async resolveCustomEditor(document, webviewPanel) {
webviewPanel.webview.options = { enableScripts: false };
const fs = require('node:fs/promises');
let html;
try {
html = moduleHtml(parseModuleImage(await fs.readFile(document.uri.fsPath)));
} catch (error) {
html = `<!DOCTYPE html><html><body style="font-family: sans-serif; color: var(--vscode-errorForeground)">${escapeHtml(error.message)}</body></html>`;
}
webviewPanel.webview.html = html;
},
};
context.subscriptions.push(vscode.window.registerCustomEditorProvider('zi.moduleViewer', provider,
{ supportsMultipleEditorsPerDocument: false }));
}
module.exports = { parseModuleImage, moduleHtml, registerModuleViewer };
+104
View File
@@ -0,0 +1,104 @@
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import Module from 'node:module';
import { createRequire } from 'node:module';
import { test } from 'node:test';
const require = createRequire(import.meta.url);
const disposable = { dispose() {} };
const registered = [];
const providers = [];
class Position {
constructor(line, character) { this.line = line; this.character = character; }
translate(lineDelta, characterDelta) {
return new Position(this.line + lineDelta, this.character + characterDelta);
}
}
const vscode = {
commands: {
registerCommand(name) { registered.push(name); return disposable; },
executeCommand() {},
},
window: {
createOutputChannel: () => ({ append() {}, appendLine() {}, show() {}, dispose() {} }),
registerCustomEditorProvider: (viewType) => { providers.push(viewType); return disposable; },
activeTextEditor: undefined,
showErrorMessage: async () => undefined,
showInformationMessage: async () => undefined,
showQuickPick: async () => null,
createTerminal: () => ({ show() {}, sendText() {} }),
},
languages: {
createDiagnosticCollection: () => ({ set() {}, delete() {}, clear() {}, dispose() {} }),
registerCompletionItemProvider: (languages, provider) => { providers.push(provider); return disposable; },
},
workspace: {
getConfiguration: () => ({ get: () => '' }),
workspaceFolders: [],
},
extensions: { getExtension: () => undefined },
env: { openExternal: async () => undefined },
Uri: {
file: (fsPath) => ({ fsPath }),
parse: (value) => ({ value }),
},
Range: class { constructor(start, end) { this.start = start; this.end = end; } },
Position,
Diagnostic: class { constructor(range, message, severity) { this.range = range; this.message = message; this.severity = severity; } },
DiagnosticSeverity: { Error: 0 },
CompletionItem: class { constructor(label, kind) { this.label = label; this.kind = kind; } },
CompletionItemKind: { Module: 8 },
};
const resolveFilename = Module._resolveFilename;
Module._resolveFilename = function (request, ...rest) {
if (request === 'vscode') return 'vscode-mock';
return resolveFilename.call(this, request, ...rest);
};
require.cache['vscode-mock'] = { id: 'vscode-mock', filename: 'vscode-mock', loaded: true, exports: vscode };
const { activate } = require('../extension.cjs');
const subscriptions = [];
activate({ subscriptions });
test('activation registers the Zi commands, the module viewer, and import completions', () => {
assert.deepEqual(registered.slice().sort(), ['zi.build', 'zi.run', 'zi.web']);
assert.ok(providers.includes('zi.moduleViewer'));
const completions = providers.find((provider) => provider && provider.provideCompletionItems);
assert.ok(completions);
});
test('import completions list manifest modules', async () => {
const project = mkdtempSync(path.join(tmpdir(), 'zi-extension-'));
const nested = path.join(project, 'examples', 'two-counters');
mkdirSync(nested, { recursive: true });
writeFileSync(path.join(project, 'ziran.toml'), [
'[app]',
'id = "examples/two-counters"',
'source = "host.tsx"',
'',
'[modules."ziran/math"]',
'source = "../../modules/math/math.ts"',
'kind = "library"',
'',
].join('\n'));
const source = path.join(nested, 'host.tsx');
writeFileSync(source, 'import { twice } from "ziran/ma"');
const document = {
uri: { fsPath: source },
lineAt: () => ({ text: 'import { twice } from "ziran/ma"' }),
};
const position = new Position(0, 30);
try {
const completions = providers.find((provider) => provider && provider.provideCompletionItems);
const items = await completions.provideCompletionItems(document, position);
assert.deepEqual(items.map((item) => item.label), ['ziran/math']);
} finally {
rmSync(project, { recursive: true, force: true });
}
});
-51
View File
@@ -1,51 +0,0 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { test } from 'node:test';
import oniguruma from 'vscode-oniguruma';
import textmate from 'vscode-textmate';
const require = createRequire(import.meta.url);
await oniguruma.loadWASM(readFileSync(require.resolve('vscode-oniguruma/release/onig.wasm')));
const registry = new textmate.Registry({
onigLib: Promise.resolve({
createOnigScanner: (sources) => new oniguruma.OnigScanner(sources),
createOnigString: (source) => new oniguruma.OnigString(source),
}),
loadGrammar: async (scopeName) => {
if (scopeName !== 'source.kryon') {
return null;
}
const source = readFileSync('syntaxes/kryon.tmLanguage.json', 'utf8');
return textmate.parseRawGrammar(source, 'kryon.tmLanguage.json');
},
});
const grammar = await registry.loadGrammar('source.kryon');
function scopesAt(line, index) {
const { tokens } = grammar.tokenizeLine(line);
const token = tokens.find(({ startIndex, endIndex }) => startIndex <= index && index < endIndex);
assert.ok(token, `No grammar token at index ${index} in ${line}`);
return token.scopes;
}
for (const directive of ['#else', '#else_if WEB', '#elif WEB']) {
test(`inline ${directive} leaves its opening brace visible to the editor`, () => {
const line = ` } ${directive} {`;
assert.ok(scopesAt(line, line.indexOf('#')).includes('meta.preprocessor.kryon'));
assert.ok(!scopesAt(line, line.lastIndexOf('{')).some((scope) => scope.startsWith('comment.')));
});
}
test('a function attribute does not hide its opening brace', () => {
const line = 'function :: () #export #attr "EMSCRIPTEN_KEEPALIVE" {';
assert.ok(scopesAt(line, line.indexOf('#attr')).includes('storage.modifier.kryon'));
assert.ok(!scopesAt(line, line.lastIndexOf('{')).some((scope) => scope.startsWith('comment.')));
});
test('ordinary hash comments remain comments', () => {
const line = ' # explanation {';
assert.ok(scopesAt(line, line.lastIndexOf('{')).includes('comment.line.number-sign.kryon'));
});
+72
View File
@@ -0,0 +1,72 @@
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { test } from 'node:test';
const require = createRequire(import.meta.url);
const { moduleHtml, parseModuleImage } = require('../tao-module.cjs');
function header(magic, version) {
return Buffer.concat([Buffer.from(magic, 'latin1'), Buffer.from([version, 0, 0, 0])]);
}
function str(value) {
const bytes = Buffer.from(value, 'utf8');
const out = Buffer.alloc(2 + bytes.length);
out.writeUInt16LE(bytes.length);
bytes.copy(out, 2);
return out;
}
function u16(value) {
const out = Buffer.alloc(2);
out.writeUInt16LE(value);
return out;
}
function libraryImage() {
return Buffer.concat([
header('AO01', 1),
Buffer.from([0x0b]), str('ziran/math'),
Buffer.from([0xff]),
]);
}
function appImage() {
return Buffer.concat([
header('TAO1', 3),
Buffer.from([0x0b]), str('examples/two-counters'),
Buffer.from([0x0c, 2]), str('twice'), str('ziran/math'),
Buffer.from([0x0d]), str('double'), Buffer.from([1, 2]), u16(4), Buffer.from([1, 2, 3, 4]),
Buffer.from([0x02, 0x00]),
]);
}
test('library images parse and end at the module record', () => {
const info = parseModuleImage(libraryImage());
assert.equal(info.kind, 'library');
assert.equal(info.id, 'ziran/math');
assert.deepEqual(info.imports, []);
assert.deepEqual(info.exports, []);
assert.equal(info.trailing, undefined);
assert.match(info.sha256, /^[0-9a-f]{64}$/);
});
test('app images keep imports, exports, and trailing view records', () => {
const info = parseModuleImage(appImage());
assert.equal(info.kind, 'app');
assert.equal(info.id, 'examples/two-counters');
assert.deepEqual(info.imports, [{ name: 'twice', id: 'ziran/math', kind: 'wildcard' }]);
assert.deepEqual(info.exports, [{ name: 'double', public: true, arity: 2, bytes: 4 }]);
assert.equal(info.views, 2);
});
test('foreign magic and broken versions are rejected', () => {
assert.throws(() => parseModuleImage(Buffer.from('NOPE0000')));
assert.throws(() => parseModuleImage(header('TAO1', 9)));
});
test('module html escapes ids and lists imports', () => {
const html = moduleHtml(parseModuleImage(appImage()));
assert.match(html, /examples\/two-counters/);
assert.match(html, /ziran\/math/);
assert.match(html, /wildcard/);
});
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
set -eu
version=${1:-$(sed -n 's/^## \([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)$/\1/p' CHANGELOG.md | head -n 1)}
test -n "$version"
node - "$version" <<'NODE'
const fs = require('node:fs');
const version = process.argv[2];
for (const file of ['package.json', 'package-lock.json']) {
const data = JSON.parse(fs.readFileSync(file, 'utf8'));
data.version = version;
if (file === 'package-lock.json') data.packages[''].version = version;
fs.writeFileSync(file, JSON.stringify(data, null, 2) + '\n');
}
NODE