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

8.6 KiB Raw
/**
 * Hover: the type of what is under the cursor, how it was declared, and
 * its doc comment.
 */

import {
  CompilerTarget, ProgramCheckResult, SemanticModel, findNodeAtOffset, typeToString,
} from 'compiler/compiler';
import { Type, ClassType, FieldInfo, MethodInfo } from 'compiler/types';
import { Symbol, ScopeResult } from 'compiler/scope';
import {
  Node, Module, Identifier, IdentifierPattern, ThisExpression, MemberExpression, Parameter, ClassDeclaration, FieldDefinition, MethodDefinition, ImportSpecifier,
} from 'compiler/ast';
import { attachComments } from 'compiler/comment-attachment';
import { DocComment, declarationDoc, docCommentAt } from 'compiler/doc-comment';
import { FileAnalysis, spans, symbolUnder } from './analysis.zena';

/**
 * What hover shows: the type, a label that reads like the declaration
 * (`let x: i32`, `class Point`), and the doc comment, empty if none.
 */
export class HoverResult {
  typeStr: String;
  label: String;
  docComment: String;
  new(this.typeStr, this.label, this.docComment);
}

/** A doc comment's text, or empty when there is none. */
function docText(doc: DocComment | null) {
  return doc?.raw ?? '';
}

/** The name a node spells, for an identifier or a binding pattern. */
function nodeName(node: Node): String | null {
  return match (node) {
  case Identifier {name}: name
  case IdentifierPattern {name}: name
  case _: null
};
}

/** The class declaration around `offset`, if any. */
function enclosingClass(ast: Module, offset: i32): ClassDeclaration | null {
  for (let stmt in ast.body) {
    if (stmt is ClassDeclaration && spans(stmt, offset)) {
      return stmt;
    }
  }
  return null;
}

/**
 * A class's type. The checker records it on the declaration; the
 * binding is where to look when it did not.
 */
function classTypeOf(decl: ClassDeclaration, model: SemanticModel): Type | null {
  let nodeType = model.getNodeType(decl);
  if (nodeType != null) {
    return nodeType;
  }
  let sym = model.resolveDeclaration(decl);
  if (sym == null) {
    return null;
  }
  return model.getBindingType(sym);
}

/** A label that reads like the declaration of `node`, of type `typeStr`. */
function hoverLabel(node: Node, typeStr: String, scopes: ScopeResult | null) {
  let name = nodeName(node);
  if (name == null) {
    return typeStr;
  }
  let sym = if (scopes == null) { null } else { scopes.symbols.getByNode(node) };
  if (sym == null) {
    return `let ${name}: ${typeStr}`;
  }
  let decl = sym.declaration;
  if (decl is Parameter) {
    return `(parameter) ${name}: ${typeStr}`;
  }
  if (decl is ClassDeclaration) {
    return `class ${name}`;
  }
  if (sym.isType() && !sym.isValue()) {
    return `type ${name} = ${typeStr}`;
  }
  let keyword = if (sym.isValue() && sym.isMutable) { 'var' } else { 'let' };
  return `${keyword} ${name}: ${typeStr}`;
}

/**
 * The type of an imported symbol, from the model of the module that
 * declares it.
 */
function importedType(sym: Symbol, program: ProgramCheckResult): Type | null {
  let target = sym.resolveTarget();
  if (let (true, result) = program.results.get(target.modulePath)) {
    let bound = result.model.getBindingType(target);
    if (bound != null) {
      return bound;
    }
    let decl = target.declaration;
    if (decl != null) {
      return result.model.getNodeType(decl);
    }
  }
  return null;
}

/**
 * A symbol's type, when the node under the cursor has none.
 *
 * The binding's type is the first choice. It can be missing for a type
 * reference, like `Symbol` in `Map<String, Symbol>`: the reference names
 * the type's symbol, and the checker recorded the value's. The
 * declaration's type is the fallback, read in the declaring module's
 * model when the symbol is imported.
 */
function symbolType(sym: Symbol, model: SemanticModel, program: ProgramCheckResult): Type | null {
  let bound = model.getBindingType(sym);
  if (bound != null) {
    return bound;
  }
  let decl = sym.declaration;
  if (decl == null) {
    return null;
  }
  if (decl is ImportSpecifier) {
    return importedType(sym, program);
  }
  return model.getNodeType(decl);
}

/**
 * The doc comment on a symbol's declaration, following an import to the
 * module that declares it.
 */
function symbolDoc(sym: Symbol, file: FileAnalysis, target: CompilerTarget): DocComment | null {
  let declaredBy = sym.resolveTarget();
  let decl = declaredBy.declaration;
  // An import that did not resolve has only its import specifier.
  if (decl == null || decl is ImportSpecifier) {
    return null;
  }
  if (sym.importTarget == null) {
    return declarationDoc(decl, file.ast, attachComments(file.ast));
  }
  let source = target.getSourceFile(declaredBy.modulePath);
  if (source == null) {
    return null;
  }
  return declarationDoc(decl, source.ast, attachComments(source.ast));
}

function fieldHover(name: String, classType: ClassType): HoverResult | null {
  if (let (true, info) = classType.members.get(name)) {
    if (info is FieldInfo) {
      let typeStr = typeToString(info.type);
      let keyword = if (info.isMutable) { '(property) var' } else { '(property)' };
      return new HoverResult(typeStr, `${keyword} ${name}: ${typeStr}`, '');
    }
  }
  return null;
}

function methodHover(name: String, classType: ClassType): HoverResult | null {
  if (name == 'new') {
    let ctor = classType.constructorType;
    if (ctor == null) {
      return null;
    }
    let typeStr = typeToString(ctor);
    return new HoverResult(typeStr, `(constructor) new${typeStr}`, '');
  }
  if (let (true, info) = classType.members.get(name)) {
    if (info is MethodInfo) {
      let typeStr = typeToString(info.type);
      return new HoverResult(typeStr, `(method) ${name}${typeStr}`, '');
    }
  }
  return null;
}

/** Hover for a member whose name is at `offset`, without its doc comment. */
function memberNameHover(member: Node, classType: ClassType, offset: i32): HoverResult | null {
  return match (member) {
  case FieldDefinition {name} if spans(name, offset): {
    if (let Identifier {name as id} = name) { fieldHover(id, classType) } else { null }
  }
  case MethodDefinition {name} if spans(name, offset): {
    if (let Identifier {name as id} = name) { methodHover(id, classType) } else { null }
  }
  case _: null
};
}

/**
 * Hover for a class member's name where it is declared. The name is in
 * no scope's maps, and the checker keeps member types on the class type
 * rather than on the member's nodes, so both come from the class.
 */
function memberHover(file: FileAnalysis, offset: i32): HoverResult | null {
  let decl = enclosingClass(file.ast, offset);
  if (decl == null) {
    return null;
  }
  let classType = classTypeOf(decl, file.model);
  if (classType is ClassType) {
    for (let member in decl.body) {
      let hover = memberNameHover(member, classType, offset);
      if (hover != null) {
        let doc = docCommentAt(file.ast, offset, attachComments(file.ast));
        return new HoverResult(hover.typeStr, hover.label, docText(doc));
      }
    }
  }
  return null;
}

/** Hover for the cursor at `offset` in a checked file, or null for none. */
export function hoverAt(
  file: FileAnalysis,
  offset: i32,
  program: ProgramCheckResult,
  target: CompilerTarget,
): HoverResult | null {
  let node = findNodeAtOffset(file.ast, offset);
  if (node == null) {
    return null;
  }
  if (node is ThisExpression) {
    let decl = enclosingClass(file.ast, offset);
    let classType = if (decl == null) { null } else { classTypeOf(decl, file.model) };
    if (classType == null) {
      return null;
    }
    let typeStr = typeToString(classType);
    return new HoverResult(typeStr, `this: ${typeStr}`, '');
  }
  // The syntax walk does not visit a member expression's property, so
  // the cursor on one finds the whole member expression.
  if (let MemberExpression {property} = node) {
    if (spans(property, offset)) {
      let memberType = file.model.getNodeType(node);
      if (memberType != null) {
        let typeStr = typeToString(memberType);
        return new HoverResult(typeStr, `(property) ${property.name}: ${typeStr}`, '');
      }
    }
  }

  let sym = symbolUnder(file.scopes, node, offset);
  var nodeType = file.model.getNodeType(node);
  if (nodeType == null && sym != null) {
    nodeType = symbolType(sym, file.model, program);
  }
  if (nodeType == null) {
    // With no symbol either, the cursor may be on a class member's name
    // where it is declared. With a symbol, it is on a reference inside a
    // member, and the member's hover would be the wrong one.
    if (sym == null) {
      return memberHover(file, offset);
    }
    return null;
  }
  let typeStr = typeToString(nodeType);
  let doc = if (sym == null) { null } else { symbolDoc(sym, file, target) };
  return new HoverResult(typeStr, hoverLabel(node, typeStr, file.scopes), docText(doc));
}
  • 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