language-service 0.0.2-preview.1

The Zena language service, which gives editors diagnostics, completions and navigation

Readme Files Dependencies Versions

language-service#

The Zena language service and Language Server Protocol (LSP) library: diagnostics, lint findings and quick fixes, hover, completions, go-to-definition, document symbols, and formatting.

Used by zena lsp (in packages/cli) and compiled to WebAssembly by @zena-lang/compiler (packages/compiler-js) for JavaScript, browser, and VS Code hosts.

Usage in Zena#

import { createLanguageService } from 'language-service';
import { LspServer } from 'language-service/server';
import { readFile } from 'zena:fs';

async function readOrNull(path: String): Future<String | null> {
  try {
    return await readFile(path);
  } catch (e) {
    return null;
  }
}

let service = createLanguageService('/stdlib', readOrNull, 'zena-component');
let diagnostics = await service.check('/workspace/main.zena', 'export let x = 42;');

Zena Libraries#

  • language-service / language-service/service — LanguageService (createLanguageService, check, lint, hover, completions, definition, documentSymbols)
  • language-service/server — LspServer JSON-RPC request/notification handler (LspServer, MessageReader, frame, offsetOf, positionOf)
  • language-service/protocol — LSP JSON serializers and error codes
  • language-service/framing — Content-Length message framing (MessageReader, frame)
  • language-service/positions — UTF-16 line/character positions to and from byte offsets (offsetOf, positionOf)
  • language-service/hover — hover type and doc-comment formatting
  • language-service/completion — identifier, member, and keyword completions
  • language-service/symbols — document symbol outline (documentSymbols, DocumentSymbol, SymbolKind)
  • language-service/compile — in-memory compilation to WebAssembly bytes (compileToWasm)
  • language-service/host — overlay CompilerHost serving open documents in place of disk files (DocumentHost)
  • language-service/analysis — per-document checked AST and scope analysis

License#

MIT

5.1 KiB Raw
/**
 * The compiler host behind the language service. It serves the
 * documents an editor has open in place of the files on disk.
 */

import { CompilerHost, buildStdlibConfig } from 'compiler/compiler';
import { ModuleExport, stdlibIdToRelativeFile } from 'compiler/module-resolver';
import { isWitModulePath, synthesizeWitModule } from 'compiler/wit-module-synth';
import { readWitSource } from 'compiler/wit-source';

/**
 * Reads a file that is not open in the editor, by path; null when there
 * is no such file.
 */
export type FileReader = (path: String) => Future<String | null>;

/**
 * Lists the entry names in a directory on the host; null when there is no
 * such directory.
 */
export type DirReader = (path: String) => Future<Array<String> | null>;

/**
 * A path as the service keys its state. An editor may send a path
 * without its leading slash; a standard library id like `zena:core` or a
 * synthesized WIT id like `wit:...` is left as it is.
 */
export function normalizePath(path: String): String {
  return if (path.startsWith('/') || path.startsWith('zena:') || path.startsWith('wit:')) {
    path
  } else {
    `/${path}`
  };
}

/** Strips any trailing slash from `dir` unless `dir` is `/`. */
function trimTrailingSlash(dir: String) {
  if (dir.length > 1 && dir.endsWith('/')) {
    return dir.sliceBytes(0, dir.length - 1);
  }
  return dir;
}

/**
 * Serves the compiler the editor's copy of each open document, and
 * everything else through the reader it was given.
 */
export class DocumentHost implements CompilerHost {
  #openDocuments = new Map<String, String>();
  #stdlibRoot: String;
  #stdlibExports: HashMap<String, ModuleExport> | null;
  #readFile: FileReader;
  #listDir: DirReader | null;
  var #wasiWitLoaded = false;
  var #wasiWit = '';

  new(stdlibRoot: String, readFile: FileReader, listDir: DirReader | null = null)
    : #stdlibRoot = trimTrailingSlash(stdlibRoot),
      #stdlibExports = buildStdlibConfig(trimTrailingSlash(stdlibRoot)).exports,
      #readFile = readFile,
      #listDir = listDir;

  /**
   * Maps a path inside `#stdlibRoot` to its canonical `zena:` module id
   * (matching `ModuleResolver`), leaving all other paths unchanged.
   */
  canonicalizePath(path: String): String {
    if (path.startsWith('zena:') || path.startsWith('wit:')) {
      return path;
    }
    let norm = normalizePath(path);
    let prefix = `${this.#stdlibRoot}/`;
    if (!norm.startsWith(prefix)) {
      return path;
    }
    let rel = norm.sliceBytes(prefix.length, norm.length);
    if (!rel.endsWith('.zena')) {
      return path;
    }
    if (!rel.contains('/')) {
      let name = rel.sliceBytes(0, rel.length - 5);
      let exports = this.#stdlibExports;
      if (exports != null) {
        if (let (true, moduleExport) = exports.get(name)) {
          if (moduleExport.virtual == null && moduleExport.path == null) {
            return `zena:${name}`;
          }
        }
      }
    }
    return `zena:${rel}`;
  }

  /**
   * Where a module is on disk: a standard library id like `zena:core`
   * maps into the standard library's directory, and any other path is
   * already one.
   */
  resolveToFilesystemPath(path: String): String {
    if (path.startsWith('zena:')) {
      let sub = path.sliceBytes(5, path.length);
      if (sub == 'core' || sub == 'core.zena') {
        return `${this.#stdlibRoot}/core/index.zena`;
      }
      return `${this.#stdlibRoot}/${stdlibIdToRelativeFile(path)}`;
    }
    return path;
  }

  /** Registers or updates an open document's source. */
  setDocument(path: String, source: String): void {
    this.#openDocuments[path] = source;
    let canonical = this.canonicalizePath(path);
    if (canonical != path) {
      this.#openDocuments[canonical] = source;
    }
  }

  deleteDocument(path: String): void {
    this.#openDocuments.delete(path);
    let canonical = this.canonicalizePath(path);
    if (canonical != path) {
      this.#openDocuments.delete(canonical);
    }
  }

  async #ensureWasiWit(): Future<String> {
    if (this.#wasiWitLoaded) {
      return this.#wasiWit;
    }
    this.#wasiWitLoaded = true;
    try {
      this.#wasiWit = await readWitSource(this, `${this.#stdlibRoot}/wit`);
    } catch (e) {
      this.#wasiWit = '';
    }
    return this.#wasiWit;
  }

  async readFile(path: String): Future<String> {
    if (isWitModulePath(path)) {
      let wasiWit = await this.#ensureWasiWit();
      return await synthesizeWitModule(this, path, wasiWit);
    }
    if (let (true, source) = this.#openDocuments.get(path)) {
      return source;
    }
    let fsPath = this.resolveToFilesystemPath(path);
    if (let (true, openByFs) = this.#openDocuments.get(fsPath)) {
      return openByFs;
    }
    let read = this.#readFile;
    let content = await read(fsPath);
    if (content == null) {
      throw new Error(`File not found: ${fsPath}`);
    }
    return content;
  }

  /**
   * Lists a directory through the host's directory reader, or null when
   * none was provided or the path is not a directory.
   */
  async listDir(path: String): Future<Array<String> | null> {
    let list = this.#listDir;
    if (list == null) {
      return null;
    }
    let fsPath = this.resolveToFilesystemPath(path);
    return await list(fsPath);
  }
}
  • compiler compiler.zena-lang.pkg.zena-lang.dev 0.0.2-preview.1
  • formatter formatter.zena-lang.pkg.zena-lang.dev 0.0.2-preview.1
  • lint lint.zena-lang.pkg.zena-lang.dev 0.0.2-preview.1
VersionPublishedDependenciesApproved by
0.0.2-preview.1 2026-11-19
  • compiler compiler.zena-lang.pkg.zena-lang.dev 0.0.2-preview.1
  • formatter formatter.zena-lang.pkg.zena-lang.dev 0.0.2-preview.1
  • lint lint.zena-lang.pkg.zena-lang.dev 0.0.2-preview.1