A method, apparatus, and related product for code detection
By automating the detection of memory leaks, global variables, cookies, and compatibility issues in code through the ESLint plugin, the problem of low accuracy in manual detection is solved, achieving more efficient and accurate code detection and repair.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- TENCENT TECHNOLOGY (SHENZHEN) CO LTD
- Filing Date
- 2025-01-08
- Publication Date
- 2026-07-10
AI Technical Summary
Current code inspection technologies rely on manual inspection, which is easily affected by subjective factors, resulting in low accuracy. Furthermore, the technology is prone to fatigue and errors when faced with a large amount of repetitive work.
Using pre-configured detection rules from the ESLint plugin, it automatically detects memory leaks, global variables, cookies, and code compatibility issues in the code, generating error reports to improve accuracy.
Automated detection reduces subjective and fatigue-related errors in human detection, improves the accuracy and efficiency of code detection, promptly identifies and fixes compatibility and security issues, and reduces project risks and maintenance costs.
Smart Images

Figure CN122364041A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of computer technology, and in particular to a method, apparatus and related products for code detection. Background Technology
[0002] With the development of technology, code applications have permeated almost every aspect of modern society, from everyday mobile applications to the financial systems supporting the global economy, and extending to fields such as healthcare, education, and entertainment. Therefore, ensuring the proper functioning of code is crucial. Real-time code inspection is necessary for this, but current solutions primarily rely on manual inspection to guarantee code quality and compatibility. However, manual inspection is susceptible to subjective factors, which may lead to overlooked or misjudged issues. Furthermore, manual inspectors are prone to fatigue when faced with repetitive tasks, increasing the error rate. In short, manual inspection may result in lower code inspection accuracy. Summary of the Invention
[0003] This application provides a method, apparatus, and related products for code detection, aiming to improve the accuracy of code detection results.
[0004] The first aspect of this application provides a method for code detection, including:
[0005] Obtain the code to be detected;
[0006] Determine the detection requirements for the code to be detected; the detection requirements include at least one of memory leak detection, global variable detection, cookie detection, and code compatibility detection.
[0007] Determine the detection rules that match the detection requirements from the configured rules of the ESLint plugin;
[0008] The code to be detected is tested based on the detection rules to determine the detection result; the detection result is a first result or a second result; the first result indicates that the code to be detected is correct; the second result indicates that there is an error in the code to be detected; the second result includes an error report, and the error report records the error type.
[0009] A second aspect of this application provides a code detection apparatus, comprising:
[0010] The acquisition unit is used to acquire the code to be detected;
[0011] The requirement unit is used to determine the detection requirements of the code to be detected; the detection requirements include at least one of memory leak detection, global variable detection, cookie detection, and code compatibility detection.
[0012] A matching unit is used to determine, from the configured rules of the ESLint plugin, a detection rule that matches the detection requirement;
[0013] A detection unit is used to detect the code to be detected based on the detection rules and determine the detection result; the detection result is a first result or a second result; the first result indicates that the code to be detected is correct; the second result indicates that there is an error in the code to be detected; the second result includes an error report, and the error report records the error type.
[0014] A third aspect of this application provides a computer device, the device comprising a processor and a memory:
[0015] The memory is used to store computer programs and to transfer the computer programs to the processor;
[0016] The processor is configured to execute the steps of the code detection method provided in the first aspect according to the instructions in the computer program.
[0017] A fourth aspect of this application provides a computer-readable storage medium for storing a computer program that, when executed, implements the steps of the code detection method provided in the first aspect.
[0018] The fifth aspect of this application provides a computer program product, including a computer program that, when executed, implements the steps of the code detection method provided in the first aspect.
[0019] As can be seen from the above technical solutions, the embodiments of this application have the following advantages:
[0020] The technical solution of this application first obtains the code to be tested and determines the testing requirements for the code. For any testing requirement among memory leak detection, global variable detection, cookie detection, and code compatibility detection, since the ESLint plugin is pre-configured with testing rules matching various testing requirements, the testing step that meets the testing requirements can be implemented by determining the testing rule matching the testing requirements from the ESLint plugin. Finally, the code to be tested is tested based on the testing rules to determine the testing result. The testing result of this application has two possibilities: a first result or a second result. A first result indicates that the code to be tested is correct; a second result indicates that there is an error in the code to be tested, and the second result includes an error report. Based on the pre-configured testing rules of the ESLint plugin, this application uses the ESLint plugin to replace manual code testing, enabling global variable detection, cookie detection, memory leak detection, and code compatibility testing. When any of the above problems are found in the code, the ESLint plugin can directly generate an error report, avoiding the low accuracy that may be caused by manual testing, thereby improving the accuracy of code testing. Attached Figure Description
[0021] Figure 1 A flowchart illustrating a code detection method provided in this application embodiment;
[0022] Figure 2 This is a schematic diagram of the detection process provided in an embodiment of this application;
[0023] Figure 3 A flowchart illustrating the workflow of the ESLint plugin provided in this application embodiment;
[0024] Figure 4 This is a schematic diagram of the structure of the code detection device provided in the embodiments of this application;
[0025] Figure 5 A schematic diagram of a server structure provided in an embodiment of this application;
[0026] Figure 6 This is a schematic diagram of a terminal device structure provided in an embodiment of this application. Detailed Implementation
[0027] In terms of code inspection, current technologies mainly rely on manual inspection. However, manual inspection has many uncertainties, such as strong subjective factors and fatigue, which may lead to low accuracy in code inspection.
[0028] In view of the above problems, this application provides a method, apparatus, and related products for code inspection. The technical solution provided in this application utilizes pre-configured detection rules for the ESLint plugin to replace manual code inspection, enabling global variable detection, cookie detection, memory leak detection, and code compatibility detection. When any of the above-mentioned problems are detected in the code, the ESLint plugin can directly generate an error report, avoiding the low accuracy that may result from manual inspection, thereby improving the accuracy of code inspection.
[0029] First, we will explain several terms that may be involved in the embodiments of this application below.
[0030] Cookie: A small text file stored in a user's browser to store user preferences, session information, or other data specific to a website.
[0031] Variable declaration statement: A syntax structure in a programming language used to define variables. It reminds the compiler or interpreter to allocate storage space for a certain identifier in the program and specifies the data type of that storage space.
[0032] Assignment expression: In programming languages, this is an operation used to assign a value to a variable. It typically involves an assignment operator (most commonly the equals sign =), where the left side is a variable and the right side is an expression. The value of the expression is evaluated and stored in the variable on the left side.
[0033] Global variables: Variables that are accessible throughout the entire program, meaning that the variable can be read and modified from anywhere in the program.
[0034] Variable Declaration Node: A node type in the Abstract Syntax Tree (AST) of a programming language, used to represent variable declaration statements. In a compiler or interpreter, source code is parsed into an AST, a tree-structured data representation that reflects the syntactic structure of the program. Each node represents a construction in the source code, and the VariableDeclaration node specifically corresponds to a variable declaration.
[0035] Function Expression Node: A node type in the Abstract Syntax Tree (AST) used to represent anonymous functions or named function expressions. In programming languages, a function expression is a way to define a function that can be assigned to a variable, passed as an argument to another function, or executed immediately.
[0036] Delayed execution function (setTimeout): A built-in function in JavaScript that executes a given block of code or function once after a specified delay.
[0037] Member Expression Node: A node type in AST used to represent member access expressions. A member access expression is an expression that uses dot notation or square bracket notation to access an object's properties or method calls.
[0038] `var`: One of the keywords in JavaScript used to declare variables. It has function scope (inside a function) or global scope (outside a function), and supports variable hoisting.
[0039] External variables: These are variables defined outside a specific code block (such as a function, class, or module) that can be shared and accessed by multiple code blocks throughout the file or program.
[0040] Scope: Defines the valid scope of a variable, function, or other identifier, that is, where the variable, function, or other identifier can be accessed.
[0041] CallExpression: A node type in the Abstract Syntax Tree (AST) used to represent expressions that indicate function or method calls. When the parser encounters a function call, it creates a CallExpression node to represent the call operation. This node typically contains information about the function or method being called and the parameters passed to that node.
[0042] The document query selector (document.querySelector) is a JavaScript method used to select a specific element in a document. It returns the first element that matches the provided CSS selector string. If no element matches, it returns null.
[0043] ESLint plugin: An AST-based JavaScript code inspection tool that can check the syntax, style, and errors of code during the coding process, helping developers write more standardized and readable code.
[0044] AST: Abstract Syntax Tree, a tree-like data structure that describes the structure of code, making it easy to analyze and manipulate code.
[0045] The execution subject of the code detection method provided in this application embodiment can be a terminal device. As examples, the terminal device may include, but is not limited to, mobile phones, desktop computers, tablet computers, laptops, PDAs, smart voice interaction devices, smart home appliances, vehicle terminals, and aircraft. The execution subject of the code detection method provided in this application embodiment can also be a server; that is, an ESLint plugin can be installed on the server to check the code. The method provided in this application embodiment can also be executed collaboratively by a terminal device and a server. Therefore, this application embodiment does not limit the implementation subject of the technical solution of this application.
[0046] A server can be a standalone physical server, a server cluster consisting of multiple physical servers, or a distributed system. Furthermore, a server can also be a cloud server providing basic cloud computing services such as cloud services, cloud databases, cloud computing, cloud functions, cloud storage, network services, cloud communication, middleware services, domain name services, security services, CDN, and big data and artificial intelligence platforms.
[0047] Figure 1 This is a flowchart illustrating a code detection method provided in an embodiment of this application. Figure 1 One code detection method shown includes:
[0048] S101: Obtain the code to be detected.
[0049] The code to be detected can be complete or partial.
[0050] S102: Determine the detection requirements for the code to be detected.
[0051] After obtaining the code to be tested, the testing requirements of the code can be determined according to the user's needs. The testing requirements involved in this application are mainly memory leak detection, global variable detection, cookie detection, and code compatibility detection.
[0052] If there are multiple detection requirements, such as the code needing both memory leak detection and global variable detection, you can choose to run the ESLint plugin once or twice. If you choose to run the ESLint plugin once, the detection rules will correspond to both items. After one item is detected, the other item will be detected. If both are found to have problems, the output error report will include the error types corresponding to memory leak detection and global variable detection. If you choose to run the ESLint plugin twice, memory leak detection and global variable detection will be performed separately. If both are found to have problems, the error reports corresponding to memory leak detection and global variable detection will be output separately. Because the four detection requirements involved in this application are relatively independent, each detection requirement can be run independently. If there are three or four detection requirements, you can also choose to run them once or multiple times, the difference being the number of detection results.
[0053] Figure 2 This is a schematic diagram of the detection provided in the embodiments of this application, such as... Figure 2 As shown, the code is written first, and then the code is checked for compatibility, global variables, cookies, and memory leaks in sequence. Figure 2 The detection order shown is an example of a detection order. In actual applications, other orders can also be used for detection, as long as the detection requirements of the code are met. This application does not limit the detection order of various detection requirements.
[0054] After clarifying the detection requirements for the code to be detected, proceed to S103.
[0055] S103: Determine the detection rules that match the detection requirements from the configured rules of the ESLint plugin.
[0056] This application assumes that the ESLint plugin is already installed on the server or terminal device and that detection rules have been configured for the ESLint plugin.
[0057] If the ESLint plugin is not installed on the server or terminal device, you will need to install the ESLint plugin on the server or terminal device and configure the detection rules for the ESLint plugin before using S103.
[0058] Once the testing rules are determined, proceed to S104.
[0059] S104: Detect the code to be detected based on the detection rules and determine the detection result.
[0060] The ESLint plugin's detection rules are used to inspect the code, potentially producing two results: one indicating the code is error-free and can run normally; the other indicating errors and prevents normal operation. For clarity, these results will be referred to as the first result and the second result. A first result indicates the code is correct; a second result indicates errors, and the ESLint plugin will output an error report. Therefore, the second result includes the error report, which records the error type.
[0061] If the detection result is the second result, in this embodiment of the application, the code to be detected can be further modified based on the error type recorded in the error report. Developers can directly modify the code according to the error category recorded in the error report, which improves the efficiency of code correction.
[0062] In summary, S104 of this application mainly describes the application process of the detection rules in the ESLint plugin. The specific application process of the detection rules in the ESLint plugin in this application will now be explained in detail, i.e., the specific process of S104:
[0063] Figure 3 The flowchart of the ESLint plugin provided in the embodiments of this application is as follows: Figure 3 The operation of the ESLint plugin can be divided into the following steps:
[0064] Code parsing: The ESLint plugin uses a parser (such as Acorn or Babel) to parse the code into an AST.
[0065] Configuration Rules: The ESLint plugin uses a set of configuration rules to inspect code. These rules define the syntax and style the code should follow, such as which indentation style to use and whether global variables are allowed. Developers can configure these rules according to their needs.
[0066] Traversing the AST: The ESLint plugin traverses the AST, examining each node. For each node, the ESLint plugin checks for any violations of the configuration rules, and if any are found, reports an error or warning.
[0067] Output: The ESLint plugin outputs the inspection results and determines whether to automatically fix issues based on the configured rules. Developers can modify the code based on the inspection results, thereby improving code quality and maintainability.
[0068] In summary, the ESLint plugin works based on the Abstract Syntax Tree (AST). It checks and repairs code by parsing the code, configuring rules, traversing the AST, and outputting results, thereby helping developers write more standardized and readable code.
[0069] Therefore, before using detection rules to detect code, it is first necessary to use the ESLint plugin to parse the code to be detected and obtain the abstract syntax tree corresponding to the code to be detected.
[0070] Then, each node of the abstract syntax tree is tested using detection rules that match the detection requirements to determine the detection result of the code to be detected.
[0071] The detection rules involved in this application mainly include memory leak detection rules, global variable detection rules, cookie detection rules, and code compatibility detection rules. Other detection rules can also be configured for the ESLint plugin according to the specific detection requirements.
[0072] Because the ESLint plugin contains various detection rules, each corresponding to a specific detection requirement, it is necessary to determine the code's detection requirements before using the ESLint plugin to perform code checks. Then, the detection rules within the ESLint plugin that match these requirements are used to check the code. This application uses the specific application and practical application of four detection rules as examples to explain the detection process in detail:
[0073] The global variable detection rule will now be explained in detail, taking its specific application and practical use as examples.
[0074] The specific application of global variable detection rules is as follows:
[0075] If the detection requirement is for global variables, then the global variable detection rules are used to determine whether multiple nodes in the abstract syntax tree satisfy any one of the global variable error conditions, thus obtaining the first judgment result. The global variable error conditions include a first condition and a second condition; the first condition is for global variable error judgment regarding variable declaration statements; the second condition is for global variable error judgment regarding assignment expressions.
[0076] The first condition specifically requires that multiple nodes in the abstract syntax tree contain variable declaration statements, and the initialization expression of the variable declaration node conforms to the first preset object name; the second condition specifically requires that multiple nodes in the abstract syntax tree contain assignment expressions, the left-hand side expression of the assignment expression node conforms to the first preset object name, and the property name of the left-hand side expression of the assignment expression node is a global variable. The first preset object name includes `window`.
[0077] If the first judgment result is yes, then the detection result is determined to be the second result, and the error report of the code to be detected is recorded as a global variable error.
[0078] If the first judgment result is negative, then the test result is determined to be the first result.
[0079] For cases where the detection requirement is global variable detection, this application performs global variable detection on the code from both variable declaration statements and assignment expressions, based on the global variable detection rules configured in the ESLint plugin. This is primarily because detecting global variables from both declaration and assignment expressions ensures comprehensive capture of all possible scenarios where variables could become global. This helps identify all potential global variable definitions and their initial assignment locations, thereby better managing and controlling the global namespace and avoiding unnecessary pollution or conflicts. The specific reasons are as follows:
[0080] Explicit global variable declarations: By examining variable declaration statements (such as var, let, or const in JavaScript), you can find variables that are explicitly declared as being in the global scope. This includes variables declared in the global context (e.g., in top-level code), as well as any global variables implicitly created within a function body when strict mode is not used.
[0081] Preventing Accidental Global Variables: Some programming languages may automatically hoist local variables to the global scope when developers forget to declare them using keywords such as `var`, `let`, or `const`. Analyzing variable declaration statements can help identify and warn of such errors, reducing the risk of accidentally creating global variables.
[0082] Catching undeclared global variables: Developers might directly assign a value to an identifier that hasn't been declared yet, especially when strict mode isn't enabled. This type of operation implicitly creates a global variable. By analyzing the assignment expression, these instances of undeclared but assigned global variables can be captured.
[0083] Variable initialization: Understanding when and how variables are first assigned a value is crucial for understanding program behavior. Even if a variable is declared in the global scope, knowing this can help to more accurately assess its impact if its initial assignment occurs in a different place (such as inside a function).
[0084] Dynamic property setting: In some cases, code may dynamically add new properties to an object, and these properties can be considered a kind of "global state." Such behavior can be detected by inspecting assignment expressions, allowing you to determine if further review is necessary.
[0085] In short, combining the analysis of variable declaration statements and assignment expressions provides a more complete and accurate detection of global variables. This is especially important for static code analysis tools (such as ESLint), as the goal of this detection is to help developers write clearer, safer, and more maintainable code. In this way, not only can existing global variables be identified, but potential future problems can also be prevented, ensuring the quality and stability of the codebase.
[0086] This application also provides a practical application of global variable detection rules, as follows:
[0087] This plugin defines arrays of global variables and methods, checks assignment expressions and variable declaration statements, verifies whether global variables or methods have been added to the code, and disables the ability to assign variables to the window object. The core idea of the plugin is to improve code maintainability and readability by checking assignment expressions and variable declaration statements in the code to prevent variables from being assigned to the window object and to avoid adding unnecessary global variables and methods.
[0088] First, define an array `windowArr`; `windowArr` is used to store all global variables and methods, and all global variables and methods stored in `windowArr` can be accessed in the `window` object.
[0089] Next, define an ESLint plugin that exports a function via `module.exports`, which takes a `context` parameter. This function returns an object containing two methods: `AssignmentExpression` and `VariableDeclarator`. The code is as follows:
[0090]
[0091] In the `AssignmentExpression` method, it first checks if the current node is an assignment expression. If so, it further checks if the object name of the expression on the left is `window`. If so, it checks if the property name of the expression on the left is a global variable or method. If the property name is not in the `objectInWindow` array, it uses the `context.report()` method to report an error. The specific code is as follows:
[0092]
[0093] In the `VariableDeclarator` method, check if the current node is a variable declaration statement and if the variable's initialization expression is `window`. If so, use the `context.report()` method to report the error. The specific code is as follows:
[0094]
[0095] The purpose of global variable detection rules is to check whether global variables or methods have been added in the code, and to prevent variables from pointing to the `window` object.
[0096] In short, the global variable detection rules are the ESLint plugin's real-time monitoring of the definition and usage of global variables in the code. It automatically flags and prompts developers, suggesting the use of safer variable scopes.
[0097] The following section will explain the cookie detection rules in detail, taking their specific and practical applications as examples.
[0098] The specific application of cookie detection rules is as follows:
[0099] If the detection requirement is cookie detection, then the cookie detection rules are used to determine whether each node in the abstract syntax tree meets the cookie error conditions, and a second judgment result is obtained.
[0100] Cookie error conditions include: multiple nodes in the abstract syntax tree contain assignment expressions; the left-hand side expression of the assignment expression node matches the second preset object name; the left-hand side expression of the assignment expression node has the attribute name "cookie"; and the current domain of the node with the attribute name "cookie" in the left-hand side expression of the assignment expression node is located in a preset data group. The preset data group is used to store subdomains that cannot have global cookies set. The second preset object name includes "document".
[0101] If the second judgment result is yes, then the detection result is determined to be the second result, and the error report of the code to be detected is recorded as a cookie setting error.
[0102] If the second judgment result is negative, then the detection result is determined to be the first result.
[0103] For cases where the detection requirement is cookie detection, this application uses the assignment expressions in the code as the detection target, combined with the cookie detection rules configured in the ESLint plugin, to complete the cookie detection. This is mainly because cookies are usually set through specific HTTP response headers (Set-Cookie) or operations in JavaScript. In client-side JavaScript, the creation, modification, and deletion of cookies are all achieved by assigning values to the document.cookie property. Therefore, analyzing the assignment expressions can help identify all operations that may affect cookies. The specific reasons are as follows:
[0104] Identifying cookie creation and modification: Creating a new cookie: When a developer sets a cookie for the first time, they define the cookie's name, value, and other attributes (such as expiration time, path, etc.) by assigning a string to document.cookie.
[0105] Discovering potential security risks: By checking whether the assignment expression contains the Secure flag, it can be determined whether cookies are sent only over HTTPS connections, thereby assessing whether there is a risk of insecure data transmission.
[0106] Cross-Site Scripting (XSS): If a cookie does not have the HttpOnly flag set, it can be accessed via JavaScript, increasing the likelihood of an XSS attack. By examining assignment expressions, it's possible to identify which cookies might be vulnerable to this type of attack.
[0107] Missing `samesite` attribute: Modern browsers recommend using the `samesite` attribute to restrict cookie behavior in cross-site requests to prevent CSRF (Cross-Site Request Forgery) attacks. Examining the assignment expression can help identify which cookies are missing this important attribute.
[0108] Conditional settings: Sometimes cookie settings depend on certain conditions or logical branches. By analyzing assignment expressions, we can understand under what circumstances a specific cookie will be created or modified, helping to better understand the program's behavior.
[0109] Setting cookies within function calls: If the cookie setting occurs inside a function, the specific call point can be located by detecting the assignment expression, ensuring comprehensive coverage of the detection scope even in complex application structures.
[0110] In summary, in-depth analysis of assignment expressions can not only capture all instances of direct manipulation of document.cookie, but also provide valuable feedback to developers, helping them write safer, more compliant, and more efficient code.
[0111] This application also provides a practical application of cookie detection rules, as follows:
[0112] The ESLint plugin works by defining a `forbiddenCookieSubdomains` array, checking whether a global cookie is added in the assignment expression, and checking whether the current domain is any subdomain in the `forbiddenCookieSubdomains` array. This avoids adding global cookies to sub-products, improving code security and maintainability.
[0113] Define an array `forbiddenCookieSubdomains` to store a list of subdomains where global cookies cannot be set. For example, if a sub-product's domain is `example.com`, its subdomain `sub.example.com` can be added to the `forbiddenCookieSubdomains` array, indicating that global cookies cannot be set under `sub.example.com`. The specific code is as follows:
[0114] const forbiddenCookieSubdomains=['sub.example.com','sub2.example.com'];
[0115] Define an ESLint plugin that returns an object. This object contains a method `AssignmentExpression` to check the assignment expression. The code is as follows:
[0116]
[0117] In the `AssignmentExpression` method, it first checks if the current node is an assignment expression and if the object name of the expression on the left is `document`. If so, it further checks if the property name of the expression on the left is `cookie`. If so, it checks if the current domain is any subdomain in the `forbiddenCookieSubdomains` array. If so, it uses the `context.report()` method to report the error. The specific code is as follows:
[0118]
[0119]
[0120] In short, cookie detection rules are the parts of the ESLint plugin's code that involve cookie operations, especially those write methods that may cause security or compatibility issues. Optimization suggestions are provided, such as using more secure methods or standards-compliant write methods.
[0121] The memory leak detection rules will now be explained in detail, taking their specific application and practical use as examples.
[0122] The specific application of memory leak detection rules is as follows:
[0123] If the detection requirement is memory leak detection, then the memory leak detection rules are used to determine whether any one of the memory leak error conditions is met among multiple nodes of the abstract syntax tree, and a third judgment result is obtained. The memory leak error conditions include the third condition, the fourth condition, the fifth condition, and the sixth condition. Among them, the third condition is the memory leak error judgment condition for the VariableDeclaration node; the fourth condition is the memory leak error judgment condition for the FunctionExpression node; the fifth condition is the memory leak error judgment condition for the setTimeout variable; and the sixth condition is the memory leak error judgment condition for the MemberExpression node.
[0124] If the third judgment result is yes, then the detection result is determined to be the second result, and the error report of the code to be detected is recorded as a memory leak warning.
[0125] If the third judgment result is negative, then the test result is determined to be the first result.
[0126] The third condition includes the existence of a VariableDeclaration node among multiple nodes in the abstract syntax tree, and the VariableDeclaration node in the abstract syntax tree is of type var.
[0127] The fourth condition includes the existence of a FunctionExpression node among multiple nodes in the abstract syntax tree, the FunctionExpression node in the abstract syntax tree satisfying the leakage condition, and the FunctionExpression node in the abstract syntax tree referencing external variables and scope; the leakage condition is that the parent node of the FunctionExpression node is CallExpression and the function called is named setTimeout.
[0128] The fifth condition includes the existence of a setTimeout variable in multiple nodes of the abstract syntax tree, and the existence of a setTimeout variable in a node in the global scope.
[0129] The sixth condition includes the existence of a MemberExpression node in multiple nodes of the abstract syntax tree, and the MemberExpression node of the abstract syntax tree references the document.querySelector method.
[0130] For memory leak detection, this application, in conjunction with the memory leak detection rules configured in the ESLint plugin, performs memory leak detection on the VariableDeclaration node, FunctionExpression node, setTimeout variable, and MemberExpression node. This is primarily because these nodes represent key programming constructs and patterns that may cause memory leaks. This will be explained in detail below:
[0131] Global variables and closures: When variables are declared in the global scope or closures are created inside a function, memory leaks can occur if these variables reference large objects or DOM elements and are not properly released. In particular, closures can retain references to external variables even after the outer function has returned, preventing the garbage collector from cleaning up these objects.
[0132] Anonymous functions and closures: FunctionExpressions are often used to define anonymous functions or immediately invoked function expressions (IIFEs), which may create closure environments. Closures have access to all variables in their creation context, which can lead to unnecessary memory consumption if not managed carefully.
[0133] Callback functions: FunctionExpressions passed as arguments to other functions (such as callback functions for asynchronous operations) may also hold references to external objects, thus delaying garbage collection.
[0134] Uncancelled Timers: `setTimeout` is typically used to schedule code to execute at a future point in time. However, if a long-running timer is set but forgotten to be canceled, or if the object held by the timer is no longer needed but is still referenced, a memory leak can occur. This problem is particularly severe when the timer callback function forms a closure and references a large amount of data.
[0135] Circular references: Sometimes, the callback function of setTimeout may accidentally create references to itself or other long-lived objects, making them unable to be garbage collected.
[0136] DOM references: MemberExpression is used to represent access to object members, such as accessing properties of DOM elements. If JavaScript code holds references to DOM nodes, and those nodes are later removed from the document but the references still exist, the browser will not release the memory occupied by those nodes.
[0137] Event handlers: Similarly, if event handlers are added to DOM elements and accessed through MemberExpression, and these handlers are not subsequently removed properly, it can also lead to memory leaks.
[0138] Analyzing the node types described above can help identify potential sources of memory leaks. Static code analysis tools can traverse the Abstract Syntax Tree (AST) to find these problematic patterns and provide warnings or suggestions for code improvement. This helps improve application performance and reduces the stability risks associated with memory leaks.
[0139] This application also provides practical applications of memory leak detection rules, as follows:
[0140] Define the detection rules for the ESLint plugin to detect code patterns that may lead to memory leaks, including the definition of global variables, inappropriate use of closures in setTimeout, global use of setTimeout, and references to DOM elements.
[0141] Check global variable definitions:
[0142] When iterating through the VariableDeclaration node, the plugin checks whether the variable declaration type (node.kind) is var.
[0143] If it's a `var` type, it means this is a global variable definition. The ESLint plugin will report a warning message, reminding developers to avoid using global variables because it may cause memory leaks. See the code example below:
[0144]
[0145] Inspect the closure in setTimeout:
[0146] When iterating through a FunctionExpression node, the ESLint plugin checks whether this function is used as an argument to setTimeout (i.e., whether its parent node is CallExpression and the function being called is named setTimeout).
[0147] If the conditions are met, the ESLint plugin will further check whether the closure function references variables from the outer scope. This is done by checking the statement type (ExpressionStatement), expression type (AssignmentExpression), and left-hand side type (MemberExpression) in the function body.
[0148] If the ESLint plugin detects that a closure function references a variable from the outer scope, it will report a warning message, reminding developers to avoid using such closures in `setTimeout`, as this could lead to memory leaks. See the code example below:
[0149]
[0150]
[0151] Check the globally used setTimeout:
[0152] When the program ends (Program:exit node), the ESLint plugin retrieves the global scope (context.getScope()) and then looks for a variable named setTimeout.
[0153] If the setTimeout variable is found, the ESLint plugin will iterate through all references to this variable (setTimeoutVar.references) and check whether these references are write operations in the global scope (reference.isWrite()).
[0154] If a write operation to `setTimeout` is detected in the global scope, the ESLint plugin will report a warning message, reminding developers to avoid using `setTimeout` in the global scope, as this may lead to memory leaks. See the code example below:
[0155]
[0156] Check references to DOM elements:
[0157] When iterating through a MemberExpression node, the ESLint plugin checks whether the expression references the document.querySelector method.
[0158] If it's a reference to the `document.querySelector` method, it means the code may be retaining references to DOM elements. The ESLint plugin will report a warning message reminding developers to avoid retaining references to DOM elements, as this can lead to memory leaks. See the following code example:
[0159]
[0160] In short, memory leak detection rules are implemented by the ESLint plugin through dynamic analysis of the code's memory usage at runtime. It detects code segments that may cause memory leaks, generates alerts in advance, and points out specific lines of code and potential memory leak risks.
[0161] With the rapid development of JavaScript, new syntax is constantly emerging. However, this also brings a problem: during development, the latest syntax is often chosen, but this syntax may not be supported in older browsers, leading to page errors. Therefore, during code development, it's necessary to provide as many hints as possible about the use of these new syntaxes, allowing users to evaluate compatibility and reducing incompatibility issues. This application uses automated compatibility detection to promptly identify and fix compatibility problems. It also provides hints about the syntax used in the code, encouraging developers to consider compatibility as much as possible when writing code, thereby improving the maintainability and stability of the project.
[0162] The code compatibility detection rules will now be explained in detail, taking their specific application and practical use as examples.
[0163] The specific application of code compatibility detection rules is as follows:
[0164] If the detection requirement is code compatibility detection, then the code compatibility detection rules are used to determine whether each node of the abstract syntax tree is compatible with the target browser, resulting in the fourth judgment result.
[0165] If the fourth judgment result is yes, then the test result is determined to be the first result.
[0166] If the fourth judgment result is negative, then the detection result is determined to be the second result, and the error report of the code to be detected is recorded as browser incompatibility.
[0167] This application also provides practical application examples of code compatibility detection rules, as follows:
[0168] To check the compatibility of JavaScript code, you can create an ESLint plugin. This plugin will check whether new syntax features used in the code are compatible with the target browser. To achieve this, you can use the eslint-plugin-compat plugin.
[0169] Install the eslint-plugin-compat plugin. The specific code is as follows:
[0170] npminstall eslint-plugin-compat--save-dev
[0171] Create or modify the .eslintrc.js file in the root directory of your project to use the eslint-plugin-compat plugin in your project. The specific code is as follows:
[0172]
[0173] Existing technologies require significant human resources for manual inspection, increasing project development costs. Furthermore, as projects evolve, code maintenance and testing workloads may continue to increase, leading to long-term human resource investment. This application, through real-time code analysis and compatibility testing, automatically identifies and alerts developers to potential issues, significantly reducing their workload. Developers no longer need to invest substantial human resources in manually inspecting code, thereby lowering project development costs.
[0174] Existing technologies relying on manual inspection are susceptible to subjective factors, potentially leading to overlooked or misjudged issues. Furthermore, manual inspection can become fatigued when faced with repetitive tasks, increasing the error rate. This application, through automated detection and evaluation, avoids the subjective and fatigue-related errors inherent in manual inspection, reducing the likelihood of overlooked or misjudged issues. It maintains consistent inspection quality and efficiency even with a large volume of repetitive work. Moreover, this application's detection technology for code security issues (such as improper cookie usage) incorporates the use of global variables, helping developers write secure code and reducing the risk of runtime security vulnerabilities.
[0175] Existing technologies do not run code on different browsers, operating systems, and devices, and do not check code compatibility, which may lead to unreliable code compatibility and interface errors on some browsers. This application enables code to run on different browsers, operating systems, and devices, and checks code compatibility. Through automated compatibility testing, compatibility issues can be identified and fixed in a timely manner, ensuring that the code runs normally on various platforms.
[0176] In summary, this application can automatically detect and fix compatibility and security issues in code, reducing the time and effort developers spend on manual detection and fixing, and improving development efficiency. It can promptly identify and fix compatibility and security issues in code, avoiding project risks and user experience problems caused by code quality problems, thus improving code quality. Furthermore, it can automatically detect and fix compatibility and security issues in code, reducing project risks and lowering project maintenance and repair costs.
[0177] Based on the embodiments described above, this application also provides a code detection device. The following, in conjunction with... Figure 4 Please provide an explanation. Figure 4 This is a schematic diagram of the structure of the code detection device provided in an embodiment of this application. Figure 4 The following are included:
[0178] The acquisition unit is used to acquire the code to be detected.
[0179] The requirement unit is used to determine the detection requirements of the code to be tested. Detection requirements must include at least one of the following: memory leak detection, global variable detection, cookie detection, and code compatibility detection.
[0180] The matching unit is used to determine the detection rules that match the detection requirements from the configured rules of the ESLint plugin.
[0181] The detection unit is used to detect the code to be detected based on detection rules and determine the detection result. The detection result is either a first result or a second result; the first result indicates that the code to be detected is correct; the second result indicates that there is an error in the code to be detected; the second result includes an error report, which records the error type.
[0182] In one optional implementation, if the detection result output by the detection unit is the second result, the code to be detected is modified based on the error type recorded in the error report.
[0183] In one optional implementation, the detection unit includes a parsing module and a detection rule application module. The function of each module in the detection unit is described below:
[0184] The parsing module is used to parse the code to be tested using the ESLint plugin to obtain the abstract syntax tree corresponding to the code to be tested.
[0185] The detection rule application module is used to detect each node of the abstract syntax tree using detection rules that match the detection requirements, and to determine the detection result of the code to be detected.
[0186] The detection rule application module has multiple application scenarios. This application uses four application scenarios as examples to further illustrate the functionality of the detection rule application module:
[0187] In one optional implementation, in the first application scenario, the detection rule application module is specifically used for:
[0188] If the detection requirement is global variable detection, then the global variable detection rules are used to determine whether multiple nodes in the abstract syntax tree satisfy any one of the global variable error conditions, resulting in a first judgment result. The global variable error conditions include a first condition and a second condition; the first condition is a global variable error judgment condition regarding variable declaration statements; the second condition is a global variable error judgment condition regarding assignment expressions. If the first judgment result is yes, then the detection result is determined to be the second result, and the error report of the code to be detected is recorded as a global variable error. If the first judgment result is no, then the detection result is determined to be the first result. Specifically, the first condition is that multiple nodes in the abstract syntax tree contain variable declaration statements, and the initialization expression of the node containing the variable declaration statement conforms to a first preset object name. Specifically, the second condition is that multiple nodes in the abstract syntax tree contain assignment expressions, the left-hand side expression of the node containing the assignment expression conforms to a first preset object name, and the attribute name of the left-hand side expression of the node containing the assignment expression is a global variable.
[0189] In one optional implementation, under the second application scenario, the detection rule application module is specifically used for:
[0190] If the detection requirement is cookie detection, then the cookie detection rules are used to determine whether each node in the abstract syntax tree meets the cookie error conditions, resulting in a second judgment result. If the second judgment result is yes, then the detection result is determined to be the second result, and the error report of the code to be detected is recorded as a cookie setting error. If the second judgment result is no, then the detection result is determined to be the first result. The cookie error conditions include: multiple nodes in the abstract syntax tree contain assignment expressions; the left-hand expression of the node containing the assignment expression matches the second preset object name; the left-hand expression of the node containing the assignment expression has the attribute name "cookie"; and the current domain of the node with the attribute name "cookie" in the left-hand expression of the node containing the assignment expression is located in a preset data group. The preset data group is used to store subdomains that cannot set global cookies.
[0191] In one optional implementation, under the third application scenario, the detection rule application module is specifically used for:
[0192] If the detection requirement is memory leak detection, then memory leak detection rules are used to determine whether any one of the memory leak error conditions is met among multiple nodes in the abstract syntax tree, resulting in a third judgment result. The memory leak error conditions include a third condition, a fourth condition, a fifth condition, and a sixth condition. Specifically, the third condition is for the VariableDeclaration node; the fourth condition is for the FunctionExpression node; the fifth condition is for the setTimeout variable; and the sixth condition is for the MemberExpression node. If the third judgment result is yes, the detection result is determined as the second result, and the error report for the code to be detected is recorded as a memory leak warning. If the third judgment result is no, the detection result is determined as the first result.
[0193] The third condition includes the existence of a VariableDeclaration node among multiple nodes in the abstract syntax tree, and the VariableDeclaration node in the abstract syntax tree is of type var.
[0194] The fourth condition includes the existence of a FunctionExpression node among multiple nodes in the abstract syntax tree, the FunctionExpression node in the abstract syntax tree satisfying the leakage condition, and the FunctionExpression node in the abstract syntax tree referencing external variables and scope; the leakage condition is that the parent node of the FunctionExpression node is CallExpression and the function called is named setTimeout.
[0195] The fifth condition includes the existence of a setTimeout variable in multiple nodes of the abstract syntax tree, and the existence of a setTimeout variable in a node in the global scope.
[0196] The sixth condition includes the existence of a MemberExpression node in multiple nodes of the abstract syntax tree, and the MemberExpression node of the abstract syntax tree references the document.querySelector method.
[0197] In one optional implementation, under the fourth application scenario, the detection rule application module is specifically used for:
[0198] If the detection requirement is code compatibility testing, then code compatibility testing rules are used to determine whether each node of the abstract syntax tree is compatible with the target browser, resulting in a fourth judgment result. If the fourth judgment result is yes, then the detection result is determined as the first result. If the fourth judgment result is no, then the detection result is determined as the second result, and the error report of the code to be tested is recorded as browser incompatibility.
[0199] In one alternative implementation, the code detection device further includes:
[0200] The configuration unit is used to install ESLint plugins and configure detection rules for these plugins. These rules include memory leak detection rules, global variable detection rules, cookie detection rules, and code compatibility detection rules.
[0201] This application provides a device, which can be a server. Figure 5 This is a schematic diagram of a server structure provided in an embodiment of this application. The server 900 can vary significantly due to different configurations or performance. It may include one or more central processing units (CPUs) 922 (e.g., one or more processors) and memory 932, and one or more storage media 930 (e.g., one or more mass storage devices) for storing application programs 942 or data 944. The memory 932 and storage media 930 can be temporary or persistent storage. The program stored in the storage media 930 may include one or more modules (not shown in the diagram), each module may include a series of instruction operations on the server. Furthermore, the CPU 922 may be configured to communicate with the storage media 930 and execute the series of instruction operations in the storage media 930 on the server 900.
[0202] Server 900 may also include one or more power supplies 926, one or more wired or wireless network interfaces 950, one or more input / output interfaces 958, and / or one or more operating systems 941.
[0203] CPU 922 is used to perform the following steps:
[0204] Obtain the code to be tested.
[0205] Determine the detection requirements for the code to be tested. Detection requirements should include at least one of the following: memory leak detection, global variable detection, cookie detection, and code compatibility detection.
[0206] Identify the detection rules that match the detection requirements from the configured rules of the ESLint plugin.
[0207] The code to be tested is analyzed based on the detection rules, and the detection result is determined. The detection result is either a first result or a second result; the first result indicates that the code to be tested is correct; the second result indicates that there is an error in the code to be tested; the second result includes an error report, which records the error type.
[0208] This application also provides another device, which can be a terminal device. For example... Figure 6 As shown, for ease of explanation, only the parts related to the embodiments of this application are shown. For specific technical details not disclosed, please refer to the method section of the embodiments of this application. Taking a mobile phone as an example:
[0209] Figure 6 The diagram shown is a block diagram of a portion of the structure of a mobile phone provided in an embodiment of this application. (Reference) Figure 6 The mobile phone includes: a radio frequency (RF) circuit 1010, a memory 1020, an input unit 1030, a display unit 1040, a sensor 1050, an audio circuit 1060, a wireless fidelity (WiFi) module 1070, a processor 1080, and a power supply 1090, etc. Those skilled in the art will understand that... Figure 6 The mobile phone structure shown does not constitute a limitation on the mobile phone and may include more or fewer components than shown, or combine certain components, or have different component arrangements.
[0210] The following is combined Figure 6 A detailed introduction to each component of a mobile phone:
[0211] The RF circuit 1010 can be used for receiving and transmitting signals during information transmission or calls. Specifically, it receives downlink information from the base station and processes it with the processor 1080; additionally, it transmits uplink data to the base station. Typically, the RF circuit 1010 includes, but is not limited to, an antenna, at least one amplifier, a transceiver, a coupler, a low-noise amplifier (LNA), a duplexer, etc. Furthermore, the RF circuit 1010 can also communicate wirelessly with networks and other devices. The aforementioned wireless communications may use any communication standard or protocol, including but not limited to Global System for Mobile Communications (GSM), General Packet Radio Service (GPRS), Code Division Multiple Access (CDMA), Wideband Code Division Multiple Access (WCDMA), Long Term Evolution (LTE), email, and Short Messaging Service (SMS).
[0212] The memory 1020 can be used to store software programs and modules. The processor 1080 executes various mobile phone functions and data processing by running the software programs and modules stored in the memory 1020. The memory 1020 may mainly include a program storage area and a data storage area. The program storage area may store the operating system, applications required for at least one function (such as sound playback function, image playback function, etc.), etc.; the data storage area may store data created according to the use of the mobile phone (such as audio data, phonebook, etc.). In addition, the memory 1020 may include high-speed random access memory, and may also include non-volatile memory, such as at least one disk storage device, flash memory device, or other volatile solid-state storage device.
[0213] The input unit 1030 can be used to receive input numerical or character information, and to generate key signal inputs related to user settings and function control of the mobile phone. Specifically, the input unit 1030 may include a touch panel 1031 and other input devices 1032. The touch panel 1031, also known as a touch screen, can collect touch operations performed by the user on or near it (such as operations performed by the user using a finger, stylus, or any suitable object or accessory on or near the touch panel 1031), and drive the corresponding connection devices according to a pre-set program. Optionally, the touch panel 1031 may include two parts: a touch detection device and a touch controller. The touch detection device detects the user's touch position and the signal generated by the touch operation, and transmits the signal to the touch controller; the touch controller receives touch information from the touch detection device, converts it into touch point coordinates, and sends it to the processor 1080, and can also receive and execute commands sent by the processor 1080. In addition, the touch panel 1031 can be implemented using various types such as resistive, capacitive, infrared, and surface acoustic wave. In addition to the touch panel 1031, the input unit 1030 may also include other input devices 1032. Specifically, other input devices 1032 may include, but are not limited to, one or more of the following: physical keyboard, function keys (such as volume control buttons, power buttons, etc.), trackball, mouse, joystick, etc.
[0214] The display unit 1040 can be used to display information input by the user or information provided to the user, as well as various menus of the mobile phone. The display unit 1040 may include a display panel 1041, which may optionally be configured as a Liquid Crystal Display (LCD), Organic Light-Emitting Diode (OLED), or similar display panel 1041. Further, a touch panel 1031 may cover the display panel 1041. When the touch panel 1031 detects a touch operation on or near it, it transmits the information to the processor 1080 to determine the type of touch event. Subsequently, the processor 1080 provides corresponding visual output on the display panel 1041 according to the type of touch event. Although in Figure 6 In this embodiment, the touch panel 1031 and the display panel 1041 are two separate components to realize the input and output functions of the mobile phone. However, in some embodiments, the touch panel 1031 and the display panel 1041 can be integrated to realize the input and output functions of the mobile phone.
[0215] The mobile phone may also include at least one sensor 1050, such as a light sensor, a motion sensor, and other sensors. Specifically, the light sensor may include an ambient light sensor and a proximity sensor. The ambient light sensor can adjust the brightness of the display panel 1041 according to the ambient light level, and the proximity sensor can turn off the display panel 1041 and / or the backlight when the phone is moved to the ear. As a type of motion sensor, an accelerometer sensor can detect the magnitude of acceleration in various directions (generally three axes). When stationary, it can detect the magnitude and direction of gravity and can be used for applications that recognize the phone's posture (such as landscape / portrait switching, related games, magnetometer posture calibration), vibration recognition-related functions (such as pedometer, taps), etc. Other sensors that may be configured in the mobile phone, such as gyroscopes, barometers, hygrometers, thermometers, and infrared sensors, will not be described in detail here.
[0216] The audio circuit 1060, speaker 1061, and microphone 1062 provide an audio interface between the user and the mobile phone. The audio circuit 1060 converts the received audio data into electrical signals and transmits them to the speaker 1061, where the speaker 1061 converts them into sound signals for output. On the other hand, the microphone 1062 converts the collected sound signals into electrical signals, which are then received by the audio circuit 1060, converted into audio data, and then processed by the processor 1080 before being transmitted via the RF circuit 1010 to, for example, another mobile phone, or the audio data can be output to the memory 1020 for further processing.
[0217] WiFi is a short-range wireless transmission technology. Through the WiFi module 1070, mobile phones can help users send and receive emails, browse web pages, and access streaming media, providing users with wireless broadband internet access. Although Figure 6 The WiFi module 1070 is shown, but it is understood that it is not an essential component of a mobile phone and can be omitted as needed without changing the essence of the invention.
[0218] The processor 1080 is the control center of the mobile phone, connecting various parts of the phone through various interfaces and lines. It executes software programs and / or modules stored in the memory 1020 and calls data stored in the memory 1020 to perform various functions and process data, thereby collecting overall data and information from the phone. Optionally, the processor 1080 may include one or more processing units; preferably, the processor 1080 may integrate an application processor and a modem processor, wherein the application processor mainly handles the operating system, user interface, and applications, and the modem processor mainly handles wireless communication. It is understood that the modem processor may not be integrated into the processor 1080.
[0219] The mobile phone also includes a power supply 1090 (such as a battery) that supplies power to various components. Preferably, the power supply can be logically connected to the processor 1080 through a power management system, thereby enabling functions such as charging, discharging, and power consumption management through the power management system.
[0220] Although not shown, mobile phones may also include a camera, Bluetooth module, etc., which will not be described in detail here.
[0221] In this embodiment of the application, the processor 1080 included in the mobile phone also has the following functions:
[0222] Obtain the code to be tested.
[0223] Determine the detection requirements for the code to be tested. Detection requirements should include at least one of the following: memory leak detection, global variable detection, cookie detection, and code compatibility detection.
[0224] Identify the detection rules that match the detection requirements from the configured rules of the ESLint plugin.
[0225] The code to be tested is analyzed based on the detection rules, and the detection result is determined. The detection result is either a first result or a second result; the first result indicates that the code to be tested is correct; the second result indicates that there is an error in the code to be tested; the second result includes an error report, which records the error type.
[0226] This application also provides a computer-readable storage medium for storing a computer program that, when run, enables any of the aforementioned code detection methods to be implemented.
[0227] This application also provides a computer program product including a computer program, which, when run on a computer, enables the execution of any of the aforementioned code detection methods.
[0228] Those skilled in the art will understand that, for the sake of convenience and brevity, the specific working process of the system and equipment described above can be referred to the corresponding process in the foregoing method embodiments, and will not be repeated here.
[0229] In this application embodiment, the terms "module" or "unit" refer to a computer program or part of a computer program that has a predetermined function and works with other related parts to achieve a predetermined goal, and can be implemented wholly or partially using software, hardware (such as processing circuitry or memory), or a combination thereof. Similarly, a processor (or multiple processors or memory) can be used to implement one or more modules or units. Furthermore, each module or unit can be part of an overall module or unit that includes the functionality of that module or unit.
[0230] In the several embodiments provided in this application, it should be understood that the disclosed apparatus and methods can be implemented in other ways. For example, the apparatus embodiments described above are merely illustrative; for instance, the division of the apparatus is only a logical functional division, and in actual implementation, there may be other division methods. For example, multiple systems may be combined or integrated into another apparatus, or some features may be ignored or not executed. Furthermore, the coupling or direct coupling or communication connection shown or discussed may be an indirect coupling or communication connection through some interfaces, apparatuses, or units, and may be electrical, mechanical, or other forms.
[0231] The devices described as separate components may or may not be physically separate, and the components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.
[0232] Furthermore, the functional units in the various embodiments of this application can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit. The integrated unit can be implemented in hardware or as a software functional unit.
[0233] If the integrated unit is implemented as a software functional unit and sold or used as an independent product, it can be stored in a computer-readable storage medium. Based on this understanding, the technical solution of this application, in essence, or the part that contributes to the prior art, or all or part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods of the various embodiments of this application. The aforementioned storage medium includes: USB flash drives, portable hard drives, read-only memory (ROM), random access memory (RAM), magnetic disks, optical disks, and other media capable of storing computer programs.
[0234] 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 of the technical features. Such modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the spirit and scope of the technical solutions of the embodiments of this application.
Claims
1. A method for code detection, characterized in that, include: Obtain the code to be detected; Determine the detection requirements for the code to be detected; the detection requirements include at least one of memory leak detection, global variable detection, cookie detection, and code compatibility detection. Determine the detection rules that match the detection requirements from the configured rules of the ESLint plugin; The code to be detected is tested based on the detection rules, and the detection result is determined; the detection result is a first result or a second result. The first result indicates that the code to be detected is correct; The second result indicates that an error exists in the code to be detected; the second result includes an error report, which records the error type.
2. The method according to claim 1, characterized in that, The method further includes: Install the ESLint plugin and configure detection rules for it. The configured detection rules include memory leak detection rules, global variable detection rules, cookie detection rules, and code compatibility detection rules.
3. The method according to claim 1, characterized in that, The step of detecting the code to be detected based on the detection rules and determining the detection result includes: The code to be detected is parsed using the ESLint plugin to obtain the abstract syntax tree corresponding to the code to be detected; Each node of the abstract syntax tree is detected using detection rules that match the detection requirements to determine the detection result of the code to be detected.
4. The method according to claim 3, characterized in that, The step of using detection rules that match the detection requirements to detect each node of the abstract syntax tree and determining the detection result of the code to be detected specifically includes: If the detection requirement is global variable detection, then the global variable detection rules are used to determine whether multiple nodes of the abstract syntax tree satisfy any one of the global variable error conditions, and a first judgment result is obtained; the global variable error conditions include a first condition and a second condition; wherein, the first condition is a global variable error judgment condition for variable declaration statements; the second condition is a global variable error judgment condition for assignment expressions; If the first judgment result is yes, then the detection result is determined to be the second result, and the error report of the code to be detected is recorded as a global variable error; If the first judgment result is negative, then the detection result is determined to be the first result.
5. The method according to claim 4, characterized in that, The first condition specifically refers to the existence of variable declaration statements in multiple nodes of the abstract syntax tree, and the initialization expression of the node containing the variable declaration statement conforms to the first preset object name; the second condition specifically refers to the existence of assignment expressions in multiple nodes of the abstract syntax tree, the left-hand side expression of the node containing the assignment expression conforms to the first preset object name, and the attribute name of the left-hand side expression of the node containing the assignment expression is a global variable.
6. The method according to claim 3, characterized in that, The step of using detection rules that match the detection requirements to detect each node of the abstract syntax tree and determining the detection result of the code to be detected specifically includes: If the detection requirement is cookie detection, then the cookie detection rules are used to determine whether each node in the abstract syntax tree meets the cookie error condition, and a second judgment result is obtained; If the second judgment result is yes, then the detection result is determined to be the second result, and the error report of the code to be detected is recorded as a cookie setting error; If the second judgment result is negative, then the detection result is determined to be the first result.
7. The method according to claim 6, characterized in that, The cookie error conditions include the existence of assignment expressions in multiple nodes of the abstract syntax tree, the left-hand expression of the node of the assignment expression conforming to the second preset object name, the attribute name of the left-hand expression of the node of the assignment expression being cookie, and the current domain name of the node with the attribute name cookie in the left-hand expression of the node of the assignment expression being located in a preset data group. The preset data group is used to store subdomains that cannot have global cookies set.
8. The method according to claim 3, characterized in that, The step of using detection rules that match the detection requirements to detect each node of the abstract syntax tree and determining the detection result of the code to be detected specifically includes: If the detection requirement is memory leak detection, then the memory leak detection rules are used to determine whether any one of the memory leak error conditions is met among multiple nodes of the abstract syntax tree, resulting in a third judgment result. The memory leak error conditions include a third condition, a fourth condition, a fifth condition, and a sixth condition; wherein, the third condition is a memory leak error judgment condition for the VariableDeclaration node; the fourth condition is a memory leak error judgment condition for the FunctionExpression node; the fifth condition is a memory leak error judgment condition for the setTimeout variable; and the sixth condition is a memory leak error judgment condition for the MemberExpression node. If the third judgment result is yes, then the detection result is determined to be the second result, and the error report of the code to be detected is recorded as a memory leak warning; If the third judgment result is negative, then the detection result is determined to be the first result.
9. The method according to claim 8, characterized in that, The third condition includes the existence of a VariableDeclaration node among multiple nodes of the abstract syntax tree, and the type of the VariableDeclaration node in the abstract syntax tree is var. The fourth condition includes the existence of a FunctionExpression node among multiple nodes in the abstract syntax tree, the FunctionExpression node in the abstract syntax tree satisfying the leakage condition, and the FunctionExpression node in the abstract syntax tree referencing an external variable and its scope; the leakage condition is that the parent node of the FunctionExpression node is CallExpression and the function called is named setTimeout. The fifth condition includes the existence of a setTimeout variable in multiple nodes of the abstract syntax tree, and the existence of a setTimeout write operation in the global scope of the node containing the setTimeout variable. The sixth condition includes the existence of a MemberExpression node among multiple nodes of the abstract syntax tree, and the MemberExpression node of the abstract syntax tree referencing the document.querySelector method.
10. The method according to claim 3, characterized in that, The step of using detection rules that match the detection requirements to detect each node of the abstract syntax tree and determining the detection result of the code to be detected specifically includes: If the detection requirement is code compatibility detection, then the code compatibility detection rules are used to determine whether each node of the abstract syntax tree is compatible with the target browser, and the fourth judgment result is obtained. If the fourth judgment result is yes, then the detection result is determined to be the first result; If the fourth judgment result is negative, then the detection result is determined to be the second result, and the error report of the code to be detected is recorded as browser incompatibility.
11. The method according to claim 1, characterized in that, The method further includes: If the detection result is the second result, then the code to be detected is modified based on the error type recorded in the error report.
12. A code detection device, characterized in that, include: The acquisition unit is used to acquire the code to be detected; The requirement unit is used to determine the detection requirements of the code to be detected; the detection requirements include at least one of memory leak detection, global variable detection, cookie detection, and code compatibility detection. A matching unit is used to determine, from the configured rules of the ESLint plugin, a detection rule that matches the detection requirement; A detection unit is configured to detect the code to be detected based on the detection rules and determine the detection result; the detection result is a first result or a second result. The first result indicates that the code to be detected is correct; The second result indicates that an error exists in the code to be detected; the second result includes an error report, which records the error type.
13. A computer device, characterized in that, The device includes a processor and a memory: The memory is used to store computer programs and to transfer the computer programs to the processor; The processor is configured to execute the code detection method according to any one of claims 1 to 11, based on instructions in the computer program.
14. A computer-readable storage medium, characterized in that, The computer-readable storage medium is used to store a computer program that, when executed, implements the code detection method according to any one of claims 1 to 11.
15. A computer program product, characterized in that, Includes a computer program that, when executed, implements the code detection method according to any one of claims 1 to 11.