Skip to content

@instanceOf class with a relative @module is imported relative to the module that matches on it #9520

In review

Description

@JonoPrest

An @instanceOf type can name its class with a @module path relative to its own file (#9309). When an untagged variant with that type as a case is matched in a module of another directory, the generated import is the same relative string, so it points at a file beside the module with the match, not beside the module that declares the type.

Tested on master at e2318f2, built from source. The feature is not in a release yet.

Layout:

src/shapes/shapes.js
src/shapes/Shapes.res
src/app/App.res

rescript.json uses "sources": {"dir": "src", "subdirs": true}, "package-specs": {"module": "esmodule", "in-source": true}, "suffix": ".mjs".

// src/shapes/shapes.js
export class Circle {}
// src/shapes/Shapes.res
@module("./shapes.js") @instanceOf("Circle")
type circle

@new @module("./shapes.js") external makeCircle: unit => circle = "Circle"
// src/app/App.res
@unboxed
type value =
  | Circle(Shapes.circle)
  | Plain({"plain": bool})

let kind = value =>
  switch value {
  | Circle(_) => "circle"
  | Plain(_) => "plain"
  }

let circle = kind(Circle(Shapes.makeCircle()))

Actual src/app/App.mjs:

import * as Shapes from "../shapes/Shapes.mjs";
import * as ShapesJs from "./shapes.js";

function kind(value) {
  if (value instanceof ShapesJs.Circle) {

node src/app/App.mjs fails:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '.../src/app/shapes.js' imported from .../src/app/App.mjs

If a src/app/shapes.js exists, that is the file the import names, so the check would use whatever it exports as Circle.

Expected: import * as ShapesJs from "../shapes/shapes.js";, and for a type declared in a dependency package, a path into that package. Package specifiers such as "three" and global classes are fine. The existing test (untagged_module_class_test.res) keeps everything in one directory, so it does not see this.

Externals with a relative path avoid the same problem because they are called through the declaring module. A type has no value to go through, so the path needs to be rewritten for the module that compiles the check.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions