-
Notifications
You must be signed in to change notification settings - Fork 0
feat: Complete function overloading, TypeScript bindings generator, and JavaScript interop enhancements #25
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
Conversation
- Add new `dts2-extern` CLI command to convert TypeScript declaration files - Integrate SWC parser for TypeScript AST parsing - Implement converter that maps TypeScript interfaces and types to Husk extern declarations - Support for basic type mappings (string, number, boolean, etc.) - Convert interface methods to Husk impl blocks - Handle function declarations and type aliases - Add comprehensive implementation plan documentation Example usage: `husk dts2-extern input.d.ts -o output.husk` 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Process namespace body content including functions, variables, and types - Convert namespace functions with prefixed names (namespace$function) - Transform namespace variables into extern constants - Collect and output type declarations within namespaces - Add comprehensive debug logging for namespace processing The Express .d.ts file now generates meaningful output with all namespace members properly converted. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Add HuskType::Qualified variant for module-qualified types - Implement proper parsing of TsQualifiedName (e.g., core.Express) - Convert qualified types to Husk's module::Type syntax - Handle nested qualified names through recursive extraction Now TypeScript declarations like `core.Express` are properly converted to `core::Express` in Husk extern declarations. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Track all TypeScript import statements (namespace, named, default) - Store import information with source, alias, and type - Output imports as comments in generated Husk code for reference - Add import statistics to debug output - Preserve import context for better understanding of type references The converter now provides full visibility into module dependencies, making it easier to understand and resolve external type references. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Track extends clauses for all interfaces - Support single and multiple inheritance - Handle qualified extends (e.g., core::Application) - Output extends information as comments above type declarations - Extract type names from both simple and member expressions Now interfaces that extend other interfaces are properly documented, making it easier to understand type hierarchies in the generated Husk code. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
…ds in parameters - Fixed lexer to properly tokenize identifiers starting with underscore (e.g., _GlobOptions) - Added parameter name sanitization in dts2extern to append _ to reserved keywords - Created fs-example to demonstrate the fixes working with Node.js fs module types - Updated namespace generation to use proper extern mod syntax - Removed unused is_identifier_start method to eliminate warning 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Added comprehensive examples of Node.js fs module operations - Demonstrates file creation, reading, writing, and deletion - Shows directory operations (create, remove) and file manipulation (rename, copy) - Includes file system queries (exists, stats) and access control checks - Uses extern function declarations with proper bindings - Successfully runs and completes all 10 example operations The example validates that: - Lexer properly handles underscore-prefixed identifiers - Reserved keywords in parameters are properly sanitized - Extern declarations work correctly with Node.js modules 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Added external::fs import to main.husk - Created extern-bindings.json to map function names to implementations - Added add-bindings.js post-build script to inject bindings - Updated package.json with build scripts - Enhanced README with complete documentation and running instructions - The example now successfully runs all 10 file system operations This is a temporary solution until Husk's build system natively supports extern function bindings configuration. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
This commit enables importing extern declarations from other Husk files, creating a global registry of types. It also introduces the `any` type for TypeScript compatibility. Key changes: - Add support for importing extern declarations via local modules - Implement `Type::Any` for opaque TypeScript types - Update semantic analyzer to handle extern declarations in imported modules - Add type resolution for extern function parameters - Update dts2extern to generate `type Foo = any;` for opaque types - Fix module resolution to include file context This allows writing `use local::fs_types;` to import all extern declarations from another file, making type information globally available. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Add AttributeKind and AttributeArgument enums for Rust-like attributes - Support three attribute syntaxes: Flag (#[test]), CallStyle (#[test(arg)]), NameValue (#[js_name = "string"]) - Update parser to handle all three attribute syntaxes - Update transpiler to use new attribute structure for js_name - Update dts2extern to generate correct #[js_name = "string"] syntax - Fix all code using old attr.args to use new structure - Remove unused has_extern_module method 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Use new #[js_name = "string"] syntax instead of old #[js_name(string)] - All camelCase JavaScript functions now have snake_case Husk names - Includes all fs module functions with proper overloads 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Add extern_functions HashMap to SemanticVisitor to track js_name mappings - Add getter method get_extern_functions() to SemanticVisitor - Update process_extern_item_for_module and process_extern_item to extract js_name attributes - Add extern_functions field to JsTranspiler and set_extern_functions() method - Update lib.rs to pass extern_functions from semantic analyzer to transpiler - Fix visit_enum_variant_or_method_call to use js_name mapping for module function calls - Now fs::write_file_sync with #[js_name = "writeFileSync"] transpiles to fs.writeFileSync 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
This commit completes the js_name attribute implementation by fixing
the critical import generation bug and implementing the recommended
aliasing approach for extern function imports.
Key changes:
- Fixed broken import generation that tried to import non-existent snake_case names
- Implemented import aliasing: `import { existsSync as exists_sync } from 'fs'`
- Updated semantic analyzer to pass extern_functions mappings to transpiler
- Enhanced transpiler import logic to check js_name mappings during generation
- Updated fs-example to use snake_case function names consistently
The aliasing approach allows Husk developers to use familiar snake_case
conventions while properly importing JavaScript camelCase function names,
providing the best developer experience and language consistency.
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <[email protected]>
- Fix visit_extern_type method signature to include missing type_alias parameter - Fix ExternItem::Type pattern matching to destructure all 3 fields - Ensures compatibility with extern type declaration enhancements 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Add find_function_by_name helper method for improved function resolution - Fix function iteration logic to handle Vec<FunctionSignature> correctly - Provide specific "expects X arguments" errors when function exists but argument count mismatches - Resolves test_wrong_number_of_arguments test failure 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Update test_import_map_wildcard_import to expect 'import * as axios from ...' - Previous expectation 'import * from ...' is invalid JavaScript syntax - Transpiler correctly generates valid ES6 import statements 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
…pt implementation plan - Add JS_INTEROP_PROGRESS_TRACKER.md with detailed task breakdown and progress tracking - Add TYPESCRIPT_ADVANCED_TYPES_IMPLEMENTATION_PLAN.md with 5-phase approach for Tasks 11-14 - Documents all completed JavaScript interoperability features and future enhancements - Provides clear roadmap for advanced TypeScript type system support 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Remove DTS_CONVERTER_MISSING_FEATURES.md (superseded by JS_INTEROP_PROGRESS_TRACKER.md) - Remove DTS_TO_HUSK_CONVERTER_PLAN.md (superseded by TYPESCRIPT_ADVANCED_TYPES_IMPLEMENTATION_PLAN.md) - Consolidates documentation into comprehensive tracking files 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Add resolved_type field to HuskExternType for simple type aliases - Implement try_resolve_simple_type_alias function for basic TypeScript types - Update type alias processing to resolve string, number, boolean types - Generate proper Husk type declarations instead of opaque any types - Support type alias resolution in both top-level and namespace contexts 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
|
@claude review this PR |
|
Claude finished @fcoury's task —— View job PR Review: Complete JS Interop FeaturesComprehensive review of JavaScript interoperability features implementation completed. Review Checklist
🔍 Review SummaryThis PR implements a comprehensive JavaScript interoperability system for Husk. The implementation is well-architected and addresses a critical need for TypeScript integration. Here's my detailed analysis: ✅ Strengths1. Solid Architecture
2. Comprehensive TypeScript Integration
3. Excellent Working Example
|
|
Claude finished @fcoury's task —— View job Code Review: JS Interop & Function Overloading ImplementationReviewing this comprehensive PR that implements JavaScript interoperability features, function overloading, and TypeScript integration. Review Progress
Executive SummaryThis is a substantial and well-architected PR that successfully implements comprehensive JavaScript interoperability features. The implementation is solid with good separation of concerns, but there are several important issues that should be addressed before merging. Detailed Code Review✅ Strengths
|
…resolution ## Summary - Completed implementation of type-aware function overload resolution - Added first-class function support for functions as parameters - Fixed instance method overload resolution for extern impl blocks - Achieved 100% test coverage (20/20) for function overloading ## Key Changes - **First-class functions**: Functions can now be used as parameters and identifiers - **Method resolution**: Fixed extern impl method lookup using correct naming patterns - **Type matching**: Proper self parameter type resolution for struct methods - **Parser enhancements**: Support for complex types (arrays, tuples, function types) ## Test Results - All 20 function overload tests passing (100%) - All 584 library tests passing - No regressions detected ## Implementation Details - Enhanced `visit_identifier` to recognize function names as first-class values - Fixed `visit_extern_impl` to use correct struct type for self parameters - Added dual lookup pattern for both static (::) and instance (.) method calls - Improved error messages with detailed overload information 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
…ameters - Add test_regular_function_with_function_parameters for semantic analysis - Add test_regular_function_with_function_parameters_interpreter for runtime execution - Verify that regular (non-extern) Husk functions support function parameters - Fix clippy warnings for format string inlining - Confirms first-class function support works in both analysis and interpreter 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
…RL handling CRITICAL SECURITY FIXES: - Add URL validation to prevent SSRF attacks - Block private IP ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) - Block AWS metadata endpoint (169.254.169.254) - Block metadata domains and suspicious endpoints - Restrict HTTP to localhost only (127.0.0.1, localhost) - Enforce HTTPS for all external URLs SECURITY FEATURES: - Secure HTTP client with 30s timeout and redirect limits - Content-type and size validation (10MB limit) - Comprehensive security test suite (13 tests) - Protection against protocol bypass attacks DEPENDENCIES: - Add url crate for robust URL parsing and validation This addresses the high-priority SSRF vulnerability that could allow attackers to access internal services, cloud metadata endpoints, and private networks through malicious dts2extern URLs. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
…mentation The function overload changes introduced a regression in struct instance method resolution. The issue was that struct type comparison for method resolution was too strict - it compared complete struct definitions including field details and ordering. ## Problem - Method calls like `p.distance_from_origin()` failed with "Unknown enum variant or method" - Function signatures were registered with empty/different field ordering than actual types - `types_match()` required exact struct equality including field details ## Solution - Modified `types_match()` to compare only struct/enum names for method resolution - This allows method calls to work regardless of field ordering or completeness - Added similar handling for enum types to be consistent ## Test Coverage - All existing tests continue to pass (586/586) - Function overload tests pass (22/22) - Manual testing confirms method calls now work correctly 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Add function_index HashMap for O(1) parameter count filtering - Implement add_function_signature helper for index maintenance - Update all function registration points to use optimized method - Add comprehensive performance tests demonstrating <1μs lookup times - Maintain backward compatibility with fallback to original lookup - Achieve 736ns average lookup time for 1000 iterations 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Implement validate_js_identifier() function to ensure js_name values are valid JavaScript identifiers - Check for valid starting characters (letter, underscore, dollar sign) - Validate all characters are alphanumeric, underscore, or dollar sign - Reject JavaScript reserved words (function, class, var, etc.) - Add comprehensive test suite covering all validation scenarios - Apply validation to all js_name attribute processing locations This prevents runtime errors in generated JavaScript by catching invalid identifiers during semantic analysis. 🤖 Generated with Claude Code (https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Fixed potential panic in span.rs pretty_print function - Added validation for out-of-bounds spans - Returns descriptive error message instead of panicking - Handles edge cases: start > end, indices beyond code length - Added comprehensive test coverage for bounds checking - String slice and char_at operations with out-of-bounds indices - Array index bounds validation - Unicode string handling - Span formatting with invalid bounds - Verified TypeScript type conversion bounds safety - Optional parameter handling generates correct overloads - Interface extends array processing is safe - Namespace collection handling has proper bounds - Made camel_to_snake_case function accessible for testing - Changed visibility to pub(crate) for internal testing - Added edge case tests for empty strings and acronyms This ensures the codebase handles out-of-bounds access gracefully without panics, improving robustness and error reporting. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
- Add 17 test cases covering various error scenarios: - Non-existent file handling - Invalid file extensions - Malformed TypeScript syntax - Circular type references - Reserved keyword handling - Permission errors - Binary file input - UTF-8 BOM handling - Set up integration tests using Command execution - Verify error messages and exit codes - All tests pass successfully
- Rename command from dts2-extern to bindgen for better clarity - Update all references throughout the codebase: - Rename files: dts2extern.rs → bindgen.rs - Rename struct: Dts2ExternCommand → BindgenCommand - Update CLI command: dts2-extern → bindgen - Update user agent string to husk-bindgen/0.1.1 - Update documentation and examples - All tests passing (610 total)
Summary
This PR implements comprehensive function overloading support, a TypeScript bindings generator (bindgen), and extensive JavaScript interoperability enhancements for Husk, including security hardening, performance optimizations, and comprehensive testing.
Major Features
1. Function Overloading with Type-Aware Resolution
2. TypeScript Bindings Generator (
husk bindgen)dts2-externtobindgenfor better clarity3. JavaScript Interoperability Enhancements
Security & Performance Improvements
Security Enhancements
Performance Optimizations
Testing & Quality
Comprehensive Test Coverage
Real-World Example
Complete Node.js fs module integration demonstrating:
Technical Implementation Details
Function Overloading Architecture
FunctionSignaturewith full type informationoverloaded_functions: HashMap<String, Vec<(FunctionSignature, bool)>>Bindgen Implementation
Parser Enhancements
int[],string[][](int, string) -> boolBreaking Changes
None - all changes are backwards compatible and enhance existing functionality.
Commits Summary
Test Plan
✅ Function Overloading
✅ Bindgen Command
✅ JavaScript Interop
✅ Integration Testing