Skip to content

Conversation

@fcoury
Copy link
Owner

@fcoury fcoury commented Jun 30, 2025

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

  • Implemented complete function overload resolution based on parameter types, not just count
  • Support for first-class functions as parameters
  • Proper type matching for arrays, tuples, functions, and complex nested types
  • Instance method overload resolution for extern implementations

2. TypeScript Bindings Generator (husk bindgen)

  • Renamed from dts2-extern to bindgen for better clarity
  • Converts TypeScript .d.ts files to Husk extern declarations
  • Supports both local files and HTTPS URLs with security validation
  • Handles complex TypeScript features:
    • Type aliases and interface extensions
    • Namespaces and qualified types
    • Function overloading
    • Generic type parameters
    • Optional parameters

3. JavaScript Interoperability Enhancements

  • js_name Attribute Validation: Validates JavaScript identifiers and prevents reserved words
  • Import Aliasing: Automatic camelCase to snake_case conversion with proper aliasing
  • Cross-file Extern Support: Import and use extern functions across modules
  • Any Type Support: Fallback for complex TypeScript types

Security & Performance Improvements

Security Enhancements

  • SSRF Protection: Comprehensive URL validation for bindgen HTTP requests
  • IP Range Blocking: Prevents access to private IPs and metadata endpoints
  • Content Validation: Size limits and content type checking
  • Reserved Keyword Handling: Automatic escaping of JavaScript reserved words

Performance Optimizations

  • Function Lookup Indexing: HashMap indexing by parameter count for O(1) lookup
  • Efficient Overload Resolution: Quick filtering before type checking
  • Bounds Checking: Comprehensive bounds validation for array and string operations

Testing & Quality

Comprehensive Test Coverage

  • 610 tests all passing
  • Function overloading with 20+ test cases
  • Security validation tests for URL handling
  • Error case testing for bindgen command (17 scenarios)
  • Bounds checking tests for TypeScript conversion
  • JavaScript identifier validation tests

Real-World Example

Complete Node.js fs module integration demonstrating:

// Generated by: husk bindgen fs.d.ts
extern mod fs {
    #[js_name = "existsSync"]
    fn exists_sync(path: string) -> bool;
    
    #[js_name = "readFileSync"]
    fn read_file_sync(path: string) -> Buffer;
    #[js_name = "readFileSync"]
    fn read_file_sync(path: string, encoding: string) -> string;
}

Technical Implementation Details

Function Overloading Architecture

  • Enhanced FunctionSignature with full type information
  • overloaded_functions: HashMap<String, Vec<(FunctionSignature, bool)>>
  • Type-aware matching with proper conversion support (int to float)
  • Clear error messages showing all available overloads

Bindgen Implementation

  • SwC-based TypeScript parser integration
  • Recursive type resolution with circular reference handling
  • Intelligent module name inference
  • Support for filter and simplify options

Parser Enhancements

  • Array type syntax: int[], string[][]
  • Function type syntax: (int, string) -> bool
  • Extern impl parsing for instance methods
  • Tuple type support in parameters

Breaking Changes

None - all changes are backwards compatible and enhance existing functionality.

Commits Summary

  • ✨ Complete function overloading with type-aware resolution
  • 🔧 Rename dts2-extern to bindgen command
  • 🔒 Add comprehensive security validation for HTTP URLs
  • ⚡ Optimize function lookup with parameter indexing
  • ✅ Add extensive test coverage for all new features
  • 🐛 Fix struct method call regression
  • 📝 Add JavaScript identifier validation
  • 🛡️ Add bounds checking for TypeScript conversion
  • 🎯 Implement first-class function support

Test Plan

Function Overloading

  • Type-based resolution works correctly
  • Error messages show all available overloads
  • Cross-file usage maintains overload information
  • Performance optimization doesn't affect correctness

Bindgen Command

  • Converts complex TypeScript definitions accurately
  • Security validation prevents SSRF attacks
  • Handles edge cases (BOM, circular refs, binary files)
  • Generated code compiles and runs correctly

JavaScript Interop

  • js_name attributes validated properly
  • Import aliasing generates correct JavaScript
  • Reserved keywords automatically escaped
  • All extern features work together seamlessly

Integration Testing

  • fs-example demonstrates complete workflow
  • Real Node.js APIs work correctly
  • No regressions in existing functionality
  • All 610 tests passing

fcoury and others added 20 commits June 29, 2025 00:44
- 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]>
@fcoury
Copy link
Owner Author

fcoury commented Jun 30, 2025

@claude review this PR

@claude
Copy link
Contributor

claude bot commented Jun 30, 2025

Claude finished @fcoury's task —— View job


PR Review: Complete JS Interop Features

Comprehensive review of JavaScript interoperability features implementation completed.

Review Checklist

  • Review core semantic analysis changes (semantic.rs)
  • Analyze transpiler modifications for import aliasing (transpiler.rs)
  • Check attribute parsing and AST extensions (parser.rs)
  • Review dts2extern converter implementation (dts/ module)
  • Evaluate function overloading implementation
  • Assess security implications of TypeScript integration
  • Check test coverage and example quality
  • Performance considerations analysis
  • Code quality and best practices review
  • Final review summary and recommendations

🔍 Review Summary

This 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:

Strengths

1. Solid Architecture

  • Function overloading via HashMap<String, Vec<FunctionSignature>> in semantic.rs:25 is a clean approach
  • Import aliasing in transpiler.rs:1276-1290 correctly handles js_name mappings
  • AST extensions properly support key-value attributes: #[js_name = "actualName"]

2. Comprehensive TypeScript Integration

  • dts2extern converter uses SWC parser - industry standard for TypeScript parsing
  • Smart camelCase→snake_case conversion with proper acronym handling (dts/converter.rs:18-47)
  • Reserved keyword sanitization prevents conflicts (dts/converter.rs:105-111)

3. Excellent Working Example

  • examples/fs-example/ demonstrates real Node.js fs module integration
  • Generated fs_types.husk shows proper function overloading (lines 60-68)
  • Complete usage example in main.husk with proper error handling

⚠️ Issues & Recommendations

1. Function Overloading Limitations

  • find_matching_function only matches by argument count (semantic.rs:162-173)
  • Risk: Won't distinguish between readFile(path: string) and readFile(path: Buffer)
  • Recommendation: Implement type-aware overload resolution

2. Security Concerns

  • dts2extern command accepts HTTP URLs (commands/dts2extern.rs:33-49)
  • Risk: Could fetch malicious TypeScript definitions
  • Recommendation: Add URL validation, restrict to known registries, or add --allow-http flag

3. Error Handling Gaps

  • No validation of js_name attribute values
  • Missing bounds checking in TypeScript type conversion
  • Recommendation: Add validation for special characters in js_name values

4. Performance Considerations

  • Function lookup is O(n) through signature vectors
  • Impact: Could be slow with many overloads
  • Recommendation: Consider indexing by argument count for O(1) initial lookup

🧪 Test Coverage Assessment

Strong Coverage:

  • Type casting transpilation tests (transpiler_js_interop_tests.rs)
  • Semantic analysis for type casts (semantic_js_interop_tests.rs)
  • Working fs-example integration test

Missing Coverage:

  • No specific tests for function overloading resolution
  • Limited error case testing for dts2extern
  • No security tests for HTTP URL handling

🔒 Security Analysis

Moderate Risk Areas:

  1. HTTP fetching in dts2extern without validation
  2. String interpolation in generated code paths
  3. No input sanitization for TypeScript identifiers

Mitigation Applied:

  • Reserved keyword checking prevents code injection
  • Proper escaping in generated JavaScript

💡 Specific Recommendations

High Priority:

  1. Fix overload resolution: Implement type-aware matching in find_matching_function
  2. Secure HTTP handling: Add URL validation or restrict to localhost/known registries
  3. Add overload tests: Create comprehensive function overloading test suite

Medium Priority:

  1. Optimize lookups: Index function signatures by parameter count
  2. Validate js_name: Ensure attribute values are valid JavaScript identifiers
  3. Better error messages: More specific errors for overload resolution failures

Code Quality:

// Consider this improvement for function resolution:
fn find_matching_function(&self, name: &str, arg_types: &[Type]) -> Option<&FunctionSignature> {
    if let Some(signatures) = self.functions.get(name) {
        // First try exact type match, then fallback to count-based matching
        signatures.iter()
            .find(|(params, _, _)| self.types_match(params, arg_types))
            .or_else(|| signatures.iter().find(|(params, _, _)| params.len() == arg_types.len()))
    } else {
        None
    }
}

🎯 Overall Assessment

Verdict: APPROVE with minor improvements

This is a well-implemented feature that significantly enhances Husk's JavaScript interoperability. The core architecture is sound, the TypeScript integration is comprehensive, and the working example demonstrates real-world usage.

The identified issues are mostly edge cases and performance optimizations rather than fundamental flaws. The security concerns are manageable with the suggested improvements.

Breaking Changes: ✅ None - purely additive functionality
Documentation: ✅ Comprehensive with working examples
Test Coverage: ⚠️ Good but could be more comprehensive for overloading
Performance: ⚠️ Acceptable but could be optimized
Security: ⚠️ Minor concerns with HTTP fetching

Recommendation: Merge after addressing the function overloading resolution and HTTP security issues.


@claude
Copy link
Contributor

claude bot commented Jun 30, 2025

Claude finished @fcoury's task —— View job


Code Review: JS Interop & Function Overloading Implementation

Reviewing this comprehensive PR that implements JavaScript interoperability features, function overloading, and TypeScript integration.

Review Progress

  • Analyze core language changes (parser.rs, semantic.rs, transpiler.rs)
  • Review dts2extern converter implementation
  • Examine function overloading logic
  • Check attribute system implementation
  • Review import aliasing and transpilation
  • Analyze examples and test coverage
  • Identify potential bugs, security issues, or performance concerns
  • Assess code quality and maintainability
  • Provide final review summary

Executive Summary

This 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

  1. Excellent Architecture: Clean separation between parsing, semantic analysis, and transpilation phases
  2. Comprehensive Feature Set: Covers the full spectrum from TypeScript parsing to JavaScript generation
  3. Good Examples: The fs-example demonstrates real-world usage effectively
  4. Backward Compatibility: Maintains compatibility with existing Husk code
  5. Consistent Patterns: js_name extraction and usage follows consistent patterns throughout

⚠️ Critical Issues

1. Function Overload Resolution is Inadequate (src/semantic.rs:162-173)

Issue: Only matches by parameter count, not types:

signatures.iter().find(|(params, _, _)| params.len() == arg_count)

Problem: Could call wrong overload if multiple functions have same parameter count but different types.

Impact: Runtime errors and incorrect function calls.

2. No js_name Collision Detection (src/semantic.rs:579)

Issue: Multiple functions can map to the same JavaScript name:

self.extern_functions.insert(full_name.clone(), js_name.clone()); // No collision check

Problem: Last mapping wins silently, causing function calls to resolve incorrectly.

3. Overload Resolution Edge Cases (src/semantic.rs:117)

Issue: Arbitrary selection of first overload for type checking:

if let Some((params, return_type, _)) = signatures.first()

Problem: May miss better-matching overloads during semantic analysis.

🐛 Bugs & Issues

4. CamelCase Conversion Bug (src/dts/converter.rs:28-36)

Issue: Acronym handling is complex and may not handle edge cases:

if !prev_was_uppercase {
    result.push('_');
} else if let Some(&next_ch) = chars.peek() {
    if next_ch.is_lowercase() {
        result.push('_');
    }
}

Potential Problems:

  • XMLParserxml_parser
  • HTMLElementAPI → could become html_element_api or htmlelement_api

5. Reserved Keyword Collision (src/dts/converter.rs:105-111)

Issue: Simple suffix approach may not prevent all conflicts:

fn sanitize_param_name(name: String) -> String {
    if is_reserved_keyword(&name) {
        format!("{}_", name)  // struct → struct_
    } else {
        name
    }
}

Problem: struct_ could still conflict with user-defined struct_ parameter.

6. Debug Output in Production Code (src/dts/converter.rs:182+)

Issue: Excessive eprintln! statements throughout converter:

eprintln!("[DEBUG] Starting conversion for module: {}", module_name);

Problem: Debug output will appear in production builds, cluttering user experience.

🔍 Code Quality Issues

7. Error Handling Inconsistencies

  • Good error messages for overloads in some places, missing in others
  • No validation for malformed js_name attributes
  • Missing bounds checking for overload counts

8. Type System Gaps

  • HuskType::Any used as fallback for complex TypeScript types
  • No validation that js_name contains valid JavaScript identifiers
  • Union types, generics marked as opaque rather than attempting conversion

9. Memory Efficiency

  • Backward compatibility with_args() creates unnecessary AttributeArgument::Identifier wrappers
  • Multiple allocations in camelCase conversion that could be optimized

📋 Missing Features

  1. Type-based overload resolution - Critical for correctness
  2. Comprehensive validation - js_name format, collision detection
  3. Better TypeScript type mapping - Unions, generics partially supported
  4. Error recovery - Parser fails completely on attribute errors

🧪 Test Coverage Assessment

Good Coverage:

  • Basic transpilation tests exist
  • Working examples demonstrate integration
  • Type casting tests cover common scenarios

Missing Coverage:

  • Edge cases in overload resolution
  • js_name collision scenarios
  • Complex TypeScript type conversions
  • Error conditions and malformed attributes

Recommendations

Must Fix Before Merge:

  1. Implement proper overload resolution with type matching, not just parameter count
  2. Add js_name collision detection with clear error messages
  3. Remove debug output from dts2extern converter
  4. Add comprehensive tests for overload resolution edge cases

Should Fix:

  1. Improve error handling consistency across all modules
  2. Validate js_name format to ensure valid JavaScript identifiers
  3. Better TypeScript type mapping for unions and generics
  4. Add bounds checking and input validation

Consider for Future:

  1. Performance optimization of camelCase conversion
  2. Enhanced TypeScript support for complex types
  3. Better error recovery in attribute parsing

Security Assessment

No security issues identified. The implementation properly handles user input and doesn't introduce any obvious vulnerabilities.

Final Verdict

This PR implements an impressive and comprehensive JavaScript interop system with solid architecture. However, the function overload resolution logic has critical correctness issues that could lead to wrong function calls at runtime.

Recommendation: Request changes to fix the overload resolution and collision detection issues before merge. The implementation is otherwise excellent and these fixes should be straightforward.


Files Reviewed: 37 changed files focusing on core language changes, dts2extern converter, examples, and test coverage.

fcoury and others added 7 commits June 30, 2025 12:16
…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]>
fcoury added 2 commits June 30, 2025 14:59
- 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)
@fcoury fcoury changed the title Complete JS Interop: js_name Attributes, Function Overloading & TypeScript Integration feat: Complete function overloading, TypeScript bindings generator, and JavaScript interop enhancements Jun 30, 2025
@fcoury fcoury merged commit f69389e into master Jun 30, 2025
1 check passed
@fcoury fcoury deleted the feat/function-overloading branch June 30, 2025 18:43
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.

2 participants