Skip to content
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

#### :bug: Bug fix

- Fix references to a `@val` global reading a binding with the same name, e.g. a toplevel `let` declared before them. https://github.com/rescript-lang/rescript/pull/8785
- Evaluate the unused arguments of an inlined function call in parameter order. https://github.com/rescript-lang/rescript/pull/8786
- Fix editor completion of values from modules included with `include await M`. https://github.com/rescript-lang/rescript/pull/8770
- Fix editor completion inside dict literals and dict patterns, which suggested untyped values. https://github.com/rescript-lang/rescript/pull/8770
Expand Down
153 changes: 107 additions & 46 deletions compiler/core/js_pass_external_shadow.ml
Original file line number Diff line number Diff line change
Expand Up @@ -28,66 +28,127 @@ module String_set = Set.Make (String)

let global_this = E.js_global "globalThis"

(* Only rewrite for lexical bindings (let-style). *)
let is_lexical_binding_kind (property : J.property) =
match property with
| Strict | StrictOpt | Alias -> true
| Variable -> false
(* A reference to a JS global [x] is printed as [x]. If a binding printed as
[x] is in scope there, that name refers to the binding instead, so the
reference has to go through [globalThis.x]. *)

(* Skip JS globals/keywords and compiler-reserved JS ids. *)
let should_rewrite_binding (ident : Ident.t) =
(not (Ext_ident.is_js ident))
&& (not (Js_reserved_map.is_js_keyword ident.name))
&& not (Js_reserved_map.is_js_global ident.name)
(* The name a binding is printed with. Bindings named like JS keywords or
reserved globals are printed with a [$$] prefix, so they shadow nothing. *)
let add_binding (ident : Ident.t) names =
if Ext_ident.is_js ident then names
else String_set.add (Ext_ident.convert ident.name) names

(* A JS [let], [const] or function declaration is in scope in its whole block,
including before the declaration. *)
let add_declarations (block : J.block) names =
Ext_list.fold_left block names (fun acc (st : J.statement) ->
match st.statement_desc with
| Variable {ident} -> add_binding ident acc
| _ -> acc)

(* The cases of a switch are printed without braces, so they share one scope. *)
let add_switch_declarations (clauses : (_ * J.case_clause) list)
(default : J.block option) names =
let names =
Ext_list.fold_left clauses names (fun acc (_, c) ->
add_declarations c.switch_body acc)
in
match default with
| Some block -> add_declarations block names
| None -> names

(* Statically imported modules are toplevel bindings of the generated module
([import * as M from ...] or [let M = require(...)]). *)
let imported_modules (js : J.program) =
let names = ref String_set.empty in
let super = Js_record_iter.super in
let self =
{
super with
module_id =
(fun _ (m : J.module_id) ->
if not m.dynamic_import then names := add_binding m.id !names);
}
in
self.program self js;
!names

let program (js : J.program) : J.program =
let shadowed_globals =
Ext_list.fold_left js.block String_set.empty (fun acc (st : J.statement) ->
match st.statement_desc with
| Variable {ident; property}
when is_lexical_binding_kind property && should_rewrite_binding ident
->
String_set.add ident.name acc
| _ -> acc)
(* printed names of the bindings in scope at the current point *)
let in_scope = ref (imported_modules js) in
let with_bindings add f =
let outer = !in_scope in
in_scope := add outer;
let result = f () in
in_scope := outer;
result
in
(* Names of the lexical bindings whose initializer is being traversed: a JS
global with such a name can't be referenced directly there. *)
let enclosing_bindings = ref String_set.empty in
let super = Js_record_map.super in
let map_cases (self : Js_record_map.iter) clauses default =
with_bindings (add_switch_declarations clauses default) (fun () ->
( Ext_list.map clauses (fun (key, (c : J.case_clause)) ->
(key, {c with switch_body = self.block self c.switch_body})),
match default with
| None -> None
| Some block -> Some (self.block self block) ))
in
let self =
{
super with
block =
(fun self block ->
with_bindings (add_declarations block) (fun () ->
super.block self block));
expression =
(fun self expr ->
match expr.expression_desc with
| Var (Id id)
when Ext_ident.is_js id
&& String_set.mem id.name !enclosing_bindings ->
when Ext_ident.is_js id && String_set.mem id.name !in_scope ->
E.dot global_this id.name
| Static_index (obj, field, pos) ->
let obj = self.expression self obj in
let obj =
match obj.expression_desc with
| Var (Id id)
when Ext_ident.is_js id
&& String_set.mem id.name shadowed_globals ->
E.dot global_this id.name
| _ -> obj
in
{expr with expression_desc = Static_index (obj, field, pos)}
| Fun {params} ->
with_bindings
(fun names ->
Ext_list.fold_left params names (fun acc p -> add_binding p acc))
(fun () -> super.expression self expr)
| _ -> super.expression self expr);
variable_declaration =
(fun self (vd : J.variable_declaration) ->
match vd with
| {ident; value = Some _; property}
when is_lexical_binding_kind property
&& should_rewrite_binding ident ->
let outer = !enclosing_bindings in
enclosing_bindings := String_set.add ident.name outer;
let vd = super.variable_declaration self vd in
enclosing_bindings := outer;
vd
| _ -> super.variable_declaration self vd);
statement =
(fun self (st : J.statement) ->
match st.statement_desc with
| ForRange (_, _, _, ident, _, _)
| ForOf (_, ident, _, _)
| ForAwaitOf (_, ident, _, _) ->
with_bindings (add_binding ident) (fun () ->
super.statement self st)
(* The cases of a switch are printed without braces, so they share
one scope. The discriminant is evaluated before that scope is
entered. *)
| Int_switch (e, clauses, default) ->
let e = self.expression self e in
let clauses, default = map_cases self clauses default in
{st with statement_desc = Int_switch (e, clauses, default)}
| String_switch (e, clauses, default) ->
let e = self.expression self e in
let clauses, default = map_cases self clauses default in
{st with statement_desc = String_switch (e, clauses, default)}
(* The catch parameter is only in scope in the handler. *)
| Try (body, catch, finally) ->
let body = self.block self body in
let catch =
match catch with
| None -> None
| Some (ident, handler) ->
Some
( ident,
with_bindings (add_binding ident) (fun () ->
self.block self handler) )
in
let finally =
match finally with
| None -> None
| Some block -> Some (self.block self block)
in
{st with statement_desc = Try (body, catch, finally)}
| _ -> super.statement self st);
}
in
self.program self js
63 changes: 63 additions & 0 deletions tests/ounit_tests/ounit_external_shadow_tests.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
let ( >:: ), ( >::: ) = OUnit.(( >:: ), ( >::: ))

module E = Js_exp_make

let statement desc : J.statement =
{statement_desc = desc; comment = None; source_loc = None}

let case body : J.case_clause =
{switch_body = body; should_break = true; comment = None; source_loc = None}

(* [switch (g) { case 1: let g = 1; f(g, <global g>) }] *)
let switch_on_global () =
let local = Ident.create "g" in
let read_global =
statement
(Exp
(E.call ~info:Js_call_info.na_full_call (E.js_global "f")
[E.var local; E.js_global "g"]))
in
let body =
[
Js_stmt_make.define_variable ~kind:Lambda.Strict local (E.small_int 1);
read_global;
]
in
let program : J.program =
{
block = [statement (Int_switch (E.js_global "g", [(1, case body)], None))];
exports = [];
export_set = Set_ident.empty;
}
in
Js_pass_external_shadow.program program

let is_global_read (e : J.expression) =
match e.expression_desc with
| Var (Id id) -> Ext_ident.is_js id && id.name = "g"
| _ -> false

let is_global_this_read (e : J.expression) =
match e.expression_desc with
| Static_index ({expression_desc = Var (Id gt)}, "g", _) ->
Ext_ident.is_js gt && gt.name = "globalThis"
| _ -> false

let suites =
__FILE__
>::: [
( "switch discriminant is read outside the scope of the cases"
>:: fun _ ->
match switch_on_global () with
| {block = [{statement_desc = Int_switch (discr, [(_, c)], None)}]}
-> (
OUnit.assert_bool "discriminant reads the global directly"
(is_global_read discr);
match c.switch_body with
| [_; {statement_desc = Exp {expression_desc = Call (_, args, _)}}]
->
OUnit.assert_bool "read in the case goes through globalThis"
(List.exists is_global_this_read args)
| _ -> OUnit.assert_failure "unexpected case body")
| _ -> OUnit.assert_failure "unexpected program shape" );
]
1 change: 1 addition & 0 deletions tests/ounit_tests/ounit_tests_main.ml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ let suites =
Ounit_object_mutability_tests.suites;
Ounit_pattern_printer_tests.suites;
Ounit_js_analyzer_tests.suites;
Ounit_external_shadow_tests.suites;
Ounit_flow_parser_tests.suites;
Ounit_jsx_loc_tests.suites;
Ounit_parser_cursor_tests.suites;
Expand Down
2 changes: 1 addition & 1 deletion tests/tests/src/ExternalShadow.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ let X = {};

let process = globalThis.process;

let proc = process;
let proc = globalThis.process;

let New = {};

Expand Down
6 changes: 3 additions & 3 deletions tests/tests/src/ExternalShadow.res
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
/* Avoid @val shadowing: `let process = X.process` must not read itself.
The initializer should compile to `globalThis.process`, while other
uses of the external stay as plain `process`. */
The toplevel `process` binding is in scope in the whole module, so every
use of the external compiles to `globalThis.process`. */
module X = {
@val external process: unknown = "process"
}

let process = X.process /* expect `globalThis.process` */
let proc = X.process /* expect plain `process` */
let proc = X.process /* expect `globalThis.process` */

/* @new does not have the same shadowing issue because it uses `new URL(...)`. */
module New = {
Expand Down
100 changes: 100 additions & 0 deletions tests/tests/src/external_shadow_test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Generated by ReScript, PLEASE EDIT WITH CARE

import * as Mocha from "mocha";
import * as Test_utils from "./test_utils.mjs";

globalThis.shadowA = 10;
globalThis.shadowB = 20;
globalThis.shadowC = 30;
globalThis.shadowD = 40;
globalThis.shadowE = 50;
globalThis.shadowF = 60;
globalThis.Test_utils = 70;
;

let G = {};

function shadowA(n) {
return (n * n | 0) + globalThis.shadowA | 0;
}

function readAAfter() {
return globalThis.shadowA;
}

let valueA = globalThis.shadowA;

function readFBefore() {
return globalThis.shadowF;
}

function shadowF(n) {
return ((n * n | 0) * n | 0) + globalThis.shadowF | 0;
}

function paramB(shadowB) {
return (shadowB * shadowB | 0) + globalThis.shadowB | 0;
}

function localC(n) {
let before = globalThis.shadowC + n | 0;
let shadowC = (before * before | 0) + n | 0;
return (shadowC * shadowC | 0) + globalThis.shadowC | 0;
}

function switchD(x) {
switch (x) {
case 0 :
let shadowD = (x * x | 0) + 7 | 0;
return (shadowD * shadowD | 0) + globalThis.shadowD | 0;
case 1 :
return globalThis.shadowD + 1 | 0;
case 2 :
return (globalThis.shadowD << 1);
case 3 :
return globalThis.shadowD - 3 | 0;
default:
return globalThis.shadowD + x | 0;
}
}

function loopE() {
let sum = 0;
for (let shadowE = 0; shadowE <= 2; ++shadowE) {
sum = (sum + (shadowE * shadowE | 0) | 0) + globalThis.shadowE | 0;
}
return sum;
}

Mocha.describe("File \"external_shadow_test.res\", line 70, characters 9-16", () => {
Mocha.test("globals shadowed by bindings with the same name", () => {
Test_utils.eq("File \"external_shadow_test.res\", line 72, characters 7-14", shadowA(2), 14);
Test_utils.eq("File \"external_shadow_test.res\", line 73, characters 7-14", globalThis.shadowA, 10);
Test_utils.eq("File \"external_shadow_test.res\", line 74, characters 7-14", valueA, 10);
Test_utils.eq("File \"external_shadow_test.res\", line 75, characters 7-14", globalThis.shadowF, 60);
Test_utils.eq("File \"external_shadow_test.res\", line 76, characters 7-14", shadowF(2), 68);
Test_utils.eq("File \"external_shadow_test.res\", line 77, characters 7-14", paramB(3), 29);
Test_utils.eq("File \"external_shadow_test.res\", line 78, characters 7-14", localC(1), 925474);
Test_utils.eq("File \"external_shadow_test.res\", line 79, characters 7-14", switchD(0), 89);
Test_utils.eq("File \"external_shadow_test.res\", line 80, characters 7-14", shadowD + 1 | 0, 41);
Test_utils.eq("File \"external_shadow_test.res\", line 81, characters 7-14", (shadowD << 1), 80);
Test_utils.eq("File \"external_shadow_test.res\", line 82, characters 7-14", shadowD - 3 | 0, 37);
Test_utils.eq("File \"external_shadow_test.res\", line 83, characters 7-14", shadowD + 5 | 0, 45);
Test_utils.eq("File \"external_shadow_test.res\", line 84, characters 7-14", loopE(), 155);
Test_utils.eq("File \"external_shadow_test.res\", line 85, characters 7-14", globalThis.Test_utils, 70);
});
});

export {
G,
shadowA,
readAAfter,
valueA,
readFBefore,
shadowF,
paramB,
localC,
switchD,
loopE,
}
/* Not a pure module */
Loading
Loading