Skip to content

Commit cf580f1

Browse files
cknittclaude
andcommitted
Reject a namespace that is not a valid module name
Why: A namespace becomes a module, but a package named "_" or "123" with "namespace": true, or a "namespace" value such as "_ns", yielded a name no ReScript code can refer to. Both build systems now reject it when loading rescript.json, for the root package and every dependency. Diagnostic added (invalid namespace): Example: {"name": "_", "namespace": true} After (diagnostic): /path/to/rescript.json: namespace "_" derived from package name "_" is not a valid module name; set "namespace" to a valid module name or rename the package A valid module name is what the scanner reads as an upper-case identifier: an ASCII capital, then letters, digits, '_', '\'' and '$'. Packages without a namespace keep accepting any name, including "_". Review: Why not reserve the package name "_" as bsb did? bsb reserved it only because the compiler used "_" as an internal "no package" sentinel, which a variant replaced in 2019 (8ed242a). Review: What else is now rejected? "namespace": "" (an empty namespace module), which the parity table listed as accepted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Kr4cjoUi2f5VpMvE6wT9bo Signed-off-by: Christoph Knittel <ck@cca.io>
1 parent 39bd7be commit cf580f1

7 files changed

Lines changed: 116 additions & 6 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
- Reject a namespace in `rescript.json` that is not a valid module name, such as one derived from the package name `_`.

‎rewatch-ocaml/config.ml‎

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -108,15 +108,39 @@ let decode_namespace path ~name fields =
108108
optional_member "namespace-entry" fields
109109
|> Option.map (string path "namespace-entry")
110110
in
111+
(* The namespace becomes a module, so a name the scanner cannot read as one
112+
is rejected here instead of producing unusable compiler arguments. *)
113+
let module_name ~source ~fix namespace =
114+
if is_module_name namespace then namespace
115+
else
116+
fail path
117+
(Printf.sprintf
118+
"namespace \"%s\" derived from %s is not a valid module name; set \
119+
\"namespace\" to a valid module name%s"
120+
namespace source fix)
121+
in
122+
let from_package_name () =
123+
namespace_from_package_name name
124+
|> module_name
125+
~source:(Printf.sprintf "package name \"%s\"" name)
126+
~fix:" or rename the package"
127+
in
128+
let from_value value namespace =
129+
module_name
130+
~source:(Printf.sprintf "\"namespace\" value \"%s\"" value)
131+
~fix:"" namespace
132+
in
111133
let namespace_name =
112134
match optional_member "namespace" fields with
113135
| None | Some (`Bool false) -> None
114-
| Some (`Bool true) -> Some (namespace_from_package_name name)
115-
| Some (`String "true") -> Some (namespace_from_package_name name)
116-
| Some (`String value) when is_upper_flat_case value -> Some value
136+
| Some (`Bool true) -> Some (from_package_name ())
137+
| Some (`String "true") -> Some (from_package_name ())
138+
| Some (`String value) when is_upper_flat_case value ->
139+
Some (from_value value value)
117140
| Some (`String value) when Option.is_some namespace_entry ->
118-
Some (pascal_case value)
119-
| Some (`String value) -> Some (namespace_from_package_name value)
141+
Some (from_value value (pascal_case value))
142+
| Some (`String value) ->
143+
Some (from_value value (namespace_from_package_name value))
120144
| Some _ -> fail path "field \"namespace\" must be a boolean or string"
121145
in
122146
match (namespace_entry, namespace_name) with

‎rewatch-ocaml/config_decode.ml‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,20 @@ let is_upper_flat_case value =
212212
String.concat "" (List.map String.uppercase_ascii (pascal_case_words value))
213213
= value
214214

215+
(* A module name as the ReScript scanner reads an upper-case identifier
216+
(compiler/syntax/src/res_scanner.ml): an ASCII capital, then letters,
217+
digits, '_', '\'' and '$'. *)
218+
let is_module_name value =
219+
value <> ""
220+
&& (match value.[0] with
221+
| 'A' .. 'Z' -> true
222+
| _ -> false)
223+
&& String.for_all
224+
(function
225+
| 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '_' | '\'' | '$' -> true
226+
| _ -> false)
227+
value
228+
215229
let compiler_flags path field = function
216230
| `List values ->
217231
values

‎rewatch-ocaml/config_decode.mli‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ val strings : string -> string -> Yojson.Safe.t -> string list
2727
val namespace_from_package_name : string -> string
2828
val pascal_case : string -> string
2929
val is_upper_flat_case : string -> bool
30+
val is_module_name : string -> bool
3031
val compiler_flags : string -> string -> Yojson.Safe.t -> string list
3132

3233
val dependency_alias :

‎rewatch-ocaml/tests/config_acceptance_cases.tsv‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,13 @@ namespace false accept {"name":"config-shape","namespace":false}
226226
namespace true accept {"name":"scope/config-shape","namespace":true}
227227
namespace string-true accept {"name":"scope/config-shape","namespace":"true"}
228228
namespace custom accept {"name":"config-shape","namespace":"custom-name"}
229-
namespace empty-string accept {"name":"config-shape","namespace":""}
229+
namespace empty-string reject {"name":"config-shape","namespace":""}
230+
namespace scoped-package accept {"name":"@scope/my-pkg","namespace":true}
231+
namespace underscore-package reject {"name":"_","namespace":true}
232+
namespace digit-package reject {"name":"123","namespace":true}
233+
namespace underscore-string reject {"name":"config-shape","namespace":"_ns"}
234+
namespace digit-string-entry reject {"name":"config-shape","namespace":"1st","namespace-entry":"Entry"}
235+
namespace underscore-without-namespace accept {"name":"_"}
230236
namespace entry accept {"name":"config-shape","namespace":true,"namespace-entry":"Entry"}
231237
namespace null-entry accept {"name":"config-shape","namespace":true,"namespace-entry":null}
232238
namespace boolean-outer reject {"name":"config-shape","namespace":1}

‎rewatch/src/config.rs‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -710,16 +710,53 @@ fn namespace_from_package_name(package_name: &str) -> String {
710710
buf
711711
}
712712

713+
/// A module name as the ReScript scanner reads an upper-case identifier
714+
/// (compiler/syntax/src/res_scanner.ml): an ASCII capital, then letters,
715+
/// digits, '_', '\'' and '$'.
716+
fn is_module_name(name: &str) -> bool {
717+
name.starts_with(|c: char| c.is_ascii_uppercase())
718+
&& name
719+
.chars()
720+
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '\'' | '$'))
721+
}
722+
713723
impl Config {
714724
/// Try to convert a config from a certain path to a config struct
715725
pub fn new(path: &Path) -> Result<Self> {
716726
let read =
717727
fs::read_to_string(path).map_err(|e| anyhow!("Could not read '{}': {}", path.display(), e))?;
718728
let mut config = Config::new_from_json_string(&read)?;
719729
config.set_path(path.to_path_buf())?;
730+
config.validate_namespace()?;
720731
Ok(config)
721732
}
722733

734+
/// The namespace becomes a module, so a name the scanner cannot read as one
735+
/// is rejected here instead of producing unusable compiler arguments.
736+
fn validate_namespace(&self) -> Result<()> {
737+
let namespace = match self.get_namespace() {
738+
packages::Namespace::NoNamespace => return Ok(()),
739+
packages::Namespace::Namespace(namespace)
740+
| packages::Namespace::NamespaceWithEntry { namespace, .. } => namespace,
741+
};
742+
if is_module_name(&namespace) {
743+
return Ok(());
744+
}
745+
let (source, fix) = match &self.namespace {
746+
Some(NamespaceConfig::String(value)) if value != "true" => {
747+
(format!("\"namespace\" value \"{value}\""), "")
748+
}
749+
_ => (
750+
format!("package name \"{}\"", self.name),
751+
" or rename the package",
752+
),
753+
};
754+
Err(anyhow!(
755+
"{}: namespace \"{namespace}\" derived from {source} is not a valid module name; set \"namespace\" to a valid module name{fix}",
756+
self.path.display()
757+
))
758+
}
759+
723760
/// Try to convert a config from a string to a config struct
724761
fn new_from_json_string(config_str: &str) -> Result<Self> {
725762
let raw_value = serde_json::from_str::<serde_json::Value>(config_str).ok();
@@ -2436,6 +2473,22 @@ pub mod tests {
24362473
);
24372474
}
24382475

2476+
#[test]
2477+
fn test_invalid_namespace_module_name() {
2478+
let tmp = tempfile::tempdir().expect("tempdir");
2479+
let path = tmp.path().join("rescript.json");
2480+
std::fs::write(&path, r#"{ "name": "_", "namespace": true }"#).expect("write");
2481+
2482+
let error = Config::new(&path).unwrap_err().to_string();
2483+
assert_eq!(
2484+
error,
2485+
format!(
2486+
"{}: namespace \"_\" derived from package name \"_\" is not a valid module name; set \"namespace\" to a valid module name or rename the package",
2487+
path.display()
2488+
)
2489+
);
2490+
}
2491+
24392492
#[test]
24402493
fn test_bsconfig_json_filename_deprecation() {
24412494
let tmp = tempfile::tempdir().expect("tempdir");

‎tests/rewatch_ounit_tests/config_tests.ml‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,17 @@ let validation_tests =
249249
with Config.Error message -> contains message "jsx.version"
250250
in
251251
check rejected "unsupported JSX versions are rejected without panicking";
252+
write_file path {|{"name":"_","namespace":true}|};
253+
let rejected =
254+
try
255+
ignore (Config.load path);
256+
false
257+
with Config.Error message ->
258+
message
259+
= path
260+
^ {|: namespace "_" derived from package name "_" is not a valid module name; set "namespace" to a valid module name or rename the package|}
261+
in
262+
check rejected "a namespace must be a valid module name";
252263
write_file path
253264
{|{"name":"internal-path","path":"ignored","gentypeconfig":{}}|};
254265
let alias_dir = Filename.concat root "alias" in

0 commit comments

Comments
 (0)