Skip to content

Import an @instanceOf class of a relative module from the declaring file - #9523

Open
JonoPrest wants to merge 2 commits into
masterfrom
fix/instanceof-relative-module
Open

JonoPrest wants to merge 2 commits into
masterfrom
fix/instanceof-relative-module

Conversation

@JonoPrest

Copy link
Copy Markdown
Contributor

Fixes #9520

@module("./shapes.js") @instanceOf("Circle") type circle names a file beside the module that declares the type. The module that compiles a class check adds the import, and it wrote the path as it is, so a match in another directory or package imported a file beside itself.

A class with a relative module now records the compilation unit that declares it. A check in another unit imports the path from the JavaScript file of that unit, which is found the same way as an import of the unit itself, per output format: ../shapes/shapes.js from src/app, shapes-dep/src/hex/dep_shapes.js from another package. Checks in the declaring file, package specifiers and globals are written as before.

Things worth a look:

  • A relative class is identified with the unit that declares it, because the type checker has no dependable view of a unit's directory (interfaces are compiled without -bs-package-output). So the same "./shapes.js" annotation in two files is two classes, also in one directory: a signature with such a type is not matched from another file, and a variant can have both as cases. An annotation that repeats the abbreviated type's still names that type's class. The @module on @instanceOf feature is unreleased, so no released program changes. UntaggedVariants.md spells this out.
  • The path comes from the declaring unit's .cmj. A package that does not depend on that unit's package gets an error asking for the dependency, and a function with such a check is not inlined into it. Without a package (plain bsc) the path stays as written when the .cmj or JS file is missing.
  • With out-of-source output the import points beside the declaring module's output, like the path of an external, so the JS file has to be there.
  • Two modules in different directories that name one JS file give two imports of the same specifier.
  • This does not overlap with Explain that import() cannot load a relative external from its own file #9516: it only reads External_ffi_types.is_package_relative_path and leaves primitive.ml, translcore.ml and typemod.ml alone. Both are about relative @module paths across modules, but that one is about externals and import(), this one about @instanceOf types.

Tests: the first commit adds the project test alone and fails on master (src/app/App.mjs imports ./shapes.js); the second fixes it and extends it. tests/project_tests/instance_of_relative_module builds with the build system and runs the ES module output for consumers in the same, a sibling, a deeper and a shallower directory, named/default/scoped exports, the same relative string in two directories, a namespaced dependency package, a class of a transitive dependency, an inlined check, interface files, abbreviations, restated annotations, module aliases and includes. The CommonJS out-of-source output and the unloadable-dependency error are checked as text only. The plain bsc fallback I checked by hand, not in a test. make test and make checkformat pass locally.

The commits are not signed off.

Checklist

  • Added a changelog fragment (see changes/README.md), or no release notes are needed and a maintainer should apply changelog:skip.
  • Added tests for the fix or feature.
  • Gave every commit a description below its subject, saying why it is made (see "Commit messages" in CONTRIBUTING.md).
  • Signed off every commit for the DCO (git commit -s).

Replaces #9521, which was opened from my fork.

Why:
    A type can name its class with a module path relative to its own
    file, `@module("./shapes.js") @instanceof("Circle")`. An untagged
    variant switch in a module of another directory writes that path into
    its own import, where it names another file or none.

    This commit only adds the project test, which fails on its first
    module of another directory: src/app/App.mjs imports `./shapes.js`,
    not `../shapes/shapes.js`. The next commit fixes the import.

JS added (class check in another directory):
Example:
    // src/shapes/Shapes.res
    @module("./shapes.js") @instanceof("Circle")
    type circle

    // src/app/App.res
    @unboxed
    type value =
      | Circle(Shapes.circle)
      | Plain({"plain": bool})

    let kind = value =>
      switch value {
      | Circle(_) => "circle"
      | Plain(_) => "plain"
      }
Before (js): src/app/App.mjs, as the compiler writes it today
    import * as ShapesJs from "./shapes.js";

    function kind(value) {
      if (value instanceof ShapesJs.Circle) {
        return "circle";
      } else {
        return "plain";
      }
    }
After (text): node src/app/App.mjs
    Error [ERR_MODULE_NOT_FOUND]: Cannot find module '…/src/app/shapes.js' imported from …/src/app/App.mjs
After (text): node input.js, the test
    AssertionError [ERR_ASSERTION]: imports of src/app/App.mjs
      actual: [ './shapes.js' ],
      expected: [ '../shapes/shapes.js' ],

Signed-off-by: Jono Prest <jjprest@gmail.com>
Why:
    `@module("./shapes.js") @instanceof("Circle") type circle` names a
    file beside the module that declares the type. The module that
    compiles a class check adds the import, and it wrote the path as it
    is, so a check in another directory or package imported a file
    beside itself: another file, or none.

    A class with a relative module now records the compilation unit that
    declares it. A check in another unit imports the path from the
    JavaScript file of that unit, which is found as an import of the unit
    is, for each output format. Externals avoid the same problem by
    calling through the declaring module's export; a type has no export
    to go through, so the path is rewritten instead.

JS modified (class check in another directory):
Example:
    // src/shapes/Shapes.res
    @module("./shapes.js") @instanceof("Circle")
    type circle

    // src/app/App.res
    @unboxed
    type value =
      | Circle(Shapes.circle)
      | Plain({"plain": bool})

    let kind = value =>
      switch value {
      | Circle(_) => "circle"
      | Plain(_) => "plain"
      }
Before (js): src/app/App.mjs
    import * as ShapesJs from "./shapes.js";

    function kind(value) {
      if (value instanceof ShapesJs.Circle) {
        return "circle";
      } else {
        return "plain";
      }
    }
After (js): src/app/App.mjs
    import * as ShapesJs from "../shapes/shapes.js";

    function kind(value) {
      if (value instanceof ShapesJs.Circle) {
        return "circle";
      } else {
        return "plain";
      }
    }

JS modified (class check in another package):
Example:
    // node_modules/shapes-dep/src/hex/Dep.res, namespace ShapesDep
    @module("./dep_shapes.js") @instanceof("Hexagon")
    type hexagon

    // src/app/Classes.res
    @unboxed
    type value =
      | Hexagon(ShapesDep.Dep.hexagon)
      | Plain({"plain": bool})
Before (js): src/app/Classes.mjs, and lib/js/src/app/Classes.cjs
    import * as Dep_shapesJs from "./dep_shapes.js";

    let Dep_shapesJs = require("./dep_shapes.js");
After (js): src/app/Classes.mjs, and lib/js/src/app/Classes.cjs
    import * as Dep_shapesJs from "shapes-dep/src/hex/dep_shapes.js";

    let Dep_shapesJs = require("shapes-dep/lib/js/src/hex/dep_shapes.js");

Representation modified (class of an @instanceof type):
Before (representation):
    @module("./shapes.js") @instanceof("Circle")  ↦  {module_ = Some "./shapes.js"; path = "Circle"}
    @module("three") @instanceof("Mesh")          ↦  {module_ = Some "three"; path = "Mesh"}
After (representation): in Shapes.res
    @module("./shapes.js") @instanceof("Circle")  ↦  {module_ = Some "./shapes.js"; relative_to = Some "Shapes"; path = "Circle"}
    @module("three") @instanceof("Mesh")          ↦  {module_ = Some "three"; relative_to = None; path = "Mesh"}

Diagnostic modified (the same relative path in two files):
Example:
    // Class_types.res
    module type S = {
      @module("./shapes.js") @instanceof("Circle")
      type t
    }

    // Class_use.res
    module M: Class_types.S = {
      @module("./shapes.js") @instanceof("Circle")
      type t
    }
Before (diagnostic): none
After (diagnostic):
    Signature mismatch:
    …
    The declarations read the same, but a type they mention differs:
      Actual declaration: instances of Circle from "./shapes.js" relative to Class_use
      Expected declaration: instances of Circle from "./shapes.js" relative to Class_types

Review: Is a check in the declaring file itself changed? No. There the
    unit is the one being compiled, the path is written as it is, and the
    import is shared with the file's externals of the same path, as
    before; untagged_module_class_test.mjs is unchanged.
Review: What does an annotation mean that repeats the abbreviated
    type's, in another file? It names the abbreviated type's class, with
    the path from that type's file, so an interface that restates
    `@module("./shapes.js") @instanceof("Circle") type circle =
    Shapes.circle` still compiles in any directory.
Review: Where does the import go when the output is not beside the
    sources? Beside the output of the declaring module, in each format:
    the path is read from the generated JavaScript file, as the path of
    an external is, so the file has to be there, as for an external.
Review: Are two declarations of one file's class one class? No. A
    relative module is identified with the unit that declares the type,
    since the type checker does not know which directory a unit is in:
    the same `"./shapes.js"` declared in two files is two classes, also in
    one directory. A signature with such a type is not matched from
    another file, as the diagnostic above shows, and a variant can have
    both types as cases, each with its own import of the file. The
    feature is not released yet (changes/instance-of-module.fix.md), so
    no released program changes meaning.
Review: What if the declaring unit cannot be loaded? Its .cmj gives the
    path, and a package that does not depend on the unit's package has
    none. A check there is an error that asks for the dependency
    (`Cannot import the class Triangle from "./hidden.js" relative to
    Hidden …`), and a function with such a check is not inlined into
    that package, like a body that names a module it cannot load.
    Without a package (plain bsc), where the unit's .cmj or JavaScript
    file may not exist, the path stays as written, as before.
Review: Can every package import the file? Only if the declaring package
    lets it: a package that limits its `exports` has to export the file,
    as it has to export its compiled modules.
Review: Does this touch the externals that #9516 changes? No. It reads
    `External_ffi_types.is_package_relative_path` and leaves primitive.ml,
    translcore.ml and typemod.ml alone.
Signed-off-by: Jono Prest <jjprest@gmail.com>
@JonoPrest
JonoPrest requested a review from cknitt December 4, 2026 11:08
@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown

Changelog

🐛 Bug fix

  • Import the class of an @instanceOf type with a relative @module path from the file that declares the type when an untagged variant is matched in a module of another directory or package.

Semantic Diff

2 commits · Full page

Test an @instanceOf class of a relative module from other directories

239f066 · JonoPrest · Dec 04, 2026, 08:08 UTC

Why

A type can name its class with a module path relative to its own file, @module("./shapes.js") @instanceOf("Circle"). An untagged variant switch in a module of another directory writes that path into its own import, where it names another file or none.

This commit only adds the project test, which fails on its first module of another directory: src/app/App.mjs imports ./shapes.js, not ../shapes/shapes.js. The next commit fixes the import.

JS added (class check in another directory)

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

// src/app/App.res
@unboxed
type value =
  | Circle(Shapes.circle)
  | Plain({"plain": bool})

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

js · Before · src/app/App.mjs, as the compiler writes it today

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

function kind(value) {
  if (value instanceof ShapesJs.Circle) {
    return "circle";
  } else {
    return "plain";
  }
}

text · After · node src/app/App.mjs

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

text · After · node input.js, the test

AssertionError [ERR_ASSERTION]: imports of src/app/App.mjs
  actual: [ './shapes.js' ],
  expected: [ '../shapes/shapes.js' ],
Import an @instanceOf class of a relative module from the declaring file

22b65dd · JonoPrest · Dec 04, 2026, 08:14 UTC

Why

@module("./shapes.js") @instanceOf("Circle") type circle names a file beside the module that declares the type. The module that compiles a class check adds the import, and it wrote the path as it is, so a check in another directory or package imported a file beside itself: another file, or none.

A class with a relative module now records the compilation unit that declares it. A check in another unit imports the path from the JavaScript file of that unit, which is found as an import of the unit is, for each output format. Externals avoid the same problem by calling through the declaring module's export; a type has no export to go through, so the path is rewritten instead.

JS modified (class check in another directory)

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

// src/app/App.res
@unboxed
type value =
  | Circle(Shapes.circle)
  | Plain({"plain": bool})

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

js · src/app/App.mjs

-import * as ShapesJs from "./shapes.js";
+import * as ShapesJs from "../shapes/shapes.js";
 
 function kind(value) {
   if (value instanceof ShapesJs.Circle) {
     return "circle";
   } else {
     return "plain";
   }
 }

JS modified (class check in another package)

// node_modules/shapes-dep/src/hex/Dep.res, namespace ShapesDep
@module("./dep_shapes.js") @instanceOf("Hexagon")
type hexagon

// src/app/Classes.res
@unboxed
type value =
  | Hexagon(ShapesDep.Dep.hexagon)
  | Plain({"plain": bool})

js · src/app/Classes.mjs, and lib/js/src/app/Classes.cjs

-import * as Dep_shapesJs from "./dep_shapes.js";
+import * as Dep_shapesJs from "shapes-dep/src/hex/dep_shapes.js";
 
-let Dep_shapesJs = require("./dep_shapes.js");
+let Dep_shapesJs = require("shapes-dep/lib/js/src/hex/dep_shapes.js");

Representation modified (class of an @instanceOf type)

representation · After: in Shapes.res

-@module("./shapes.js") @instanceOf("Circle") ↦ {module_ = Some "./shapes.js"; path = "Circle"}
-@module("three") @instanceOf("Mesh")         ↦ {module_ = Some "three"; path = "Mesh"}
+@module("./shapes.js") @instanceOf("Circle") ↦ {module_ = Some "./shapes.js"; relative_to = Some "Shapes"; path = "Circle"}
+@module("three") @instanceOf("Mesh")         ↦ {module_ = Some "three"; relative_to = None; path = "Mesh"}

Diagnostic modified (the same relative path in two files)

// Class_types.res
module type S = {
  @module("./shapes.js") @instanceOf("Circle")
  type t
}

// Class_use.res
module M: Class_types.S = {
  @module("./shapes.js") @instanceOf("Circle")
  type t
}

diagnostic

-none
+Signature mismatch:
+…
+The declarations read the same, but a type they mention differs:
+  Actual declaration: instances of Circle from "./shapes.js" relative to Class_use
+  Expected declaration: instances of Circle from "./shapes.js" relative to Class_types

Review

  • Is a check in the declaring file itself changed? No. There the unit is the one being compiled, the path is written as it is, and the import is shared with the file's externals of the same path, as before; untagged_module_class_test.mjs is unchanged.
  • What does an annotation mean that repeats the abbreviated type's, in another file? It names the abbreviated type's class, with the path from that type's file, so an interface that restates @module("./shapes.js") @instanceOf("Circle") type circle = Shapes.circle still compiles in any directory.
  • Where does the import go when the output is not beside the sources? Beside the output of the declaring module, in each format: the path is read from the generated JavaScript file, as the path of an external is, so the file has to be there, as for an external.
  • Are two declarations of one file's class one class? No. A relative module is identified with the unit that declares the type, since the type checker does not know which directory a unit is in: the same "./shapes.js" declared in two files is two classes, also in one directory. A signature with such a type is not matched from another file, as the diagnostic above shows, and a variant can have both types as cases, each with its own import of the file. The feature is not released yet (changes/instance-of-module.fix.md), so no released program changes meaning.
  • What if the declaring unit cannot be loaded? Its .cmj gives the path, and a package that does not depend on the unit's package has none. A check there is an error that asks for the dependency (Cannot import the class Triangle from "./hidden.js" relative to Hidden …), and a function with such a check is not inlined into that package, like a body that names a module it cannot load. Without a package (plain bsc), where the unit's .cmj or JavaScript file may not exist, the path stays as written, as before.
  • Can every package import the file? Only if the declaring package lets it: a package that limits its exports has to export the file, as it has to export its compiled modules.
  • Does this touch the externals that Explain that import() cannot load a relative external from its own file #9516 changes? No. It reads External_ffi_types.is_package_relative_path and leaves primitive.ml, translcore.ml and typemod.ml alone.

@JonoPrest

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-04T11:12:01.762539Z 22b65dd Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 22b65ddd2f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown

✅ Compiler benchmarks

Allocated words

In total: 653,429,548 → 653,437,035 (±0.00%).

Generated projects: 627,286,493 → 627,286,606 (±0.00%).

None of the 265 benchmarks changed by 0.1% or more.

Instructions

In total: 8,967,192,662 → 8,965,894,329 (-0.01%).

Benchmark Base Head Change
packages/@rescript/runtime/Stdlib_Math.resi 21,354,546 21,305,297 -0.23%
packages/@rescript/runtime/Stdlib_Temporal_PlainDateTime.res 25,671,255 25,612,801 -0.23%
packages/@rescript/runtime/Stdlib_List.resi 24,638,389 24,584,466 -0.22%
packages/@rescript/belt/src/Belt_Array.resi 33,821,957 33,752,557 -0.21%
packages/@rescript/runtime/Stdlib_Temporal_PlainDate.res 24,222,972 24,175,270 -0.20%
parse/RedBlackTreeNoComments.res 14,569,529 14,541,818 -0.19%
packages/@rescript/runtime/Stdlib_String.resi 29,503,709 29,450,027 -0.18%
packages/@rescript/runtime/Stdlib_Date.resi 34,298,486 34,236,148 -0.18%
parse/RedBlackTree.res 14,974,903 14,949,398 -0.17%
packages/@rescript/runtime/Stdlib_Temporal_ZonedDateTime.res 31,338,141 31,294,528 -0.14%
5 more changes
Benchmark Base Head Change
packages/@rescript/belt/src/Belt_List.resi 39,045,742 38,993,835 -0.13%
packages/@rescript/runtime/Stdlib_TypedArray.res 41,418,446 41,366,872 -0.12%
packages/@rescript/runtime/Stdlib_Array.resi 40,064,847 40,020,294 -0.11%
format/RedBlackTreeNoComments.res 24,142,912 24,117,266 -0.11%
format/RedBlackTree.res 24,487,740 24,462,094 -0.10%

Output size

In total: 27,460,200 → 27,461,721 (+0.01%).

None of the 13 benchmarks changed by 0.1% or more.

Pull request 22b65dd compared with base e489471 in this run.

@pkg-pr-new

pkg-pr-new Bot commented Dec 4, 2026

Copy link
Copy Markdown

Open in StackBlitz

rescript

npm i https://pkg.pr.new/rescript@9523

@rescript/belt

npm i https://pkg.pr.new/@rescript/belt@9523

@rescript/darwin-arm64

npm i https://pkg.pr.new/@rescript/darwin-arm64@9523

@rescript/linux-arm64

npm i https://pkg.pr.new/@rescript/linux-arm64@9523

@rescript/linux-x64

npm i https://pkg.pr.new/@rescript/linux-x64@9523

@rescript/runtime

npm i https://pkg.pr.new/@rescript/runtime@9523

@rescript/win32-x64

npm i https://pkg.pr.new/@rescript/win32-x64@9523

commit: 22b65dd

@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown

@cknitt

cknitt commented Dec 4, 2026

Copy link
Copy Markdown
Member

Thanks, this fixes #9520. We built the PR's compiler and rescript build system and tried many cases. Imports are right in other directories, in namespaced packages, and in other packages, for both in-source ESM and out-of-source CommonJS output. This also holds when the type is reached through an intermediate module, a functor, module type of, or an interface. Moving Shapes.res and an incremental rebuild recompiles every module that uses the type. The inlining guard covers the only place class checks are compiled (Switch_variant).

All the main points come from one design choice: a class is identified by the file that declares it plus the path string.

1. One JS class declared in two files gives a match that silently takes the wrong arm. src/geo/Shapes.res and src/geo/Shapes2.res both declare:

@module("./shapes.js") @instanceOf("Circle")
type circle
@unboxed
type v = A(Shapes.circle) | B(Shapes2.circle)
let kind = v => switch v { | A(_) => "A" | B(_) => "B" }

This compiles, with two imports of ./shapes.js, and kind(B(...)) returns "A". Without this PR, the same variant is the "At most one case can be an instance of Circle" error. Inside one file it still is. One fix would be to reject cases whose @module and path read the same but come from different files. That would also reject the same "./shapes.js" in two directories, which Classes.res tests as intended. So this is a trade-off, and I'd like your view: a rare false error in that case, or a silent wrong arm in this one.

2. Another file can't hide such a type behind an abstract type. Say src/mid/Facade.res has

module type S = { @module("../moved/shapes.js") @instanceOf("Circle") type t }
module M: S = { type t = Shapes.circle }

This is rejected. The two declarations are Circle from "./shapes.js" relative to Shapes and Circle from "../moved/shapes.js" relative to Facade, even though both paths lead to the same file. The same happens with an abstract type in Facade.resi over type t = Shapes.circle in Facade.res. A bindings package that keeps classes in an internal module and shows them abstractly through a facade can't do that now. The only way out is to keep the type public. The docs mention this, but maintainers should decide it explicitly.

3. Messages show internal module names. In a namespaced package the errors say relative to Shapes-Ns. The advice "Add the package of Shapes-Ns to the dependencies" can't name the package. Within a single file, "relative to …" adds nothing. Could the messages use the plain module name, and say "relative to" only when two different files are involved? Class_unit_not_found also has no source location. The switch has one.

Simplifications

  • Script-mode fallback: without a package (plain bsc), the path could simply stay as written. That removes the Js_not_found handler in js_name_of_module_id.ml and the new public Dependency_error.Error. This is also the one part of the change no test covers.
  • Ext_path.node_path_from_dir: the handling of package names, scopes and a//../b only matters for paths that leave their package, which can't work anyway. Removing . segments and resolving .. against real directories is enough, or such a path could be an error.
  • Can the declaring module be loaded? checks_unloadable_class and class_constructor both decide this. One helper in Lam_compile_env could serve both, and can_load would not need to be exported.
  • Optional: relative_to is Some exactly when module_ is relative. A variant such as Global | Package(string) | Relative({path, unit}) would state that in the type.

Small points

  • "." and ".." as module paths aren't treated as relative, so @module("..") keeps the original bug. Externals have the same gap in is_package_relative_path, so a fix there covers both.
  • The changelog fragment fixes a feature that hasn't been released yet (changes/instance-of-module.fix.md). It could be folded into that fragment.
  • relative_to = _ in the class_constructor pattern can go.
  • The description says the commits aren't signed off, but they are.

This review was done by Claude (Opus 5.5 and Fable 5.2, independently).

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

2 participants