System for assisting to transplant Android language to ArkTS (Arkaus) language of swan Mongolia
By assisting the system's code input, parsing, translation, and distributed computing architecture, the system solves the language differences and complex syntax processing issues encountered when porting Android applications to the HarmonyOS platform, achieving efficient and accurate code conversion and improved stability.
Patent Information
- Application Number
- CN202510887295.7
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-06-30
- Publication Date
- 2025-10-17
- Estimated Expiration
- Not applicable · inactive patent
AI Technical Summary
There are problems in porting existing Android applications to the HarmonyOS platform, such as large differences in programming languages, difficulty for code conversion tools to handle complex syntax, low parallel processing efficiency, and system performance bottlenecks, resulting in low porting efficiency and prone to errors.
A system is provided to assist in porting the Android language to the Hongmeng ArkTS language, including a code input module, a parsing module, a translation module, and a distributed computing architecture. It achieves efficient and accurate code conversion through an improved syntax parsing algorithm, type dynamic mapping, and template filling algorithm.
It significantly improves the conversion efficiency from Android code to HarmonyOS ArkTS code, reduces the error rate, lowers development costs and technical barriers, and improves system stability and code reuse rate.
Smart Images

Figure CN120803527A_ABST
Abstract
Description
TECHNICAL FIELD
[0001] The present application relates to the technical field of computer software engineering and cross-platform development, and particularly relates to a system for assisting in porting an Android language to a Hongmeng ArkTS language. BACKGROUND
[0002] With the rapid development of the Hongmeng operating system ecosystem, it is a key requirement to enrich the Hongmeng application ecosystem and improve the user experience by migrating a large number of existing Android applications to the Hongmeng platform. However, Android applications are mainly developed based on Java and Kotlin languages, while the ArkTS language used for Hongmeng application development has significant differences in syntax rules, programming paradigms, and running mechanisms from the Android development language, which makes the porting of Android applications to the Hongmeng platform face many technical challenges, as follows.
[0003] From the perspective of programming language characteristics, Java, Kotlin, and ArkTS have obvious differences in type systems, syntax structures, and programming habits. For example, the object-oriented programming mode of Java, the functional programming features of Kotlin, and the class Web programming style of ArkTS have large differences. ArkTS has unique syntax features such as decorators and declarative UI programming, which do not exist in the Android development language. At the same time, some features in the Android development language, such as specific UI component invocation methods and system permission application logic, need to be implemented in a completely new way in the Hongmeng system. Manually converting Android code to ArkTS code not only requires developers to be proficient in both languages and their corresponding development frameworks, but also requires a lot of time and effort to refactor the code, which is extremely inefficient and prone to errors.
[0004] In terms of code analysis and translation, traditional code conversion tools mostly target a single language or simple syntax structures, and lack a deep understanding of the complex syntax and semantics of the Android development language, making it difficult to accurately handle complex syntax structures such as generics, lambda expressions, and annotations. Moreover, these tools often cannot effectively handle the differences in syntax and API usage between different versions of Android code, resulting in syntax errors, logic confusion, and other problems in the converted code, which cannot be directly run on the Hongmeng platform.
[0005] In addition, with the continuous expansion of mobile application scale, large-scale Android projects contain a huge amount of code and complex module dependency relationships. Existing porting solutions cannot efficiently implement parallel processing and resource scheduling, and when processing large-scale code porting tasks, system performance bottlenecks are easily encountered, resulting in slow porting processes or even crashes, which cannot meet the urgent need to quickly migrate a large number of Android applications to the Hongmeng platform.
[0006] Therefore, a system for assisting in transplanting an Android language to a Harmony ArkTS language is proposed to solve the above problems. SUMMARY
[0007] The present application aims to provide a system for assisting in transplanting an Android language to a Harmony ArkTS language to solve the problems raised in the background art.
[0008] To achieve the above-mentioned purpose, the present application provides the following technical solutions:
[0009] A system for assisting in transplanting an Android language to a Harmony ArkTS language, comprising:
[0010] A code input module for obtaining Android source code, supporting Java and Kotlin dual-language input;
[0011] A parsing module connected to the code input module, executing an improved syntax parsing algorithm;
[0012] A translation module connected to the parsing module, constructing an abstract syntax tree (AST) based on the parsing results and generating an attribute description array;
[0013] A generation module connected to the translation module, generating ArkTS interface code according to the attribute description array;
[0014] A distributed computing architecture including a task scheduler, a syntax model server, and a result aggregator, used for parallel computing and resource management.
[0015] As a preferred solution, the parsing module executing the improved syntax parsing algorithm includes the following operations:
[0016] Computing the syntax tree generation probability: weighting and fusing the probability model output and the rule model output;
[0017] Probability model output: calculating the product of the generation probabilities of all syntax units in the corresponding context environment;
[0018] Rule model output: calculating the average value of the matching weights of all activated custom syntax rules;
[0019] Setting the fusion coefficient λ between 0.6 and 0.8 to balance the contribution of the two models;
[0020] Wherein, the probability model is implemented through an LSTM neural network, and the rule model calculates the matching degree based on the edit distance and keyword weight.
[0021] As a preferred solution, the rule matching weight calculation includes:
[0022] The edit distance similarity and the keyword weight matching degree are combined by using weighted summation method;
[0023] The edit distance similarity reflects the character-level similarity between the code snippet and the syntax rule;
[0024] The keyword weight matching degree reflects the statistical significance of the key term in the code;
[0025] The edit distance weight α is set to be not less than 0.7, ensuring that the structural similarity dominates the rule matching.
[0026] As a preferred solution, the translation module performs type dynamic mapping:
[0027] A three-layer type processing logic is established:
[0028] The preset mapping rule is directly applied to the native type;
[0029] The unique identifier is generated by triggering recursive analysis for the custom type;
[0030] The type parameter expansion operation is performed on the generic type;
[0031] The native type mapping includes: int of Java / Kotlin→number of ArkTS, String→string, boolean→boolean;
[0032] The custom type processing preserves the class inheritance relationship and dependency chain.
[0033] As a preferred solution, the generic type processing includes:
[0034] The type parameter set in the generic container is parsed;
[0035] The type mapping operation is recursively performed on each type parameter;
[0036] The expanded type parameter sequence is generated;
[0037] The nested hierarchical relationship of the generic structure is maintained.
[0038] As a preferred solution, the generation module performs template filling:
[0039] The attribute description array is split into subsets according to the data pattern;
[0040] The optimal code template is matched for each data subset;
[0041] The code snippet is generated by performing template instantiation;
[0042] All fragments are aggregated to form a complete interface definition.
[0043] As a preferred solution, the selection of templates includes:
[0044] Calculate the structural similarity score of candidate templates;
[0045] Calculate the type compatibility score of candidate templates;
[0046] Weighted sum of the two scores, select the template with the highest total score;
[0047] Set the structural similarity weight γ between 0.5 and 0.7 to balance the contributions of the two indicators.
[0048] As a preferred solution, it also includes a post-processing optimization module for:
[0049] Perform format correction: adjust indentation, line breaks, and other code format specifications;
[0050] Perform naming correction: unify identifier naming style according to the naming specifications of Hongmeng;
[0051] Perform dependency package correction: automatically add missing import declarations;
[0052] Superimpose the above optimization on the basis of the initial generated code.
[0053] As a preferred solution, the distributed computing architecture includes:
[0054] Task scheduler: select the computing node with the smallest product of load factor and response time;
[0055] Syntax model server: dynamically update model parameters according to parsing accuracy and error rate;
[0056] Result aggregator: solve result conflicts through consistency check and voting mechanism;
[0057] Support multi-node parallel processing of large-scale code library.
[0058] As a preferred solution, the attribute description array is stored in JSON-LD format, including:
[0059] Class name unique identifier and its namespace;
[0060] Field type mapping path and version mark;
[0061] Generic expansion state identifier and type parameter chain;
[0062] Hash digest value of method signature;
[0063] Source code location metadata.
[0064] From the above technical solutions provided by the present application, the system for assisting in transplanting the Android language to the Hongmeng ArkTS language has the beneficial effects that:
[0065] Efficient code transplantation capability: the system supports dual-language input of Java and Kotlin, the code input module can quickly obtain Android source code, and through efficient processing of the parsing module, the translation module and the generation module, the Android code is automatically converted into Hongmeng ArkTS interface code; the distributed computing architecture adopts a load balancing algorithm and a parallel processing mechanism, which greatly improves the processing speed, can shorten the transplantation time of a large project from several weeks to several days in the traditional method, significantly improves the development efficiency, and speeds up the development process of Hongmeng applications;
[0066] Precise code conversion quality: the parsing module executes an improved syntax parsing algorithm, combines the syntax unit generation probability calculated by the LSTM neural network and the custom rule matching weight, accurately understands the syntax and semantics of the Android code; the translation module ensures the accuracy of type conversion through type dynamic mapping and generic processing technologies; the generation module uses template filling algorithm and intelligent template selection strategy to generate code that meets the syntax specifications of ArkTS; the post-processing optimization module further corrects the code format, adjusts the naming specification and corrects the dependency package import, ensures that the finally generated code is of high quality and has few errors, can completely retain the functions and logic of the original Android code, and reduces the manual correction workload;
[0067] Strong compatibility and adaptability: the system can process Android project code of different versions and different sizes, the code input module has code version compatibility processing capability and extensibility, the parsing module and the translation module can cope with various features and complex syntax structures of Java and Kotlin languages; the dynamic updating mechanism of the syntax model server enables it to adapt to new features of the Android language and changes in the development of Hongmeng ArkTS, ensuring long-term usability of the system and effectively reducing transplantation barriers caused by language upgrades or changes in project requirements;
[0068] Reducing development costs and technical barriers: the automated code transplantation process reduces the dependence on professional Hongmeng developers, and Android developers without ArkTS development experience can also quickly transplant existing Android applications to the Hongmeng platform, reducing personnel training costs and technical barriers; at the same time, accurate code conversion and optimization reduce the debugging and repair costs caused by transplantation errors, improve the code reuse rate, reduce the human, time and capital investment of enterprises in Hongmeng application development, and improve economic efficiency;
[0069] Good system stability and reliability: The distributed computing architecture adopts load balancing, dynamic resource scheduling and conflict resolution mechanisms to ensure the stable operation of the system under high load. The fault-tolerant design of the task scheduler and result aggregator guarantees the reliability of task execution. The self-checking and fault-tolerant module monitors the key parts of the system in real time, promptly detects and handles faults, and ensures the system's continuous and reliable operation in complex environments through fault isolation, redundant switching and data storage and forwarding functions, thereby improving the overall robustness and availability of the system. BRIEF DESCRIPTION OF THE DRAWINGS
[0070] Figure 1 This is a schematic diagram of the overall structure of a system for assisting in porting the Android language to the Hongmeng ArkTS language according to the present invention. DETAILED DESCRIPTION
[0071] In order to make the purpose, technical solutions and advantages of the present invention more clearly understood, the present invention will be further described in detail below with reference to the accompanying drawings and embodiments. It should be understood that the specific embodiments described herein are only used to explain the present invention and are not intended to limit the present invention.
[0072] In order to better understand the above technical solution, the above technical solution will be described in detail below with reference to the accompanying drawings and specific implementation methods.
[0073] like Figure 1 As shown, an embodiment of the present invention provides a system for assisting in porting the Android language to the Hongmeng ArkTS language, including:
[0074] Code input module: used to obtain Android source code, supporting Java and Kotlin dual-language input;
[0075] Parsing module: connects to the code input module and executes the improved syntax parsing algorithm;
[0076] Translation module: connects to the parsing module, builds an abstract syntax tree (AST) based on the parsing results and generates an attribute description array;
[0077] Generation module: connects to the translation module and generates ArkTS interface code based on the attribute description array;
[0078] Distributed computing architecture: includes task scheduler, grammar model server and result aggregator, used to implement parallel computing and resource management.
[0079] In this embodiment, the code input module serves as the "data entry" for assisting the transplantation of the Android language into the ArkTS language system of Hongmeng. It undertakes the key task of obtaining Android source code and completing format preprocessing. Its performance and compatibility directly affect the quality of subsequent code parsing and translation. The following will comprehensively and in detail describe this module from the aspects of overall function, submodule composition, key technology principle, and workflow:
[0080] I. Overall function overview:
[0081] The code input module is mainly responsible for obtaining Android source code, supporting Java and Kotlin dual-language input, and being able to handle Android project code of different versions and scales. After obtaining the code, it performs preprocessing work such as format specification inspection and syntax preliminary verification to ensure the integrity and validity of the input code, providing an accurate and standardized data source for subsequent parsing modules. It also needs to have good extensibility to adapt to possible future additions of programming languages or code formats.
[0082] II. Submodule composition and function:
[0083] (1) Multi-language code acquisition unit:
[0084] File reading and parsing: By scanning the user-specified local folder, project compressed package, or pulling Android project code from version control systems (such as Git), Java and Kotlin files are identified. File parsing technology is used to read file content, extract code text information, and store it in a format that the system can handle. Metadata information such as file path and hierarchical structure is also recorded for subsequent tracing and management.
[0085] Network code acquisition: Supports direct acquisition of Android project code from remote code repositories (such as GitHub, GitLab, etc.). Through network request interfaces, after verifying user permissions, the target code is downloaded. During the download process, network interruption, connection timeout, and other exceptions are handled to ensure complete code acquisition, such as using the breakpoint resume technology to continue downloading the unfinished part after the network is restored.
[0086] Code version compatibility processing: Establishes a version recognition mechanism for different versions of Java and Kotlin language features. When obtaining code, it automatically detects the language version used by the code. For incompatible syntax or features, it provides corresponding prompt information and performs compatibility conversion to a certain extent, allowing different versions of code to smoothly enter the subsequent processing flow.
[0087] (2) Code preprocessing unit:
[0088] Format specification check: According to the code format specifications of Java and Kotlin, the obtained code is checked, including code indentation, bracket matching, comment format, etc. For code that does not meet the specifications, automatic format correction is performed, such as uniform indentation style, supplementing missing brackets, etc. to ensure code format consistency and standardization, and improve subsequent processing efficiency;
[0089] Syntax preliminary verification: Use lightweight syntax analysis tools to perform preliminary syntax verification on the code to detect obvious syntax errors such as keyword spelling errors and statement structure errors. For syntax errors found, generate detailed error reports, mark error locations and error types, and provide corresponding modification suggestions to facilitate user code correction;
[0090] Invalid code filtering: Identify and filter out invalid parts of the code, such as unused variable declarations and redundant code snippets, to reduce unnecessary data processing and improve system performance. At the same time, preserve code comments to provide assistance in understanding code logic during subsequent translation;
[0091] (Three) Code metadata management unit:
[0092] Metadata extraction: Extract various metadata information from the obtained code, including identifier information such as class name, method name, variable name, package name, and code creation time, modification time, author information, etc. Also record the reference relationship between code files to build a code dependency graph, providing rich context information for subsequent code analysis and translation;
[0093] Metadata storage: Store the extracted metadata information in a structured manner in a database or cache for quick query and access. Use efficient data storage structures such as hash tables and tree structures to improve metadata storage and retrieval efficiency, ensuring quick access to required metadata information during subsequent processing;
[0094] Metadata update and maintenance: When the code is modified or updated, update the corresponding metadata information in a timely manner to maintain consistency between metadata and code. Also, periodically clean and optimize metadata, delete expired or useless metadata, and release system resources to improve system efficiency;
[0095] Three, key technology principles:
[0096] (I) Multi-language code recognition and analysis technology principles:
[0097] The multilingual code recognition and analysis technology is based on the theory of lexical analysis and syntax analysis. It constructs the corresponding lexical analyzer and syntax analyzer according to the lexical rules and syntax rules of Java and Kotlin languages. The lexical analyzer decomposes the code text into individual word symbols, and the syntax analyzer analyzes the word symbols according to the syntax rules to construct an abstract syntax tree (AST), thereby realizing the understanding of the code structure and semantics. By continuously optimizing the definition of lexical and syntax rules and the matching algorithm, the recognition and analysis capability of different styles and complex degree of code is improved.
[0098] (II) Code preprocessing technology principle:
[0099] The code preprocessing technology combines code formatting tools and static code analysis technology. The code formatting tool formats the code according to the pre-defined format specification. The static code analysis technology detects syntax errors and potential code problems by static scanning. Regular expressions, syntax tree traversal and other technical means are used to realize efficient checking and correction of code format and syntax, ensuring the quality and standardization of input code.
[0100] (III) Metadata management technology principle:
[0101] The metadata management technology is based on data modeling and database management theory. It abstracts and models the code metadata, defines the structure and relationship of the metadata, and uses database management system (DBMS) to store, query and update the metadata. Index technology, transaction processing and other mechanisms are used to ensure the integrity, consistency and efficient access of metadata. At the same time, combined with version control technology, the changes of metadata are recorded and managed, which is convenient for tracing the evolution process of code.
[0102] Four, the working process of the module:
[0103] (I) Initialization stage:
[0104] After the code input module is started, the lexical rules, syntax rules and code format specifications of Java and Kotlin languages are loaded, and the lexical analyzer, syntax analyzer and code formatting tool are initialized.
[0105] Establish communication connection with other modules of the system (such as analysis module, storage module, etc.), configure data transmission protocol and interface, and prepare to receive user input code acquisition instructions and related parameters.
[0106] (II) Code acquisition stage:
[0107] Receive user-specified code acquisition method and target code source information, such as local folder path, remote code repository address, etc.
[0108] According to the acquisition method, the corresponding code acquisition operation is performed; for local code, the folder is scanned to read Java and Kotlin files; for remote code, the code is downloaded from the code repository through a network request and integrity verification is performed to ensure that the acquired code is complete and accurate;
[0109] (Three) Code preprocessing phase:
[0110] The acquired code is sent to the code preprocessing unit, which first performs format specification checking and automatically formats the code that does not meet the format requirements;
[0111] Then, a preliminary syntax check is performed using a syntax analysis tool to detect syntax errors in the code, generate an error report and feed it back to the user (if the system provides a user interaction interface), and repair syntax errors that can be automatically corrected;
[0112] Finally, the invalid parts of the code are filtered out, leaving only the valid code and comment information to reduce the burden on subsequent processing;
[0113] (Four) Metadata processing phase:
[0114] Metadata extraction is performed on the preprocessed code, the code structure is analyzed, various metadata information is extracted, and a dependency graph of the code is constructed;
[0115] The extracted metadata information is stored in a designated database or cache and indexed for quick query and access;
[0116] (Five) Data output phase:
[0117] The preprocessed code and related metadata information are transmitted to the parsing module to provide accurate and standardized data input for subsequent code parsing and translation; meanwhile, data encryption and integrity verification are performed during data transmission to ensure data security and reliability;
[0118] (Six) End phase:
[0119] When a stop command is received or all code input tasks are completed, the code input module stops data acquisition and processing operations, closes communication connections with other modules, releases occupied system resources, and saves the current configuration information and running state record for quick recovery next time.
[0120] In this embodiment, the improved syntax parsing algorithm executed by the parsing module includes the following operations:
[0121] Calculate the syntax tree generation probability: weight and fuse the probability model output and the rule model output;
[0122] The probability model output: calculate the generation probability product of all syntax units in the corresponding context environment;
[0123] The rule model output: calculate the average value of the matching weight of all activated custom grammar rules;
[0124] Set the fusion coefficient λ between 0.6 and 0.8 to balance the contribution of the two models;
[0125] Wherein, the probability model is realized by LSTM neural network, and the rule model calculates the matching degree based on edit distance and keyword weight;
[0126] Further, the parsing module serves as an auxiliary "grammar understanding engine" for transplanting the Android language into the ArkTS language system of Hongmeng, and is responsible for converting the input Java / Kotlin code into an intermediate representation form that can be processed by the system. The parsing accuracy and efficiency directly determine the quality and accuracy of subsequent translation. The following will comprehensively explain the overall function, core algorithm, submodule design, workflow and technical advantages, etc.:
[0127] I. Overall function overview:
[0128] The parsing module based on the improved grammar parsing algorithm provides in-depth syntax analysis for the Android source code provided by the code input module, constructs an abstract syntax tree (AST) and generates an attribute description array. This module not only recognizes the standard syntax structure of Java / Kotlin, but also handles complex language features (such as generics, lambda expressions, etc.), and has good fault tolerance, which can deal with non-standard code format and common syntax errors, providing structured and standardized intermediate representation for subsequent translation modules;
[0129] II. Core algorithm details:
[0130] (1) Improved probability-rule fusion parsing algorithm:
[0131] The parsing module uses an innovative probability-rule fusion parsing algorithm:
[0132] (wherein, is the probability of generating the target syntax tree structure under the condition of inputting the Android source code fragment ; is the output target syntax tree structure, representing a tree structure that meets the syntax of the ArkTS language; is the input Android source code fragment; is the probability-rule fusion coefficient, with a value range of , to balance the contribution of probabilistic model and rule model in the parsing process; Context vectors computed for LSTM neural network Lower CFG unit Conditional probability, to capture the association between code contexts; CFG unit, the basic unit of CFG tree; Context vector, containing the information of the context before and after the CFG unit ; Total number of CFG units; The first custom rule Matching weight of the source code snippet ; Custom rule, a pre-set rule for matching code structure and semantics; Source code snippet; Number of activated custom rules);
[0133] This algorithm captures the statistical regularity of code through the probabilistic model, and uses the rule model to handle the deterministic constraints of language, significantly improving the parsing ability of complex syntax structures;
[0134] (2) Rule matching weight calculation:
[0135] The rule matching weight adopts a hybrid scoring mechanism:
[0136] (Where, The first custom rule Matching weight of the source code snippet ; And are weighting coefficients, satisfying and , used to adjust the importance of similarity based on edit distance and keyword weight matching degree in calculating the matching weight; Structural similarity of the rule and the code snippet , calculated based on edit distance, indicating the minimum number of single-character editing operations required to convert one string to another; Keyword weight matching degree of the rule and the code snippet , calculated based on term frequency-inverse document frequency, used to measure the importance of keywords in the code snippet; Custom rule; Source code snippet);
[0137] This hybrid mechanism takes into account both the similarity of code structure and the degree of matching of key syntax elements, effectively improving the accuracy of rule application.
[0138] III. Submodule Design and Functionality:
[0139] (I) Lexical Analyzer:
[0140] Function Description: Converts the source code character stream into a meaningful sequence of lexical units (Tokens), such as identifiers, keywords, and operators.
[0141] Technical Implementation: Based on Finite State Automata (FSA) for fast lexical scanning; supports Java / Kotlin dual-language lexical rules; implements intelligent processing of comments and white space.
[0142] Innovation: Adaptive lexical segmentation strategy can handle non-standard format code (such as missing semicolons, abnormal indentation, etc.).
[0143] (II) Syntax Analyzer:
[0144] Function Description: Converts the Token sequence into an Abstract Syntax Tree (AST) according to Java / Kotlin syntax rules.
[0145] Technical Implementation: Based on LALR(1) parser generator to build the core parsing engine; extended to support Android-specific syntax structures (such as AndroidManifest.xml references); implemented syntax error recovery mechanism (such as inserting / deleting necessary Tokens).
[0146] Optimization: Use a probability prediction model to select the most likely syntax path in advance, improving parsing efficiency.
[0147] (III) Semantic Analyzer:
[0148] Function Description: Performs semantic checks on AST, builds symbol tables, and resolves type information and reference relationships.
[0149] Technical Implementation: Constructs multi-level symbol tables (global, class, method, block level); implements type inference and generic parsing; handles inheritance relationships and polymorphism.
[0150] Feature: Dynamic type resolver can handle Kotlin's null safety type system and Java's primitive type differences.
[0151] (IV) Intermediate Representation Generator:
[0152] Function Description: Converts the AST after semantic analysis into a unified property description array (JSON-LD format).
[0153] Technology implementation: Define a standardized intermediate representation format; Implement mapping rules from AST nodes to attribute descriptions; Generate metadata structures containing complete type information;
[0154] IV. Workflow details:
[0155] (I) Initialization phase:
[0156] Load Java / Kotlin syntax rule files and pre-trained LSTM models;
[0157] Initialize symbol table manager and type system;
[0158] Establish data channels with code input module;
[0159] (II) Lexical analysis phase:
[0160] Read source code character stream;
[0161] Identify and generate Token sequence;
[0162] Handle comments and white space characters;
[0163] Record Token position information (for error positioning);
[0164] (III) Syntax analysis phase:
[0165] Build predictive analysis table;
[0166] Select the optimal parsing path based on probability models;
[0167] Recursive descent constructs AST;
[0168] Handle syntax errors (insert / delete Token to recover parsing);
[0169] (IV) Semantic analysis phase:
[0170] Traverse AST to establish symbol table;
[0171] Parse type information and reference relationships;
[0172] Perform semantic checks (such as type consistency, access permissions);
[0173] Handle complex structures such as generics and lambda expressions;
[0174] (V) Intermediate representation generation phase:
[0175] Traverse the AST after semantic analysis;
[0176] Generate attribute description arrays according to mapping rules;
[0177] Supplement metadata information (such as code location, type constraints);
[0178] Output intermediate representation in JSON-LD format;
[0179] (6) Result output stage:
[0180] Pass the attribute description array to the translation module;
[0181] Generate parsing reports (including error messages and performance indicators);
[0182] Save intermediate results for debugging and optimization;
[0183] 5. Key technological advantages:
[0184] (1) High-precision analytical capabilities:
[0185] By using a probability-rule fusion algorithm, the parsing module achieved a 98.7% grammatical structure recognition accuracy rate in the CodeNet benchmark test, significantly outperforming traditional pure rule parsers (approximately 92%).
[0186] (2) Cross-language adaptability:
[0187] The same parsing framework seamlessly supports both Java and Kotlin, and achieves unified processing of both languages by dynamically loading different lexical / grammar rule files;
[0188] (3) Self-learning optimization mechanism:
[0189] The parsing module has a built-in model update mechanism:
[0190] (in, Update operations for the grammar model; Based on accuracy and error rate Model update function; is the current translation accuracy of the model; is the current translation error rate of the model);
[0191] By continuously learning new code patterns and optimizing LSTM model parameters, we can improve our ability to analyze unknown code patterns.
[0192] (IV) Efficient memory management:
[0193] By adopting incremental parsing strategy and memory pool technology, when processing large Android projects (such as projects containing 500+ source files), memory usage is reduced by 40% compared with traditional parsers, and parsing speed is increased by 30%.
[0194] In this embodiment, the translation module performs dynamic mapping of types:
[0195] The three-layer type processing logic is established:
[0196] The preset mapping rule is directly applied to the native type;
[0197] The unique identifier is generated by triggering recursive resolution for the custom type;
[0198] The type parameter expansion operation is performed on the generic type;
[0199] The native type mapping includes: int of Java / Kotlin -> number of ArkTS, String -> string, boolean -> boolean;
[0200] The custom type processing preserves the class inheritance relationship and dependency chain;
[0201] Further, the translation module is a "language conversion hub" that assists in porting the Android language to the Harmony ArkTS language system. It is based on the abstract syntax tree (AST) and attribute description array output by the parsing module, and realizes semantic mapping and code conversion from the Android language to the Harmony ArkTS language. The accuracy and completeness of its functions directly determine the usability of the ported code. The following describes the overall function, core mechanism, submodule design, and workflow in detail:
[0202] I. Overall function overview:
[0203] The translation module receives the processing results of the parsing module, constructs an abstract syntax tree (AST) and generates an attribute description array based on the syntax and semantic differences between Android and Harmony ArkTS languages, and through techniques such as dynamic mapping of types and generic processing, converts the logic and structure of Android code into a representation form that conforms to the Harmony ArkTS language specification. Finally, it outputs intermediate data that can be used to generate ArkTS interface code, providing accurate conversion basis for the subsequent generation module;
[0204] II. Core mechanism details:
[0205] (1) Type dynamic mapping mechanism:
[0206] The translation module performs dynamic mapping of types, with the formula as follows:
[0207] (where, is the type mapping function, responsible for converting the source language type to the target language type; is the type representation in the source language (Android); It is a collection of primitive types, including basic data types such as int and boolean; It is the native type mapping rule, which is used to accurately map Android native types to the corresponding native types of ArkTS; Process rules for custom classes, and handle the conversion logic between the two languages for user-defined classes and interfaces; It is a generic expansion function that specifically processes generic types in the source language; when When it belongs to the native type set, the native type mapping rules are used for conversion; when When it is a custom type, use the custom class processing rules; when If it is a generic type, the generic expansion function is called for processing);
[0208] (2) Generic expansion function:
[0209] The generic expansion function is specifically implemented as follows:
[0210] (in, It is a generic container type, such as List, Map, etc. A collection of type parameters ; is the number of type parameters; is the first type parameters; Generic container Each type parameter in , through the type mapping function Mapped to the corresponding ArkTS type to form an expanded type set, ensuring accurate transmission and adaptation of generic type information during the conversion process);
[0211] 3. Submodule design and function:
[0212] (1) AST semantic parsing unit:
[0213] Function Description: Performs in-depth semantic analysis on the abstract syntax tree (AST) output by the parsing module, extracting semantic elements such as type information, variable declarations, method definitions, and control structures from the code, clarifying the logical relationship between each syntax node, and providing detailed semantic basis for subsequent translation;
[0214] Technical Implementation: A tree traversal algorithm is used to recursively access each node in the AST. Combined with symbol table information, the semantic attributes of the node are parsed. For example, for class nodes, information such as the class name, inheritance relationship, and implemented interfaces are extracted. For method nodes, the method name, parameter list, and return value type are parsed. Furthermore, the semantic parsing of complex grammatical structures such as lambda expressions and annotations is handled.
[0215] (ii) Language mapping rule execution unit:
[0216] Function description: According to the mapping rules between Android and ArkTS language, the source language semantic elements parsed are converted into the representation form of the target language; for different types of syntax structure and semantic elements, the corresponding mapping rules are applied for conversion;
[0217] Technical implementation: Establish a mapping rule library to store native type mapping, keyword replacement, and sentence structure conversion rules; for example, map the Button class in Android to the corresponding UI component class in ArkTS; adjust the structure of if-else conditional statements according to the syntax specifications of ArkTS; through rule matching and replacement operations, accurately convert the syntax and semantics;
[0218] (iii) Attribute description array generation unit:
[0219] Function description: The translated semantic information is sorted and generated into an attribute description array, stored in JSON-LD format; the array contains class name identifiers, field type mapping paths, generic expansion markers, method signature hash values, and code location metadata, providing structured data input for module generation;
[0220] Technical implementation: According to the translation results, build attribute description objects, fill in class, field, and method information into objects according to the predetermined format; for example, for a class, generate an object containing class name, inheritance class name, field list, method list, and other attributes; then organize multiple objects into an array and convert it to JSON-LD format to ensure data standardization and readability;
[0221] Four, workflow details:
[0222] (i) Data receiving stage:
[0223] The translation module receives the abstract syntax tree (AST) and related metadata output by the parsing module, checks the completeness and accuracy of the data; if there are problems with the data, such as incomplete AST structure or missing metadata, return error information and request retransmission;
[0224] (ii) Semantic analysis stage:
[0225] Use the AST semantic analysis unit to traverse and analyze the received AST, build a symbol table to record variables, types, and other information, and analyze the logical structure and semantic relationship of the code to lay the foundation for subsequent translation;
[0226] (iii) Language translation stage:
[0227] According to the mapping rules in the language mapping rule execution unit, the semantic elements obtained by parsing are translated one by one; for native types, directly apply For custom types, call Rule processing; when encountering a generic type, it is processed by Function expansion and mapping;
[0228] (IV) Array generation stage:
[0229] The translated result is passed to the property description array generation unit, which generates a property description array in JSON-LD format according to the predetermined format. The array is verified to ensure data consistency and accuracy, such as checking whether the field type mapping path is correct and whether the method signature hash value is calculated accurately.
[0230] (V) Result output stage:
[0231] The generated attribute description array is transferred to the generation module. At the same time, key information of the translation process, such as translation time, number of lines of code converted, special cases encountered, etc., is recorded to generate a translation log for subsequent debugging and analysis.
[0232] 5. Key technological advantages:
[0233] (1) Accurate type conversion:
[0234] The dynamic type mapping mechanism accurately handles the complex type differences between Android and Hongmeng ArkTS, including native types, custom types, and generic types, ensuring the type safety of the ported code and reducing errors caused by type mismatches.
[0235] (2) Efficient rule matching:
[0236] The language mapping rule execution unit uses an optimized rule matching algorithm to quickly locate and apply appropriate mapping rules, improving translation efficiency. Even when faced with large-scale code conversion tasks, it can complete the translation work in a short time.
[0237] (III) Standardized data output:
[0238] The JSON-LD format data output by the attribute description array generation unit has good standardization and versatility, which facilitates data interaction with the generation module. It also facilitates the expansion and maintenance of the system and reduces the difficulty of integration between different modules.
[0239] In this embodiment, the generation module performs template filling:
[0240] Split the attribute description array into subsets based on data patterns;
[0241] Match the optimal code template to each data subset;
[0242] Execute template instantiation to generate code snippets;
[0243] Aggregate all fragments to form a complete interface definition;
[0244] Furthermore, the generation module serves as a "code-forming workshop" to assist in porting the Android language to the Hongmeng ArkTS language system. Based on the attribute description array output by the translation module, it converts abstract semantic information into runnable ArkTS interface code. The quality and efficiency of the generated code directly affect the usability and development adaptation costs of the final porting results. The following is a detailed explanation of the overall function, core algorithm, sub-module composition, workflow, and other dimensions:
[0245] 1. Overview of overall functions:
[0246] The generation module takes an array of attribute descriptions as input and generates interface code that conforms to the HarmonyOS ArkTS syntax specification through a template filling algorithm and intelligent template selection strategy. This module not only ensures the syntactic correctness of the generated code, but also takes into account the consistency of code style, naming standards, and dependency import integrity. It also supports the precise conversion of complex code structures (such as polymorphism, inheritance, and generics), ultimately outputting high-quality ArkTS code that can be directly integrated into the HarmonyOS project.
[0247] 2. Detailed explanation of core algorithm:
[0248] (1) Template filling algorithm:
[0249] The generation module performs the template filling algorithm:
[0250] Generate (Generate To describe an array based on its attributes The overall function that generates ArkTS code; The attribute description array output by the translation module contains information such as class name identifier, field type mapping path, generic expansion mark, etc. is the number of templates in the template set; For the data subset The best matching code template; To use the template Filling data subsets Generate the operation function of the corresponding code snippet; the algorithm divides the attribute description array into multiple subsets, matches the optimal template to fill them, and finally merges them to generate the complete ArkTS code);
[0251] (2) Template selection strategy:
[0252] Template selection adopts a weighted scoring mechanism:
[0253] (Wherein, is the final selected optimal matching template; is a pre-defined code template set, covering class definitions, method declarations, variable initializations, and various ArkTS code structure templates; is an attribute description array Similarity score of the structure of the template , used to measure the degree of code structure matching; is an attribute description array Type compatibility score of the template , to assess the adaptability of data types and template parameters; is the weight coefficient, with a value range , used to balance the importance of structural similarity and type compatibility in template selection; this strategy ensures that the template that best fits the semantic requirements is selected for code generation through quantitative evaluation);
[0254] III. Submodule design and function:
[0255] (I) Template library management unit:
[0256] Function description: Maintain the pre-defined ArkTS code template library, support template creation, update, deletion and classification management; according to the differences between Android and ArkTS language characteristics, design templates covering classes, interfaces, methods, variables and other syntax structures, and provide template version control function to adapt to the evolution of language specifications;
[0257] Technical implementation: Organize template data in a structured storage mode (such as XML or JSON format), and index templates by version number and label; for example, classify class definition templates into normal classes, abstract classes, singleton classes, etc. to facilitate quick retrieval and matching;
[0258] (II) Code generation engine unit:
[0259] Function description: Based on template filling algorithm and selected template, convert attribute description array to ArkTS code snippet; support the generation of complex code logic (such as loop nesting, conditional judgment, exception handling), and handle generic type instantiation, method overload and other special scenarios;
[0260] Technical implementation: Fill the data in the attribute description array into the template placeholders dynamically through string replacement and parameterized template technology; for example, replace the {{ClassName}} placeholder in the template with the class name string, and parse the field type mapping path into a specific ArkTS type declaration; at the same time, use recursive algorithm to process nested structures (such as inner classes, multi-layer generics);
[0261] (Three) Code optimization and verification unit:
[0262] Function description: Perform syntax verification, format optimization and dependency check on the generated initial code; ensure that the code conforms to the ArkTS syntax specification, correct indentation, bracket matching and other format issues, automatically import missing dependency packages, and adjust the code naming specification (such as using camel case);
[0263] Technical implementation: Integrate ArkTS syntax checker for static analysis, use regular expressions and syntax tree traversal technology for format correction; by parsing the type reference in the code, matching the system dependency library, and automatically generating import statements; for example, when detecting that the code uses the Text component, automatically add "import ohos.agp.components.Text;";
[0264] Four, workflow details:
[0265] (I) Initialization phase:
[0266] Load the predefined ArkTS code template library, parse the template structure and establish an index;
[0267] Initialize the code optimization rule set, including syntax specifications, format standards and naming conventions;
[0268] Establish a data receiving channel with the translation module and configure the data parsing format;
[0269] (Two) Data receiving and parsing phase:
[0270] Receive the JSON-LD format attribute description array output by the translation module and perform integrity check;
[0271] Parse the attribute description array, extract class, field, method and other semantic information, and build internal data structures; for example, organize class name, inheritance relationship, field list and other information into a class definition object;
[0272] (Three) Template matching phase:
[0273] Iterate through the template library, calculate the structural similarity of the attribute description array and each template And type compatibility ;
[0274] Calculate scores according to the template selection formula, select the template with the highest score As the basis for generation; if there are multiple high-scoring templates, prefer more specific specialized templates (such as templates for specific design patterns);
[0275] (Four) Code generation phase:
[0276] Divide the attribute description array into subsets corresponding to template parameters , call function to fill in the template and generate initial code snippets;
[0277] Merge the generated code snippets and handle the dependencies between code snippets (such as method call order, variable scope) to form a complete ArkTS code;
[0278] (Five) Optimization and verification phase:
[0279] Use the code optimization and verification unit to perform syntax checking on the generated code and correct syntax errors (such as missing semicolons, type mismatches);
[0280] Apply format optimization rules to unify code indentation, line breaks, and bracket formats to improve code readability;
[0281] Scan the types referenced in the code and automatically import the required dependency packages to generate correct import statements;
[0282] (Six) Result output phase:
[0283] Output the optimized ArkTS code to the specified path or pass it to the subsequent post-processing module;
[0284] Generate a code generation report to record key information (such as template usage, optimization operations, time consumption statistics) during the generation process for log auditing and performance analysis;
[0285] Five, Key technology advantages:
[0286] (I) High-fidelity code generation:
[0287] Through precise template matching and data filling, the generated module achieved 97.3% code logic fidelity in open source project testing, effectively reducing the workload of manual code correction;
[0288] (II) Dynamic template adaptation:
[0289] The template library supports dynamic expansion and version updates, which can quickly adapt to new version features of ArkTS language or specific project requirements, such as customizing templates for Hongmeng distributed development scenarios;
[0290] (III) Intelligent optimization capability:
[0291] Code optimization and verification unit integrates static analysis and automatic repair technology, automatically solves more than 80% of common format and dependency problems during generation, and significantly improves code quality.
[0292] In this embodiment, the system further includes a post-processing optimization module for:
[0293] Performing format correction: adjusting indentation, line break, and other code format specifications;
[0294] Performing naming correction: unifying identifier naming style according to the Harmony naming specification;
[0295] Performing dependency package correction: automatically adding missing import declarations;
[0296] Stacking the above optimization on the basis of the initial generated code;
[0297] Further, the post-processing optimization module serves as a "quality controller" for assisting in porting the Android language to the Harmony ArkTS language system. After the generation module outputs the initial ArkTS code, it performs comprehensive optimization and correction to ensure that the final code meets the Harmony development specifications, has good readability and maintainability. The following details are described from the aspects of overall function, core algorithm, submodule design, and workflow:
[0298] I. Overall function overview:
[0299] The post-processing optimization module receives the initial ArkTS code output by the generation module and performs deep optimization through format correction, naming specification adjustment, and dependency package import correction. This module not only ensures correct code syntax but also unifies code style, clarifies structure, and meets the development standards of Harmony projects. It also solves potential problems in the code, such as missing necessary dependencies and non-standard naming, providing high-quality ArkTS code that can be directly used by developers;
[0300] II. Core algorithm and formula details:
[0301] The post-processing optimization uses a comprehensive optimization formula:
[0302] (where, is the function for optimizing the initial generated code ; is the initial ArkTS code output by the generation module; is the format correction amount, used to adjust the code format to meet the ArkTS specifications; Naming standard correction, used to correct the naming of identifiers in the code to follow the naming style of Harmony development; Dependency package import correction, used to automatically add missing necessary dependency package import statements in the code to ensure the completeness of resources required during code execution; this formula realizes the comprehensive optimization of the code by correcting the code in three key dimensions: format, naming, and dependency;
[0303] III. Submodule Design and Function:
[0304] (I) Code format optimization unit:
[0305] Function description: The initial code is standardized and formatted, including code indentation, line breaks, bracket matching, and space usage, to make the code have a unified and clear format, improve the readability and maintainability of the code;
[0306] Technical implementation: Use regular expressions and syntax tree analysis techniques to identify parts of the code that do not meet the format specifications; for example, use regular expression matching to match the indentation pattern in the code and unify inconsistent indentation to standard 4 spaces; based on syntax tree traversal, check the matching of brackets and automatically supplement missing brackets or correct redundant brackets; at the same time, adjust the format of the code comments to ensure that the comments are closely integrated with the code structure and have a consistent style;
[0307] (II) Naming standard correction unit:
[0308] Function description: Check if the naming of identifiers such as class names, method names, and variable names in the code conforms to the naming conventions of Harmony development, such as using the camel case naming convention for class names and the lower camel case naming convention for method names and variable names; automatically correct non-standard naming and record modification logs for easy developer traceability;
[0309] Technical implementation: Establish a Harmony naming standard rule library to define the naming rules and examples of various identifiers; through lexical analysis, extract the identifiers in the code and compare them with the rule library; for identifiers that do not conform to the rules, rename them according to the rules; for example, automatically correct the class name "my_class" to "MyClass"; correct the method name "getuserinfo" to "getUserInfo"; update all references to the identifier in the code during the renaming process to ensure the integrity of the code logic;
[0310] (III) Dependency package management unit:
[0311] Function description: Analyze the classes, interfaces, functions, etc. used in the code, determine the required dependency packages, and check if the relevant dependencies have been correctly imported in the code. For missing dependency packages, automatically add the corresponding import statements to ensure that the code can correctly reference external resources at runtime.
[0312] Technical implementation: Build a mapping relationship library for commonly used dependency packages in ArkTS language, record the dependency package to which each class or interface belongs. Through syntax tree analysis, identify external elements used in the code and find their corresponding dependency packages in the mapping relationship library. If an unimported dependency package is found, add an import statement at the appropriate position at the beginning of the code. For example, when the Text component is used in the code, automatically add the "import ohos.agp.components.Text;" statement. At the same time, clean up the repeatedly imported dependency packages to avoid redundant imports affecting code performance.
[0313] (Four) Code quality detection unit:
[0314] Function description: Perform quality detection on the optimized code, including checking for potential syntax errors, logical vulnerabilities, performance bottlenecks, etc. in the code. Through static code analysis, provide a code quality evaluation report to provide a reference for developers to further optimize the code.
[0315] Technical implementation: Integrate static code analysis tools, based on the syntax rules and programming best practices of ArkTS language, to perform multi-dimensional detection on the code. For example, detect unused variables, null pointer reference risks, and deep loop nesting, etc. Use code complexity analysis algorithms to evaluate the structural complexity of the code and provide optimization suggestions for code blocks with high complexity. Organize the detection results into a detailed report, marking the problem location, type, and severity, and providing corresponding solutions.
[0316] Four, workflow details:
[0317] (I) Initialization phase:
[0318] Load ArkTS code format specifications, naming conventions, and dependency package mapping relationships, etc. configuration files, initialize the rule library and tools of each optimization unit;
[0319] Establish a data receiving channel with the generation module, configure the data transmission format and verification mechanism to ensure that the received initial code is complete and accurate;
[0320] (II) Code receiving and preprocessing phase:
[0321] Receive the initial ArkTS code output by the generation module, perform integrity and syntax preliminary verification, and return error information to the generation module for correction if serious syntax errors are found.
[0322] Tokenization and syntax tree construction provide a structured data foundation for subsequent optimization operations;
[0323] (Three) Format optimization phase:
[0324] Input the code into the code format optimization unit, adjust the indentation, line breaks, parentheses, and other formats of the code according to the format specification rules;
[0325] Optimize the comment format to ensure that the comments clearly and accurately explain the code function and logic;
[0326] Generate a version of the code after format optimization, record the specific operations and location information of format adjustment;
[0327] (Four) Naming specification correction phase:
[0328] Use the naming specification correction unit to check and correct the naming of various identifiers in the code;
[0329] Traverse the code and update all references to renamed identifiers to ensure the consistency of the code logic;
[0330] Generate a version of the code after naming specification correction, output the naming modification log;
[0331] (Five) Dependency package management phase:
[0332] Analyze the code through the dependency package management unit to determine the required dependency packages;
[0333] Check the existing dependency package import statements in the code, add missing dependency package imports, and clean up duplicate imports;
[0334] Generate a version of the code after dependency package correction, record the addition and deletion of dependency packages;
[0335] (Six) Code quality detection phase:
[0336] Send the optimized code to the code quality detection unit for static code analysis and quality assessment;
[0337] Generate a code quality detection report, detailing the detected problems and optimization suggestions;
[0338] (Seven) Result output phase:
[0339] Output the final optimized code to the specified location for developers to use or further integrate into the Hongmeng project;
[0340] Organize and archive information such as code quality detection reports, format optimization records, and naming modification logs for easy access and traceability by developers.
[0341] In this embodiment, the distributed computing architecture comprises:
[0342] Task scheduler: select the computing node with the minimum product of load factor and response time;
[0343] Syntax model server: dynamically update model parameters according to parsing accuracy and error rate;
[0344] Result aggregator: solve result conflicts through consistency check and voting mechanism;
[0345] Support multi-node parallel processing of large-scale code library;
[0346] Further, the distributed computing architecture as the "power engine" of the system, through the coordinated operation of multiple components, realizes the efficient parallel execution of code processing tasks; it uses the distributed characteristics to improve the processing speed and system stability for the large amount of computing demand in the process of Android language to Hongmeng ArkTS language transplantation; the following describes in detail from the aspects of architecture composition, component functions, key algorithms and work flow, etc.:
[0347] I. Overall composition of architecture:
[0348] The distributed computing architecture of the application is composed of three core components of task scheduler, syntax model server and result aggregator, and relies on distributed storage system and communication network to form an efficient collaborative computing system; each component interacts with data through standardized interface, ensuring the scalability and compatibility of the architecture, which can flexibly cope with code transplantation tasks of different scales;
[0349] II. Detailed description of core component functions:
[0350] (I) Task scheduler:
[0351] Task receiving and parsing: receive Android code transplantation tasks from the front end of the system, disassemble the tasks, and divide them into multiple subtasks according to code size, complexity and other factors; for example, for a large Android project containing multiple modules, it is divided into independent subtasks according to modules, and each subtask corresponds to the processing of one or more code files;
[0352] Load balancing algorithm: adopt load balancing algorithm (where, represents the computing node selected to execute the task; is the current task queue length of the th computing node, reflecting the current task backlog of the node; is the average task processing time of the th computing node, reflecting the processing capacity of the node; For the The system uses a load evaluation indicator for each node to comprehensively measure the node load and select the node with the lowest load to execute the task. It also monitors the load status of computing nodes in real time, including parameters such as CPU usage, memory usage, and task queue length, and assigns subtasks to computing nodes with the lightest load and appropriate processing power, thus avoiding load imbalance between nodes and improving overall processing efficiency.
[0353] Task monitoring and management: Continuously track the execution status of each subtask, recording information such as the task's start time, execution progress, and estimated completion time. If any task execution anomalies (such as timeouts or failures) are detected, timely retry, reallocation, or alarm processing will be performed to ensure successful task completion.
[0354] (2) Syntax model server:
[0355] Syntax model storage and management: This section stores syntax models used for code parsing, including parsing models for Java and Kotlin, and conversion models adapted for the Hongmeng ArkTS language. These models are trained based on deep learning algorithms (such as LSTM neural networks) and a large number of code samples, and can accurately identify and process different grammatical structures.
[0356] Dynamic update mechanism: execute dynamic update formula (in, Indicates the grammar model update operation; The current translation accuracy of the model is obtained by analyzing the correctness of the processed code. is the current translation error rate of the model; It is a model update function based on accuracy and error rate. When the error rate exceeds the threshold or there is a large room for accuracy improvement, the model update process is triggered. Regularly analyze the accuracy and error rate of the model in actual task processing. Combined with emerging code syntax features and porting requirements, it automatically updates syntax model parameters or introduces new model structures to ensure that the model always maintains high parsing accuracy.
[0357] Model distribution and invocation: Based on the task requirements of the computing nodes, the corresponding syntax model is distributed to the nodes that perform code parsing tasks. When processing the code, the computing nodes call the syntax model to perform operations such as syntax analysis and semantic understanding to ensure the accuracy of code parsing.
[0358] (3) Result Aggregator:
[0359] Result receiving and sorting: Collect the result data output by each computing node after completing the subtask, including the parsed abstract syntax tree, the translated intermediate code segment, and the attribute description array, etc. Format the results uniformly and preliminarily sort them to ensure data consistency and standardization, facilitating subsequent processing;
[0360] Conflict resolution algorithm: Execute the conflict resolution formula (Wherein, represents the operation of merging two translation results and ; is a function for checking the consistency of two results by comparing key information such as syntax structure, variable definition, and method call to determine whether the results are consistent; is a conflict resolution mechanism based on majority voting. When there is a difference between the two results, according to the voting situation of multiple node results, the result with the highest frequency is selected as the final merged result. Because different computing nodes may produce inconsistent results due to data differences, model versions, etc. when processing tasks, the result aggregator resolves the conflict through consistency checking and voting mechanism to ensure the uniqueness and correctness of the final output result;
[0361] Result integration and output: Integrate the results after conflict resolution to form complete final data that can be used to generate ArkTS interface code, and pass it to the subsequent module (such as the generation module) of the system to complete the subsequent process of code migration;
[0362] III. Key technical principles:
[0363] (1) Distributed collaborative processing principle:
[0364] Based on the theory of distributed systems, large-scale code migration tasks are divided into multiple subtasks and distributed to different computing nodes for parallel processing. Each node independently completes the subtask under the coordination of the task scheduler and realizes the aggregation and integration of the results through the result aggregator. Distributed storage systems are used to realize data sharing and storage, ensuring that each node can access the required code data and model resources. At the same time, high-speed communication networks are used to ensure the data transmission efficiency between nodes, realizing efficient collaborative computing;
[0365] (2) Dynamic resource scheduling principle:
[0366] The task scheduler dynamically adjusts the task allocation strategy according to the real-time load state of the computing nodes and the task characteristics; through the load balancing algorithm, the tasks are reasonably distributed to different nodes, avoiding the situation that some nodes are overloaded while some nodes are idle; at the same time, the syntax model server dynamically updates the model according to the model performance index, ensuring accurate parsing ability in different task scenarios; this dynamic resource scheduling mechanism enables the system to adapt to changes in task quantity and fluctuations in the computing environment, maintaining efficient and stable operation;
[0367] IV. Workflow:
[0368] (I) Task submission and disassembly phase:
[0369] The user submits an Android code porting task to the system, and the task scheduler receives the task and related parameters (such as code path, target Harmony version, etc.);
[0370] The task scheduler analyzes the task, disassembles it into multiple sub-tasks according to the code structure and size, and generates a unique identifier and task description for each sub-task;
[0371] (II) Task allocation phase:
[0372] The task scheduler monitors the load state of the computing nodes in real time, obtaining information such as the task queue length, average task processing time, etc. of each node;
[0373] Using a load balancing algorithm, the task scheduler selects the appropriate computing node for each sub-task, assigns the sub-task to the selected node, and notifies the node to execute the task through a message queue or RPC (Remote Procedure Call) mechanism;
[0374] (III) Task execution phase:
[0375] After receiving the task, the computing node obtains the corresponding Android code data from the distributed storage system;
[0376] Request the required syntax model from the syntax model server, and use the syntax model to parse, translate, etc. the code to generate the processing result of the sub-task;
[0377] (IV) Result return and aggregation phase:
[0378] After completing the sub-task, the computing node returns the processing result to the result aggregator;
[0379] The result aggregator receives the result, performs format unification and preliminary checking, and then processes possible result conflicts through a conflict resolution algorithm;
[0380] Integrate the results after resolving conflicts to form a complete task processing result and output it to the subsequent modules of the system;
[0381] (V) System optimization and feedback phase:
[0382] The task scheduler optimizes the allocation strategy of subsequent tasks according to the node load change and task processing time during the task execution process;
[0383] The grammar model server triggers the model updating process according to the accuracy and error rate data in the task processing result, continuously optimizes the grammar model performance, and improves the overall processing capacity of the system.
[0384] Although embodiments of the present application have been shown and described, it is to be understood that various modifications, substitutions, replacements and changes can be made to these embodiments without departing from the principles and spirit of the present application, and the scope of the present application is defined by the appended claims and their equivalents.
Claims
1. A system for assisting in porting the Android language to the Hongmeng ArkTS language, characterized by: include: Code input module: used to obtain Android source code, supporting Java and Kotlin dual-language input; Parsing module: connected to the code input module and executes the improved syntax parsing algorithm; Translation module: connects to the parsing module, builds an abstract syntax tree (AST) based on the parsing results and generates an attribute description array; Generation module: connects to the translation module and generates ArkTS interface code according to the attribute description array; Distributed computing architecture: includes task scheduler, grammar model server and result aggregator, used to implement parallel computing and resource management.
2. The system for assisting in porting the Android language to the Hongmeng ArkTS language according to claim 1, characterized in that: The parsing module performs the improved grammar parsing algorithm including the following operations: Calculate the probability of syntax tree generation: perform weighted fusion of the probability model output and the rule model output; Probabilistic model output: Calculate the product of the generation probabilities of all grammatical units in the corresponding context; Rule model output: Calculate the average matching weight of all activated custom grammar rules; Set the fusion coefficient λ between 0.6 and 0.8 to balance the contribution of the two models; Among them, the probability model is implemented through the LSTM neural network, and the rule model calculates the matching degree based on the edit distance and keyword weight.
3. The system for assisting in porting the Android language to the Hongmeng ArkTS language according to claim 2, characterized in that: The rule matching weight calculation includes: The weighted sum method is used to combine the edit distance similarity and keyword weight matching; Edit distance similarity reflects the character-level similarity between code snippets and grammatical rules; Keyword weight matching reflects the statistical significance of key terms in the code; The edit distance weight α is set to no less than 0.7 to ensure that structural similarity dominates rule matching.
4. The system for assisting in porting the Android language to the Hongmeng ArkTS language according to claim 1, characterized in that: The translation module performs dynamic mapping of types: Establish three-layer type processing logic: Directly apply preset mapping rules to native types; Trigger recursive parsing for custom types and generate unique identifiers; Perform type parameter expansion operations on generic types; Native type mappings include: Java / Kotlin int → ArkTS number, String → string, boolean → boolean; Custom type handling preserves class inheritance and dependency chains.
5. The system for assisting in porting the Android language to the Hongmeng ArkTS language according to claim 4, characterized in that: The generic type processing includes: Resolve type parameter sets in generic containers; Recursively perform type mapping operations on each type parameter; Generates the expanded type parameter sequence; Maintain the nested hierarchy of generic structures.
6. The system for assisting in porting the Android language to the Hongmeng ArkTS language according to claim 1, characterized in that: The generation module performs template filling: Split the attribute description array into subsets based on data patterns; Match the optimal code template to each data subset; Execute template instantiation to generate code snippets; Aggregate all the fragments to form a complete interface definition.
7. The system for assisting in porting the Android language to the Hongmeng ArkTS language according to claim 6, characterized in that: The template selection includes: Calculate the structural similarity score of the candidate template; Calculate the type compatibility score of the candidate template; Take a weighted sum of the two scores and select the template with the highest total score; The structural similarity weight γ is set between 0.5 and 0.7 to balance the contribution of the two indicators.
8. The system for assisting in porting the Android language to the Hongmeng ArkTS language according to claim 1, characterized in that: Also includes post-processing optimization modules for: Perform format correction: adjust code format specifications such as indentation and line breaks; Perform naming corrections: unify the identifier naming style according to the Hongmeng naming standards; Perform dependency package correction: automatically add missing import statements; Add the above optimizations to the initial generated code.
9. The system for assisting in porting the Android language to the Hongmeng ArkTS language according to claim 1, characterized in that: The distributed computing architecture includes: Task scheduler: selects the computing node with the smallest product of load factor and response time; Syntax model server: dynamically updates model parameters based on parsing accuracy and error rate; Result aggregator: resolves result conflicts through consistency checking and voting mechanism; Supports multi-node parallel processing of large-scale code bases.
10. The system for assisting in porting Android language to Hongmeng ArkTS language according to claim 1, characterized in that: The attribute description array is stored in JSON-LD format and includes: The class name unique identifier and its namespace; Field type mapping path and version tag; Generic expansion state identification and type parameter chain; The hash digest value of the method signature; Source code location metadata.
Citation Information
Cited By
Method and device for integrating G code in IEC 61131-3 programming system
CN121166093A
Code editor cross-language function positioning method based on hierarchical context driving
CN121209838A
JS script automatic generation method and system suitable for swan mongolian NEXT simulator
CN121255156A
Automatic code generation system and method
CN121387267A