Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

#### :bug: Bug fix

- Support the flat `lib/rescript` build layout in ReScript 13. https://github.com/rescript-lang/rescript-vscode/issues/1194

- Fix language server crash (`ERR_INVALID_URL`) when resolving platform binaries for ReScript v12+ projects. https://github.com/rescript-lang/rescript-vscode/issues/1181

#### :rocket: New Feature
Expand Down
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ SHELL = /bin/bash
build:
dune build
cp -f _build/install/default/bin/rescript-editor-analysis analysis/rescript-editor-analysis.exe
cp -f _build/install/default/bin/rescript-editor-analysis rescript-editor-analysis.exe
cp -f _build/install/default/bin/rescript-tools rescript-tools.exe
install -m 755 _build/install/default/bin/rescript-editor-analysis rescript-editor-analysis.exe
install -m 755 _build/install/default/bin/rescript-tools rescript-tools.exe

test:
make -C analysis test
Expand Down
10 changes: 8 additions & 2 deletions server/src/bsc-args/rewatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export async function getRewatchBscArgs(
entry.file.sourceFilePath,
];

const env: NodeJS.ProcessEnv = {};
const env: NodeJS.ProcessEnv = entry.flatLayout ? { ...process.env } : {};
if (bscBinaryLocation != null) {
env["RESCRIPT_BSC_EXE"] = bscBinaryLocation;
}
Expand Down Expand Up @@ -122,7 +122,13 @@ export async function getRewatchBscArgs(
}

const compilerArgs = JSON.parse(
cp.execFileSync(rewatchPath, rewatchArguments, { env }).toString().trim(),
cp
.execFileSync(rewatchPath, rewatchArguments, {
env,
...(entry.flatLayout ? { cwd: entry.project.rootPath } : {}),
})
.toString()
.trim(),
) as RewatchCompilerArgs;

entry.buildRewatch = {
Expand Down
9 changes: 0 additions & 9 deletions server/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,9 @@ export let bsconfigPartialPath = "bsconfig.json";
export let rescriptJsonPartialPath = "rescript.json";
export let compilerDirPartialPath = path.join("lib", "bs");
export let compilerOcamlDirPartialPath = path.join("lib", "ocaml");
export let compilerLogPartialPath = path.join("lib", "bs", ".compiler.log");
export let compilerInfoPartialPath = path.join(
"lib",
"bs",
"compiler-info.json",
);
export let buildNinjaPartialPath = path.join("lib", "bs", "build.ninja");
export let rewatchLockPartialPath = path.join("lib", "rewatch.lock");
export let rescriptLockPartialPath = path.join("lib", "rescript.lock");
export let resExt = ".res";
export let resiExt = ".resi";
export let cmiExt = ".cmi";
export let startBuildAction = "Start Build";

// bsconfig defaults according configuration schema (https://rescript-lang.org/docs/manual/latest/build-configuration-schema)
Expand Down
4 changes: 2 additions & 2 deletions server/src/find-runtime.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { readdir, stat as statAsync, readFile } from "fs/promises";
import { join, resolve } from "path";
import { compilerInfoPartialPath } from "./constants";
import { buildLayout } from "../../shared/src/buildLayout";
import { NormalizedPath, normalizePath } from "./utils";

// Efficient parallel folder traversal to find node_modules directories
Expand Down Expand Up @@ -97,7 +97,7 @@ async function findRuntimePath(
project: NormalizedPath,
): Promise<NormalizedPath[]> {
// Try a compiler-info.json file first
const compilerInfo = resolve(project, compilerInfoPartialPath);
const compilerInfo = resolve(project, buildLayout(project).compilerInfo);
try {
const contents = await readFile(compilerInfo, "utf8");
const compileInfo: { runtime_path?: string } = JSON.parse(contents);
Expand Down
155 changes: 67 additions & 88 deletions server/src/incrementalCompilation.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { buildLayout, compiledArtifact } from "../../shared/src/buildLayout";
import * as path from "path";
import fs from "fs";
import * as utils from "./utils";
Expand All @@ -18,12 +19,6 @@ import { getLogger } from "./logger";

const execFilePromise = promisify(cp.execFile);

const INCREMENTAL_FOLDER_NAME = "___incremental";
const INCREMENTAL_FILE_FOLDER_LOCATION = path.join(
c.compilerDirPartialPath,
INCREMENTAL_FOLDER_NAME,
);

export type IncrementallyCompiledFileInfo = {
file: {
/** File type. */
Expand All @@ -42,6 +37,7 @@ export type IncrementallyCompiledFileInfo = {
originalTypeFileLocation: NormalizedPath;
};
buildSystem: "bsb" | "rewatch";
flatLayout: boolean;
/** Cache for build.ninja assets. */
buildNinja: {
/** When build.ninja was last modified. Used as a cache key. */
Expand Down Expand Up @@ -113,75 +109,65 @@ export function incrementalCompilationFileChanged(changedPath: NormalizedPath) {
getLogger().log("[watcher] Was compiling, killing");
cancelActiveCompilation(entry);
}
cleanUpIncrementalFiles(
entry.file.sourceFilePath,
entry.project.rootPath,
);
cleanUpIncrementalFiles(entry);
}
}
}

export function removeIncrementalFileFolder(
// Discard scratch output from a previous editor session before opening a project.
export async function removeIncrementalFileFolder(
projectRootPath: NormalizedPath,
onAfterRemove?: () => void,
rescriptVersion?: string,
) {
fs.rm(
path.resolve(projectRootPath, INCREMENTAL_FILE_FOLDER_LOCATION),
{ force: true, recursive: true },
(_) => {
onAfterRemove?.();
},
);
}

export function recreateIncrementalFileFolder(projectRootPath: NormalizedPath) {
getLogger().log("Recreating incremental file folder");
removeIncrementalFileFolder(projectRootPath, () => {
fs.mkdir(
path.resolve(projectRootPath, INCREMENTAL_FILE_FOLDER_LOCATION),
{ recursive: true },
(_) => {},
try {
await fs.promises.rm(
path.resolve(
projectRootPath,
buildLayout(projectRootPath, rescriptVersion).incremental,
),
{ force: true, recursive: true },
);
});
} catch (error) {
getLogger().log(
`Could not clear ReScript incremental scratch files: ${error}`,
);
}
}

export function cleanUpIncrementalFiles(
filePath: NormalizedPath,
projectRootPath: NormalizedPath,
) {
const ext = filePath.endsWith(".resi") ? ".resi" : ".res";
const namespace = utils.getNamespaceNameFromConfigFile(projectRootPath);
const fileNameNoExt = path.basename(filePath, ext);
const moduleNameNamespaced =
namespace.kind === "success" && namespace.result !== ""
? `${fileNameNoExt}-${namespace.result}`
: fileNameNoExt;

getLogger().log("Cleaning up incremental file assets for: " + fileNameNoExt);

fs.unlink(
path.resolve(
projectRootPath,
INCREMENTAL_FILE_FOLDER_LOCATION,
path.basename(filePath),
),
(_) => {},
function cleanUpIncrementalFiles(entry: IncrementallyCompiledFileInfo) {
const { moduleNameNamespaced, incrementalFilePath } = entry.file;
getLogger().log(
"Cleaning up incremental file assets for: " + moduleNameNamespaced,
);
fs.unlink(incrementalFilePath, () => {});

[
moduleNameNamespaced + ".ast",
moduleNameNamespaced + ".cmt",
moduleNameNamespaced + ".cmti",
moduleNameNamespaced + ".cmi",
moduleNameNamespaced + ".cmj",
].forEach((file) => {
[".ast", ".cmt", ".cmti", ".cmi", ".cmj"].forEach((extension) => {
fs.unlink(
path.resolve(projectRootPath, INCREMENTAL_FILE_FOLDER_LOCATION, file),
(_) => {},
path.join(
entry.project.incrementalFolderPath,
moduleNameNamespaced + extension,
),
() => {},
);
});
}

export function invalidateCompilerArgs(
projectRootPath: NormalizedPath,
send: send,
) {
for (const entry of incrementallyCompiledFileInfo.values()) {
if (
entry.project.rootPath === projectRootPath ||
entry.project.workspaceRootPath === projectRootPath
) {
entry.buildNinja = null;
entry.buildRewatch = null;
entry.project.callArgs = figureOutBscArgs(send, entry);
}
}
}

export async function getBscArgs(
send: (msg: p.Message) => void,
entry: IncrementallyCompiledFileInfo,
Expand Down Expand Up @@ -290,37 +276,30 @@ function triggerIncrementalCompilationOfFile(
);
}

const layout = buildLayout(projectRootPath, project.rescriptVersion);
const bscBinaryLocation = project.bscBinaryLocation;
if (bscBinaryLocation == null) {
getLogger().log("Could not find bsc binary location for " + filePath);
return;
}
const ext = filePath.endsWith(".resi") ? ".resi" : ".res";
const moduleName = path.basename(filePath, ext);
const moduleNameNamespaced =
project.namespaceName != null
? `${moduleName}-${project.namespaceName}`
: moduleName;
const moduleNameNamespaced = project.namespaceName
? `${moduleName}-${project.namespaceName}`
: moduleName;

// projectRootPath is already NormalizedPath, appending a constant string still makes it a NormalizedPath
const incrementalFolderPath: NormalizedPath = path.join(
projectRootPath,
INCREMENTAL_FILE_FOLDER_LOCATION,
layout.incremental,
) as NormalizedPath;

const relSourcePath = path.relative(projectRootPath, filePath);
const relSourceDir = path.dirname(relSourcePath);
const typeExt = ext === ".res" ? ".cmt" : ".cmti";
const originalTypeFileName =
project.namespaceName != null
? `${moduleName}-${project.namespaceName}${typeExt}`
: `${moduleName}${typeExt}`;
// projectRootPath is already NormalizedPath, appending constant strings still yields a NormalizedPath
const originalTypeFileLocation = path.resolve(
const originalTypeFileLocation = compiledArtifact(
projectRootPath,
c.compilerDirPartialPath,
relSourceDir,
originalTypeFileName,
filePath,
project.namespaceName,
ext === ".res" ? ".cmt" : ".cmti",
layout,
) as NormalizedPath;

incrementalFileCacheEntry = {
Expand All @@ -344,7 +323,9 @@ function triggerIncrementalCompilationOfFile(
bscBinaryLocation,
incrementalFolderPath,
},
buildSystem: foundRewatchLockfileInProjectRoot ? "rewatch" : "bsb",
flatLayout: layout.flat,
buildSystem:
layout.flat || foundRewatchLockfileInProjectRoot ? "rewatch" : "bsb",
buildRewatch: null,
buildNinja: null,
compilation: null,
Expand Down Expand Up @@ -415,10 +396,7 @@ async function figureOutBscArgs(
let callArgs: Array<string> = [];

if (config.extensionConfiguration.incrementalTypechecking?.acrossFiles) {
callArgs.push(
"-I",
path.resolve(entry.project.rootPath, INCREMENTAL_FILE_FOLDER_LOCATION),
);
callArgs.push("-I", entry.project.incrementalFolderPath);
}

buildArgs.forEach(([key, value]: Array<string>) => {
Expand Down Expand Up @@ -448,7 +426,7 @@ rule mij
}
} else {
// TODO: once ReScript v12 is out we can remove this check for `.`
if (value === ".") {
if (value === "." && !entry.flatLayout) {
callArgs.push(
"-I",
path.resolve(entry.project.rootPath, c.compilerOcamlDirPartialPath),
Expand Down Expand Up @@ -522,7 +500,7 @@ function remapCodeActionsToSourceFile(
*/
function filterIncrementalDiagnostics(
diagnostics: p.Diagnostic[],
sourceFileName: string,
scratchFile: string,
): { filtered: p.Diagnostic[]; hasIgnoredMessages: boolean } {
let hasIgnoredMessages = false;

Expand All @@ -535,7 +513,7 @@ function filterIncrementalDiagnostics(
.filter((d) => {
if (
!d.message.startsWith("Uninterpreted extension 'rescript.") &&
(!d.message.includes(`/${INCREMENTAL_FOLDER_NAME}/${sourceFileName}`) ||
(!d.message.replace(/\\/g, "/").includes(scratchFile) ||
// The `Multiple definition of the <kind> name <name>` type error's
// message includes the filepath with LOC of the duplicate definition
d.message.startsWith("Multiple definition of the") ||
Expand Down Expand Up @@ -614,7 +592,7 @@ function processAndPublishDiagnostics(
const rawDiagnostics = Object.values(result)[0] ?? [];
const { filtered: res, hasIgnoredMessages } = filterIncrementalDiagnostics(
rawDiagnostics,
entry.file.sourceFileName,
`/${path.basename(entry.project.incrementalFolderPath)}/${entry.file.sourceFileName}`,
);

// Log error if compilation produced unexpected output
Expand Down Expand Up @@ -669,7 +647,7 @@ async function compileContents(
entry.project.callArgs = Promise.resolve(callArgsRetried);
} else {
getLogger().log(
"Could not figure out call args. Maybe build.ninja does not exist yet?",
"Could not get compiler arguments. The project may need a build first.",
);
return;
}
Expand All @@ -687,7 +665,7 @@ async function compileContents(
let cwd =
entry.buildSystem === "bsb"
? entry.project.rootPath
: path.resolve(entry.project.rootPath, c.compilerDirPartialPath);
: path.dirname(entry.project.incrementalFolderPath);

getLogger().log(
`About to invoke bsc from \"${cwd}\", used ${entry.buildSystem}`,
Expand Down Expand Up @@ -801,7 +779,8 @@ export function handleClosedFile(filePath: NormalizedPath) {
getLogger().log("Closed: " + filePath);
const entry = incrementallyCompiledFileInfo.get(filePath);
if (entry == null) return;
cleanUpIncrementalFiles(filePath, entry.project.rootPath);
cancelActiveCompilation(entry);
cleanUpIncrementalFiles(entry);
incrementallyCompiledFileInfo.delete(filePath);
originalTypeFileToFilePath.delete(entry.file.originalTypeFileLocation);
}
Expand Down
Loading
Loading