Repository navigation
fix(codegen): preserve class names across namespace reexports #11264
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Fix class names being overwritten by aliases or internal namespace keys when classes are reexported through a module namespace (#11259). Only the defining module registers the JavaScript display name. Add LLVM-emission and native Node-oracle coverage for namespace reexports, aliases, constructor names, class identity, and inheritance. |
147 changes: 147 additions & 0 deletions
147
crates/perry-codegen/src/codegen/class_name_registration_tests.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| //! Only defining modules may publish user-visible class names. | ||
|
|
||
| use crate::{compile_module, CompileOptions, ImportedClass}; | ||
| use perry_hir::{Class, Module}; | ||
|
|
||
| fn imported_class() -> ImportedClass { | ||
| ImportedClass { | ||
| name: "Original".to_string(), | ||
| local_alias: None, | ||
| namespace: None, | ||
| source_prefix: "source_ts".to_string(), | ||
| constructor_param_count: 0, | ||
| has_own_constructor: false, | ||
| constructor_has_rest: false, | ||
| constructor_has_synthetic_arguments: false, | ||
| has_instance_fields: false, | ||
| method_names: Vec::new(), | ||
| proven_this_method_names: Vec::new(), | ||
| proven_this_tower_method_names: Vec::new(), | ||
| method_return_types: Vec::new(), | ||
| method_param_counts: Vec::new(), | ||
| method_has_rest: Vec::new(), | ||
| method_has_synthetic_arguments: Vec::new(), | ||
| method_arguments_length_only: Vec::new(), | ||
| static_field_names: Vec::new(), | ||
| static_method_names: Vec::new(), | ||
| static_method_return_types: Vec::new(), | ||
| static_method_param_counts: Vec::new(), | ||
| static_method_has_rest: Vec::new(), | ||
| static_method_has_user_rest: Vec::new(), | ||
| static_method_has_synthetic_arguments: Vec::new(), | ||
| getter_names: Vec::new(), | ||
| getter_return_types: Vec::new(), | ||
| setter_names: Vec::new(), | ||
| parent_name: None, | ||
| field_names: Vec::new(), | ||
| field_types: Vec::new(), | ||
| source_class_id: Some(42), | ||
| return_shape_imports: Vec::new(), | ||
| object_literal: None, | ||
| } | ||
| } | ||
|
|
||
| fn local_class(id: u32, name: &str) -> Class { | ||
| Class { | ||
| id, | ||
| name: name.to_string(), | ||
| type_params: Vec::new(), | ||
| extends: None, | ||
| extends_name: None, | ||
| native_extends: None, | ||
| extends_expr: None, | ||
| heritage_lexically_shadowed: false, | ||
| fields: Vec::new(), | ||
| constructor: None, | ||
| methods: Vec::new(), | ||
| getters: Vec::new(), | ||
| setters: Vec::new(), | ||
| static_accessor_names: Vec::new(), | ||
| static_accessor_fn_ids: Vec::new(), | ||
| static_fields: Vec::new(), | ||
| static_methods: Vec::new(), | ||
| computed_members: Vec::new(), | ||
| decorators: Vec::new(), | ||
| is_exported: false, | ||
| aliases: Vec::new(), | ||
| is_nested: false, | ||
| alloc_width_hint: 0, | ||
| specialized_from: None, | ||
| } | ||
| } | ||
|
|
||
| fn ir(module: &Module, imported: Vec<ImportedClass>) -> String { | ||
| String::from_utf8( | ||
| compile_module( | ||
| module, | ||
| CompileOptions { | ||
| emit_ir_only: true, | ||
| imported_classes: imported, | ||
| ..Default::default() | ||
| }, | ||
| ) | ||
| .expect("class metadata compiles"), | ||
| ) | ||
| .expect("LLVM IR is UTF-8") | ||
| } | ||
|
|
||
| fn name_registrations(ir: &str) -> Vec<&str> { | ||
| ir.lines() | ||
| .filter(|line| line.contains("call void @js_register_class_name(")) | ||
| .collect() | ||
| } | ||
|
|
||
| #[test] | ||
| fn imported_namespace_classes_do_not_register_display_names() { | ||
| let module = Module::new("namespace_consumer.ts"); | ||
| let mut imported = imported_class(); | ||
| imported.namespace = Some("NS".to_string()); | ||
| let ir = ir(&module, vec![imported]); | ||
| assert!( | ||
| ir.contains("call void @js_register_class_id(i32 42)"), | ||
| "imported class must be present in the fixture" | ||
| ); | ||
| assert!( | ||
| name_registrations(&ir).is_empty(), | ||
| "the defining module owns the display name: {:?}", | ||
| name_registrations(&ir) | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn imported_aliases_do_not_register_display_names() { | ||
| let module = Module::new("alias_consumer.ts"); | ||
| let mut imported = imported_class(); | ||
| imported.local_alias = Some("Renamed".to_string()); | ||
| let ir = ir(&module, vec![imported]); | ||
| assert!( | ||
| ir.contains("call void @js_register_class_id(i32 42)"), | ||
| "imported class must be present in the fixture" | ||
| ); | ||
| assert!( | ||
| name_registrations(&ir).is_empty(), | ||
| "a local alias must not overwrite the source name: {:?}", | ||
| name_registrations(&ir) | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn local_classes_register_their_recorded_display_name_once() { | ||
| let mut module = Module::new("class_source.ts"); | ||
| let mut class = local_class(42, "InternalUniqueName"); | ||
| class.aliases.push("SelfBinding".to_string()); | ||
| module.classes.push(class); | ||
| module.class_display_names.insert(42, "Visible".to_string()); | ||
| let ir = ir(&module, Vec::new()); | ||
| let registrations = name_registrations(&ir); | ||
| assert_eq!( | ||
| registrations.len(), | ||
| 1, | ||
| "the local class must still register its name once" | ||
| ); | ||
| assert!(registrations[0].contains("i32 42")); | ||
| assert!( | ||
| ir.contains(r#"c"Visible\00""#), | ||
| "the recorded JS display name must be emitted" | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| //! Imported class names belong to the defining module, including namespace reexports. | ||
|
|
||
| use std::path::{Path, PathBuf}; | ||
| use std::process::{Command, Output}; | ||
|
|
||
| fn successful(command: &mut Command, subject: &str) -> Output { | ||
| let output = command | ||
| .output() | ||
| .unwrap_or_else(|error| panic!("{subject}: {error}")); | ||
| assert!( | ||
| output.status.success(), | ||
| "{subject} failed\nstdout:\n{}\nstderr:\n{}", | ||
| String::from_utf8_lossy(&output.stdout), | ||
| String::from_utf8_lossy(&output.stderr) | ||
| ); | ||
| output | ||
| } | ||
|
|
||
| #[test] | ||
| fn namespace_class_names_match_node() { | ||
| let dir = tempfile::tempdir().unwrap(); | ||
| let root = dir.path().canonicalize().unwrap(); | ||
| std::fs::write( | ||
| root.join("binary.ts"), | ||
| r#"export class Binary {} | ||
| export class UUID extends Binary {} | ||
| "#, | ||
| ) | ||
| .unwrap(); | ||
| std::fs::write( | ||
| root.join("bson.ts"), | ||
| r#"export { Binary, UUID } from "./binary.ts"; | ||
| "#, | ||
| ) | ||
| .unwrap(); | ||
| std::fs::write( | ||
| root.join("index.ts"), | ||
| r#"import * as BSON from "./bson.ts"; | ||
| export * from "./bson.ts"; | ||
| export { BSON }; | ||
| "#, | ||
| ) | ||
| .unwrap(); | ||
| std::fs::write( | ||
| root.join("control.ts"), | ||
| r#"export * as Control from "./binary.ts"; | ||
| "#, | ||
| ) | ||
| .unwrap(); | ||
| std::fs::write( | ||
| root.join("alias.ts"), | ||
| r#"export { UUID as PublicUUID, Binary as PublicBinary } from "./binary.ts"; | ||
| "#, | ||
| ) | ||
| .unwrap(); | ||
| std::fs::write(root.join("main.ts"), r#"import { UUID, Binary, BSON } from './index.ts'; | ||
| import { PublicUUID as Renamed, PublicBinary } from './alias.ts'; | ||
| import { Control } from './control.ts'; | ||
| console.log('named', UUID.name, Binary.name); | ||
| console.log('namespace', BSON.UUID.name, BSON.Binary.name); | ||
| console.log('instance', new UUID().constructor.name, new BSON.UUID().constructor.name); | ||
| console.log('alias', Renamed.name, PublicBinary.name, new Renamed().constructor.name); | ||
| console.log('control', Control.UUID.name, Control.Binary.name); | ||
| console.log('identity', BSON.UUID === UUID, Renamed === UUID, Control.UUID === UUID); | ||
| console.log('inheritance', new Renamed() instanceof Binary, new BSON.UUID() instanceof PublicBinary); | ||
| "#).unwrap(); | ||
| std::fs::write( | ||
| root.join("control-main.ts"), | ||
| r#"import { Control } from './control.ts'; | ||
| console.log(Control.UUID.name, Control.Binary.name, new Control.UUID().constructor.name); | ||
| console.log(new Control.UUID() instanceof Control.Binary); | ||
| "#, | ||
| ) | ||
| .unwrap(); | ||
| std::fs::write( | ||
| root.join("original-main.ts"), | ||
| r#"import { UUID, Binary, BSON } from './index.ts'; | ||
| console.log(JSON.stringify(UUID.name)); | ||
| console.log(JSON.stringify(new UUID().constructor.name)); | ||
| console.log(JSON.stringify(Binary.name)); | ||
| console.log(JSON.stringify(BSON.UUID.name)); | ||
| console.log(BSON.UUID === UUID); | ||
| "#, | ||
| ) | ||
| .unwrap(); | ||
| let compiler = PathBuf::from(env!("CARGO_BIN_EXE_perry")); | ||
| let runtime = std::env::var_os("PERRY_RUNTIME_DIR") | ||
| .map(PathBuf::from) | ||
| .unwrap_or_else(|| compiler.parent().unwrap().to_path_buf()); | ||
| let workspace = Path::new(env!("CARGO_MANIFEST_DIR")) | ||
| .join("../..") | ||
| .canonicalize() | ||
| .unwrap(); | ||
| // The standalone control has no leaking consumer initializer in its graph. | ||
| for (name, expected) in [ | ||
| ("original-main.ts", "\"UUID\"\n\"UUID\"\n\"Binary\"\n\"UUID\"\ntrue\n"), | ||
| ("main.ts", "named UUID Binary\nnamespace UUID Binary\ninstance UUID UUID\nalias UUID Binary UUID\ncontrol UUID Binary\nidentity true true true\ninheritance true true\n"), | ||
| ("control-main.ts", "UUID Binary UUID\ntrue\n"), | ||
| ] { | ||
| let entry = root.join(name); | ||
| let node = successful(Command::new("node").current_dir(&root).arg(&entry), name); | ||
| assert_eq!(node.stdout, expected.as_bytes(), "Node fixture: {name}"); | ||
| let executable = root.join(if cfg!(windows) { "app.exe" } else { "app-native" }); | ||
| successful( | ||
| Command::new(&compiler) | ||
| .current_dir(&root) | ||
| .env("PERRY_RUNTIME_DIR", &runtime) | ||
| .env("PERRY_WORKSPACE_ROOT", &workspace) | ||
| .args(["compile", "--no-cache", "--no-auto-optimize"]) | ||
| .arg(&entry).arg("-o").arg(&executable), | ||
| name, | ||
| ); | ||
| let native = successful(Command::new(&executable).current_dir(&root), name); | ||
| assert_eq!(native.stdout, node.stdout, "class names and identity: {name}"); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: PerryTS/perry
Length of output: 15703
🏁 Script executed:
Repository: PerryTS/perry
Length of output: 32566
🏁 Script executed:
Repository: PerryTS/perry
Length of output: 24864
🏁 Script executed:
Repository: PerryTS/perry
Length of output: 11341
🌐 Web query:
Node.js v26.5.1 official documentation TypeScript type stripping default node file.ts💡 Result:
Add an ES module marker to the temporary fixture tree.
The fixtures use
importandexport, but the test does not createpackage.json. Node therefore treats the.tsfiles as CommonJS and can fail before producing the expected output. The pinned Node26.5.1runtime does support type stripping, but it does not change module-mode resolution.Suggested fix
let dir = tempfile::tempdir().unwrap(); let root = dir.path().canonicalize().unwrap(); + std::fs::write(root.join("package.json"), r#"{"type":"module"}"#).unwrap(); std::fs::write( root.join("binary.ts"),📝 Committable suggestion
🤖 Prompt for AI Agents