Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d27ad25cfc | ||
|
|
571f6dbf2c | ||
|
|
2e6ff5462e | ||
|
|
cb06e01764 | ||
|
|
6baa709f45 | ||
|
|
3423d65d28 | ||
|
|
771332f14a | ||
|
|
9ffb4e34b3 | ||
|
|
874e01a2f7 | ||
|
|
0aebcc4ed7 | ||
|
|
e795d212f9 | ||
|
|
80005abb13 | ||
|
|
7dd0fe963f | ||
|
|
b8ba182d82 | ||
|
|
df36044cc6 | ||
|
|
c10612795e | ||
|
|
76a07546ab | ||
|
|
568dbeeed5 | ||
|
|
26bf07e3de | ||
|
|
9c34866c1d | ||
|
|
635de9a96f | ||
|
|
6d9be7844b | ||
|
|
192fff9b86 | ||
|
|
80fa347024 | ||
|
|
b47e9e2e62 | ||
|
|
b7cef6ace4 | ||
|
|
69524923ce | ||
|
|
ace798f63d | ||
|
|
8259ce596f | ||
|
|
b86b59457b | ||
|
|
74e7b20258 | ||
|
|
689c349e10 | ||
|
|
4b981fbc54 | ||
|
|
907d5653e1 | ||
|
|
30615d3dbd | ||
|
|
9eca22b3eb | ||
|
|
ffbdc20b2b | ||
|
|
05cc99700a | ||
|
|
7d8c05af48 | ||
|
|
3d51ab48e2 | ||
|
|
cf93f3943b | ||
|
|
2207ccd865 | ||
|
|
3ca95ac909 | ||
|
|
f7fe2c9b30 | ||
|
|
fb95178645 | ||
|
|
3688f31785 | ||
|
|
4e1202dfbe | ||
|
|
b788d17a48 | ||
|
|
5c53e295be | ||
|
|
eb0dcb5413 | ||
|
|
3c45c1c67f | ||
|
|
f41098b7c6 | ||
|
|
872d62e6e1 | ||
|
|
28d6b7f941 | ||
|
|
2ab50616bf | ||
|
|
3932dde4cc | ||
|
|
0608354071 | ||
|
|
46eddfca56 | ||
|
|
490f642a2a | ||
|
|
e84cb6efc9 | ||
|
|
f2219c8580 | ||
|
|
a9e60efac6 | ||
|
|
4766f7295c | ||
|
|
968eb989ca | ||
|
|
8c85576568 | ||
|
|
4d20b2f770 | ||
|
|
ecffbf8734 | ||
|
|
c537a21f63 | ||
|
|
0fc191f204 |
No files matched your search
@@ -25,12 +25,13 @@ jobs:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
- 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:
|
||||
@@ -43,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,2 +1,3 @@
|
||||
node_modules/
|
||||
*.vsix
|
||||
tests/.runtime-*/
|
||||
+6
-1
@@ -1,6 +1,11 @@
|
||||
node_modules/**
|
||||
scripts/**
|
||||
tests/**
|
||||
.github/**
|
||||
.gitignore
|
||||
*.vsix
|
||||
package-lock.json
|
||||
update_version.sh
|
||||
TODO.md
|
||||
.npmrc
|
||||
DONE.md
|
||||
backup/**
|
||||
@@ -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`.
|
||||
@@ -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.
|
||||
@@ -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
@@ -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 |
@@ -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 |
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"comments": {
|
||||
"lineComment": "#"
|
||||
},
|
||||
"brackets": [
|
||||
["{", "}"],
|
||||
["[", "]"],
|
||||
["(", ")"]
|
||||
],
|
||||
"autoClosingPairs": [
|
||||
{"open": "{", "close": "}"},
|
||||
{"open": "[", "close": "]"},
|
||||
{"open": "(", "close": ")"},
|
||||
{"open": "\"", "close": "\"", "notIn": ["string"]}
|
||||
],
|
||||
"surroundingPairs": [
|
||||
["{", "}"],
|
||||
["[", "]"],
|
||||
["(", ")"],
|
||||
["\"", "\""]
|
||||
],
|
||||
"indentationRules": {
|
||||
"increaseIndentPattern": "\\{[^}]*$",
|
||||
"decreaseIndentPattern": "^\\s*\\}"
|
||||
}
|
||||
}
|
||||
Generated
+11
-2
@@ -1,13 +1,16 @@
|
||||
{
|
||||
"name": "kryon-language",
|
||||
"name": "ziran-language",
|
||||
"version": "0.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "kryon-language",
|
||||
"name": "ziran-language",
|
||||
"version": "0.1.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@iarna/toml": "^2.2.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vscode/vsce": "^3.6.0"
|
||||
},
|
||||
@@ -236,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",
|
||||
|
||||
+93
-16
@@ -1,39 +1,116 @@
|
||||
{
|
||||
"name": "kryon-language",
|
||||
"displayName": "Kryon Language",
|
||||
"description": "Syntax highlighting and editor behavior for Kryon .kry files",
|
||||
"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"
|
||||
},
|
||||
"categories": ["Programming Languages"],
|
||||
"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"],
|
||||
"extensions": [".kry"],
|
||||
"configuration": "./language-configuration.json"
|
||||
"viewType": "zi.moduleViewer",
|
||||
"displayName": "Zi Module",
|
||||
"selector": [
|
||||
{
|
||||
"filenamePattern": "*.zx"
|
||||
}
|
||||
],
|
||||
"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": {
|
||||
"package": "vsce package --no-dependencies"
|
||||
"test": "node --test tests/*.test.mjs",
|
||||
"package": "vsce package"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vscode/vsce": "^3.6.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@iarna/toml": "^2.2.5"
|
||||
}
|
||||
}
|
||||
@@ -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|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)\\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
@@ -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) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[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 };
|
||||
@@ -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 });
|
||||
}
|
||||
});
|
||||
@@ -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/);
|
||||
});
|
||||
Executable
+15
@@ -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
|
||||
Reference in new issue
Block a user