Cross-language function location method based on hierarchical context-driven code editor

By constructing a source table and a hierarchical mapping rule base, combined with a file preloading context and an execution simulator, the problem of low accuracy in locating polymorphic functions in existing technologies is solved, and efficient polymorphic function location is achieved in ArkTS or TypeScript to C++ hybrid development.

CN121209838BActive Publication Date: 2026-01-30北京麟卓信息科技有限公司
View PDF 2 Cites 0 Cited by

Patent Information

Application Number
CN202511769139.7
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2025-11-28
Publication Date
2026-01-30
Estimated Expiration
2045-11-28

AI Technical Summary

Technical Problem

In existing technologies for ArkTS or TypeScript and C++ hybrid development, the accuracy of polymorphic function location is less than 75%, which cannot support the reproduction of complex scenarios. This is mainly due to the static type mapping, the single-level variable type location, and the lack of hierarchical organization of the index library, which leads to low location accuracy, insufficient coverage of complex scenarios, and low location efficiency.

Method used

Employing a hierarchical context-driven code editor, this system parses the dependency tree and abstract syntax tree of the source language project to construct a source table and hierarchical mapping rule base. Combined with file preloading context and execution simulator, it captures multi-dimensional call context, enabling accurate location of cross-language functions.

Benefits of technology

It improves the accuracy and efficiency of cross-language function location, enabling precise jumps to the definition of polymorphic functions in complex scenarios, displaying the source variable type tracing chain, and enhancing the location capabilities of the code editor.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121209838B_ABST
    Figure CN121209838B_ABST
Patent Text Reader

Abstract

This invention discloses a cross-language function location method for a code editor based on a hierarchical context-driven approach. Using an interpreted language as the source language and a compiled language as the target language, it parses the dependency tree and abstract syntax tree of the source language project to collect source variable tracing information at the module, function, and instance levels, constructing a tracing table. A hierarchical mapping rule base is built, and combined with the tracing table, a mapping relationship and confidence level between source variable types and target variable types are established. The file preloading context and intermediate instruction sequence of the source language are obtained. After incremental simulation execution, the multi-dimensional call context during cross-language calls is captured, the polymorphism parsing priority is determined, and the mapped target function is matched. Then, the source code path and line number of the target function in the target language source code are used to achieve precise jumping in the code editor. Simultaneously, the source variable type tracing chain is displayed at the target function, improving the accuracy and efficiency of locating polymorphic functions in cross-language functions.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of computer software engineering technology, specifically relating to a cross-language function location method for a code editor based on hierarchical context-driven coding. Background Technology

[0002] In ArkTS and TypeScript / C++ hybrid development projects, such as HarmonyOS applications, Electron desktop applications, and WebAssembly backend services, developers frequently need to jump from the code location where an ArkTS or TypeScript calls a C++ function to the definition of that C++ function. However, existing technical solutions have many bottlenecks, resulting in a polymorphic function location accuracy of less than 75% and an inability to support the reproduction of complex scenarios.

[0003] The existing technologies mainly suffer from the following problems: First, the type mapping from ArkTS or TypeScript to C++ is static. Existing solutions only establish a one-to-one static mapping from ArkTS or TypeScript basic types to C++ basic types, such as the mapping from number to int. They do not consider the type changes of variables during module import, function execution, and instance creation, such as variable type updates after dynamic module import and instance type constraints imposed by closure variables. This leads to a disconnect between the mapping relationship and the actual runtime type. Second, variable type positioning is at a single level. Polymorphic resolution relies solely on the declared type of the variable, such as const. The `user:User` directive ignores the type evolution of variables in scenarios such as function call chains, prototype chain modifications, and dependency injection. For example, even if `user` is assigned the value of an `AdminUser` instance, its statically declared type remains `User`, making it impossible to locate the actual runtime type. Finally, the index is not hierarchically organized. The C++ source code index only stores data in a two-dimensional structure of filenames and function names, without associating it with hierarchical context information of ArkTS or TypeScript variables, such as module dependency paths and function scopes. This makes it impossible to distinguish between polymorphic implementations of the same function name at different levels during retrieval, such as `User::getRole` and `AdminUser::getRole`.

[0004] In summary, existing technologies still suffer from problems such as low accuracy, insufficient coverage of complex scenarios, and low efficiency in locating polymorphic functions in mixed development scenarios involving statically typed, interpreted, and compiled languages. Summary of the Invention

[0005] In view of this, the present invention provides a cross-language function location method for code editors based on hierarchical context-driven methods. Based on the established dynamic mapping between interpreted language variable types and compiled language types, it realizes the accurate location of polymorphic functions in cross-language environments.

[0006] The method for locating cross-language functions in a code editor based on hierarchical context-driven logic provided by this invention specifically includes the following steps:

[0007] Interpreted languages ​​serve as the source language, and compiled languages ​​serve as the target language. Parsing the source language project yields source variable information across three layers: module, function, and instance, forming a type tracing chain. A tracing table is constructed using the first identifier of the source variable as the key and the type tracing chain as the value. A hierarchical mapping rule base is established for the source language project, including three layers of mapping rules consisting of triggering conditions, mapping logic, and priorities. This, combined with the tracing table, establishes the first mapping relationship table from source variable types to target variable types. The file preloading context of the source language project is obtained and saved as a cache fragment, and a cache update log is recorded.

[0008] The execution simulator of the source language is launched to compile the file into an intermediate instruction sequence. According to the cache update log, the modified instructions in the changed files are marked as instructions to be simulated. The instructions to be simulated are executed sequentially to obtain a simulation result cache containing the actual types of variables and the return value types of functions. When the cross-language function call instruction is executed, the context capture interrupt is triggered, the simulation execution state is recorded, the multi-dimensional call context is extracted, and the polymorphic resolution priority is established. The conflict between static and dynamic types in the multi-dimensional call context is detected, and the corresponding information is displayed in the code editor.

[0009] Based on the type tracing chain and multi-dimensional call context, the actual type of the source function is located in the order from instance layer, function layer to module layer to obtain the hierarchical location result. Then, the first target function and the first target variable group are determined according to the first mapping relationship table.

[0010] Locate the root function in the target language source code that matches the first target function, determine the source file path and line number, and use the code editor to jump to the root function.

[0011] Furthermore, the first identifier of the source variable consists of the module path, the function scope ID, and the variable name, wherein the function scope ID is the node ID in the abstract syntax tree.

[0012] Furthermore, the process of collecting traceability information at the module level includes: if the variable type is statically imported, recording the dependent module path, the import type name, and the abstract syntax tree node information corresponding to the import type; if the variable type is dynamically imported, recording the dynamic import triggering condition, the dynamic import module path, and the type assignment logic after dynamic import; if the variable type is custom within the project, recording the file path where the custom type is located and the declaration scope of the custom type.

[0013] Furthermore, the process of collecting source information at the function layer includes: identifying closure variables within the source function, recording the declaration location of the closure variables and their constraints on instance types, where the constraints on instance types include the closure variable name, instance member name, and constraint type; recording the declaration type of the source function parameters, and the parameter type modification operations within the function, including the modification location and the modified type; and recording the constraints of generic parameters for generic type parameters.

[0014] Furthermore, the process of collecting traceability information at the instance layer includes: intercepting assignment operations that modify the properties of the prototype object, recording the prototype before modification, the prototype after modification, and the modification location; if there is a prototype chain mixin operation, recording the type of the mixin object and the mixin member function; tracing the dynamic member assignment operations of the instance, recording the member name, assignment type, and assignment location; if the member is a function, recording the function type signature and the instance members that the function depends on.

[0015] Furthermore, the type tracing chain includes a context level, a type change timestamp, the changed type, the source of the change, and detailed information.

[0016] Furthermore, in the process of determining the first objective function and the first objective variable group based on the first mapping relationship table, when there are multiple candidate objective functions, the matching degree between the objective variable type of the candidate objective function and the source variable type of each layer in the tracing chain is verified according to the type tracing chain. The candidate objective function with the highest matching degree is selected as the first objective function for final mapping, and the variables related to the first objective function are recorded as the first objective variable group.

[0017] Furthermore, the file preloading context is obtained as follows: All dependent modules of the file are obtained; for each dependent module, the loading status and path alias mapping are recorded; the list of exported types and the list of exported functions are obtained according to the abstract syntax tree to form a module context; all function nodes within the file and dependent modules are traversed to obtain function parameter type annotations, return value type annotations, and scope nesting relationships; dynamic type change points are identified; and a list of closure variables is recorded to form a function context; all classes are traversed to extract constructor parameter types, record the initial structure of the prototype chain, and mark static members and instance members; instance creation nodes are traversed to record the instantiation location, associate the corresponding class ID, and predict the type change after instantiation to obtain the instance context; the file preloading context is composed of the module context, function context, and instance context.

[0018] Furthermore, the detection of conflicts between static and dynamic types in the multidimensional call context, and the display of corresponding information in the code editor, includes: using dynamic types for non-conflict scenarios, using dynamic types and issuing warnings for partially conflicting scenarios, and prioritizing dynamic types and providing quick fix options for fully conflicting scenarios; for variables with fuzzy types, obtaining the actual type through type inference backtracking, and using the default mapping type if the inference fails; saving the multidimensional call context after conflict reconciliation, and displaying the conflict reconciliation information as prompts in the code editor.

[0019] Furthermore, the step of finding the root target function in the target language source code that matches the first target function, and determining the source code file path and line number, includes: establishing a hierarchical index library for the target language source code according to the module layer, function layer, and instance layer; establishing a module layer index for basic types and global functions in the target language source code based on the file path in the module layer; establishing a function layer index for template function instances and overloaded functions in the target language source code based on the scope in the function layer; establishing an instance layer index for the implementation of virtual functions at each level in the target language source code based on the inheritance chain in the instance layer; and establishing an association between each index and the mapping relationship in the first mapping relationship table.

[0020] In the instance layer index, find the target class that matches the variable instance type of the first target variable group. Then, in the function layer index, find the target function that matches the first target function and denote it as the root target function. Finally, in the module layer index, determine the source file path and line number of the root target function.

[0021] Beneficial effects:

[0022] This invention uses an interpreted language as the source language and a compiled language as the target language. By parsing the dependency tree and abstract syntax tree of the source language project, it collects the source information of source variables at the module, function, and instance levels to construct a uniquely identified source table. A hierarchical mapping rule base from the instance and function levels to the module level is constructed, and the mapping relationship and confidence level between source variable types and target variable types are established in conjunction with the source table. The file preloading context of the source language is obtained, and the abstract syntax tree is compiled into an intermediate instruction sequence through an execution simulator. After incremental simulation execution, the multi-dimensional call context during cross-language calls is captured, type conflicts are resolved, and saved. Based on the source table and multi-dimensional call context, the actual type of the source variable is located in reverse order from the instance level to the module level, the polymorphism parsing priority is determined, and the first target function and the first target variable group of the mapping are matched. Finally, a hierarchical index library of the module, function, and instance levels is constructed for the target language source code and associated with the mapping relationship. The source code path and line number of the root target function are found through the hierarchical index, enabling precise jumping in the code editor. Simultaneously, the source variable type source chain is displayed at the target function, improving the accuracy and efficiency of locating polymorphic functions in cross-language functions. Attached Figure Description

[0023] Figure 1 This is a flowchart illustrating the cross-language function location method for a code editor based on hierarchical context-driven programming provided by the present invention. Detailed Implementation

[0024] The present invention will be described in detail below with reference to the accompanying drawings and embodiments.

[0025] The cross-language function location method for code editors based on hierarchical context-driven programming provided by this invention has the following core idea: Using interpreted languages ​​as source languages ​​and compiled languages ​​as target languages, the method parses the dependency tree and abstract syntax tree of the source language project to collect source variable tracing information at the module, function, and instance levels, constructing a uniquely identified tracing table; it then constructs a hierarchical mapping rule base from the instance and function levels to the module level, establishing a mapping relationship and confidence level between source variable types and target variable types based on the tracing table; finally, it obtains the source language's file preloading context and compiles the abstract syntax tree into an intermediate instruction sequence using a simulator. After incremental simulation execution, the multi-dimensional call context during cross-language calls is captured, type conflicts are resolved and saved. Based on the source table and multi-dimensional call context, the actual type of the source variable is located in reverse order from the instance layer to the module layer according to the priority, the polymorphism resolution priority is determined, and the first target function and the first target variable group of the mapping are matched. Finally, a hierarchical index library of module layer, function layer and instance layer is built for the target language source code and the mapping relationship is associated. The source code path and line number of the root target function are found through the hierarchical index, realizing accurate jumping in the code editor. At the same time, the source variable type source chain and the matching degree of candidate target functions are displayed at the target function.

[0026] The method for locating cross-language functions in a code editor based on hierarchical context-driven logic provided by this invention has the following process: Figure 1 As shown, the specific steps include:

[0027] Step 1: Denote the interpreted language as the source language, the functions in the source language as source functions, and the variables in the source language as source variables; denote the compiled language as the target language, the functions in the target language as target functions, and the variables in the target language as target variables.

[0028] Parse the source language project to obtain the dependency tree and abstract syntax tree. Based on the dependency tree and abstract syntax tree, obtain the information of the source variables, including the module, function and instance in which they are located. Generate a unique identifier for each source variable, which is called the first identifier. The first identifier consists of the module path, function scope ID and variable name. The function scope ID is the node ID in the abstract syntax tree.

[0029] Traverse the relevant module files of the source variable, and collect the module-level source information of the source variable based on whether the variable type is static import, dynamic import, or custom. Traverse the abstract syntax tree, collect the function-level source information of the source variable within the function node, and collect the instance-level source information of the source variable within the instance creation node and prototype modification node. Construct the type source chain of the source variable according to the order of type change, using the source information of the module layer, function layer, and instance layer. The type source chain includes the context level, type change timestamp, changed type, change source, and detailed information. Construct a source table with the first identifier of the source variable as the key and the corresponding type source chain as the value.

[0030] Furthermore, the process of collecting source variable module-level traceability information includes:

[0031] If the variable type is statically imported, record the dependent module path, the import type name, and the corresponding abstract syntax tree node information of the import type; if the variable type is dynamically imported, record the dynamic import triggering condition, the dynamic import module path, and the type assignment logic after dynamic import. The type assignment logic is obtained by traversing the abstract syntax tree node of a callback function; if the variable type is custom within the project, record the file path where the custom type is located and the declaration scope of the custom type.

[0032] Furthermore, the process of collecting source variable function-level tracing information involves traversing all function nodes in the abstract syntax tree and collecting tracing information for source variables within each source function, including:

[0033] Identify closure variables within the source function, record the declaration location of the closure variables and their constraints on instance types. The constraints on instance types include the closure variable name, instance member name, and constraint type. Record the declaration type of the source function parameters, record the parameter type modification operations within the function, including the modification location and the modified type. For generic type parameters, record the constraints of the generic parameters.

[0034] Furthermore, the process of collecting instance-level source information for source variables involves collecting instance-level source information by traversing instance creation nodes and prototype modification nodes in the abstract syntax tree, including:

[0035] Intercept all assignment operations that modify prototype object properties, record the prototype before modification, the prototype after modification, and the modification location. If prototype chain mixin operations exist, record the type of the mixin object and the mixin member functions. Track dynamic member assignment operations of instances, record the member name, assignment type, and assignment location. If the member is a function, record the function type signature and the instance members that the function depends on. The prototype object is an instance of the prototype object.

[0036] Furthermore, to facilitate subsequent read operations, the tracing table is persisted using JSON format, and incremental updates are triggered by modification events of project files. The abstract syntax tree corresponding to the modified file is regenerated, only the tracing information of variables within that file is updated, and the version number of the tracing table is recorded.

[0037] Step 2: Establish a hierarchical mapping rule library for the source language project, which includes hierarchical mapping rules for all source variables. The hierarchical mapping rules include mapping rules for each layer, such as module layer, function layer, and instance layer, consisting of triggering conditions, mapping logic, and priority. The priority of module layer, function layer, and instance layer gradually increases. Triggering conditions include the source of source variable type, type pattern, etc.

[0038] Based on the variable types of the source variables in the source table (module layer, function layer, and instance layer), the triggering conditions of the matching module layer, function layer, and instance layer are determined in the hierarchical mapping rule base. Then, based on the mapping logic and priority corresponding to the triggering conditions, a mapping relationship between the source variable type and the target variable type, as well as the mapping confidence, are established. The first mapping relationship table consists of the first identifier, source variable type, target variable type, mapping confidence, update level, and update timestamp, where the update level is the module layer, function layer, or instance layer from which the update originates.

[0039] Step 3: Parse each file in the source language project to obtain the file preloading context, and save the file preloading context as a cache fragment that can be incrementally updated; when the file is updated, regenerate the abstract syntax tree, obtain the file preloading context, update only the cache fragment corresponding to the file, and record a cache update log including the cache before the update, the cache after the update, and the modified line number range.

[0040] The file preloading context is obtained as follows: All dependent modules are retrieved; for each dependent module, its loading status and path alias mapping are recorded; its exported type list and exported function list are obtained based on the abstract syntax tree to form a module context; all function nodes within the file and its dependent modules are traversed to obtain function parameter type annotations, return value type annotations, and scope nesting relationships; dynamic type change points are identified; and a list of closure variables is recorded to form a function context; all classes are traversed to extract constructor parameter types, record the initial structure of the prototype chain, and mark static and instance members; instance creation nodes are traversed to record the instantiation location, associate the corresponding class ID, and predict type changes after instantiation to obtain the instance context; the file preloading context is composed of the module context, function context, and instance context.

[0041] The prediction method for type changes after instantiation is to determine the source variable based on relevant information in the source table, such as whether there is any modification to the prototype chain or addition of dynamic members.

[0042] Step 4: Extend the execution hook to create an execution simulator for the source language. Start the execution simulator to compile the abstract syntax tree of the files in the source language project into an intermediate instruction sequence. The intermediate instruction sequence contains instruction type, operands, and position information.

[0043] Read the intermediate instruction sequence and file preloading context; mark all instructions in unchanged files as simulated instructions according to the cache update log; mark the instructions corresponding to the modified line number range in changed files as instructions to be simulated; initialize the simulation execution state, including function scope ID, variable values ​​and types, instance and prototype object mapping relationship, and function call stack;

[0044] The instructions to be simulated are executed sequentially, and the execution results, including the actual types of variables and the return value types of functions, are saved as simulation result caches. The simulation result caches consist of instruction ID, result type, and result value. When a cross-language function call instruction is executed, a context capture interrupt is triggered, the simulation execution state at this time is recorded, and basic call information, dynamic type evolution trajectory, environment state snapshot, and call chain context are extracted to obtain the multi-dimensional call context of the source language project.

[0045] Extract the static and dynamic types of variables in the multidimensional call context, and detect whether there are conflicts, including scenarios with no conflict, partial conflict, and complete conflict. For scenarios with no conflict, use the dynamic type; for scenarios with partial conflict, use the dynamic type and issue a warning; for scenarios with complete conflict, prioritize the dynamic type and provide a quick fix option; for variables with fuzzy types, obtain the actual type through type inference backtracking, and use the default mapping type if the inference fails; save the multidimensional call context after conflict reconciliation, and display the conflict reconciliation information as a prompt in the code editor.

[0046] The basic call information includes the called function name, caller instance ID, and parameter list. The dynamic type evolution trajectory is generated based on the variable values ​​and types in the simulated execution state, combined with the type tracing chain. The dynamic type evolution trajectory includes a change timestamp, the type before the change, the type after the change, the reason for the change, and the source of the change. The environment state snapshot includes snapshots of closure variables, prototype chain state, and the actual types of generic parameters. The call chain context is obtained by arranging the function call stack order in the simulated execution state, recording the function name, scope ID, actual parameter types, and impact on the caller type of each call chain node. The impact on the caller type in the call chain nodes includes whether the caller's prototype chain or members have been modified.

[0047] Furthermore, in order to improve processing efficiency, the simulation result cache is directly reused when the same instruction is executed again in this invention, and the simulation result cache is invalidated and re-simulated when the code corresponding to the instruction is updated.

[0048] Step 5: Based on the source variable type tracing chain and multi-dimensional call context, trace back to locate the actual type of the source function in reverse order from the instance layer, function layer to the module layer. The instance layer preferentially uses the type modified from the prototype. If the type is not determined at the instance layer, the type of the closure constraint is used by the function layer. If the constraint is not traced back to the function layer, the dependent basic type is used by the module layer. The hierarchical location result of the source variable is composed of the actual type of the source variable, the type constraints at each level, and the tracing chain nodes.

[0049] Based on the hierarchical positioning results, the polymorphic parsing priority is determined by progressively decreasing priority from the instance layer, function layer to the module layer. The first mapping relationship table is used to prioritize matching the source variable type of the instance layer with the target variable type, thereby determining the target function. When there are multiple candidate target functions, the matching degree between the target variable type of the candidate target function and the source variable type of each layer in the tracing chain is verified according to the type tracing chain. The candidate target function with the highest matching degree is selected as the first target function for the final mapping, and the variables related to the first target function are recorded as the first target variable group.

[0050] This invention addresses the polymorphism rules of the target language, including virtual function tables, template instantiation, and function overloading. Based on the hierarchical location results, it determines the polymorphism parsing priority, which gradually decreases from the instance layer and function layer to the module layer. This includes:

[0051] The instance-level polymorphism resolution has the highest priority, obtaining the target language class virtual function table that matches the source variable type determined by the instance level; the function-level resolution has a lower priority, obtaining the instantiated version of the target language template class that matches the closure constraint source variable type determined by the function level; the module-level resolution has the lowest priority, obtaining the virtual functions of the target language base class that matches the dependency type determined by the module level.

[0052] Extract the generic actual type from the hierarchical positioning result, concatenate the generic parameters in the order of instance layer, function layer to module layer, and instantiate it as a template function;

[0053] Based on the type of the source variable at the instance level, function level, and module level, match the overloaded version of the target function with the same variable type.

[0054] Step 6: Establish a hierarchical index library for the target language source code according to the module layer, function layer, and instance layer. For the module layer, establish a module layer index for basic types and global functions based on file paths. For the function layer, establish a function layer index for template function instances and overloaded functions based on scope. For the instance layer, establish an instance layer index for virtual function implementations at each level based on the inheritance chain. Establish the association between each index and the mapping relationship in the first mapping table.

[0055] In the instance layer index, find the target class that matches the variable instance type of the first target variable group. Then, in the function layer index, find the target function that matches the first target function and record it as the root target function. Finally, in the module layer index, determine the source code file path and line number of the root target function.

[0056] The code editor controls the jump to the root destination function and displays the source variable type tracing chain at that function. When there are multiple candidate destination functions, it displays a list of candidate destination functions and the matching degree between the destination variable type and the source variable type at each level in the tracing chain.

[0057] Example:

[0058] This embodiment takes an integrated development environment (IDE) as an example and uses the cross-language function location method of the code editor based on hierarchical context-driven code editor provided by this invention to accurately locate C++ polymorphic functions in cross-language code constructed from ArkTS or TypeScript and C++ languages. ArkTS or TypeScript is used as the source language, and C++ is used as the target language. The specific process includes:

[0059] S1. Construct a hierarchical context-driven dynamic mapping model from ArkTS or TypeScript to C++.

[0060] This establishes a dynamic association between the type changes of ArkTS or TypeScript variables at different context levels and C++ types, overcoming the limitations of static mapping. This step relies on the ArkTS or TypeScript compiler API (such as the ArkTS or TypeScript library) and C++ parsing tools (such as Clang), and includes the following steps:

[0061] S1.1 Establish a variable type tracing table for hierarchical contexts.

[0062] S1.1.1 Obtain the complete dependency tree of the current ArkTS or TypeScript project by parsing the compilerOptions.paths and include fields of tsconfig.json and the dependencies and devDependencies fields of package.json.

[0063] S1.1.2 Generates the abstract syntax tree (AST) of the project through the API of the ArkTS or TypeScript compiler (based on LLVM), and generates a unique symbol for each variable, which can distinguish the module, function, and instance level where the variable is located.

[0064] S1.1.3 Initialize the source table structure. The source table is a globally unique JSON object, where the key is a unique identifier for the variable, and the value is an array of type source chains. The format of the unique identifier for a variable is: [module path]#[function scope ID]#[variable name], where:

[0065] Module path: Use a path relative to the project root directory, such as . / src / admin.ts;

[0066] Function scope ID: A unique identifier generated by AST traversal, in the format func_[AST node ID] (e.g., func_1024, the AST node ID can be obtained through ts.getNodeId());

[0067] Variable name: The name of the variable declaration, such as adminUser.

[0068] An example of a unique identifier is: . / src / admin.ts#func_1024#adminUser.

[0069] S1.1.4 Module-level source information collection: Traverse all module files of the ArkTS or TypeScript project and collect module-level information for each variable:

[0070] If the variable type comes from a static import (e.g., import { AdminData} from '. / base'), then record the dependent module path (e.g., . / src / base.ts), record the import type name (e.g., AdminData), and record the AST node information of the import type (e.g., node type InterfaceDeclaration, node ID 512);

[0071] If the variable type comes from a dynamic import (e.g., import('. / admin').then(m => { const data = m.AdminData})), then record the dynamic import trigger condition (e.g., process.env.NODE_ENV === 'production', obtained by analyzing the parameter expression of the import() function), record the path of the dynamically imported module (e.g., . / src / admin.ts), and record the type assignment logic after the dynamic import (e.g., the AST node corresponding to m.AdminData, obtained by traversing the AST of the then callback function).

[0072] If the variable type is a custom type within the project (such as interface User declared in the current file), then record the file path where the custom type is located (such as . / src / main.ts) and record the declaration scope of the custom type (such as global for global type, namespace Admin for namespace type).

[0073] S1.1.5, Function Layer Source Information Collection: Traverse all function nodes (FunctionDeclaration, ArrowFunction, FunctionExpression) in the AST and collect source information for the variables within each function:

[0074] Closure variable impact tracking identifies closure variables within functions (using `ts.isClosureVariable()`), such as `role` in `function createUser() { const role = 'admin'; return new User({role});}`. It records the declaration position of the closure variable (e.g., line number: 10, column number: 8 within the function), and records the constraint relationship between the closure variable and the instance type. The format is `[closure variable name] → [instance member name]: [constraint type]`, such as `role → data.role: 'admin'` (meaning the closure variable `role` constrains the `data.role` member of the `User` instance to the string literal 'admin').

[0075] Function parameter type passing tracking records the declared type of function parameters (e.g., User in function processUser(u:User) {}), tracks type modifications to parameters within the function (e.g., assignment statement u = new AdminUser()), and records the modification location (line number, column number) and the modified type (AdminUser). If the parameter is a generic type (e.g., function getValue...), it will be tracked. <t>(arg: T): T), which records the constraints of the generic parameter (e.g., T extends { id:number}).

[0076] S1.1.6. Instance-level source information collection: Traverse the instance creation node (NewExpression) and prototype modification node (AssignmentExpression, such as User.prototype = AdminUser.prototype) in the AST to collect instance-level source information:

[0077] Prototype chain modification tracking intercepts all assignment operations that modify the prototype property, recording the prototype before modification (e.g., the primitive type User of User.prototype), the prototype after modification (e.g., the type AdminUser corresponding to AdminUser.prototype), and the modification location (file path, line number); if there is a prototype chain mixin operation (e.g., Object.assign(User.prototype, AdminMixin)), it records the type of the mixin object (e.g., AdminMixin) and the mixin member function (e.g., getPerm());

[0078] Instance members are dynamically added for tracking. The dynamic member assignment operation of the instance is tracked (e.g., user.perm = ['edit']), and the member name (perm), assignment type (string[]), and assignment position (line number, column number) are recorded. If the member is a function (e.g., user.log = () => console.log()), the function type signature (() => void) and the instance members that the function depends on are recorded (e.g.).

[0079] S1.1.7. Generate a type tracing chain. For each variable, organize the tracing information of the module layer, function layer, and instance layer into a type tracing chain array in chronological order (i.e., the order in which the variable type changes). Each chain node contains the following fields:

[0080] field name type Example Explanation layer string Context hierarchy: module / function / instance timestamp number Timestamps of type changes (AST traversal order) type string The changed type name, such as AdminUser source string Sources of type changes, such as dynamicImport / closure / prototypeChange details object Detailed information, such as dependent module paths and closure constraints.

[0081] S1.1.8. Persistence and Update of the Traceability Table: The generated traceability table is stored as a .type-trace.json file in the project root directory, using JSON format for easy subsequent reading; then, listen for modification events of project files (such as the IDE's file listening API). When the file content changes: regenerate the AST corresponding to the modified file; only update the traceability information of variables within that file (incremental update) to avoid full reconstruction; record the version number of the traceability table (e.g., version: 1.0.1) for easy rollback to historical versions.

[0082] S1.1.9, Exception Handling:

[0083] If the path to the dynamically imported module for a variable does not exist (e.g., import('. / nonexist.ts')): mark source: 'invalidDynamicImport' in the source chain; trigger an IDE warning (e.g., the dynamically imported module does not exist, so a basic type mapping is temporarily used); temporarily use the variable's declared type (e.g., User). <basedata>Mapping is performed, and the mapping will be automatically updated after the module is created.

[0084] If the closure variable is modified multiple times (e.g., let role = 'user'; role = 'admin'): record all modification records in the tracing chain, sorted by timestamp; take the type after the last modification as the constraint condition (e.g., role: 'admin').

[0085] If a circular dependency exists in the prototype chain modification (e.g., User.prototype = AdminUser.prototype; AdminUser.prototype = User.prototype): when a circular dependency is detected, mark source: 'circularPrototype'; use the original type before the prototype chain modification (e.g., User) for mapping, and trigger an IDE error message.

[0086] S1.2 Implement hierarchical driven dynamic mapping updates.

[0087] S1.2.1 Initialize the hierarchical mapping rule base: The rule base is a JSON array. Each rule contains three fields: trigger condition, mapping logic, and priority. The rules are divided into three categories according to the context level.

[0088] For example, the module layer mapping rule is:

[0089] {

[0090] "layer": "module",

[0091] "trigger": {

[0092] "source": "staticImport",

[0093] "typePattern": "User<{T}>" / / ArkTS / TypeScript type pattern, {T} is the generic parameter

[0094] },

[0095] "mapping": {

[0096] "cppType": "cpp::User<{T}>" / / C++ type, {T} corresponds to the ArkTS / TypeScript generic parameter

[0097] },

[0098] "priority": 10 / / Priority, the higher the value, the higher the priority.

[0099] }

[0100] Function layer mapping rules:

[0101] {

[0102] "layer": "function",

[0103] "trigger": {

[0104] "source": "closure",

[0105] "constraintPattern": "data.role: 'admin'"

[0106] },

[0107] "mapping": {

[0108] "cppType": "cpp::User <cpp::admindata> / / Closure constraints correspond to C++ template types

[0109] },

[0110] "priority": 20

[0111] }

[0112] Instance layer mapping rules:

[0113] {

[0114] "layer": "instance",

[0115] "trigger": {

[0116] "source": "prototypeChange",

[0117] "newPrototypeType": "AdminUser"

[0118] },

[0119] "mapping": {

[0120] "cppType": "cpp::AdminUser" / / Corresponding C++ class after prototype modification

[0121] },

[0122] "priority": 30}

[0123] The rule priority setting logic is: instance layer rules (30) > function layer rules (20) > module layer rules (10), ensuring that type changes closer to runtime are matched first.

[0124] S1.2.2 Module layer mapping execution: Read the module layer source node (layer: 'module') of the variable in the source table, and traverse the module layer mapping rules to match the triggering conditions:

[0125] S1.2.2.1 If the variable type comes from a static import (source: 'staticImport'): Extract the imported ArkTS or TypeScript type (e.g., User). <admindata>); parse the corresponding header file in the C++ project (such as . / cpp / base.h), and search for the User... <admindata>Consistent C++ template classes (such as template)<typename T> (class User, and T is AdminData); establish mapping relationship: ArkTS / TypeScriptUser <admindata>→C++cpp::User <cpp::admindata>And record the confidence level of the mapping (e.g., 100%, indicating that the structures are completely consistent);

[0126] S1.2.2.2 If the variable type comes from a dynamic import (source: 'dynamicImport'): Listen for the trigger event of the dynamic import (e.g., when the IDE simulates execution to import('. / admin').then(...)); when the dynamic import is completed, extract the type of the imported module (e.g., m.AdminUser); execute the same mapping logic as the static import, establish the dynamic mapping, and update the mapping status in the source table (mappingStatus: 'completed'); if the dynamic import is not triggered (e.g., the condition is not met), temporarily store the mapping rules (mappingStatus: 'pending'), and execute them automatically when triggered.

[0127] S1.2.3, Function layer mapping execution: Read the function layer source node (layer: 'function') of the variable in the source table, then traverse the function layer mapping rules and match the triggering conditions:

[0128] S1.2.3.1 If a closure variable constraint exists (source: 'closure'): Extract the constraint conditions of the closure variable (e.g., data.role: 'admin'); parse whether there is a matching template parameter constraint in the C++ type (e.g., the role member of cpp::AdminData is the string literal "admin"); if a match exists, update the mapping relationship: ArkTS / TypeScriptUser<{role: 'admin'}> → C++cpp::User <cpp::admindata>The confidence level is maintained at 100% at the module level (if the constraints are fully matched) or reduced (if the constraints are partially matched, the confidence level is 80%). If no match is found, the module level mapping is retained, and the closure constraint is marked as 'failed' in the mapping record for easy investigation later.

[0129] S1.2.3.2 If the function parameter has a modified type (e.g., u = new AdminUser()): extract the modified type of the parameter (e.g., AdminUser); find the corresponding class in C++ (e.g., cpp::AdminUser), update the mapping relationship, and record the parameter modification triggering the mapping update (updateSource: 'paramTypeChange').

[0130] S1.2.4 Instance Layer Mapping Execution: Read the instance layer source node (layer: 'instance') of the variable in the source table; then iterate through the instance layer mapping rules and match the triggering conditions:

[0131] S1.2.4.1 If there is a prototype chain modification (source: 'prototypeChange'): Extract the modified prototype type (e.g., AdminUser); parse the corresponding class in C++ (e.g., cpp::AdminUser), and check if the class inherits from the original prototype's corresponding C++ class (e.g., cpp::User); if the inheritance relationship is valid, update the mapping relationship: ArkTS / TypeScriptUser → C++cpp::AdminUser, overriding the mapping between the module layer and the function layer, and increase the confidence to 100% (prototype modification is the most direct type evidence at runtime); if the inheritance relationship is invalid (e.g., AdminUser does not inherit from User), trigger an IDE warning (prototype modification and C++ inheritance relationship are inconsistent), and retain the function layer mapping;

[0132] S1.2.4.2 If instance members are dynamically added (e.g., user.perm = ['edit']): Extract the type of the dynamically added member (e.g., perm: string[]); check if the corresponding member exists in the C++ type (e.g., the perm member of cpp::AdminUser is std::vector). <std::string>If it exists, add the mapping details: ArkTS / TypeScriptuser.perm → C++cpp::AdminUser::perm; if it does not exist, mark the dynamic member as 'failed' in the mapping record, but this does not affect the main type mapping.

[0133] S1.2.5, Mapping Relationship Persistence and Incremental Update: The final mapping relationship is stored as a .type-mapping.json file, and each mapping record contains:

[0134] field name type Example Explanation tsVarId string ArkTS / TypeScript variable unique identifier tsType string ArkTS / TypeScript variable types cppType string Corresponding C++ type confidence number Mapping confidence (0-100) updateLayer string Last updated context level updateTime number Last updated timestamp

[0135] When the source information of a variable is updated: the mapping rules at the corresponding level are re-executed; only the mapping record of that variable is updated, without affecting other variables; a mapping update log (such as .mapping-log.json) is recorded, including the mapping before the update, the mapping after the update, and the reason for the update, to facilitate problem tracing.

[0136] S1.2.6, Exception Handling:

[0137] If the ArkTS / TypeScript type does not match the C++ type structure (e.g., ArkTS / TypeScriptUser has id: number, C++User has id: string): Calculate the structure matching degree (e.g., property name matching degree 100%, type matching degree 50%, total matching degree 75%); if the matching degree is ≥70%, establish a mapping and mark partial match (matchType: 'partial'); if the matching degree is <70%, trigger the IDE error message (ArkTS / TypeScript and C++ type structures are too different to establish a mapping) and suspend the mapping of the variable.

[0138] If a C++ template class lacks a corresponding instantiated version (e.g., ArkTS / TypeScript requires User), <admindata>C++ only instantiates User. <basedata>): Records missing template instantiation (templateInstantiation: 'missing'); calls the template instantiation interface of the C++ compiler (such as Clang) to dynamically generate User. <admindata>The instantiation code; if instantiation fails (e.g., due to type incompatibility), it falls back to the base class template (User). <basedata>) mapping.

[0139] If the same variable has multiple conflicting mappings (e.g., the instance layer maps it to AdminUser, and the function layer maps it to User), <admindata>): Select according to rule priority (instance layer has higher priority); record conflict information in the mapping log to help developers check for abnormal prototype modifications.

[0140] S2, incrementally and dynamically simulates the execution of ArkTS or TypeScript, capturing multidimensional call context.

[0141] The core objective is to obtain the dynamic context (such as actual type and parameter type) of variables when calling C++ functions by simulating the execution process of ArkTS or TypeScript, and associate it with the type tracing chain. This requires the ArkTS or TypeScript execution simulator (which can be extended based on ts-node) and the debugging API of the IDE.

[0142] S2.1 Construct a hierarchical context preloading model.

[0143] S2.1.1 Based on the ts-node register mechanism, extend the execution hook to implement the ArkTS or TypeScript execution simulator; obtain the AST of the currently edited file and the AST of dependent modules through the LLVM compiler.

[0144] S2.1.2 Module Context Preloading: Parse all dependent modules of the current file (obtained via ts.getDependencies()), generate a list of dependent modules, and for each dependent module, perform the following steps:

[0145] Read the module's AST, extract the list of exported types (e.g., export interface AdminData) and the list of exported functions (e.g., export function createAdminUser); record the module's loading status (e.g., loaded / pending / failed), statically imported modules are marked as loaded by default, and dynamically imported modules are marked as pending; store the module's path alias mapping (e.g., @ / admin corresponds to . / src / admin.ts, parsed through the paths field of tsconfig.json).

[0146] S2.1.3, Function context preloading: Traverse all function nodes in the current file and its dependent modules, generate a list of function contexts, and execute the following for each function:

[0147] Extract parameter type annotations (e.g., perm: string[]) and return value type annotations (e.g., User). <admindata>); Identify points where the type changes dynamically, i.e., where the variable type cannot be determined through static analysis, such as let x = getValue() (the return type of getValue needs to be determined at runtime), and mark it as dynamicTypePoint: true; Record the list of closure variables, and obtain the external variables referenced within the function through ts.getClosureVariables(), such as AdminData in createAdminUser; Store the scope nesting relationship of functions, such as createAdminUser nested within the then callback function, and record the parent scope ID (such as func_512);

[0148] S2.1.4 Instance context preloading: Traverse all classes and instance creation nodes (NewExpression) to generate an instance context list.

[0149] For each class, perform the following: extract the constructor parameter types (e.g., User's constructor parameter types {role:string, perm: string[]}); record the initial structure of the prototype chain, such as the initial members of User.prototype (getInfo method); mark static members and instance members, such as user.data being an instance member if it is a static member;

[0150] For each instance, create a node and perform the following: record the instantiation location (row number, column number); associate it with the corresponding class ID (e.g., class_2048, i.e., AdminUser); predict type changes after instantiation, such as whether there are prototype chain modifications or dynamic member additions;

[0151] S2.1.5 Context preloading caching and updating: Module, function, and instance contexts are stored as incrementally updatable AST fragment caches. Each cache fragment corresponds to the context information of a file. The format of the cache fragment is: [file path]#[cache version], such as . / src / admin.ts#v1.0. When the file content is modified, the AST of the file is regenerated, and only the context cache fragment corresponding to the file is updated. The caches of other files remain unchanged. A cache update log (such as .context-cache-log.json) is recorded, including the cache before the update, the cache after the update, and the range of modified line numbers.

[0152] S2.1.6 Exception handling.

[0153] If a dependent module fails to load (e.g., file not found, syntax error): mark the module status as failed; trigger an IDE warning message (dependency module failed to load, use default context); generate a default context for the module's functions and types (e.g., function parameter types default to any), which will be automatically updated after the module is fixed.

[0154] If a function has circular calls (e.g., a() calls b(), b() calls a()): mark the function's dynamicTypePoint as true; set a limit on the depth of circular calls during simulated execution (e.g., maximum depth 10) to avoid stack overflow.

[0155] If the class corresponding to the instantiated node is not defined (e.g., new UndefinedClass()): mark the instance ID as invalid; trigger the IDE error message (instantiating an undefined class) and skip the context preloading of the instance.

[0156] S2.2, Start the incremental dynamic simulation engine.

[0157] S2.2.1 Intermediate Instruction Compilation: The current file's AST is compiled into a sequence of intermediate instructions using the ArkTS or TypeScript compiler API. The format of intermediate instructions includes instruction type, operands, and position information. Supported instruction types include:

[0158] Instruction type Operand Examples illustrate VAR_DECLARE [Variable name, declared type, initial value] Variable declaration FUNCTION_CALL [Function Name, Parameter List, Caller] function call INSTANCE_NEW [Class Name, Constructor Parameters, Instance ID] Instance creation PROTOTYPE_SET [Instance ID, New Prototype ID] Prototype chain modification CROSS_CALL [Caller ID, Function Name, Parameter List] Cross-language function calls (calling C++ functions)

[0159] S2.2.2 Incremental simulation execution initialization.

[0160] Read intermediate instruction sequences and context preload cache; mark the range of simulated instructions: for unmodified files, mark all their instructions as alreadySimulated and directly reuse historical simulation results; for modified files, mark the instructions corresponding to the modified line numbers as toSimulate;

[0161] Initialize the simulated execution state object, which includes: currentScopeId, the ID of the current function scope (initially global); variableValues, the values ​​and types of variables in the current scope (initially empty); prototypeMap, the mapping between instance IDs and prototype IDs (initially a preloaded prototype chain structure); and callStack, the function call stack (initially empty).

[0162] S2.2.3 Instruction-level simulation execution: The instructions to be simulated, toSimulate, are executed sequentially, and the corresponding logic is executed for each instruction.

[0163] The VAR_DECLARE instruction: retrieves the variable name, declared type, and initial value from the operands; if the initial value is FUNCTION_CALL_RESULT, it retrieves the actual value and type from the function call result; it adds the variable to variableValues, recording the declared type and actual type (e.g., declared type User). <admindata>(Actual type: AdminUser)

[0164] The FUNCTION_CALL instruction pushes the current scope ID onto the callStack; switches currentScopeId to the scope ID of the called function; resolves the actual type of the function parameters (e.g., the actual type of ['edit'] is string[]); executes the instruction sequence inside the function to obtain the actual type of the function's return value; pops the current scope ID from the callStack and restores the scope to its state before the call.

[0165] The INSTANCE_NEW instruction: retrieves the class name and constructor parameters from the operands; generates an instance ID (e.g., instance_2048); records the initial type (class name) and constructor parameter types of the instance; and adds the instance ID to the prototypeMap, where the initial prototype ID is the prototype ID of the class.

[0166] The PROTOTYPE_SET instruction: retrieves the instance ID and the new prototype ID from the operands; updates the prototype ID of the instance in the prototypeMap; and synchronously updates the actual type of the instance in variableValues ​​(e.g., from User to AdminUser).

[0167] CROSS_CALL instruction: When this instruction is detected (indicating a call to a C++ function), a context capture interrupt is triggered, pausing the simulation execution; the current simulation execution state (variableValues, prototypeMap, callStack) is recorded for subsequent context capture.

[0168] S2.2.4 Simulation Execution Result Caching and Reuse: Store the results of executed instructions (such as the actual type of variables and the return value type of functions) as simulation result cache, in the format [instruction ID]#[result type]#[result value]; when the same instruction is executed again (e.g., the file has not been modified), the cached result is directly reused without re-execution; when the code corresponding to the instruction is modified, the cache of the instruction and subsequent instructions is invalidated, and simulation execution is performed again.

[0169] S2.2.5, Exception handling.

[0170] If an intermediate instruction fails to compile (e.g., a syntax error): mark the instruction status as compileFailed; trigger the IDE syntax error message and pause the simulation execution; after the syntax error is fixed, recompile the instruction and continue the simulation.

[0171] If a variable is undefined during simulation (e.g., console.log(undefinedVar)): mark the variable's status as undefined in variableValues; trigger an IDE warning (accessing an undefined variable); continue simulation execution, temporarily setting the variable's actual type to any.

[0172] If the C++ function corresponding to the CROSS_CALL instruction is not found (e.g., adminUser.unknownMethod()): trigger a cross-language function call not found warning; pause context capture and wait for the developer to confirm that the function name is correct.

[0173] S2.3. Capture multidimensional call context information. When the context capture interruption of the CROSS_CALL instruction is triggered and the simulation execution has been paused, perform the following steps:

[0174] Get the current simulation execution status (variableValues, prototypeMap, callStack);

[0175] Basic call information is extracted from the operands of the CROSS_CALL instruction: the called function name, such as getInfo; the caller instance ID, such as instance ID_2048 corresponding to adminUser; and the parameter list, which is an empty array if there are no parameters, and the actual type of the parameters is extracted if there are parameters (such as [string[], number]).

[0176] Dynamic type evolution trajectory extraction: Based on the caller instance ID, retrieve the instance's type change records from variableValues; then, combine the type tracing chain and generate a dynamic type evolution trajectory sorted by timestamp. The trajectory includes the following fields:

[0177] field name type Example Explanation timestamp number Type change timestamp previousType string Type before change currentType string Type after change changeReason string Reasons for type change (e.g., prototypeChange / closure) source string Source of change (e.g., the traceability chain node ID in step 1)

[0178] Environment state snapshot capture: Captures the current environment state during simulation execution, including:

[0179] A snapshot of closure variables, retrieved from the callStack, showing all closure variables in the current call chain; records the current value and actual type of the closure variable, such as role: 'admin' (type string);

[0180] A snapshot of the prototype chain state, which retrieves the prototype chain structure of the caller instance from the prototypeMap; it records a list of prototype chain nodes (from instance prototype to top-level Object.prototype).

[0181] A snapshot of the actual type of the generic parameter, if the caller type is generic (e.g., User). <admindata>Extract the actual type of the generic parameter from variableValues; record the mapping between generic parameter names and actual types;

[0182] Call chain context extraction: retrieve the current function call chain from the callStack and arrange it in the call order (from top level to the current function); and for each call chain node, record: function name and scope ID, actual parameter types when the function is called, and the function's impact on the caller type (such as whether it modifies the caller's prototype chain and members).

[0183] Context information association and persistence: basic call information, dynamic type evolution trajectory, environment state snapshot, and call chain context are merged into a multidimensional call context object; the type tracing table and dynamic mapping model are associated through the unique identifier tsVarId of the caller variable; the multidimensional call context is stored as a .call-context.json file in JSON format for easy use of polymorphic parsing.

[0184] Exception handling:

[0185] If dynamic type evolution trajectory extraction fails (e.g. instance ID not found): obtain the type of the last record from the type tracing chain; mark the trajectory status as partial, and note in the context information that part of the trajectory is missing, and use the tracing chain type;

[0186] If the variable value cannot be obtained in the closure variable snapshot (e.g., the variable is a function return value and the function has not been simulated): temporarily store the variable's declaration type and mark its value status as unavailable; continue to capture other context information and supplement it after the function is simulated and executed;

[0187] If the call chain context is not fully extracted (e.g., callStack overflow): truncate the first 10 levels of the call chain (configurable), mark truncated: true; retain the call information of the top level and the current function to ensure that the core context is not lost.

[0188] S2.4, Dynamic Type Conflict Reconciliation.

[0189] S2.4.1 Obtain the static type annotation of the variable through the compiler interface (extracted from the type annotation of the ArkTS / TypeScript code);

[0190] S2.4.2 Extraction of Static and Dynamic Types:

[0191] Extract static type annotations for variables: obtain them from variable declarations in ArkTS or TypeScript code, such as `const adminUser: User`. <admindata>The static type is User <admindata>;

[0192] Extracting the dynamic type of a variable: Obtain the type after the last change from the dynamic type evolution trajectory, such as AdminUser;

[0193] Record two types of structural information (attribute name, type, function signature) for later comparison.

[0194] S2.4.3 Type conflict detection: Compare the structural information of static and dynamic types to determine if a conflict exists.

[0195] In conflict-free scenarios, the dynamic type is a subtype of the static type or has the same structure, such as static type User and dynamic type AdminUser (AdminUser inherits from User). In partial conflict scenarios, the dynamic type and static type have some structural inconsistencies, such as static type User. <basedata>(BaseData has no perm members), dynamic type User <admindata>(AdminData has a perm member); a complete conflict scenario, where dynamic and static types have no inheritance relationship and have large structural differences, such as static type User and dynamic type Product.

[0196] S2.4.4, Type Conflict Reconciliation Strategy:

[0197] In conflict-free scenarios: the dynamic type is directly used as the basis for subsequent polymorphic resolution; no prompts are displayed in the IDE, only type consistency logs are recorded.

[0198] In some conflict scenarios: Dynamic types are used as the basis, while the compatibility part of static types is supplemented; a warning message is displayed in the IDE's issue panel, in the format: The static type [static type] of variable [variable name] is inconsistent with the dynamic type [dynamic type] part: [inconsistent field], which has been located using dynamic types; Example warning message: The static type User of variable adminUser is inconsistent with the dynamic type User part: The dynamic type has multiple perm:string[] members, which has been located using dynamic types.

[0199] In cases of complete conflict: Dynamic typing is prioritized, and an error message is displayed in the IDE in the format: "The static type [static type] of variable [variable name] completely conflicts with the dynamic type [dynamic type]. Dynamic typing has been used, but the message prompts you to check if the type annotation is correct." Quick fix options are also provided (such as updating the static type annotation to [dynamic type]) to facilitate developers correcting static types. If the dynamic type cannot be mapped to a C++ type (e.g., Product has no corresponding C++ type), it reverts to static type and marks dynamicTypeUnusable: true.

[0200] S2.4.5, Fuzzy Type Handling: If the static type of a variable is any or unknown (fuzzy type), the actual type is obtained through type inference backtracking.

[0201] If the variable is a function return value, trace the dynamic type of the function's return value (e.g., `const x = getValue()`, trace the return type of `getValue`); if the variable is a parameter, trace the parameter's passing path (e.g., `function process(x:any) { ...}`, trace the type of the actual parameter passed when calling `process`); if the variable is an instance property, trace the property's assignment type (e.g., `user.data = {role: 'admin'}`, trace the assignment type of `data`); if the inference fails (e.g., the source of the variable's assignment cannot be traced), trigger an IDE warning (Unable to infer the actual type of the `any` type variable, temporarily using basic type mapping), and use the module-level mapping type (e.g., `User`). <basedata>(This will be updated after further simulations to obtain more information.)

[0202] S2.4.6, Persistence of reconciliation results and interaction with the IDE.

[0203] The type conflict reconciliation result is stored as a .type-reconciliation.json file, which contains the variable ID, static type, dynamic type, reconciliation result, and IDE prompts. The reconciliation result is displayed in the IDE: no conflict: no prompt; partial conflict: warning prompt, displaying inconsistent fields; complete conflict: error prompt, providing quick fix options; ambiguous type: information prompt, displaying the inferred dynamic type.

[0204] S2.4.7, Exception handling.

[0205] If the static type annotation is missing (e.g., const adminUser = createAdminUser(), no type annotation): mark staticType: 'missing'; directly use dynamic type, without triggering conflict detection; display a message in the IDE (the variable is not marked with a static type, and has been located using dynamic type).

[0206] If type inference backtracking fails (e.g., the variable is 'any' and there is no assignment source): mark inferenceStatus as 'failed'; use the default mapping type (e.g., User). <basedata>); triggers an IDE warning (Unable to infer the actual type of any type variable, using default type mapping).

[0207] If the reconciliation result causes the C++ type mapping to fail (e.g., using the dynamic type Product, which has no corresponding C++ type): it will fall back to the static type mapping; an error message will be displayed in the IDE (the dynamic type has no corresponding C++ type and has fallen back to the static type mapping).

[0208] By using caching and instruction-level tracing, the problem of low efficiency in full simulation is solved, and the simulation speed of large projects is improved by more than 80%. The proposed intermediate instruction compilation mechanism converts ArkTS or TypeScript code into traceable instruction sequences, enabling refined simulation execution.

[0209] S3. C++ Polymorphic Function Analysis Based on Hierarchical Variable Type Tracing

[0210] By leveraging a dynamic mapping model and a multidimensional call context, combined with C++ polymorphism rules (virtual function tables, template instantiation, function overloading), the target C++ function is parsed.

[0211] S3.1, Hierarchical tracing to locate the actual type of variables.

[0212] Based on the variable type tracing table, the actual type of a variable is located by tracing back from the instance layer, function layer to the module layer:

[0213] Instance layer priority: Check the prototype chain state of the instance (e.g., whether adminUser.__proto__ is AdminUser.prototype). If there is a prototype modification, directly locate the instance type to the type corresponding to the prototype (e.g., AdminUser). Function layer supplement: If the instance layer has no explicit type, trace the closure constraints of the function layer (e.g., in createAdminUser, role='admin' constrains User.data.role, locating the type as User<{role: 'admin'}>). Module layer: If the function layer has no constraints, trace the dependency types of the module layer (e.g., imported BaseData, locating the type as User). <basedata>);

[0214] Output hierarchical location results: including the final actual type of the variable, the type constraints of each level, and the traceability chain nodes (e.g., the location result of adminUser: type AdminUser, constraint module . / admin.AdminData + function perm:string[]).

[0215] S3.2, Hierarchical type-driven polymorphic resolution priority.

[0216] S3.2.1 Based on the hierarchical localization results, establish a new polymorphic parsing priority (priority from high to low):

[0217] Priority 1: The instance layer locates the type (e.g., AdminUser) to the C++ class virtual function table that matches that type (e.g., getRole of cpp::AdminUser).

[0218] Priority 2: The type of the function layer closure constraint (e.g., User<{role: 'admin'}>) matches the instantiated version of the C++ template class (e.g., cpp::User). <admindata>);

[0219] Priority 3, basic types that the module layer depends on (such as User) <basedata>To match the virtual functions of the C++ base class (such as cpp::User). <basedata>::getRole).

[0220] S3.2.2 If multiple candidate functions exist during the parsing process (e.g., the subclass does not override virtual functions), then the matching degree between the candidate functions and the variable types at each level is verified through hierarchical tracing (e.g., cpp::User). <admindata>The match rate between ::getRole and the function layer perm:string[] is 90%, cpp::User <basedata>::getRole (match rate 60%), selects the function with the highest match rate.

[0221] S3.3 Layered adaptation of template functions and overloaded functions.

[0222] S3.3.1, Regarding C++ template functions (such as template)<typename T> User <t>::getRole(): Extracts the generic actual type from the hierarchical positioning result of the variable (such as AdminData in the module layer, perm:string[] in the function layer); concatenates the generic parameters (such as T=AdminData, containing perm:string[] members) in the order from the instance layer, function layer to the module layer, and instantiates the template function;

[0223] S3.3.2. For C++ function overloading (such as void func(int) / void func(string)): trace the type of variable parameters at each level (such as perm in the function level is string[], id in the module level is number); match the overloaded version that is completely consistent with the level type (such as func(string[]) instead of func(int)).

[0224] S4, Hierarchical Context-Driven C++ Function Locator and Intelligent Jump.

[0225] S4.1 Build a hierarchical context index library.

[0226] The C++ source code index is organized hierarchically by module, function, and instance: the module level index is categorized by C++ header file / source file path, storing basic types (such as BaseData) and global functions; the function level index is categorized by function scope, storing template function instances (such as User). <admindata>::getRole), overloaded functions; instance-level indexes, categorized by class inheritance chain, storing implementations of virtual functions at each level (e.g., AdminUser::getRole / User::getRole); and associating each index entry with TypeScript hierarchical tracing matching rules (e.g., AdminUser::getRole associating with the rule that the instance-level prototype is AdminUser).

[0227] S4.2, Hierarchical Precise Search and Intelligent Jump.

[0228] The retrieval process follows the order of instance-level index, function-level index, and module-level index: first, it searches for C++ classes (such as AdminUser) that match the variable instance type in the instance-level index; then, it searches for functions (such as getRole) that match the hierarchical resolution result in the function-level index of that class; finally, it locates the source code file path and line number of the function through the module-level index.

[0229] Enhanced navigation: After navigation, TypeScript variable hierarchical tracing information is displayed next to the C++ code (e.g., associating TypeScript variable adminUser: instance layer AdminUser, function layer createAdminUser to module layer . / admin); if there are multiple candidate functions, the matching degree of each function with the hierarchical type is marked in the candidate list (e.g., AdminUser::getRole(100%) / User::getRole(60%)), and the matching degree can be clicked to view the tracing basis.

[0230] This embodiment achieves accurate location of C++ polymorphic functions in ArkTS or TypeScript and C++ hybrid development scenarios through hierarchical context modeling and full-link variable type tracing. Verification through testing (based on 10 large-scale hybrid development projects, including 500+ polymorphic function call scenarios): Variable type location accuracy: In complex scenarios with multiple dependencies, closures, and prototype modifications, the accuracy rate of variable type location has increased from 75% of existing solutions to 99.8%, with a reconciliation accuracy rate exceeding 95% in completely conflicting scenarios; Polymorphic resolution coverage: Covering all scenarios of C++ virtual functions, template functions, and function overloading, the resolution coverage has increased from 85% of existing solutions to 100%, handling complex scenarios such as generic instantiation and dynamic prototype modification; Development efficiency optimization: Location time: Hierarchical indexing and incremental simulation reduce the single location time from 1.2s to 0.3s, an efficiency improvement of 75%; Verification time: Traceability information display and matching degree annotation reduce the verification time of location results from an average of 3 minutes to 10 minutes. Seconds, efficiency improved by 94%; Debugging efficiency: Type conflict hints and quick fixes reduce the time developers spend correcting type annotations by 80%.

[0231] This embodiment is based on the standard ArkTS or TypeScript compiler API and Clang toolchain, and can be extended to other compiled languages ​​that support polymorphism (such as Java and C#), as well as other mainstream IDEs (such as Visual Studio and JetBrains series IDEs).

[0232] In summary, the above are merely preferred embodiments of the present invention and are not intended to limit the scope of protection of the present invention. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the scope of protection of the present invention.< / admindata> < / t> < / basedata> < / admindata> < / basedata> < / basedata> < / admindata> < / basedata> < / basedata> < / basedata> < / admindata> < / basedata> < / admindata> < / admindata> < / admindata> < / admindata> < / admindata> < / admindata> < / basedata> < / admindata> < / basedata> < / admindata> < / std::string> < / cpp::admindata> < / cpp::admindata> < / admindata> < / admindata> < / admindata> < / cpp::admindata> < / basedata> < / t>

Claims

1. A method for cross-language function localization based on hierarchical context-driven code editor, characterized in that, Specifically comprising the following steps: The interpreter type language is the source language, the compiled language is the target language, the source language project is parsed to obtain the traceability information of the source variable in the three layers of module layer, function layer and instance layer to form a type traceability chain, a traceability table is constructed by taking the first identifier of the source variable as the key and the type traceability chain as the value; a hierarchical mapping rule library is established for the source language project, including three layers of mapping rules composed of trigger conditions, mapping logic and priority, and a first mapping relationship table of the source variable type to the target variable type is established in combination with the traceability table; a file preloading context of the source language project is obtained and saved as a cache segment, and a cache update log is recorded; An execution simulator of the source language is started to compile the file into an intermediate instruction sequence, the instructions modified in the changed file are marked as to-be-simulated instructions according to the cache update log; the to-be-simulated instructions are sequentially executed to obtain a simulation result cache containing the actual types of variables and the return value types of functions, and a context capture interruption is triggered when a cross-language function call instruction is executed, a multi-dimensional call context is recorded, and a polymorphic analysis priority is established; Conflicts between static types and dynamic types in the multi-dimensional call context are detected, and corresponding information is displayed in the code editor; According to the type traceability chain and the multi-dimensional call context, the actual types of the source functions are located in sequence from the instance layer, the function layer to the module layer to obtain hierarchical positioning results, and a first target function and a first target variable group are determined according to the first mapping relationship table; A root target function matching the first target function is searched in the source code of the target language, the source code file path and line number are determined, and the code editor is controlled to jump to the root target function.

2. The code editor cross-language function locating method of claim 1, wherein, The first identifier of the source variable is composed of a module path, a function scope ID and a variable name, wherein the function scope ID is a node ID in an abstract syntax tree.

3. The code editor cross-language function locating method of claim 1, wherein, The traceability information acquisition process of the module layer includes: if the variable type is statically imported, recording the dependent module path, the import type name and the import type corresponding abstract syntax tree node information; if the variable type is dynamically imported, recording the dynamic import trigger condition, the dynamic import module path and the type assignment logic after dynamic import; if the variable type is self-defined in the project, recording the file path where the self-defined type is located and the declaration range of the self-defined type.

4. The code editor cross-language function locating method of claim 1, wherein, The traceability information acquisition process of the function layer includes: identifying the closure variables in the source function, recording the declaration position of the closure variable and the constraint relationship to the instance type, wherein the constraint relationship to the instance type includes the closure variable name, the instance member name and the constraint type; recording the declaration type of the source function parameter, the type modification operation of the parameter in the function, including the modification position and the modified type; for the generic type parameter, recording the constraint condition of the generic parameter.

5. The code editor cross-language function locating method of claim 1, wherein, The traceability information acquisition process of the instance layer includes: intercepting the assignment operation of modifying the prototype object attribute, recording the prototype before modification, the prototype after modification and the modification position, and if there is a prototype chain mixing operation, recording the type of the mixed object and the mixed member function; tracking the dynamic member assignment operation of the instance, recording the member name, the assignment type and the assignment position, and if the member is a function, recording the function type signature and the instance member dependent in the function.

6. The code editor cross-language function locating method of claim 1, wherein, The type provenance chain includes a context level, a type change timestamp, a changed type, a change source and detailed information.

7. The code editor cross-language function locating method of claim 1, wherein, In the process of determining the first objective function and the first objective variable group according to the first mapping relationship table, when there are multiple candidate objective functions, the matching degrees of the objective variable types of the candidate objective functions and the source variable types in the provenance chain are verified according to the type provenance chain, the candidate objective function with the highest matching degree is selected as the final mapped first objective function, and the variables related to the first objective function are recorded as the first objective variable group.

8. The code editor cross-language function locating method of claim 1, wherein, The file preloading context is obtained in the following manner: all dependent modules of the file are obtained, the loading state and path alias mapping of each dependent module are recorded, the exported type list and the exported function list are obtained according to the abstract syntax tree, and the module context is formed; all function nodes in the file and the dependent modules are traversed, the parameter type annotation, the return value type annotation and the scope nesting relationship of the functions are obtained, the type dynamic change point is identified, the closure variable list is recorded to form the function context; the instance context is obtained by traversing all classes to extract the constructor parameter type, recording the prototype chain initial structure and marking the static members and the instance members, traversing the instance creation node to record the instantiation position, associating the corresponding class ID and predicting the type change after instantiation; the file preloading context is composed of the module context, the function context and the instance context.

9. The code editor cross-language function locating method of claim 1, wherein, The conflicts between the static type and the dynamic type in the multi-dimensional calling context are detected, and corresponding information is displayed in the code editor, including: for the non-conflict scenario, the dynamic type is adopted, for the partial conflict scenario, the dynamic type is adopted and a warning is prompted, and for the complete conflict scenario, the dynamic type is adopted preferentially and a quick repair option is provided; for the ambiguous type variable, the actual type is obtained through type inference backtracking, and the default mapping type is adopted if the inference fails; the multi-dimensional calling context after the conflict reconciliation is saved, and the conflict reconciliation information is displayed as prompt information in the code editor.

10. The code editor cross-language function locating method of claim 1, wherein, The root objective function matching the first objective function in the source code of the target language is found, and the source code file path and the line number are determined, including: a hierarchical index library is established for the source code of the target language according to the module layer, the function layer and the instance layer, the module layer index of the basic type and the global function is established for the source code of the target language according to the file path, the function layer index of the template function instance and the overloaded function is established for the source code of the target language according to the scope, and the instance layer index of the virtual function at each level is established for the source code of the target language according to the inheritance chain; the association between each index and the mapping relationship in the first mapping relationship table is established; The objective class matching the variable instance type of the first objective variable group is found in the instance layer index, the objective function matching the first objective function is found in the function layer index, and the objective function is recorded as the root objective function, and finally the source code file path and the line number of the root objective function are determined in the module layer index.

Citation Information

Patent Citations

  • Static compiling method and device for TypeScript

    CN117032719A

  • Static analysis method, system, chip and equipment for multi-language application

    CN117688573A