UNPKG

coc-autark

Version:

Autark build-script completion for coc.nvim

533 lines (496 loc) • 14.7 kB
import path from 'node:path'; import fs from 'node:fs'; import * as data from './data.js'; import * as paths from './paths.js'; import * as scan from './scan.js'; // LSP CompletionItemKind values (kept local: this module must stay usable // without a coc.nvim runtime for unit tests). const KIND = { Function: 3, Variable: 6, Property: 10, Keyword: 14, File: 17, Folder: 19, }; export const DEFAULT_CONFIG = { cacheDir: 'autark-cache', checkScriptDirs: ['.autark', 'autark'], completePaths: true, }; function positionAt(text, offset) { let line = 0; let lineStart = 0; for (let i = 0; i < offset && i < text.length; i += 1) { if (text[i] === '\n') { line += 1; lineStart = i + 1; } } return { line, character: offset - lineStart }; } /** Attaches the text edit range and stable sort keys to raw items. */ function finish(items, range) { const counters = new Map(); return items.map((item) => { const group = item.group || '9'; const index = counters.get(group) || 0; counters.set(group, index + 1); return { label: item.label, kind: item.kind, detail: item.detail, documentation: item.documentation, filterText: item.filterText || item.label, sortText: `${group}${String(index).padStart(4, '0')}`, textEdit: { range: { start: range.start, end: range.end }, newText: item.insertText === undefined ? item.label : item.insertText, }, }; }); } function directiveItems() { return data.DIRECTIVES.map(([label, documentation]) => ({ label, kind: KIND.Keyword, detail: 'directive', documentation, group: '3', })); } function conditionItems() { return data.CONDITIONS.map(([label, documentation]) => ({ label, kind: KIND.Function, detail: 'condition', documentation, group: '0', })); } function fieldItems(rule) { return (data.RULE_FIELDS[rule] || []).map(([label, documentation]) => ({ label, kind: KIND.Property, detail: `${rule} field`, documentation, group: '0', })); } function pathItems(baseDir, typed) { return paths.completePath(baseDir, typed).map((entry) => pathItem(entry)); } function pathItem(entry) { return { label: entry.label, kind: entry.isDir ? KIND.Folder : KIND.File, detail: entry.isDir ? 'directory' : 'file', insertText: entry.insertText, filterText: entry.label, group: '0', }; } /** Merges path completion of several roots, keeping the first match. */ function mergedPathItems(baseDirs, typed) { const seen = new Set(); const items = []; for (const baseDir of baseDirs) { for (const entry of paths.completePath(baseDir, typed)) { if (seen.has(entry.insertText)) { continue; } seen.add(entry.insertText); items.push(pathItem(entry)); } } return items; } function variableItems(ctx) { const items = []; const seen = new Set(); for (const [label, documentation] of data.VARIABLES) { seen.add(label); items.push({ label, kind: KIND.Variable, detail: 'built-in variable', documentation, group: '0' }); } const add = (name, detail, group) => { if (seen.has(name)) { return; } seen.add(name); items.push({ label: name, kind: KIND.Variable, detail, group }); }; // Declarations of the buffer itself take precedence over the project scan. for (const definition of scan.collectDefinitions(ctx.text).values()) { add(definition.name, `${definition.detail}, line ${definition.line}`, '1'); } for (const output of scan.collectCheckOutputs(ctx.text, data.CHECK_OUTPUT_ARGS)) { add(output.name, `set by ${output.script}`, '2'); } for (const definition of projectDefinitions(ctx).values()) { add(definition.name, `${definition.detail} in ${definition.file}, line ${definition.line}`, '3'); } for (const cached of cacheVariables(ctx).values()) { add(cached.name, cached.value === '' ? 'set by the build cache' : `set by the build cache: ${cached.value}`, '4'); } return items; } // Aggregated build cache variables are cached briefly: caches change only // when a build runs, not while typing. const buildCacheVariables = new Map(); const BUILD_CACHE_TTL_MS = 5000; function cacheVariables(ctx) { const key = ctx.cacheRoot; const cached = buildCacheVariables.get(key); if (cached && Date.now() - cached.at < BUILD_CACHE_TTL_MS) { return cached.names; } const names = new Map(); const add = (name, value) => { const clean = String(value || '').replace(/\s+/g, ' ').trim(); if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || names.has(name)) { return; } names.set(name, { name, value: clean.slice(0, 80) }); }; for (const file of paths.listCacheStateFiles(key)) { let content; try { content = fs.readFileSync(file, 'utf8'); } catch (_) { continue; } if (file.endsWith('.env')) { // `NAME=value` lines of a node environment. for (const line of content.split('\n')) { const separator = line.indexOf('='); if (separator > 0) { add(line.slice(0, separator).trim(), line.slice(separator + 1)); } } } else { // `.deps` lines: <type><flags><name>\1<value>[\1<serial>]. for (const line of content.split('\n')) { const type = line[0]; if (type !== 'e' && type !== 's') { continue; } const parts = line.slice(2).split('\u0001'); add(String(parts[0] || '').trim(), parts.length > 1 ? parts[1] : ''); } } } buildCacheVariables.set(key, { at: Date.now(), names }); return names; } export function clearBuildCacheVariables() { buildCacheVariables.clear(); } // Project-wide declarations are cached by file modification time: completion // runs on every keystroke and must not re-read the included scripts each time. const sourceCache = new Map(); function readSource(file) { let stat; try { stat = fs.statSync(file); } catch (_) { sourceCache.delete(file); return 0; } const cached = sourceCache.get(file); if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) { return cached; } let text; try { text = fs.readFileSync(file, 'utf8'); } catch (_) { return 0; } const source = { mtimeMs: stat.mtimeMs, size: stat.size, definitions: scan.collectDefinitions(text), includes: scan.collectIncludes(text), }; sourceCache.set(file, source); return source; } export function clearSourceCache() { sourceCache.clear(); } /** * Collects declarations of the whole project: the root script, the current * script and every script reachable through `include` rules. Autark children * inherit the parent scope, so this union is what a script may reference. */ function projectDefinitions(ctx) { const result = new Map(); const visited = new Set(); const limit = { files: 64 }; const visitFile = (file, depth) => { if (!file || depth > 16 || limit.files <= 0) { return; } let real; try { real = fs.realpathSync(file); } catch (_) { return; } if (visited.has(real)) { return; } visited.add(real); limit.files -= 1; const source = readSource(real); if (!source) { return; } const relative = path.relative(ctx.projectRoot, real) || path.basename(real); for (const definition of source.definitions.values()) { if (!result.has(definition.name)) { result.set(definition.name, { name: definition.name, detail: definition.detail, line: definition.line, file: relative }); } } for (const include of source.includes) { visitFile(path.resolve(path.dirname(real), include), depth + 1); } }; // The root script is the parent scope of everything below it. visitFile(path.join(ctx.projectRoot, 'Autark'), 0); // Includes of the buffer as saved on disk. if (ctx.filePath) { visitFile(ctx.filePath, 0); } return result; } function macroItems(text) { const items = []; for (const definition of scan.collectDefinitions(text).values()) { if (definition.detail !== 'macro') { continue; } items.push({ label: definition.name, kind: KIND.Function, detail: 'macro', group: '0' }); } return items; } /** Reads the leading `#` comment block of a check script as its description. */ function readScriptDoc(file) { let content; try { content = fs.readFileSync(file, 'utf8'); } catch (_) { return ''; } const lines = []; for (const line of content.split(/\r?\n/).slice(0, 40)) { const trimmed = line.trim(); if (!trimmed) { if (lines.length) { break; } continue; } if (trimmed.startsWith('#!') && !lines.length) { continue; } if (!trimmed.startsWith('#')) { break; } lines.push(trimmed.replace(/^#+\s?/, '')); if (lines.length === 4) { break; } } return lines.join(' '); } function checkScriptDirs(ctx) { const dirs = []; const stop = ctx.projectRoot || ctx.scriptDir; let dir = ctx.scriptDir; for (;;) { for (const name of ctx.config.checkScriptDirs) { dirs.push(path.join(dir, name)); } if (dir === stop) { break; } const parent = path.dirname(dir); if (parent === dir) { break; } dir = parent; } return dirs; } function checkScriptItems(ctx) { const items = []; const seen = new Set(); const standard = new Map(data.CHECK_SCRIPTS); const add = (name, documentation, detail) => { if (seen.has(name)) { return; } seen.add(name); items.push({ label: name, kind: KIND.Function, detail, documentation, group: '0' }); }; // Scripts vendored into the project win over the well-known list, because // their header comment documents the local variant. Standard scripts without // a header comment fall back to the built-in description. for (const dir of checkScriptDirs(ctx)) { for (const entry of paths.listDir(dir)) { if (entry.isDir || !entry.name.endsWith('.sh')) { continue; } const documentation = readScriptDoc(path.join(dir, entry.name)) || standard.get(entry.name) || ''; add(entry.name, documentation, 'project check script'); } } for (const [name, documentation] of data.CHECK_SCRIPTS) { add(name, documentation, 'check script'); } if (ctx.state.prevWord && data.PATH_CHECK_SCRIPTS.has(ctx.state.prevWord) && pathsEnabled(ctx)) { items.push(...pathItems(ctx.scriptDir, ctx.state.prefix)); } return items; } function pathsEnabled(ctx) { return ctx.config.completePaths !== false; } function inlineItems(ctx) { const frame = ctx.state.frame; if (frame.name === '$') { return ctx.state.firstWord ? variableItems(ctx) : []; } if (!pathsEnabled(ctx)) { return []; } switch (frame.name) { case 'S': return pathItems(ctx.projectRoot, ctx.state.prefix); case 'SS': return pathItems(ctx.scriptDir, ctx.state.prefix); case 'C': return pathItems(ctx.cacheRoot, ctx.state.prefix); case 'CC': return pathItems(ctx.unitCacheDir, ctx.state.prefix); case '%': return pathItems(ctx.scriptDir, ctx.state.prefix); default: // @{...}, @@{...}, ^{...} and &{...} take commands or expressions. return []; } } function ruleItems(ctx) { const { state } = ctx; const name = state.frame.name; if (name.endsWith('.sh')) { // Arguments of a check script: no static completion is available. return []; } switch (name) { case 'check': return checkScriptItems(ctx); case 'if': case 'and': case 'or': return conditionItems().concat(directiveItems()); case 'call': return state.firstWord ? macroItems(ctx.text) : []; case 'set': case 'let': case 'library': return state.firstWord ? fieldItems(name).concat(directiveItems()) : directiveItems(); case 'include': case 'configure': return pathsEnabled(ctx) ? pathItems(ctx.scriptDir, state.prefix) : []; case 'install': case 'install-sources': if (state.firstWord) { return [ { label: 'exact', kind: KIND.Keyword, detail: `${name} modifier`, documentation: 'Preserve the source file mode exactly.', group: '0', }, ]; } if (!pathsEnabled(ctx)) { return []; } // Installed artifacts may come from the unit cache or the sources. return name === 'install-sources' ? pathItems(ctx.projectRoot, state.prefix) : mergedPathItems([ctx.unitCacheDir, ctx.scriptDir], state.prefix); case 'in-sources': return directiveItems(); case 'meta': case 'echo': return fieldItems(name).concat(directiveItems()); case 'toolchain': return fieldItems(name); case 'cc': case 'cxx': case 'host-cc': case 'host-cxx': case 'run': case 'run-on-install': return fieldItems(name).concat(directiveItems()); case 'foreach': case 'macro': return directiveItems(); case 'env': case 'option': case 'error': return []; default: // Custom rules may contain any nested directive. return directiveItems(); } } /** * Builds the completion context from buffer text and its project location. */ export function buildContext(input) { const config = Object.assign({}, DEFAULT_CONFIG, input.config); const filePath = input.filePath || ''; const scriptDir = filePath ? path.dirname(filePath) : input.workspaceRoot || '.'; const projectRoot = paths.findProjectRoot(scriptDir) || input.workspaceRoot || scriptDir; const cacheRoot = paths.resolveCacheRoot(projectRoot, config.cacheDir); return { text: input.text, offset: Math.max(0, Math.min(input.offset, input.text.length)), filePath, scriptDir, projectRoot, cacheRoot, unitCacheDir: paths.unitCacheDir(projectRoot, cacheRoot, scriptDir), config, }; } /** * Provides completion items for the cursor at `offset` of `text`. * * @returns {Array<object>} LSP completion items. */ export function provideCompletions(input) { const ctx = buildContext(input); ctx.state = scan.analyze(ctx.text, ctx.offset); if (ctx.state.inString || ctx.state.inComment) { return []; } const range = { start: positionAt(ctx.text, ctx.state.tokenStart), end: positionAt(ctx.text, ctx.offset), }; const frame = ctx.state.frame; if (frame && frame.kind === 'inline') { return finish(inlineItems(ctx), range); } if (!frame) { return finish(directiveItems(), range); } return finish(ruleItems(ctx), range); }