Code optimization method, system, and electronic device

By iteratively optimizing the initial code, the insufficient automated iterative optimization capability of the code generation model was solved, thus achieving efficient and reliable code optimization results.

CN122173095APending Publication Date: 2026-06-09ZHIYUAN STAR (SHANGHAI) INTELLIGENT TECHNOLOGY CO LTD

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
ZHIYUAN STAR (SHANGHAI) INTELLIGENT TECHNOLOGY CO LTD
Filing Date
2026-03-05
Publication Date
2026-06-09

AI Technical Summary

Technical Problem

Existing code generation models lack automated iterative optimization capabilities, which affects the stability and reliability of the generated results.

Method used

The initial code is iteratively optimized, including quality assessment, issue list updates, and iteration context management. Optimization is performed using an optimization rule base until the iteration termination condition is met, at which point the optimal code version is output.

Benefits of technology

It enables automatic and continuous optimization of the code generation process, improving optimization efficiency and success rate, and enhancing the reliability and quality of the final output.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122173095A_ABST
    Figure CN122173095A_ABST
Patent Text Reader

Abstract

The application relates to a code optimization method, system and electronic equipment, the method comprising: obtaining initial code generated based on a natural language description; performing at least one round of iterative optimization on the initial code, a current round of iteration process comprising: performing quality evaluation on current code to obtain a code quality score and a problem list of the current round; updating an iteration context based on the code quality score and the problem list of the current round and judging whether an iteration termination condition is met, the iteration context being used for recording a set of invalid optimization rules that have failed to be executed or have caused rollback in previous iterations; when the iteration termination condition is met, outputting an optimal code version from historical code versions; when the iteration termination condition is not met, performing optimization processing on the current code based on the problem list, an optimization rule library and the updated iteration context to obtain optimized code for use in the next round of iterative optimization. The application realizes iterative optimization on the initial generated code.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of computer technology, and in particular to a code optimization method, system, and electronic device. Background Technology

[0002] With the rapid development of artificial intelligence technology, code generation models can now generate corresponding code based on user intent descriptions. For example, the A2UI (Agent-to-User Interface) protocol, a technology related to natural language layout generation, allows developers or AI (Artificial Intelligence) agents to directly output corresponding structured layout code using natural language descriptions (such as "create a user interface with avatars and buttons"), which is then rendered as native UI (User Interface) components by the client.

[0003] However, although the aforementioned one-time code generation scheme can quickly produce UI layouts using NLP (Natural Language Processing) and code generation technologies, its code generation is unidirectional. Once the generated code has quality problems, developers still need to manually debug it, lacking automated iterative optimization capabilities, which affects the stability and reliability of the generated results. Summary of the Invention

[0004] In view of this, embodiments of this application provide a code optimization method, system, and electronic device to solve at least one problem existing in the background art.

[0005] In a first aspect, embodiments of this application provide a code optimization method, the method comprising: Obtain the initial code generated based on the natural language description; Perform at least one round of iterative optimization on the initial code, wherein the current round of iteration includes: Perform a quality assessment on the current code to obtain the code quality score and a list of issues for the current round; Based on the code quality score and issue list of the current round, update the iteration context and determine whether the iteration termination condition is met. The iteration context is used to record the set of failed optimization rules that failed to execute or caused rollback in each iteration. When the iteration termination condition is met, the optimal code version is output from the historical code versions, which include the version corresponding to the initial code and / or the code versions generated in each iteration; If the iteration termination condition is not met, the current code is optimized based on the problem list, the optimization rule base, and the updated iteration context to obtain optimized code for use in the next iteration optimization.

[0006] Secondly, embodiments of this application provide a code optimization system, the system comprising: The acquisition unit is used to acquire the initial code generated based on the natural language description. An optimization unit is configured to perform at least one round of iterative optimization on the initial code; The optimization unit is used to perform the following operations during the current iteration: Perform a quality assessment on the current code to obtain the code quality score and a list of issues for the current round; Based on the code quality score and issue list of the current round, update the iteration context and determine whether the iteration termination condition is met. The iteration context is used to record the set of failed optimization rules that failed to execute or caused rollback in each iteration. When the iteration termination condition is met, the optimal code version is output from the historical code versions, which include the version corresponding to the initial code and / or the code versions generated in each iteration; If the iteration termination condition is not met, the current code is optimized based on the problem list, the optimization rule base, and the updated iteration context to obtain optimized code.

[0007] Thirdly, embodiments of this application provide an electronic device including a processor, the processor being configured to invoke instructions to cause the terminal device to implement the code optimization method as described in any possible implementation of the first aspect.

[0008] Fourthly, embodiments of this application provide a storage medium on which an executable program is stored, wherein the executable program, when executed by a processor, implements the code optimization method as described in any possible implementation of the first aspect.

[0009] This application provides a code optimization method, system, and electronic device. By acquiring initial code generated based on natural language description, it performs at least one round of iterative optimization on the initial code, transforming the unidirectional code generation process into an automatically and continuously optimized iterative flow. In each iteration, a code quality score and a problem list are obtained by evaluating the execution quality of the current code. Based on the code quality score and problem list, the iteration context is updated, and it is determined whether the iteration termination condition is met. If the iteration termination condition is not met, the current code is optimized by combining the problem list, optimization rule base, and updated iteration context to obtain optimized code for use in the next round of iteration optimization. This not only allows for precise optimization using the specific problem list generated in each iteration, improving optimization efficiency, but also reduces repeated invalid attempts by recording failure rules in the iteration context, increasing the success rate of the optimization process and achieving precise and efficient continuous optimization. In addition, when the iteration termination condition is met, the optimal code version is output from historical code versions, effectively improving the reliability and quality of the final output result. Attached Figure Description

[0010] Figure 1 This is a flowchart illustrating a code optimization method according to an embodiment of this application; Figure 2 A schematic diagram of a multi-dimensional evaluation process provided in an embodiment of this application is shown; Figure 3 for Figure 1 The flowchart of step S204 is shown below; Figure 4 for Figure 3 The flowchart of step S2042 is shown below; Figure 5 This is a flowchart illustrating a code optimization method according to another embodiment of this application; Figure 6 This is a schematic diagram of the structure of a code optimization system according to an embodiment of this application. Detailed Implementation

[0011] To make the technical solution and beneficial effects of this application more apparent and understandable, a detailed description is provided below by listing specific embodiments. The accompanying drawings are not necessarily drawn to scale, and local features may be enlarged or reduced to more clearly show the details of the local features; unless otherwise defined, the technical and scientific terms used herein have the same meanings as those in the technical field to which this application pertains.

[0012] The embodiments in this application are not exhaustive, but merely illustrative of some embodiments, and are not intended to limit the scope of protection of this disclosure. Unless otherwise specified, each step in a particular embodiment can be implemented as an independent embodiment, and the steps can be arbitrarily combined. For example, a solution after removing some steps in a particular embodiment can also be implemented as an independent embodiment, and the order of the steps in a particular embodiment can be arbitrarily interchanged. Furthermore, the optional implementation methods in a particular embodiment can be arbitrarily combined; moreover, the embodiments can be arbitrarily combined, for example, some or all steps of different embodiments can be arbitrarily combined, and a particular embodiment can be arbitrarily combined with the optional implementation methods of other embodiments.

[0013] In each embodiment of this application, unless otherwise specified or in case of logical conflict, the terminology and / or descriptions of the embodiments are consistent and can be referenced by each other. Technical features in different embodiments can be combined to form new embodiments based on their inherent logical relationships.

[0014] In the description of the embodiments of this application, it should be understood that the terms "first" and "second" are used for descriptive purposes only and should not be construed as indicating or implying relative importance or implicitly specifying the number of indicated technical features. Therefore, features defined with "first" and "second" may explicitly or implicitly include one or more of the stated features. In the description of the embodiments of this application, "multiple" means two or more, unless otherwise explicitly specified.

[0015] Figure 1 This is a flowchart illustrating a code optimization method according to an embodiment of this application. See also... Figure 1 The method includes the following steps: S100: Obtain the initial code generated based on the natural language description; S200: Perform at least one round of iterative optimization on the initial code, wherein the current round of iterative process includes: step S201, step S202, and step S203 or step S204 to be executed selectively; S201: Perform a quality assessment on the current code to obtain the code quality score and a list of issues for the current round; S202: Based on the code quality score and issue list of the current round, update the iteration context and determine whether the iteration termination condition is met. The iteration context is used to record the set of failure optimization rules that failed to execute or caused rollback in each iteration. S203: When the iteration termination condition is met, output the optimal code version from the historical code versions. The historical code versions include the version corresponding to the initial code and / or the code versions generated in each iteration. S204: When the iteration termination condition is not met, optimize the current code based on the problem list, optimization rule base and updated iteration context to obtain optimized code for use in the next iteration optimization.

[0016] The described code optimization method can be applied to a code optimization system, which can be implemented in software, hardware, or a combination of both. For example, the system can be deployed on terminal devices or servers. This code optimization method is applicable to various types of structured code that require optimization and improvement, including but not limited to: user interface (UI) layout code, business logic code, test code, configuration code, or computational logic code.

[0017] The implementation process of the above step S100 may include: receiving natural language input; and, based on the natural language input, calling a code generation model (such as an A2UI compatible engine) to generate initial layout code.

[0018] For example, the system receives a natural language layout description provided by the user. The natural language layout description is the user's interface layout requirement expressed in natural language, such as "create a user card containing an avatar, username, and a follow button." The system can parse the natural language description and convert it into layout code by calling the A2UI compatible engine. The format of the layout code includes, but is not limited to, JSON (JavaScript Object Notation, a lightweight data interchange format) or XML (eXtensible Markup Language) format.

[0019] It should be noted that the A2UI-compatible engine and other code generation models are only invoked in the first iteration. In subsequent iterations, the code generated in the previous optimization is used directly as the current code, and the code generation model is no longer invoked.

[0020] In some examples, the iteration context is used to maintain key state information throughout the iterative optimization process.

[0021] The iteration context can be used to record the following information: Basic control parameters. The basic control parameters include the current iteration round, the maximum number of iterations, and the quality achievement threshold. The initial value of the current iteration round is set to 1; the default value of the maximum number of iterations is 5, and the configurable range is 1 to 10; the default value of the quality achievement threshold is 90 points, and the configurable range is 75 to 99 points.

[0022] Scoring history. The scoring history includes a scoring history list and a problem history list. The scoring history list stores the overall score for each iteration; the problem history list stores the set of problems detected in each iteration.

[0023] Version management data. This data includes a snapshot library, the current snapshot, historical best snapshots, and historical best scores. The snapshot library uses a hash-to-code mapping structure to store layout code for each version; the historical best snapshot stores the layout code version with the highest score in each iteration.

[0024] Rule blacklist. The rule blacklist is a set of rule identifiers used to record rules that cause optimization failures, preventing their reuse in subsequent iterations.

[0025] Rollback status log. The rollback status log includes a counter for consecutive rollback counts, used to detect whether consecutive rollbacks have occurred.

[0026] In this embodiment, the iteration context records a set of failure optimization rules (i.e., a blacklist rule set). The rule set contains rule identifiers that failed to execute or caused a rollback in the current iteration session. For each problem, it can be checked whether its corresponding candidate optimization rule is in the blacklist. If a candidate rule has been added to the blacklist, the rule is removed from the candidate set to avoid reusing the failed rule.

[0027] In some embodiments, the optimization rule base is stored in a structured manner, and each rule may contain the following fields: Rule identifier, a string used to uniquely identify the rule; Applicable problem types: This indicates the set of problem types that this rule can handle.

[0028] Preconditions are conditional expressions that must be satisfied before the rule can be executed; The transformation operation, i.e. the specific code transformation logic, is described using declarative rules or executable code snippets; Post-validation includes validation conditions after the conversion is complete; Priority refers to the selection priority when multiple rules can handle the same problem.

[0029] To maintain and track the state of the entire optimization process, the method may further include: initializing the iteration context.

[0030] Before starting the optimization process, the system creates and initializes an iteration context object. This initialization may include: setting the current iteration round to 1; initializing the scoring history list to an empty list, which records the comprehensive scores generated in each iteration sequentially; initializing the snapshot library to an empty set, which stores layout code snapshots after optimization in each round and their corresponding hash values; and initializing the rule blacklist set to an empty set, which records the identifiers of optimization rules that failed to execute or caused quality regression in this optimization session.

[0031] In some examples, the iteration context updates the following information during each iteration: The scoring history is updated. The overall score for the current round is appended to the end of the scoring history list. Simultaneously, the current score is compared to the best historical score; if the current score is higher than the best historical score, the best historical score and the best historical snapshot are updated.

[0032] Issue log updated. The list of issues detected in the current round is appended to the historical issue list.

[0033] Snapshot repository update. Calculate the hash value of the current layout code and store the mapping relationship between the hash value and the code in the snapshot repository.

[0034] For the initial code generated based on natural language descriptions, and for new code generated in each subsequent iteration, the system performs a version snapshot saving operation. Specifically, the layout code for the current iteration is standardized, including: removing whitespace characters and comments from the code, sorting attribute keys alphabetically, and standardizing numeric and string quotation mark formats; calculating the hash value (e.g., using the SHA-256 algorithm) of the standardized code, which uniquely identifies the current layout code; and then storing the mapping between the hash value and the original code in a snapshot library. The saved snapshots can be used for subsequent loop state detection and for performing rollback operations in the event of quality regression.

[0035] In some examples, to prevent the optimization process from getting stuck in a loop or repeatedly ineffective, the method may further include the following steps before step S201: The hash value of the current code is compared with all historical hash values ​​stored in the snapshot library to determine if a loop has been entered. If the current hash value already exists in the snapshot library, the system is determined to have entered a loop. At this point, the iteration termination condition is met, the system terminates the iteration process, selects the historical version with the highest comprehensive score from the snapshot library as the output result, and attaches a loop detection warning message. If the current hash value does not exist in the snapshot library, it is determined that a loop has not been entered, and the process continues to execute step S201. In a preferred embodiment, the loop detection condition is a complete hash value match. In another embodiment, an approximate matching method can also be used, where a loop is determined when the similarity between two versions exceeds a preset threshold.

[0036] In some embodiments, the method may further include: after updating the iteration context, if the code quality score of the current round is lower than the quality score of the previous round, then a rollback is determined to occur; when a rollback occurs, the current code is restored to the code of the previous round, and the optimization rule that caused this rollback is recorded in the failure optimization rule set of the iteration context.

[0037] In this embodiment, rollback detection is used to identify whether quality degradation has occurred during the optimization process, such as determining whether the current iteration is the first iteration. If the current iteration number is 1, rollback detection is skipped. This avoids the anomalies caused by forced rollback detection due to the lack of preceding data for comparison in the first iteration. For iterations other than the first iteration, the score of the previous iteration is obtained. The previous score is obtained by accessing the second-to-last element of the score history list. The current score is compared with the previous score. If the current score is lower than the previous score, a rollback is determined to have occurred, and a rollback operation needs to be performed.

[0038] For example, the rollback operation may include: Restore the previous snapshot. Based on the hash value obtained from the previous snapshot, retrieve and restore the layout code of the previous snapshot from the snapshot repository. Set the current code pointer to the restored code.

[0039] Record the failure rules. Obtain the identifier of the optimization rule used in this iteration and add the rule to the rule blacklist. This way, rules in the blacklist will be excluded during subsequent iterations, avoiding the reuse of rules that caused failure.

[0040] Restore the scoring status. Set the current score to the previous round's score to ensure the scoring status matches the code status.

[0041] Update the rollback counter. Increment the consecutive rollback count by 1. If no rollback occurs in this round, set the consecutive rollback count to 0.

[0042] In some examples, the method may further include: after performing a rollback operation, checking whether the number of consecutive rollbacks has reached or exceeded a preset threshold (e.g., set to 2 times). When the number of consecutive rollbacks reaches the threshold, the system performs the following operations: terminates the iteration process; records the reason for termination as consecutive rollbacks; and returns the historical best version as the final output. This avoids the system consuming resources in ineffective optimization, and terminates and outputs the known optimal result in a timely manner.

[0043] In this embodiment, a rollback detection is performed, and when a rollback is detected, the system automatically executes code rollback, restoring the current layout code to the version saved at the end of the previous iteration. This ensures that the optimization process will not continue on the basis of degraded code. The optimization rule identifier that caused this rollback is recorded in the set of invalid optimization rules maintained by the iteration context. This effectively prevents the risk of a continuous decline in overall quality due to a single erroneous optimization attempt, and can proactively avoid known invalid optimization rules in subsequent iterations, thereby continuously improving the success rate and security of subsequent optimizations.

[0044] In some embodiments, the iteration termination condition includes at least one of the following: The code quality score for the current round has reached or exceeded the preset quality threshold. The current iteration round has reached the preset maximum number of iterations; The current code is detected to be identical to historical code recorded in previous iterations; A series of rollbacks occur, and the number of rollbacks reaches a preset threshold. The convergence condition was determined based on the trend of quality score changes in recent consecutive iterations.

[0045] In some examples, the preset quality threshold can be set to 90 points. When the current code quality score reaches or exceeds the quality threshold, it means that the layout code has achieved a good or better level in all indicators and can be directly used in a production environment.

[0046] In some examples, to avoid the possibility that too few iterations may make it difficult to reach a stable state, while too many iterations may lead to increased time costs and make it difficult to continue improving code instructions, the maximum number of iterations is set to 5.

[0047] In some examples, the current iteration round is checked to see if it meets the minimum round requirement for convergence detection. If the current round is less than the minimum round (e.g., 3 rounds), the convergence detection is skipped, and optimization proceeds directly. If the current round meets or exceeds the minimum round, convergence detection is initiated. This avoids performing convergence checks when data is insufficient and prevents misjudgments of convergence due to early fluctuations.

[0048] In some examples, the system can determine whether the currently generated code is exactly the same as a version saved in a previous iteration by calculating and comparing the code hash value.

[0049] In some examples, convergence is determined by checking if a convergence condition is met. For instance, if the score improvement in every two consecutive iterations is less than a preset convergence threshold (e.g., 2 points), then convergence is considered achieved. Terminating the process promptly when the score improvement plateaus can save computational resources.

[0050] By pre-setting iteration termination conditions, the system can end the optimization loop at an appropriate time, ensuring that the iteration process will not fall into an infinite loop or meaningless repetition, and will not continue to consume computing resources when the continuous optimization effects are similar.

[0051] When the iteration termination condition is met, such as when the overall score reaches or exceeds the quality threshold, the first termination decision is output, carrying the current layout code as the achievement result. Alternatively, the second termination decision is output when any of the following conditions are met: the iteration limit is reached; convergence is determined; or continuous backtracking reaches the threshold, carrying the historical best version as the final result.

[0052] If none of the iteration termination conditions are met, the current layout code (i.e. the layout code content to be optimized) is combined with the problem list (problems can be sorted by severity), the iteration context (including rule blacklist, scoring history, historical problems, etc.) and the optimization rule base to perform optimization processing on the current code, and the optimized code is obtained for use in the next round of iteration optimization.

[0053] It's important to note that the composition of the historical code versions depends on the actual execution of the iteration process. Specifically, if one or more new code versions are generated during the iteration, the historical code versions include the version corresponding to the initial code and the code versions generated in each iteration. Correspondingly, in each iteration, if the current code is deemed to meet the iteration termination condition after a quality evaluation, then that iteration will not perform any further code optimization operations and will directly output the optimal code version from the historical code versions. In particular, if the iteration termination condition is met in the first iteration, the historical code versions will only include the version corresponding to the initial code. In this case, the initial code is the final output optimal code version, and the iteration process ends.

[0054] This application provides a code optimization method that, by acquiring initial code generated based on natural language description, performs at least one round of iterative optimization on the initial code, transforming the unidirectional code generation process into an iterative process that can be automatically and continuously optimized. In each iteration, a code quality score and a problem list are obtained by evaluating the execution quality of the current code. Based on the code quality score and the problem list, the iteration context is updated, and it is determined whether the iteration termination condition is met. If the iteration termination condition is not met, the current code is optimized by combining the problem list, the optimization rule base, and the updated iteration context to obtain optimized code for use in the next round of iteration optimization. This not only allows for precise optimization using the specific problem list generated in each iteration, improving optimization efficiency, but also reduces repeated invalid attempts by recording failure rules in the iteration context, increasing the success rate of the optimization process, thereby achieving precise and efficient continuous optimization. In addition, when the iteration termination condition is met, the optimal code version is output from historical code versions, effectively improving the reliability and quality of the final output result.

[0055] It is understood that, in other possible embodiments, the step of obtaining the initial code generated based on the natural language description in step S100 above can be replaced by: obtaining code automatically generated based on a template or framework, or obtaining code manually written or imported by the developer; or obtaining code automatically generated by a code generation tool based on specific input (such as configuration files or interface descriptions). In other words, the method of obtaining the initial code can be flexibly adjusted according to specific application scenarios or development needs.

[0056] In this application, the current code can be evaluated across multiple analytical dimensions to obtain evaluation metric values ​​for each dimension, thereby performing a quality assessment. It is understood that, given the potential differences in structural characteristics, runtime environments, and optimization goals among different code types, the evaluation dimensions and metrics can be dynamically selected based on the specific code type during the iteration process. Each dimension can be quantitatively scored based on preset thresholds or rules, ultimately generating the code quality score and issue list for the current round.

[0057] For example, for business logic code, its evaluation dimensions may include at least one of the following: Code complexity can be measured by static metrics such as method length, number of parameters, and nesting depth. Cyclic complexity, for example, can be used to assess the complexity of logical branches by counting the number of independent linear paths in the code; Module coupling degree, for example, is determined by analyzing the calling relationships between modules (such as input coupling and output coupling) and the degree of association between methods within a module (such as the frequency of mutual calls between methods and the sharing of fields). Completeness of exception handling, such as detecting defects like uncaught exceptions, empty catch blocks, and missing default branches.

[0058] For example, evaluation dimensions for data processing scripts may include code execution efficiency, memory usage, data throughput, and / or concurrent processing capabilities; evaluation dimensions for test code may include focusing on test coverage, assertion coverage, and / or test case execution efficiency.

[0059] In some embodiments, the initial code is user interface layout code, and the implementation process of step S201 above may include: The user interface layout code is evaluated across multiple analytical dimensions to obtain evaluation metrics for each dimension. These multiple analytical dimensions include at least two of the following: static structure, dynamic rendering, device adaptation, and design specifications. Based on the evaluation metrics for these multiple analytical dimensions, a code quality score and a list of issues for the current round are generated.

[0060] In this embodiment, the user interface layout code can be evaluated in parallel across multiple analytical dimensions using an analysis engine. Based on the evaluation index values ​​of multiple analytical dimensions, a comprehensive code quality score for the current round is generated through normalization and weighted calculation. A detailed list of issues is also generated based on the detection results of each dimension. This transforms layout quality issues into objective quantitative data, providing a basis for subsequent optimization decisions.

[0061] In some embodiments, the static structure dimension includes an evaluation of at least one of the following metrics: the layout hierarchy depth of the user interface layout code, component redundancy, nesting relationship of container components, and reasonableness of container type.

[0062] In some examples, layout hierarchy depth refers to the total number of nodes traversed from the root node of the layout tree to the deepest leaf node. The layout hierarchy depth can be obtained by recursively traversing the entire view tree using a depth-first search algorithm and recording the number of nodes along the longest path. Layout hierarchy depth directly reflects the nesting complexity of the layout structure; excessive depth increases the measurement and layout calculation overhead during interface rendering. By monitoring this metric, the system can accurately identify nested structures that need to be flattened, providing a clear basis for subsequent optimization.

[0063] The layout hierarchy depth can be evaluated based on a preset correspondence between depth and score, directly identifying structural defects such as excessive nesting. The hierarchy depth is negatively correlated with the corresponding score value. For example, the score corresponding to the hierarchy depth is calculated using the formula: Hierarchical Depth Score = max(0, 100 - (depth - 3) × 20), where depth is the actual hierarchy depth.

[0064] In some examples, component redundancy can be expressed as the proportion of redundant components in the layout to the total number of components. For instance, based on component feature fingerprints, identical components are identified through comparison. Simultaneously, components with duplicate functions are filtered based on attribute similarity thresholds, and invalid components with visibility set to GONE, size zero, or empty content are counted. Then, the percentage of the sum of completely duplicated components, functionally redundant components, and invalid components relative to the total number of components is calculated as the component redundancy. Here, GONE is a visibility state of a View in Android, indicating that the view is completely invisible and does not occupy any layout space. This proportion directly quantifies the degree of code redundancy. High redundancy leads to bloated layout files, increased memory usage, and decreased rendering performance. By monitoring this metric, the system can accurately locate and remove redundant components in subsequent optimizations, simplifying the layout structure and reducing resource consumption.

[0065] The feature fingerprint includes a hash value generated from component type and key attributes (such as ID, width, height, text, background, etc.). This hash value is calculated using MD5 (Message-Digest Algorithm 5) for precise comparison. During scoring, the system categorizes redundancy based on a calculated percentage. For example, redundancy between 0% and 5% is rated excellent (100 points), 5% to 10% is good (80 points), 10% to 20% requires optimization (50 points), and over 20% is considered a serious problem (20 points). This score directly measures the degree of code redundancy.

[0066] In some examples, the nesting relationship of the container components can be analyzed based on the view hierarchy tree, and may include the following detection rules: The detection of nested containers of the same type involves traversing each node in the view hierarchy tree and checking the component types of the parent and child nodes. When the parent node type and the child node type are the same, and both are container components, it is determined that there is a nested container problem of the same type.

[0067] Redundant wrapping detection for single child nodes involves counting the number of direct child nodes for each container node. For example, if a container node contains only one child node and that container node does not have any special style attributes set (such as background color, border, etc.), it is determined that there is a redundant wrapping layer.

[0068] Deep nested chain detection involves detecting the length of consecutively nested container chains in a view hierarchy tree. When the number of consecutively nested containers reaches or exceeds three, a deep nested chain problem is identified.

[0069] For each type of problem detected, a corresponding score can be deducted from the nesting rationality score based on its impact, thereby quantifying the quality of the nesting structure. For example, the quantitative score of the nesting relationship is calculated using the following formula: Nesting rationality score = 100 - (number of nested structures of the same type × 10) - (number of redundant wrappers × 5) - (number of deep nested chains × 15).

[0070] In some examples, the appropriateness of the container type can be determined by evaluating the efficiency of the specified container type. For example, a built-in rule base can be used to classify common containers according to the efficiency of their use cases and detect inappropriate usage. For instance, the rules include: deducting 10 points for each additional nested LinearLayout (three or more levels) and suggesting a refactoring to ConstraintLayout; deducting 5 points for each non-FrameLayout container that only wraps a single child node; and deducting 15 points for each nested RelativeLayout. The sum of these deductions reflects the severity of inappropriate container selection and guides the subsequent optimization engine to perform targeted container type replacements.

[0071] In this embodiment, by evaluating the user interface layout code at the static structural dimension, the quality of code organization can be transformed into objective, quantifiable data. It is understood that in practical applications, one or more of the following can be selected for evaluation: layout hierarchy depth, component redundancy, nesting relationships of container components, and the rationality of container types. For example, all indicators can be weighted for a more comprehensive evaluation, thereby providing more reliable data for subsequent optimization.

[0072] In some embodiments, the dynamic rendering dimension includes loading layout code in a simulated runtime environment and evaluating at least one of the following runtime performance metrics: rendering performance of UI layout code, GPU (Graphics Processing Unit) overdraw level, and frame rate stability.

[0073] For example, the generated layout can be loaded in a simulator or real device environment, and rendering metrics can be collected through system application programming interfaces (APIs) or performance monitoring tools. For instance, on the Android platform, the single-frame drawing time can be collected through the OnDrawListener interface of ViewTreeObserver, and the frame interval time can be collected through the FrameCallback interface of Choreographer. On the iOS platform, the frame refresh callback time can be collected through CADisplayLink (a timer object in iOS that synchronizes with the screen refresh rate).

[0074] In some examples, the rendering performance of the UI layout code can be obtained by timing multiple key stages of the layout rendering process. These key stages include the Measure stage, the Layout stage, and the Draw stage.

[0075] In some examples, the rendering performance of UI layout code can be evaluated by the first render time and the single-frame render time.

[0076] First render time is defined as the time elapsed from the start of layout loading to the completion of the first frame display. The rating of first render time can be determined based on the range of preset durations within which it falls. For example, a first render time of less than 100 milliseconds is considered excellent, 100 to 200 milliseconds is considered good, 200 to 500 milliseconds is considered to require optimization, and more than 500 milliseconds is considered to have serious problems.

[0077] Single-frame rendering time is defined as the time consumed in a single drawing operation. The rating of single-frame rendering time can be determined based on the duration range of that time. For example, a rendering time of less than 8 milliseconds is considered excellent, 8 to 12 milliseconds is considered good, 12 to 16 milliseconds is considered requiring optimization, and more than 16 milliseconds is considered to have a serious problem. The 16-millisecond threshold is determined based on a refresh rate requirement of 60 frames per second.

[0078] In addition, the rendering performance of UI layout code can be evaluated by combining memory usage increments, which are defined as the difference in memory usage before and after layout loading. The level corresponding to the memory usage increment can be determined based on the increment range within several preset increment ranges. For example, a memory usage increment of less than 5 megabytes is considered excellent, 5 to 10 megabytes is considered good, 10 to 20 megabytes is considered to require optimization, and more than 20 megabytes is considered to have serious problems.

[0079] In some examples, GPU overdraw can be expressed as the number of times a single pixel is drawn in a single frame of rendering. Overdraw increases GPU load, leading to decreased frame rate and increased power consumption. For example, drawing once is considered no overdraw (normal); drawing twice is considered Level 1 overdraw (acceptable); drawing three times is considered Level 2 overdraw (minor issue); drawing four times is considered Level 3 overdraw (moderate issue); and drawing five or more times is considered Level 4 overdraw (serious issue).

[0080] For example, overdraw level detection can be performed through simulated environment detection or static code analysis. Simulated environment detection includes enabling GPU overdraw visualization options on an Android emulator or real device environment, obtaining a rendered overdraw heatmap, and calculating the proportion of each level region through image analysis. Static code analysis may include analyzing layout code to identify all components with a background attribute, calculating the drawing boundary rectangle of each component, and marking potentially overdrawn areas for parent-child component pairs with overlapping boundaries if both have a background attribute.

[0081] The score corresponding to the degree of overdrawing can be calculated as follows: Score = 100 - area2x×5 + area3x×15 + area4x×30, where area_2x, area_3x, and area_4x are the percentages of the overdrawn areas to the total area for Level 1, Level 2, and Level 3 overdrawing, respectively.

[0082] In some examples, frame rate stability can be obtained by continuously collecting rendering time data for no less than a preset number of frames (e.g., 120 frames), calculating frame rate statistics based on the collected data, and using the statistics to characterize the stability of the frame rate.

[0083] The statistical indicators of the frame rate include frame rate jitter rate and / or frame drop rate, and their calculation process includes: The average frame rate is calculated based on the ratio of the number of sampled frames to the total sampling time. Obtain the frame time standard deviation, frame time standard deviation = sqrtΣ(Ti-Tavg)² / N, where Ti is the rendering time of the i-th frame and Tavg is the average rendering time; Frame rate jitter is calculated as follows: Frame rate jitter = (based on frame time standard deviation / average frame time) × 100%; Get the frame drop rate. Frame drop rate = (number of frames with frame intervals exceeding a preset value (e.g., 16.67 milliseconds) / total number of frames) × 100%.

[0084] An average frame rate within the first average frame rate range (e.g., 58 frames per second or more) is considered excellent; an average frame rate within the second average frame rate range (e.g., 50 to 58 frames per second) is considered good; an average frame rate within the third average frame rate range (e.g., 40 to 50 frames per second) is considered to require optimization; and an average frame rate within the third average frame rate range (e.g., below 40 frames per second) is considered to have a serious problem.

[0085] A frame rate jitter rate within the first jitter rate range (e.g., less than 5%) is considered excellent; a frame rate jitter rate within the second jitter rate range (e.g., 5% to 10%) is considered good; a frame rate jitter rate within the third jitter rate range (e.g., 10% to 20%) is considered to require optimization; and a frame rate jitter rate within the fourth jitter rate range (e.g., more than 20%) is considered to have a serious problem.

[0086] In some embodiments, the device adaptation dimension includes evaluating at least one of the following metrics on a predefined device configuration: whether components go out of bounds, whether adjacent components overlap unexpectedly, whether text content is truncated, and whether image display is distorted. By evaluating the user interface layout code on the device adaptation dimension, it can be ensured that the generated layout code maintains reliable display performance and usability on different types of devices (e.g., mobile phones, tablets).

[0087] Specifically, device compatibility dimension detection can be performed on a predefined device configuration matrix. This device configuration matrix includes device types covering different screen sizes, resolutions, and pixel densities.

[0088] Device compatibility testing can include multiple items, such as component out-of-bounds (layout boundaries exceeding the screen), component overlap (unexpected overlap area exceeding 5%), text truncation, and image distortion (aspect ratio changes exceeding a threshold). Each item has clear pass / fail criteria. Scoring can use a comprehensive deduction method, for example, the formula is: Compatibility Score = 100 - (Number of out-of-bounds issues × 15 + Number of overlap issues × 10 + Number of text truncation issues × 8 + Number of image distortion issues × 8). A higher score indicates better display compatibility of the layout code across multiple devices.

[0089] Furthermore, the system can count the number of devices whose compatibility score reaches or exceeds a preset score (e.g., 80 points) among all tested devices, and calculate the device coverage pass rate. For example, the device coverage pass rate = number of devices with a compatibility score ≥ 80 points / total number of tested devices. The standard for overall multi-device compatibility judgment is that the device coverage pass rate reaches or exceeds a preset pass rate, for example, the preset pass rate is 90%.

[0090] In some embodiments, the design specification dimension includes compliance checks on at least one of the following specifications: component spacing, font attributes, color contrast, and interactive component size. By evaluating the user interface layout code at the design specification dimension, it is ensured that the generated layout code meets the requirements for visual consistency and accessibility.

[0091] The system can have a built-in design specification library, which may include Material Design (a design language and system) specifications, iOS human interface guidelines, and custom specifications. These can be used to verify whether spacing follows a baseline grid (e.g., multiples of 4dp), whether font attributes (font size, weight, etc.) are within a predefined compliance set, whether color contrast meets WCAG (Web Content Accessibility Guidelines) accessibility requirements (e.g., text contrast ≥ 4.5:1), and whether interactive component sizes meet the minimum operable standard (e.g., 48dp × 48dp). The evaluation index for the design specification dimension combines the deduction results from the above four specification checks. The calculation formula is: Specification Score = 100 - Σ(Number of Violations × Corresponding Deduction Weight). This total score directly reflects the degree of conformity between the layout code and the design system.

[0092] In some embodiments, generating the code quality score and issue list for the current round based on evaluation index values ​​of multiple analysis dimensions may include: normalizing the evaluation index values ​​of each analysis dimension to map indices with different dimensions and value ranges to a unified score range; weighting and summing the normalized scores of each dimension using preset weighting coefficients to calculate the code quality score; and simultaneously generating a structured issue list based on the detection results of each dimension. Each issue item in the list includes the issue type, severity (e.g., fatal, severe, moderate, minor), issue location, related component identifier, and preliminary optimization suggestions. The issue list can be sorted in descending order of severity or processing priority.

[0093] When integrating the multi-dimensional evaluation results, the system performs piecewise linear normalization on the original index values ​​of each dimension, mapping them to a unified score range. Then, based on the importance of each dimension to the overall quality, preset weights are assigned, and a single comprehensive quality score is calculated through weighted summation. Simultaneously, the system integrates all detected specific issues, generating a structured issue list. Each record includes the issue type, severity, specific location, and preliminary optimization suggestions, sorted by priority. This comprehensive score and issue list together form the data foundation driving subsequent automated optimization and iterative control decisions.

[0094] like Figure 2 As shown, Figure 2 This illustration shows a flowchart of a multi-dimensional evaluation process provided by an embodiment of this application. The analysis engine can perform parallel evaluations of static structure, dynamic rendering, device adaptation, and design specifications. Code quality scores are obtained through index normalization and weighted calculation, and a structured analysis report is output.

[0095] In some examples, code quality scores and a list of issues can be output as an analysis report, which may include: Top-level information includes timestamps, layout identifiers, overall score, quality level assessment, and whether optimization is needed.

[0096] The static analysis results include dimensional scores, hierarchical depth values, number of redundant packages, number of duplicate components, and a list of specific issues. The dynamic analysis results include dimensional scores, first rendering time, average frame time, frame drop rate, memory increment, and a list of specific issues. The adaptability analysis results include dimension scores, number of tested devices, number of devices that passed, identification of failed devices, and a list of specific issues. The design specification analysis results include dimension scores, total number of inspection items, number of inspection items that passed, and a list of specific issues.

[0097] Each issue item includes: issue type, severity, issue location and / or related component identifier, and optimization suggestions.

[0098] In some embodiments, in order to perform precise and secure optimization processing on the problems identified in the assessment, such as Figure 3 As shown, step S204 may include steps S2041 to S2044.

[0099] S2041: For each issue in the issue list, based on the issue type, severity, optimization rule base, and failure optimization rule set recorded in the iteration context, determine whether to perform automated refactoring on the issue.

[0100] For each problem in the problem list, the system determines whether the problem meets multiple preset conditions based on the problem's type, severity, preset optimization rule base, and failure optimization rule set recorded in the iteration context, in order to determine whether to adopt an automated code refactoring approach for the problem.

[0101] S2042: To address the issue of automated refactoring, refactor the code segments in the current code that are related to the issue based on the optimization rules in the optimization rule base.

[0102] For issues identified as requiring automated refactoring, the system performs transformation operations on the corresponding nodes in the abstract syntax tree of the current code based on the matching rules in the optimization rule base, and then verifies the syntax correctness of the generated code segment after the operation.

[0103] S2043: For issues where automatic refactoring is not performed or refactoring fails, generate and output optimization suggestions for the problem.

[0104] For issues determined in step S2041 that automatic refactoring should not be performed, or issues where automatic refactoring fails in step S2042 (e.g., syntax validation of the refactored code segment fails, or an exception occurs during the refactoring process), the system generates and outputs targeted optimization suggestions. These suggestions provide guidance for human intervention, and may include root cause analysis, descriptions of specific modification solutions, and examples of code modifications for reference.

[0105] S2044: Obtain the optimized code based on the refactored code segment and / or the code segment modified according to the optimization suggestions.

[0106] In some examples, if only the code segment generated by automated refactoring exists (i.e., the code segment obtained by refactoring the problem identified as an automated refactoring issue), then the refactored code segment replaces the original code segment in the current code corresponding to that problem. After the replacement operation is completed, the resulting current code is the code optimized in this iteration.

[0107] In some examples, if only the code segment modified according to the optimization suggestion exists (i.e., the code segment obtained by the user modifying the code based on the optimization suggestion), then the modified code segment replaces the original code segment in the current code corresponding to the optimization suggestion. The current code after replacement is the code optimized in this iteration.

[0108] In some examples, if both a code segment generated by automated refactoring and a code segment modified according to optimization suggestions exist simultaneously, then the refactored code segment and the modified code segment respectively replace their corresponding original code segments in the current code. After merging all replacement operations, the current code optimized in this iteration is obtained.

[0109] It should be noted that the corresponding original code segment refers to the original code fragment in the current code associated with the problem or optimization suggestion that generated the code segment. When multiple code segments exist simultaneously, these code segments usually correspond to different code locations or are non-overlapping original code segments; if overlap occurs, they are handled according to preset conflict resolution rules (e.g., prioritizing user-adopted optimization suggestions) to ensure the integrity and correctness of the final code.

[0110] In this embodiment, for each problem in the problem list, the system intelligently selects between automatic repair and manual processing paths based on the problem type, severity, optimization rule base, and set of failure optimization rules recorded in the iteration context. This avoids blindly attempting automatic repair for complex problems, thereby improving optimization efficiency while ensuring the reliability of the optimization process.

[0111] In some examples, the problem list may be preprocessed before performing step S2041 to determine the optimal processing order for each problem in the list. This preprocessing process may include the following steps: Read the list of issues, where each issue item contains an issue identifier, issue type, issue location, severity, related component information, and original description; Query the historical problem records in the iteration context, identify and mark duplicate and persistent problems in the current problem list based on the problem type and problem location. For example, the current problem list can be traversed, and for each problem, historical problems with the same problem type and the same problem location can be retrieved from the historical problem records. If a matching historical record is found, the current problem is marked as a duplicate problem, and the number of times the problem has occurred is updated. When a problem is marked as a duplicate problem and it occurs in two or more consecutive iterations, the problem is marked as a stubborn problem. Stubborn problems will be given priority for manual intervention in subsequent optimization decisions. Read the set of failed optimization rules in the iteration context to filter the candidate optimization rules for each problem. Based on the problem type, severity level, and recurrence frequency of each problem, a processing priority score is calculated. For example, the processing priority score is calculated according to the following formula: Priority score = Type weight × Severity coefficient × Recurrence frequency bonus; wherein, the type weight is configured according to the problem type, the severity coefficient is configured according to the severity level of the problem, and the recurrence frequency bonus is calculated based on the number of recurrences of the problem recorded in the iteration context; The problem list is sorted according to the processing priority score to determine the order in which to optimize the processing.

[0112] In some examples, the question types include the following: Structural issues include, for example, excessively deep layout hierarchies, nested containers of the same type, redundant wrapping layers, and single-child node containers. These structural issues affect the maintainability of the layout and rendering performance.

[0113] Performance-related issues include, for example, excessive rendering time, excessive GPU rendering, high memory usage, and unstable frame rates. These performance issues impact user experience and device resource consumption.

[0114] Adaptation issues include, for example, component out-of-bounds errors, component overlap, text truncation, and image distortion. These adaptation issues affect the display of the layout on different devices.

[0115] Issues related to compliance with design guidelines include, for example, violations of spacing, font conventions, insufficient contrast, and size regulations. These issues affect the consistency of layout with design guidelines.

[0116] In some embodiments, the criteria for determining whether to perform automated refactoring on the problem include at least two of the following: The first condition is that the optimization rule base contains optimization rules corresponding to the type of problem. Here, the optimization rule base can predefine conversion rules for various types of problems. By querying the rule base, it is checked whether there are available rules for the current problem type. If no corresponding rule exists, the result is determined as not automatically repairable, and optimization suggestions are generated.

[0117] The second condition is that the severity level of the problem falls within a preset range that allows for automatic repair. Here, for severe problems, due to the high risk of repair, automatic repair is not recommended by default, and optimization suggestions are generated first. For medium and minor problems, automatic repair is allowed. For example, this judgment logic can be adjusted through configuration parameters to allow automatic repair attempts for severe problems.

[0118] The third condition is that the optimization rule corresponding to the type of problem is not recorded in the set of failed optimization rules in the iteration context. Here, it is possible to check whether the identifier of the candidate optimization rule exists in the blacklist set. If the rule has been added to the blacklist, then skip the rule and check the next candidate rule. If all candidate rules are in the blacklist, the result is that it cannot be automatically repaired.

[0119] Fourth condition: The risk of executing the optimization rule is estimated to be controllable. The execution risk of the optimization rule is determined based on the number of components affected by the historical success rate of the rule and the scope of potential related impacts.

[0120] The execution risk (or repair risk value) of the optimization rule can be determined based on the following factors: the rule's historical success rate, the number of components involved in the problem, and the scope of the problem's associated impact. The historical success rate is the ratio of the number of successful executions of the rule to the total number of executions. Whether the execution risk of the optimization rule is controllable can be determined by comparing the execution risk of the optimization rule with a preset threshold. For example, if the historical success rate is lower than the preset threshold (e.g., 70%), the risk is considered uncontrollable. If the number of components involved in the problem exceeds the preset threshold (e.g., 10), the risk is considered uncontrollable. The scope of the problem's associated impact can be determined by analyzing the number of other components that the problem repair may affect. If the scope of impact exceeds a preset proportion of the total number of components (e.g., 30%), the risk is considered uncontrollable.

[0121] In some embodiments, such as Figure 4 As shown, step S2042 may include steps S20421 to S20424.

[0122] S20421: Locate the node related to the problem in the abstract syntax tree of the current code.

[0123] The system traverses and matches the abstract syntax tree of the current layout code based on the problem location information (such as component path or unique identifier) ​​recorded in the problem item, so as to accurately locate the specific target node or set of nodes that need to be modified.

[0124] S20422: Based on the optimization rules in the optimization rule base corresponding to the problem, perform a transformation operation on the located node and update the associated nodes of the node. The transformation operation includes at least one of the following: node deletion, node insertion, node replacement, attribute modification, node movement, and structure reorganization.

[0125] The optimization rule base is defined using a structured JSON format. Each rule includes fields such as ruleId, applicableProblems, and transformation. The rule base includes pre-defined refactoring rules for common problems. For example, the redundant wrapper elimination rule is specifically designed to handle redundant containers with only one child node and no special style; it removes the container node and promotes its single child node to its original parent node. The nested LinearLayout flattening rule optimizes LinearLayout structures with three or more consecutive nested levels by refactoring them into a single ConstraintLayout and recalculating constraints to improve performance. Additionally, there are rules such as redundant background elimination (removing backgrounds of child components that cause overdraw) and spacing normalization (adjusting spacing values ​​to the nearest integer multiple of 4dp), which address performance issues and design compliance issues, respectively.

[0126] Before performing the transformation, the system queries the optimization rule base according to the problem type, sorts the matching candidate rules according to predefined priorities, and selects the highest priority rule that is not recorded in the blacklist of failed optimization rules for loading and parameter binding. Subsequently, the system performs a series of predefined atomic transformation operations on the located AST nodes according to the transformation logic defined in the rules. These operations include node deletion (e.g., removing useless containers in the "redundant wrapper elimination rule"), node replacement (e.g., replacing LinearLayout with ConstraintLayout in the "nested LinearLayout flattening rule"), attribute modification (e.g., adjusting the spacing value to a multiple of 4dp in the "spacing normalization rule"), node movement, and structural reorganization. After completing the modification of the main nodes, the system checks and updates references to the modified nodes in other locations in the layout tree to ensure the integrity of the entire code structure.

[0127] S20423: Based on the updated nodes and associated nodes, refactor the code segment and perform syntax validation on the refactored code segment.

[0128] In some examples, reconstructing the code segment based on the updated nodes and associated nodes may include: recursively concatenating the updated nodes and their associated nodes in the abstract syntax tree according to the syntax rules of the programming language corresponding to the current code, based on their types (e.g., class declarations, method calls, variable definitions), attributes (e.g., names, modifiers, parameter lists), and hierarchical relationships, to generate the corresponding code string, thus obtaining the reconstructed code segment; alternatively, a code generator (e.g., a general abstract syntax tree to code conversion tool, or a code generation library for a specific language) may be invoked to convert the updated nodes and their associated nodes into a code segment. Subsequently, the system performs syntax validation on the reconstructed code segment, which may include format, structural integrity, and attribute validity validation.

[0129] In some examples, the refactored code segment can be directly replaced with the original code segment in the current code, and the replaced current code can be syntax-checked; or, the refactored code segment can be syntax-checked independently first, and after passing the check, it can be replaced with the current code, and the replaced current code can be syntax-checked a second time.

[0130] The refactored code segment that passes syntax validation can then be used to generate optimized code.

[0131] S20424: When an exception occurs or syntax validation fails during the refactoring process, the optimization rule used in this instance is recorded in the failure optimization rule set of the iteration context.

[0132] Anomalies during the refactoring process may include: failure to perform a transformation operation on the located node according to the optimization rule corresponding to the problem in the optimization rule base (e.g., the operation cannot be completed due to node type mismatch or structural constraint violation), or successful execution of the transformation operation but failure of subsequent steps (e.g., failure to generate code segments based on the updated node). If an anomaly occurs during the refactoring process, the current refactoring operation is abandoned, and the optimization rule used in this operation is recorded in the failed optimization rule set of the iteration context. At the same time, the problem is marked as needing to be transferred to the suggestion generation process.

[0133] Additionally, if no exceptions occur during the refactoring process, but the syntax check performed on the refactored code segment fails, it indicates that the automated refactoring attempt generated illegal code. The system will abandon this modification (or perform a rollback) and record the unique identifier of the optimization rule that caused the failure in the set of failed optimization rules (i.e., the blacklist) maintained by the iteration context. At the same time, the system will mark the issue as needing to be transferred to the suggestion generation process.

[0134] This allows the system to reduce repeated attempts at ineffective optimization rules in subsequent iterations. For example, it can proactively avoid rules that are known to cause problems in subsequent iteration decisions, thereby continuously improving the safety and success rate of the optimization process.

[0135] In some embodiments, the implementation process of step S2043 above may include: For issues where automated refactoring is not performed or where refactoring fails, an AI model is invoked to generate and output optimization suggestions for the issues. These optimization suggestions include an analysis of the causes of the issues, a textual description of the modification plan, and / or code modification examples.

[0136] The system performs a problem context analysis on issues requiring manual intervention (i.e., issues determined to be unsuitable for automated refactoring or where the refactoring has failed). This analysis collects a detailed description of the problem, its severity, specific location, all components involved, and their dependencies. Refactoring failures may include exceptions during the refactoring process or failures in syntax validation of the refactored code segment.

[0137] After completing the context analysis, the system invokes an artificial intelligence model, which can be a pre-trained generative model based on the Transformer architecture (a neural network based on a self-attention mechanism). The model's encoder encodes the structured problem description and related layout code snippets, while the decoder generates structured text output in an autoregressive manner. The generated content includes an analysis of the problem's causes, suggested optimization solutions, and specific code modification examples. The suggested text can be formatted into a suggestion report to assist human decision-making.

[0138] In some embodiments, the AI ​​model is an encoder-decoder model based on the Transformer architecture; the encoder encodes the input question information and code context. The decoder generates optimization suggestion text autoregressively.

[0139] For example, the encoder can have 6 layers, with each layer containing two sub-layers: a multi-head self-attention sub-layer and a feedforward neural network sub-layer. The multi-head self-attention sub-layer is used to obtain the query matrix, key matrix, and value matrix from the input vector through three linear transformations, respectively. It uses a multi-head attention mechanism to divide the input into 8 heads for parallel computation, and finally concatenates the output. The feedforward neural network sub-layer uses a two-layer fully connected network, and residual connections and layer normalization are applied after each sub-layer.

[0140] The decoder can have up to 6 layers. Each decoder layer contains three sub-layers: a masked self-attention sub-layer, a cross-attention sub-layer, and a feedforward neural network sub-layer. The masked self-attention sub-layer has the same structure as the encoder's self-attention sub-layer, but applies a causal mask matrix M to ensure that when generating position i, it can only focus on the already generated content from position 1 to i-1. The cross-attention sub-layer is used to establish information transfer between the decoder and the encoder. Its query vector comes from the output of the previous sub-layer of the decoder, and its key vector and value vector come from the final output of the encoder. The feedforward neural network sub-layer has the same feedforward network structure as the encoder.

[0141] The output layer of the model maps the hidden states of the decoder to a probability distribution on the vocabulary. Text generation adopts a beam search strategy, which terminates when an end marker is detected or a length threshold is reached, and returns the sequence with the highest score as the final output.

[0142] In some examples, the above steps, which invoke an AI model to generate and output optimization suggestions for the problem, may include: Input serialization steps: Parse the layout code into an abstract syntax tree structure; generate a sequence of nodes with structure tags through depth-first traversal, and perform tagging processing in conjunction with the problem description to obtain the model input; Model processing steps: The input sequence is processed using a multi-layer Transformer encoder, with multi-head attention calculation and feedforward transformation performed at each layer to extract features; mask attention and encoder cross attention are performed through a multi-layer decoder, and optimized suggestion text is generated based on the beam search strategy; Output execution steps: Format the generated text into a structured report containing code examples.

[0143] In some embodiments, the method further includes: after the AI ​​model generates and outputs optimization suggestions for the problem, displaying the following information to the user: the current iteration status (e.g., iteration round, current score, historical best score), problems to be processed (i.e., a list of problems requiring human intervention and their suggestion reports), and operation options; the operation options may include: applying suggestions and continuing iteration, modifying suggestions and continuing, abandoning the current problem and continuing other optimizations, and terminating iteration and outputting the current result.

[0144] Based on the user's selection of the operation options, the corresponding processing is performed: Option 1: Apply the suggestions and continue iterating. Apply the code modifications suggested in the suggestions to the layout code and proceed to the next iteration.

[0145] Option two: Modify the suggestion and continue. After the user modifies and applies the suggestion, the process proceeds to the next iteration.

[0146] Option 3: Abandon the current problem and continue with other optimizations. Mark the current problem as skipped by the user and move on to the next problem in the problem list. If all problems have been processed or skipped, proceed to the next iteration.

[0147] Option 4: Terminate the iteration and output the current result. The process enters the terminated state, outputting the current layout code and an optimization suggestion report as the final result.

[0148] The various embodiments or implementation methods described in this specification are presented in a progressive manner. Each embodiment focuses on the differences from other embodiments, and the same or similar parts between the embodiments can be referred to each other.

[0149] Next, taking UI layout code as an example, the code optimization method provided in this application embodiment will be further explained.

[0150] like Figure 5 As shown, this application provides a natural language generation layout code optimization method based on iterative verification and optimization feedback, which is applied to a code optimization system. The overall processing flow of the system is divided into three stages: the first stage is the initialization and initial generation stage (steps S1 to S4), the second stage is the quality assessment and regression detection stage (steps S5 to S8), and the third stage is the decision optimization and output stage (steps S9 to S18).

[0151] The system comprises three core functional modules: a multi-dimensional layout quality analysis engine (hereinafter referred to as the "analysis engine", corresponding to step S6), an intelligent optimization feedback and automated reconstruction module (hereinafter referred to as the "optimization module", corresponding to steps S13 to S16), and an iterative optimization closed-loop control module (hereinafter referred to as the "iterative control module", corresponding to steps S9 to S12).

[0152] Phase 1: Initialization and Initial Code Generation.

[0153] S1: Receive natural language input. The system receives user interface layout requests described in natural language, such as "create a user card that includes an avatar, username, and follow button".

[0154] S2: Initialize the iteration context. Create and initialize an object for maintaining the overall process state. This includes: iteration number (set to 1), an empty list of scoring history, an empty layout snapshot library, and an empty optimization rule blacklist.

[0155] S3: A2UI generates initial layout code. Only the first execution calls the A2UI-compatible engine to parse the natural language description and convert it into initial layout code (JSON or XML format).

[0156] S4: Save version snapshot. Calculate the hash value (e.g., MD5) of the current layout code and save the code snapshot and hash value to the snapshot library for subsequent loop checks and rollback operations.

[0157] Phase Two: Quality Assessment and Regression Testing.

[0158] S5: State Loop Detection. Compare the current layout hash value with the historical snapshot library. If they are duplicated, it is determined that a loop has been entered, jumps to output D, terminates the process, and outputs the historical highest-scoring version. If they are not duplicated, proceed to quality analysis step S6.

[0159] S6: Multi-dimensional analysis of layout quality.

[0160] The analysis engine performs the following assessments in parallel: static structure analysis, dynamic rendering verification, device compatibility, and design specification checks. After completing the analysis across multiple dimensions, the analysis engine performs metric normalization and comprehensive score calculation, and outputs a diagnostic report and comprehensive score.

[0161] S7: Update the iteration context. Add the overall score for this round to the scoring history list and record the list of issues found in this round.

[0162] S8: Rollback Detection. If it's the first iteration, skip the rollback detection and proceed directly to S10. If it's not the first iteration: compare the score of this iteration with the previous iteration. If the current score is lower, determine that an optimization rollback has occurred and proceed to S9a to perform the rollback operation; otherwise, proceed to S10.

[0163] S9a: Perform a rollback operation. When a rollback is detected: restore the previous layout from the snapshot library; add the optimization rules that caused the rollback to the blacklist. If two consecutive rollbacks occur: determine that a local optimum has been reached, and jump to output B. Otherwise: proceed to S11 to continue the process.

[0164] S10: Quality Compliance Judgment. Determine if the overall score reaches a preset threshold (e.g., 90 points). If it meets the threshold, jump to output A, terminate the process, and output the current compliant layout. If it does not meet the threshold, proceed to S11.

[0165] S11: Determine if the current iteration round has reached the upper limit (e.g., 5 times). If the upper limit has been reached: jump to output B, terminate the process, and output the historical best (highest score) version. If not: proceed to S12a.

[0166] S12a: Determine if there are enough rounds (≥3 rounds) for convergence analysis. If there are insufficient rounds, proceed directly to S13 to begin optimization. If there are sufficient rounds, proceed to S12b.

[0167] S12b: Convergence Detection. Analyze the changes in scores over the last three rounds. If the changes are all less than a threshold (e.g., 2 points), the optimization is considered to have converged, and the process jumps to output B; otherwise, proceed to S13.

[0168] S13: Problem preprocessing and classification.

[0169] The optimization module reads the problem diagnosis report, filters blacklist rules, marks stubborn problems, classifies them by type and severity, and calculates the processing priority.

[0170] S14: Determine if automatic refactoring is possible. For each issue, check in sequence whether there is a corresponding rule, whether the severity allows for automatic repair, whether the rule is on the blacklist, and whether the repair risk is controllable. If all conditions are met, it is determined to be an automatic refactoring and proceeds to S15A. If any condition is not met, it is determined to generate optimization suggestions and proceeds to S15B.

[0171] S15A: Automated Refactoring Execution. Load the corresponding rules, perform automated refactoring (such as hierarchy flattening) on ​​the layout code, and perform syntax validation. If the validation passes, proceed to S17. If the validation fails, add the failed rule to a temporary blacklist and proceed to S15B.

[0172] S15B: Generate optimization suggestions. Generate text descriptions, modification suggestions, and code examples for the problem, and mark it as requiring manual intervention.

[0173] S16: User Decision. Show the user the optimization suggestions. If the user adopts them and modifies the code, proceed to S17. If the user abandons the optimization, jump to output C, terminate the process, and output the optimization suggestion report.

[0174] S17: Increment the iteration round. Increment the iteration round by 1, along with the updated context.

[0175] S18: Return to iteration entry point. After step S17 is completed, the system returns the optimized layout code to step S4 (save version snapshot) in step S18 to start a new round of quality assessment and optimization process.

[0176] It should be noted that in the new iteration, step S3 (A2UI generates the initial layout) is skipped, and the refactoring code output by the optimization module is used directly to enter step S4. The iterative cycle continues until the termination condition is met in step S5, S9a, S10, S11, S12b or S16.

[0177] The following example uses the layout code for generating a product details page to illustrate the concept.

[0178] After the user inputs a natural language description of their requirement to "create a product details page, including a product image carousel, name, price, specifications selector, and a purchase button," the system calls the A2UI engine to receive the user input and generate the initial layout code.

[0179] The initial code is inspected by the system's built-in analysis engine. The engine quantifies and scores the code from multiple dimensions such as structure, performance, adaptation, and standards, and generates a list of issues, such as excessively deep layout layers, unnecessary container nesting, non-compliance with design specifications in some spacing, or text truncation on certain screen sizes.

[0180] When the score fails to meet the preset passing standard, the system initiates an iterative optimization process. The control module determines whether to continue optimization or meet the termination conditions based on the current score, historical iteration count, and snapshot records. If continued optimization is deemed necessary, the categorized and sorted list of issues is passed to the optimization module for processing.

[0181] The optimization module automatically fixes issues based on preset strategies. For issues governed by optimization rules, such as removing redundant layout containers, converting nested structures to more efficient layouts, or adjusting spacing to specified values, the system automatically applies the corresponding rules and generates refactored code. For complex or high-risk issues, the system generates suggested modifications for user reference.

[0182] After each round of optimization, the system re-analyzes and scores the newly generated code. Through optimization iterations, the quality score of the layout code improves from unsatisfactory to exceeding the acceptable quality score threshold. At this point, the control module automatically terminates the iteration and outputs the final optimized layout code and optimization report.

[0183] In summary, the technical solutions provided by the embodiments of this application have at least the following beneficial effects: 1. Improve layout generation accuracy. The system iteratively optimizes and gradually corrects layout deviations. For example, if the initial layout has excessively deep layers due to improper avatar cropping, the system can automatically identify this and use better attribute settings to improve the layout restoration effect.

[0184] 2. Optimize code performance. The system identifies performance bottlenecks such as rendering time through dynamic testing and automatically refactors the code, such as using more efficient layout containers, thereby improving the smoothness of the generated code.

[0185] 3. Enhance cross-platform adaptability. The system conducts adaptation tests by simulating multi-screen environments and automatically adjusts layout attributes according to the design specifications of different platforms to ensure consistent performance on different devices.

[0186] 4. Improve development efficiency. The system transforms the previously manual debugging process into automated iterative optimization, significantly reducing layout debugging time and allowing developers to focus more on business logic, thereby improving overall development efficiency.

[0187] This application also provides a code optimization system, such as... Figure 6 As shown, the code optimization system 100 includes: Acquisition unit 110 is used to acquire the initial code generated based on natural language description; Optimization unit 120 is used to perform at least one round of iterative optimization on the initial code; The optimization unit is used to perform the following operations during the current iteration: Perform a quality assessment on the current code to obtain the code quality score and a list of issues for the current round; Based on the code quality score and issue list of the current round, update the iteration context and determine whether the iteration termination condition is met. The iteration context is used to record the set of failed optimization rules that failed to execute or caused rollback in each iteration. When the iteration termination condition is met, the optimal code version is output from the historical code versions, which include the version corresponding to the initial code and / or the code versions generated in each iteration; If the iteration termination condition is not met, the current code is optimized based on the problem list, the optimization rule base, and the updated iteration context to obtain optimized code.

[0188] In some embodiments, the initial code is user interface layout code, and the optimization unit 120 is used to: The user interface layout code is evaluated across multiple analytical dimensions to obtain evaluation index values ​​for each analytical dimension. These multiple analytical dimensions include at least two of the following: static structure dimension, dynamic rendering dimension, device adaptation dimension, and design specification dimension. Based on the evaluation index values ​​of the multiple analysis dimensions, a code quality score and a list of issues for the current round are generated.

[0189] In some embodiments, the static structure dimension includes an evaluation of at least one of the following metrics: the layout hierarchy depth of the user interface layout code, component redundancy, nesting relationship of container components, and reasonableness of container type; And / or, the dynamic rendering dimension includes loading layout code in a simulated runtime environment and evaluating at least one of the following runtime performance metrics: rendering performance of the user interface layout code, GPU overdraw level, and frame rate stability; And / or, the device adaptation dimension includes an evaluation of at least one of the following metrics on a predefined device configuration: whether a component goes out of bounds, whether adjacent components overlap unexpectedly, whether text content is truncated, and whether image display is distorted. And / or, the design specification dimension includes a compliance check for at least one of the following specifications: component spacing, font attributes, color contrast, and interactive component size.

[0190] In some embodiments, the optimization unit 120 is used to: For each problem in the problem list, based on the problem's type, severity, the optimization rule base, and the set of failure optimization rules recorded in the iteration context, it is determined whether to perform automated refactoring on the problem. To address the issue of determining and executing automated refactoring, the code segments in the current code related to the issue are refactored according to the optimization rules in the optimization rule base that correspond to the issue. For issues such as determining whether to not perform automated refactoring or refactoring failure, generate and output optimization suggestions for the aforementioned issues; The optimized code is obtained based on the refactored code segment and / or the code segment modified according to the optimization suggestions.

[0191] In some embodiments, the optimization unit 120 determines whether to perform automated refactoring on the problem based on at least two of the following conditions: First condition: The optimization rule base contains optimization rules corresponding to the type of the problem; Second condition: The severity level of the problem falls within the preset range of levels that allow for automatic repair; Third condition: The optimization rule corresponding to the type of problem is not recorded in the failure optimization rule set of the iteration context; Fourth condition: The risk of executing the optimization rule is estimated to be controllable. The execution risk of the optimization rule is determined based on the number of components affected by the historical success rate of the rule and the scope of potential related impacts.

[0192] In some embodiments, the optimization unit 120 is used to: Locate the node related to the problem in the abstract syntax tree of the current code; According to the optimization rules in the optimization rule base corresponding to the problem, a transformation operation is performed on the located node, and the associated nodes of the node are updated. The transformation operation includes at least one of the following: node deletion, node insertion, node replacement, attribute modification, node movement, and structure reorganization. Based on the updated node and its associated nodes, the code segment is reconstructed, and the reconstructed code segment is subjected to syntax validation. When an exception occurs or syntax validation fails during the refactoring process, the optimization rule used in this instance is recorded in the failure optimization rule set of the iteration context.

[0193] In some embodiments, the optimization unit 120 is used to: For issues where automated refactoring is not performed or where refactoring fails, an AI model is invoked to generate and output optimization suggestions for the issues. These optimization suggestions include an analysis of the causes of the issues, a textual description of the modification plan, and / or code modification examples.

[0194] In some embodiments, the iteration termination condition includes at least one of the following: The code quality score for the current round has reached or exceeded the preset quality threshold. The current iteration round has reached the preset maximum number of iterations; The current code is detected to be identical to historical code recorded in previous iterations; A series of rollbacks occur, and the number of rollbacks reaches a preset threshold. The convergence condition was determined based on the trend of quality score changes in recent consecutive iterations.

[0195] In some embodiments, the optimization unit 120 is further configured to: After updating the iteration context, if the code quality score of the current round is lower than the quality score of the previous round, a rollback is determined to occur. When a rollback occurs, the current code is restored to the code of the previous iteration, and the optimization rule that caused this rollback is recorded in the failure optimization rule set of the iteration context.

[0196] In some examples, the optimization unit may include an analysis engine, an optimization module, and an iteration control module.

[0197] The code optimization system provided in this application belongs to the same concept as the code optimization method provided in the above embodiments of this application. It can execute the code optimization method provided in any of the above embodiments of this application and has the corresponding functional modules and beneficial effects for executing the code optimization method. Technical details not described in detail in this embodiment can be found in the specific implementation of the code optimization method provided in the above embodiments of this application, and will not be repeated here.

[0198] This application also provides a terminal device, including a processor and instructions for calling instructions to cause the electronic device to implement the code optimization method provided in any of the foregoing embodiments.

[0199] This application also provides a storage medium, including an executable program stored thereon, wherein when the executable program is executed by a processor, it implements the steps of the code optimization method provided in any of the foregoing embodiments.

[0200] For ease of understanding, the following focuses on explaining the terminology used in this embodiment: In this application embodiment, the processor is a circuit with signal processing capabilities. In one implementation, the processor can be a circuit with instruction read and execute capabilities, such as a Central Processing Unit (CPU), a microprocessor, a Graphics Processing Unit (GPU) (which can be understood as a type of microprocessor), or a Digital Signal Processor (DSP). In another implementation, the processor can implement certain functions through the logical relationships of hardware circuits. The logical relationships of the aforementioned hardware circuits are fixed or reconstructable. For example, the processor is a hardware circuit implemented using an Application-Specific Integrated Circuit (ASIC) or a Programmable Logic Device (PLD), such as an FPGA. In a reconstructable hardware circuit, the processor loads a configuration document, implementing a cyclical process of hardware circuit configuration. This can be understood as the processor loading instructions to implement the functions of some or all of the above units or modules in a cyclical process. In addition, it can also be a hardware circuit designed for artificial intelligence, which can be understood as an ASIC, such as a Neural Network Processing Unit (NPU), a Tensor Processing Unit (TPU), a Deep Learning Processing Unit (DPU), etc.

[0201] The computer-readable storage medium provided in this embodiment can execute the code optimization method of the above embodiment. Its implementation principle and technical effect are similar to those of the above embodiment, and will not be repeated here.

[0202] The aforementioned computer-readable storage medium can be implemented by any type of volatile or non-volatile storage device or a combination thereof, such as static random access memory (SRAM), electrically erasable programmable read-only memory (EEPROM), erasable programmable read-only memory (EPROM), programmable read-only memory (PROM), read-only memory (ROM), magnetic storage, flash memory, magnetic disk, or optical disk. The readable storage medium can be any available medium accessible to a general-purpose or special-purpose computer.

[0203] An exemplary readable storage medium is coupled to a processor, enabling the processor to read information from and write information to the readable storage medium. Of course, the readable storage medium can also be a component of the processor. The processor and the readable storage medium can reside in an Application Specific Integrated Circuit (ASIC). Alternatively, the processor and the readable storage medium can exist as discrete components in an electronic device or a host device.

[0204] Those skilled in the art will understand that all or part of the steps of the above-described method embodiments can be implemented by hardware related to program instructions. The aforementioned program can be stored in a computer-readable storage medium. When executed, the program performs the steps of the above-described method embodiments; and the aforementioned storage medium includes various media capable of storing program code, such as ROM, RAM, magnetic disks, or optical disks.

[0205] The various embodiments or implementation methods described in this specification are presented in a progressive manner. Each embodiment focuses on the differences from other embodiments, and the same or similar parts between the embodiments can be referred to each other.

[0206] In the description of this specification, references to "one embodiment," "some embodiments," "illustrative embodiment," "example," "specific example," or "some examples," etc., indicate that a specific feature, structure, material, or characteristic described in connection with an embodiment or example is included in at least one embodiment or example of this application. In this specification, the illustrative expressions of the above terms do not necessarily refer to the same embodiment or example. Furthermore, the specific features, structures, materials, or characteristics described may be combined in any suitable manner in one or more embodiments or examples.

[0207] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of this application, and are not intended to limit them. Although this application has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some or all of the technical features therein. Such modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the scope of the technical solutions of the embodiments of this application.

Claims

1. A code optimization method, characterized in that, The method includes: Obtain the initial code generated based on the natural language description; Perform at least one round of iterative optimization on the initial code, wherein the current round of iteration includes: Perform a quality assessment on the current code to obtain the code quality score and a list of issues for the current round; Based on the code quality score and issue list of the current round, update the iteration context and determine whether the iteration termination condition is met. The iteration context is used to record the set of failed optimization rules that failed to execute or caused rollback in each iteration. When the iteration termination condition is met, the optimal code version is output from the historical code versions, which include the version corresponding to the initial code and / or the code versions generated in each iteration; If the iteration termination condition is not met, the current code is optimized based on the problem list, the optimization rule base, and the updated iteration context to obtain optimized code for use in the next iteration optimization.

2. The code optimization method according to claim 1, characterized in that, The initial code is the user interface layout code. The quality assessment of the current code yields a code quality score and a list of issues for the current round, including: The user interface layout code is evaluated across multiple analytical dimensions to obtain evaluation index values ​​for each analytical dimension. These multiple analytical dimensions include at least two of the following: static structure dimension, dynamic rendering dimension, device adaptation dimension, and design specification dimension. Based on the evaluation index values ​​of the multiple analysis dimensions, a code quality score and a list of issues for the current round are generated.

3. The code optimization method according to claim 2, characterized in that, The static structure dimension includes an evaluation of at least one of the following metrics: the layout hierarchy depth of the user interface layout code, component redundancy, nesting relationship of container components, and rationality of container type; And / or, the dynamic rendering dimension includes loading layout code in a simulated runtime environment and evaluating at least one of the following runtime performance metrics: rendering performance of the user interface layout code, GPU overdraw level, and frame rate stability; And / or, the device adaptation dimension includes an evaluation of at least one of the following metrics on a predefined device configuration: whether a component goes out of bounds, whether adjacent components overlap unexpectedly, whether text content is truncated, and whether image display is distorted. And / or, the design specification dimension includes a compliance check for at least one of the following specifications: component spacing, font attributes, color contrast, and interactive component size.

4. The code optimization method according to any one of claims 1 to 3, characterized in that, If the iteration termination condition is not met, optimization processing is performed on the current code based on the problem list, optimization rule base, and updated iteration context to obtain optimized code, including: For each problem in the problem list, based on the problem's type, severity, the optimization rule base, and the set of failure optimization rules recorded in the iteration context, it is determined whether to perform automated refactoring on the problem. To address the issue of determining and executing automated refactoring, the code segments in the current code related to the issue are refactored according to the optimization rules in the optimization rule base that correspond to the issue. For issues such as determining whether to not perform automated refactoring or refactoring failure, generate and output optimization suggestions for the aforementioned issues; The optimized code is obtained based on the refactored code segment and / or the code segment modified according to the optimization suggestions.

5. The code optimization method according to claim 4, characterized in that, If the problem meets all of the following conditions, it is determined that an automated refactoring should be performed on the problem: First condition: The optimization rule base contains optimization rules corresponding to the type of the problem; Second condition: The severity level of the problem falls within the preset range of levels that allow for automatic repair; Third condition: The optimization rule corresponding to the type of problem is not recorded in the failure optimization rule set of the iteration context; Fourth condition: The risk of executing the optimization rule is estimated to be controllable. The execution risk of the optimization rule is determined based on the number of components affected by the historical success rate of the rule and the scope of potential related impacts.

6. The code optimization method according to claim 4, characterized in that, To address the issue of determining whether to perform automated refactoring, based on the optimization rules in the optimization rule base corresponding to the issue, the code segments in the current code related to the issue are refactored, including: Locate the node related to the problem in the abstract syntax tree of the current code; According to the optimization rules in the optimization rule base corresponding to the problem, a transformation operation is performed on the located node, and the associated nodes of the node are updated. The transformation operation includes at least one of the following: node deletion, node insertion, node replacement, attribute modification, node movement, and structure reorganization. Based on the updated nodes and associated nodes, the code segment is reconstructed, and the reconstructed code segment is subjected to syntax validation. When an exception occurs or syntax validation fails during the refactoring process, the optimization rule used in this instance is recorded in the failure optimization rule set of the iteration context.

7. The code optimization method according to claim 4, characterized in that, For issues related to determining whether to not perform automated refactoring or whether refactoring fails, optimization suggestions are generated and output, including: For issues where automated refactoring is not performed or where refactoring fails, an AI model is invoked to generate and output optimization suggestions for the issues. These optimization suggestions include an analysis of the causes of the issues, a textual description of the modification plan, and / or code modification examples.

8. The code optimization method according to claim 1, characterized in that, The iteration termination condition includes at least one of the following: The code quality score for the current round has reached or exceeded the preset quality threshold. The current iteration round has reached the preset maximum number of iterations; The current code is detected to be identical to historical code recorded in previous iterations; A series of rollbacks occur, and the number of rollbacks reaches a preset threshold. The convergence condition was determined based on the trend of quality score changes in recent consecutive iterations.

9. The code optimization method according to claim 1, characterized in that, The method further includes: After updating the iteration context, if the code quality score of the current round is lower than the quality score of the previous round, a rollback is determined to occur. When a rollback occurs, the current code is restored to the code of the previous iteration, and the optimization rule that caused this rollback is recorded in the failure optimization rule set of the iteration context.

10. A code optimization system, characterized in that, The system includes: The acquisition unit is used to acquire the initial code generated based on the natural language description. An optimization unit is configured to perform at least one round of iterative optimization on the initial code; The optimization unit is used to perform the following operations during the current iteration: Perform a quality assessment on the current code to obtain the code quality score and a list of issues for the current round; Based on the code quality score and issue list of the current round, update the iteration context and determine whether the iteration termination condition is met. The iteration context is used to record the set of failed optimization rules that failed to execute or caused rollback in each iteration. When the iteration termination condition is met, the optimal code version is output from the historical code versions, which include the version corresponding to the initial code and / or the code versions generated in each iteration; If the iteration termination condition is not met, the current code is optimized based on the problem list, the optimization rule base, and the updated iteration context to obtain optimized code.

11. An electronic device, characterized in that, Includes a processor, the processor being configured to invoke instructions to cause the electronic device to execute the code optimization method as described in any one of claims 1 to 9.