Ezno API参考详细解析所有可用函数与配置选项 【免费下载链接】eznoA JavaScript compiler and TypeScript checker written in Rust with a focus on static analysis and runtime performance项目地址: https://gitcode.com/gh_mirrors/ez/eznoEzno是一个用Rust编写的JavaScript编译器和TypeScript检查器专注于静态分析和运行时性能。作为新一代的TypeScript类型检查工具Ezno提供了强大的API接口让开发者能够深度集成类型检查和编译功能到自己的项目中。本文将详细介绍Ezno的完整API参考包括核心函数、配置选项以及多种使用方式。 核心API概览Ezno提供了多种使用方式包括命令行接口(CLI)、Rust库API和JavaScript/WebAssembly API。无论您是需要快速检查项目还是将类型检查功能集成到构建工具中Ezno都能满足您的需求。主要API模块Ezno的核心API主要分布在以下几个模块中检查器API(checker/src/lib.rs) - 提供类型检查的核心功能命令行接口(src/cli.rs) - 完整的CLI工具WebAssembly绑定(src/wasm_bindings.rs) - 用于浏览器和Node.js环境构建系统(src/build.rs) - 项目构建和编译功能 核心函数API1. 类型检查函数Ezno提供了多个层级的类型检查函数满足不同场景的需求// 项目级检查 pub fn check_projectT: ReadFromFS, P: ASTImplementation( entry_points: VecPathBuf, type_definition_files: VecPathBuf, read_from_filesystem: T, type_check_options: TypeCheckOptions, parser_requirements: P::ParserRequirements, cache: Optionmut impl FnMut(Path, [u8]), ) - CheckOutputP// 简化的检查函数 pub fn checkT: ReadFromFS( entry_points: VecPathBuf, read_from_filesystem: T, type_definition_module: OptionPath, type_check_options: TypeCheckOptions, ) - CheckOutputchecker::synthesis::EznoParser2. 构建函数Ezno还提供了项目构建功能支持代码优化和转换pub fn buildT: ReadFromFS( entry_points: VecPathBuf, read_from_filesystem: T, config: BuildConfig, ) - ResultBuildOutput, FailedBuildOutput3. JavaScript/WebAssembly API对于前端开发者Ezno提供了WASM绑定// TypeScript接口定义 interface WASMCheckOutput { readonly diagnostics: DiagnosticsContainer; get_type_at_position(path: string, pos: number): string; get_type_at_position_with_span(path: string): Module | null; get_module_ast(path: string): Module | null; } // 检查函数 export function check( entry_path: string, fs_resolver_js: (path: string) string | undefined, options: TypeCheckOptions | undefined ): WASMCheckOutput // 构建函数 export function experimental_build( entry_path: string, fs_resolve_js: (path: string) string | undefined, config: BuildConfig | undefined ): WASMBuildOutput⚙️ 配置选项详解TypeCheckOptions结构体Ezno的类型检查行为可以通过TypeCheckOptions结构体进行精细控制#[derive(Clone)] pub struct TypeCheckOptions { /// 参数不能被重新赋值 pub constant_parameters: bool, /// 允许省略参数JavaScript的默认行为 pub allow_elided_arguments: bool, /// 允许额外参数 pub allow_extra_arguments: bool, /// 函数声明是否为常量 pub constant_function_declarations: bool, /// 是否启用严格类型转换 pub strict_casts: bool, /// 调试模式显示详细类型信息 pub debug_types: bool, /// 允许类型断言as语法 pub allow_type_casts: bool, /// 存储类型映射用于LSP和后类型检查优化 pub store_type_mappings: bool, /// 启用额外语法支持 pub extra_syntax: bool, /// 解析注释 pub parse_comments: bool, /// LSP模式允许部分语法并收集编辑器信息 pub lsp_mode: bool, /// 记录所有赋值和读取用于代码检查 pub record_all_assignments_and_reads: bool, /// 在for循环中推断合理的约束 pub infer_sensible_constraints_in_for_loops: bool, /// 评估导出以检测死代码 pub evaluate_exports: bool, /// 最大内联计数 pub max_inline_count: u16, /// 测量执行时间 pub measure_time: bool, /// 启用高级数字功能范围和模类推断 pub advanced_numbers: bool, /// 在d.ts中打印内部诊断信息 pub debug_dts: bool, }默认配置Ezno提供了合理的默认配置适合大多数使用场景impl Default for TypeCheckOptions { fn default() - Self { Self { constant_parameters: false, allow_elided_arguments: false, allow_extra_arguments: false, constant_function_declarations: true, debug_types: false, parse_comments: true, strict_casts: false, store_type_mappings: false, lsp_mode: false, record_all_assignments_and_reads: false, infer_sensible_constraints_in_for_loops: true, allow_type_casts: true, evaluate_exports: false, max_inline_count: 300, measure_time: false, debug_dts: false, extra_syntax: true, advanced_numbers: false, } } }️ 命令行接口使用指南Ezno提供了完整的命令行工具支持多种操作模式基本命令结构ezno subcommand [options] input可用子命令1. 类型检查命令# 检查单个文件 ezno check src/index.ts # 使用自定义类型定义文件 ezno check src/index.ts -d types/definitions.d.ts # 启用高级数字功能 ezno check src/index.ts --advanced-numbers # 显示检查时间 ezno check src/index.ts --timings # 监视文件变化 ezno check src/index.ts --watch2. 构建命令# 构建项目 ezno experimental build src/index.ts dist/bundle.js # 启用最小化 ezno experimental build src/index.ts dist/bundle.js -m # 启用树摇优化 ezno experimental build src/index.ts dist/bundle.js --tree-shake # 生成source maps ezno experimental build src/index.ts dist/bundle.js --source-maps3. 代码格式化# 格式化文件 ezno experimental format src/index.ts # 检查格式化状态 ezno experimental format src/index.ts --check4. AST浏览器# 探索AST结构 ezno ast-explorer src/index.ts 输出数据结构CheckOutput结构类型检查的结果通过CheckOutput结构体返回pub struct CheckOutputP: ASTImplementation { /// 诊断信息集合 pub diagnostics: DiagnosticsContainer, /// 模块内容映射 pub module_contents: MapPathBuf, P::OwnedModule, /// 类型存储 pub types: TypeStore, /// 计时器如果启用 pub chronometer: OptionChronometer, /// 其他元数据 // ... }诊断信息类型Ezno提供了详细的诊断信息分类pub enum Diagnostic { /// 全局诊断无位置信息 Global { reason: String, kind: DiagnosticKind, }, /// 带位置的诊断 Position { reason: String, position: SpanWithSource, kind: DiagnosticKind, }, /// 带额外标签的诊断 PositionWithAdditionalLabels { reason: String, position: SpanWithSource, labels: Vec(String, SpanWithSource), kind: DiagnosticKind, }, } pub enum DiagnosticKind { Error, Warning, Info, } 文件系统接口Ezno通过ReadFromFStrait支持自定义文件系统解析器pub trait ReadFromFS { /// 读取文件内容返回Vecu8以支持二进制文件 fn read_file(self, path: std::path::Path) - OptionVecu8; } // 实现示例 let resolver |path: std::path::Path| { std::fs::read(path).ok() }; // 使用自定义解析器 let result check( vec![src/index.ts.into()], resolver, None, TypeCheckOptions::default() ); 高级功能API1. 类型查询APIEzno提供了丰富的类型查询功能// 获取指定位置的类型 pub fn get_type_at_position( self, path: str, position: u32, debug: bool, ) - OptionString // 获取带位置信息的类型 pub fn get_type_at_position_with_span( self, path: str, position: u32, debug: bool, ) - Option(String, SpanWithSource) // 获取模块AST pub fn get_module(self, path: str) - OptionP::OwnedModule2. 事件系统Ezno的事件系统可以追踪程序执行流// 获取模块事件 pub fn get_events(self) - [Event] // 事件类型示例 pub enum Event { /// 函数调用 FunctionCall { function: TypeId, arguments: VecTypeId, return_type: TypeId, }, /// 属性访问 PropertyAccess { object: TypeId, property: String, value_type: TypeId, }, /// 变量赋值 VariableAssignment { variable: String, value_type: TypeId, }, } 实用示例代码Rust中使用Ezno APIuse ezno_checker::{check_project, synthesis, TypeCheckOptions}; use std::{fs, path::Path}; fn main() { let resolver |path: std::path::Path| fs::read(path).ok(); let options TypeCheckOptions { debug_types: true, record_all_assignments_and_reads: true, max_inline_count: 600, ..Default::default() }; let result check_project::_, synthesis::EznoParser( vec![src/main.ts.into()], vec![checker::INTERNAL_DEFINITION_FILE_PATH.into()], resolver, options, (), None, ); // 处理诊断信息 for diagnostic in result.diagnostics { match diagnostic { ezno_checker::Diagnostic::Global { reason, kind } { println!({:?}: {}, kind, reason); } ezno_checker::Diagnostic::Position { reason, position, kind } { println!({:?} at {:?}: {}, kind, position, reason); } _ {} } } }JavaScript中使用WASM APIimport { check } from ezno-wasm; // 文件系统解析器 const fsResolver (path) { // 从文件系统或网络读取文件 return fetch(path).then(res res.text()); }; // 配置选项 const options { debug_types: false, allow_type_casts: true, advanced_numbers: false }; // 执行类型检查 const result check(src/index.ts, fsResolver, options); // 处理结果 if (result.diagnostics.length 0) { result.diagnostics.forEach(diagnostic { console.log(${diagnostic.kind}: ${diagnostic.reason}); }); } else { console.log(No type errors found! ); } // 查询特定位置的类型 const typeInfo result.get_type_at_position(src/index.ts, 123); console.log(Type at position 123:, typeInfo); 性能优化配置1. 缓存配置Ezno支持类型定义缓存以提高性能let cache_path Path::new(.ezno-cache); let mut cache |path: Path, data: [u8]| { if let Ok(mut file) fs::File::create(cache_path.join(path)) { let _ file.write_all(data); } }; let result check_project( entry_points, type_definition_files, resolver, options, (), Some(mut cache), );2. 内存优化通过调整内联限制控制内存使用let options TypeCheckOptions { max_inline_count: 100, // 降低内联限制以减少内存使用 ..Default::default() };3. 并行处理Ezno支持并行处理大型项目use rayon::prelude::*; let files vec![src/a.ts, src/b.ts, src/c.ts]; let results: Vec_ files.par_iter().map(|file| { check_project( vec![file.into()], definitions.clone(), resolver, options.clone(), (), None, ) }).collect(); 调试和诊断启用调试信息let options TypeCheckOptions { debug_types: true, // 显示详细类型信息 debug_dts: true, // 在d.ts中打印诊断信息 measure_time: true, // 测量执行时间 ..Default::default() };获取类型信息// 获取所有用户定义的类型 for (type_id, type_info) in result.types.user_types() { println!(Type ID: {:?}, Info: {:?}, type_id, type_info); } // 获取被调用的函数 println!(Called functions: {:?}, result.types.called_functions); // 获取模块事件 let (_, module) result.modules.into_iter().next().unwrap(); for event in module.info.get_events() { println!(Event: {:?}, event); } 最佳实践建议1. 渐进式采用// 从宽松配置开始 let options TypeCheckOptions { allow_elided_arguments: true, allow_extra_arguments: true, strict_casts: false, ..Default::default() }; // 逐步收紧检查 let strict_options TypeCheckOptions { constant_parameters: true, constant_function_declarations: true, strict_casts: true, ..options // 保留其他配置 };2. 集成到构建流程// 在CI/CD中集成Ezno检查 fn run_type_check() - Result(), VecDiagnostic { let result check_project(...); if result.diagnostics.contains_error() { let errors: Vec_ result.diagnostics .into_iter() .filter(|d| matches!(d.kind(), DiagnosticKind::Error)) .collect(); if !errors.is_empty() { return Err(errors); } } Ok(()) }3. 自定义错误处理fn format_diagnostics(diagnostics: [Diagnostic]) - String { diagnostics.iter().map(|d| match d { Diagnostic::Global { reason, kind } { format!({}: {}, kind, reason) } Diagnostic::Position { reason, position, kind } { format!({} at {}:{}: {}, kind, position.start, position.end, reason) } Diagnostic::PositionWithAdditionalLabels { reason, position, labels, kind } { let mut output format!({} at {}:{}: {}, kind, position.start, position.end, reason); for (label_reason, label_position) in labels { output.push_str(format!(\n {} at {}:{}, label_reason, label_position.start, label_position.end)); } output } }).collect::Vec_().join(\n) } 总结Ezno提供了丰富而灵活的API接口从简单的命令行检查到复杂的集成场景都能完美支持。通过合理的配置选项您可以精确控制类型检查的行为平衡严格性和灵活性。无论您是构建新的JavaScript/TypeScript项目还是将Ezno集成到现有工具链中这些API都将为您提供强大的类型安全保证。记住Ezno仍在积极开发中建议定期查看官方文档获取最新API更新和最佳实践。开始使用Ezno享受快速、准确的TypeScript类型检查体验【免费下载链接】eznoA JavaScript compiler and TypeScript checker written in Rust with a focus on static analysis and runtime performance项目地址: https://gitcode.com/gh_mirrors/ez/ezno创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考