Code conversion method and device based on domain-specific language and medium
Through a code conversion method based on domain-specific languages, the class annotations in DSL files are parsed and the target language code is generated, which solves the problem that general data structures in visual development cannot adapt to complex logic and language differences, and realizes efficient and reliable multi-language code generation.
Patent Information
- Application Number
- CN202510701868.2
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-05-28
- Publication Date
- 2025-09-09
AI Technical Summary
In the field of visualization development, the use of general data structures for metadata description cannot meet the needs of complex logical expression and adaptation to language differences.
A code conversion method based on domain-specific language is adopted. By receiving DSL files and parsing the class annotations therein, the syntax code that conforms to the target conversion language is generated. The target language identification information and construction pattern identification information in the class annotations are used to dynamically generate multi-language adaptation logic.
It significantly reduces the development and maintenance costs of multi-language support, improves development efficiency and the reliability of generated code, lowers the technical threshold, and improves the flexibility and maintainability of the system.
Smart Images

Figure CN120610708A_ABST
Abstract
Description
Technical Field
[0001] This specification relates to the field of code conversion technology, and in particular to a code conversion method, device, and medium based on a domain-specific language. Background Art
[0002] In the field of visual development, metadata descriptions such as table objects, business entities, forms, workflows, business logic, and queries are involved. These metadata are closely related and together constitute a complete application.
[0003] In the field of visual development, general data structures such as JSON are often used to describe metadata such as table objects, business entities, and forms. However, the expressive power of general data structures such as JSON is limited. JSON makes it difficult to describe complex business logic, such as conditional branches and loop control, requiring developers to write additional adaptation code. Furthermore, general data structures struggle to mask language differences. Front-end and back-end languages, such as Java and JavaScript, have syntactical differences in expressions like object construction and field access, resulting in the need to repeatedly develop multiple sets of code for the same business logic. Furthermore, the type system is fragmented, with common types such as strings having inconsistent implementations in different languages. Proprietary types, such as classes managed by the Spring container, cannot be reused across languages, requiring manual handling of type compatibility issues.
[0004] It can be seen from this that in the field of visualization development, the use of general data structures for metadata description cannot meet the needs of complex logical expression and language difference adaptation. Summary of the Invention
[0005] One or more embodiments of this specification provide a code conversion method, device and medium based on a domain-specific language, which is used to solve the following technical problems: in the field of visualization development, the use of general data structures for metadata description cannot meet the needs of complex logical expression and language difference adaptation.
[0006] One or more embodiments of this specification adopt the following technical solutions:
[0007] One or more embodiments of the present specification provide a domain-specific language-based code conversion method, the method comprising: receiving a DSL file and a target conversion language input by a user, wherein the DSL file comprises at least one class definition, and the class definition comprises a class name, a field declaration, and a method signature declaration; parsing the DSL file to extract a plurality of class annotations annotated in the class definition, wherein the class annotation comprises target language identification information, class unique identification information, construction pattern identification information, and array access pattern identification information; extracting a matching specified class annotation set from the class annotation based on the target conversion language and the target language identification information in the class annotation, so as to generate a code file conforming to the syntax of the target conversion language based on the specified class annotation set, wherein the specified class annotation set comprises class annotations, field annotations, and method annotations.
[0008] One or more embodiments of this specification provide a code conversion device based on a domain-specific language, including:
[0009] at least one processor; and,
[0010] a memory communicatively connected to the at least one processor; wherein,
[0011] The memory stores instructions that can be executed by the at least one processor. The instructions are executed by the at least one processor to enable the at least one processor to perform the above method.
[0012] One or more embodiments of this specification provide a non-volatile computer storage medium storing computer-executable instructions, wherein the computer-executable instructions are configured to execute the above method.
[0013] At least one of the above technical solutions adopted in the embodiments of this specification can achieve the following beneficial effects: through the technical solutions of the embodiments of this specification, traditional code generation solutions usually need to design conversion rules separately for each target language, resulting in a large and difficult to maintain code base; the embodiments of this specification introduce class annotations containing target language identification information to centralize the multi-language adaptation logic to the annotation configuration layer. Developers explicitly declare language features such as construction patterns and array access rules through annotations in DSL. The generator only needs to parse these configurations and call the preset template library, without having to write repeated conversion logic for different languages, which significantly reduces the development and maintenance costs of multi-language support. For example, adding a new language only requires expanding the annotation parameters and template library, rather than refactoring the entire generator; conventional methods often rely on implicit rules to infer the behavior of the target language, such as assuming that all classes support multiple languages, which can easily lead to unusable generated code due to unhandled type conflicts; the embodiments of this specification use the language identifier in the class annotation to force the definition of the language scope of the type, and the explicit declaration mechanism avoids the risk of type pollution from the source, ensuring that the generated code strictly follows the type system and grammatical specifications of the target language; traditional converters often use hard-coded logic to implement differences in language characteristics, resulting in the coupling of templates and generation logic; the embodiments of this specification separate annotations In the parsing and code generation phase, the grammatical details are abstracted into a configurable template library, so that the grammatical rules can be dynamically extended. When adding a new collection type, it is only necessary to add the corresponding template without modifying the core generation logic, thereby improving the flexibility and maintainability of the system. Conventional solutions usually find errors through compiler or runtime testing after code generation, resulting in high debugging costs. In the embodiment of this specification, the integrity check of class annotations is performed in the parsing phase. The pre-check mechanism advances the error feedback from runtime to compile time, allowing developers to quickly locate problems in DSL definitions, greatly improving development efficiency and the reliability of generated code. Traditional multi-language development requires developers to be familiar with all target languages. The syntax and framework details of the standard language are extremely costly to learn. The embodiments of this specification use DSL syntax to abstract language differences. Developers only need to master the annotation rules of DSL to generate multi-language code. The language details are encapsulated in the generator, allowing developers to focus on business logic definition, significantly reducing the technical threshold for cross-language development. Conventional generators are often deeply coupled with specific frameworks, resulting in the need to rewrite the generation logic when switching frameworks. The embodiments of this specification abstract framework dependencies into configurable items through annotation parameters. The parameterized design enables the generator to flexibly adapt to different technology stacks, avoiding the reconstruction of generation logic due to framework upgrades or replacements, and improving the life cycle and scope of application of the solution. BRIEF DESCRIPTION OF THE DRAWINGS
[0014] In order to more clearly illustrate the embodiments of this specification or the technical solutions in the prior art, the following briefly introduces the drawings required for the embodiments or the description of the prior art. Obviously, the drawings described below are only some of the embodiments described in this specification. For those skilled in the art, other drawings can be obtained based on these drawings without inventive work. In the drawings:
[0015] Figure 1 A flowchart of a code conversion method based on a domain-specific language provided in an embodiment of this specification;
[0016] Figure 2 This is a schematic diagram of the structure of a code conversion device based on a domain-specific language provided in an embodiment of this specification. DETAILED DESCRIPTION
[0017] To help those skilled in the art better understand the technical solutions in this specification, the following will provide a clear and complete description of the technical solutions in the embodiments of this specification, in conjunction with the accompanying drawings. Obviously, the described embodiments are only part of the embodiments of this specification, not all of them. All other embodiments obtained by those skilled in the art based on the embodiments of this specification without creative work should fall within the scope of protection of this specification.
[0018] The embodiments of this specification provide a code conversion method based on a domain-specific language. It should be noted that the execution subject in the embodiments of this specification can be a server or any device with data processing capabilities. Figure 1 A flowchart of a code conversion method based on a domain-specific language provided in an embodiment of this specification is shown in FIG. Figure 1 As shown, it mainly includes the following steps:
[0019] Step S101: receiving a DSL file and a target conversion language input by a user.
[0020] The DSL file includes at least one class definition, which includes a class name, field declarations, and method signature declarations;
[0021] In one embodiment of the present specification, in order to reduce the learning cost, the domain-specific language (DSL) syntax adopts the typescript syntax, and uses an object-oriented approach to abstract objects in the visualization domain into DSL objects by adding annotations to DSL classes, fields, methods, and method parameters. During the compilation phase, the ability to convert to multiple target languages is achieved by obtaining the values set in the annotations. In the process of converting DSL to multiple languages, there is little difference in statements, such as if, while, for, switch, etc., and the differences between the front-end and back-end languages are not much; however, at the expression level, such as expressions such as object construction, field access, array access, etc., there are relatively large differences.
[0022] It should be noted that the class definition in the embodiments of this specification can also be called a type definition, and the type definition itself is a DSL. The type definition only contains the class name, field definition, method and method parameter definition, and there is no implementation code in the method. Similar to the header file in C++, annotations are added to classes, fields, methods, and parameters. During the compilation phase, the DSL is converted into different target languages based on the annotation settings. Since there are multiple target languages, the annotations need to distinguish the target languages, so each annotation has language attributes. Some types are common types, such as the basic type string. There is only one string class definition in the DSL, which applies to both the front and back ends. Some types only exist in the back end or the front end, and the annotations only need to include the annotations of the language.
[0023] In one embodiment of the present specification, a DSL file input by a user and a target transformation language are received, wherein the DSL file includes at least one class definition, and the class definition includes a class name, field declarations, and method signature declarations.
[0024] Step S102: Parse the DSL file to extract multiple class annotations marked in the class definition.
[0025] The class annotation includes target language identification information, class unique identification information, construction mode identification information, and array access mode identification information;
[0026] The class definition in the DSL file is parsed to extract multiple class annotations annotated in the class definition, specifically including: extracting the field annotation annotated on the field declaration in the class definition, wherein the field annotation includes target language identification information and field access mode identification information; extracting the method annotation annotated on the method signature declaration in the class definition, wherein the method annotation includes target language identification information and method mapping identification information; extracting the construction mode identification information in the class definition, wherein the construction mode identification information includes the default construction mode and the container dependency injection mode.
[0027] In one embodiment of this specification, the parser first traverses the class definitions in the DSL file and identifies the annotation tags before the class declaration. For each class definition, the parser scans the @DSLClass annotation at the top and extracts key parameters such as the language attribute (target language identifier), constructorMode (construction mode identifier, such as default or springContainer), and arrayAccessMode (array access mode). For example, when parsing
[0028] When @DSLClass(language:"java",constructorMode:"springContainer") is specified, the class's construction in Java will be recorded as relying on Spring container injection, and the association between these parameters and the class name will be stored for use in the subsequent code generation phase.
[0029] In the field declaration section of a class definition, the @field annotation preceding each field is scanned line by line, extracting the language attribute (target language identifier) and accessMode (field access mode, such as direct, JavaBean, or hashmap) contained within it. For example, the field declaration @field({language:"java",accessMode:"JavaBean",getter:"getId"})id:string is parsed as: In Java, this field is accessed via the getId() method. The parser binds these field-level parameters to the class and field name, forming structured metadata to ensure that subsequent conversions can generate field access expressions according to the target language's rules.
[0030] For the method signature declaration in the class, focus on the @method annotation before the method and extract the language attribute (target language identifier) and method parameter (method name mapping rules in the target language). For example, the method declaration @method({language:"java",method:"substring"})
[0031] substring(start:number,length:number):string indicates that the substring method in Java should be mapped to the method of the same name, while @method({language:"javascript",method:"substr"}) indicates that it should be converted to the substr method in JavaScript. The parser associates the method name and parameter list with the mapping rules in the annotation to build a cross-language method call mapping table to support method naming differences in different languages.
[0032] The class-level constructorMode parameter is extracted from the @DSLClass annotation, and its value (such as default or springContainer) determines the object instantiation logic. For example, constructorMode: "default" directly uses the default construction method (new ClassName()), while springContainer relies on the container to obtain the instance (such as the Spring Framework's getBean method). These mode parameters are stored separately and serve as the direct basis for generating target language object creation expressions, ensuring that instantiation behavior meets expectations in different scenarios.
[0033] Through the above technical solution, compared with the traditional hard-coded conversion rules, precise adaptation to multi-language differences is achieved through fine-grained annotations such as fields, methods, and construction modes; conventional solutions usually require writing independent conversion logic for each language, while the embodiment of this specification dynamically configures the mapping relationship through annotation parameters (such as accessMode, method), avoiding repeated development; in conventional methods, language differences are often mixed with business code, resulting in maintenance difficulties; the embodiment of this specification abstracts language features into annotation parameters (such as constructorMode identifies dependency injection), so that language-related logic is concentrated in the annotation configuration layer, and the core parser does not need to perceive specific language details; when processing multiple languages, traditional solutions often lead to semantic deviations due to scattered configurations (such as Java field getter and JavaScript direct access conflicts); the embodiment of this specification requires developers to explicitly declare cross-language mapping rules in the DSL (such as @method method name mapping) through structured storage of annotation metadata for classes, fields, and methods, avoiding inconsistency problems from the source.
[0034] After extracting the matching specified class annotation set from the class annotation, the method further includes: based on the field access mode identification information, converting the field access syntax in the DSL file into a field expression corresponding to the target conversion language, wherein the field expression includes a field direct access expression, a predefined method call expression, or a key-value pair container access expression; according to the method mapping identification information, replacing the method name in the method call expression in the DSL file with the corresponding preset method name in the target conversion language, and adjusting the method parameter order to match the syntax of the target conversion language.
[0035] In one embodiment of the present specification, after completing the parsing of the class annotation, the field access expression of the target language is dynamically generated based on the accessMode identification information of the field. If the accessMode in the field annotation is direct, the field name in the DSL is directly mapped to the attribute access syntax of the target language (such as user.id). For the JavaBean mode, the field reading and writing are converted into method call expressions (such as user.getId() and user.setId(value)) according to the getter and setter method names specified in the annotation (or the default JavaBean naming rules). If the field access mode is hashmap, the access logic based on the key-value pair is generated (such as user.get("id") and user.set("id",value)), and the field name is automatically inserted into the target code as a string parameter. In this process, it is necessary to ensure that the generated expression conforms to the grammatical specifications of the target language, such as the brackets and parameter passing method of method calls in Java, or the square bracket access syntax of dynamic properties in JavaScript.
[0036] For method call expressions, name replacement is performed based on the method attribute (target language method name) in the method annotation. For example, the substring(start, length) method defined in the DSL retains its original name and generates substring(start, length) in Java, while it is mapped to substr(start, length) in JavaScript. For target language APIs with different parameter orders, the parameter positions are adjusted according to predefined parameter mapping rules. For example, if a method in a certain language requires the length parameter to be in front and the start position to be in the back, the parameter order is automatically swapped. In addition, parameter type conversions specific to the target language need to be handled, such as implicitly converting the numeric type in the DSL to the integer or floating-point type of the target language, to ensure the type safety of method calls.
[0037] When generating field and method expressions, the details are adapted in combination with the context rules of the target language. For example, Java requires method calls to contain parentheses and an explicit parameter list, while Python allows parentheses to be omitted; for hashmap access mode, Java needs to call the get() / put() method, while JavaScript can directly use the square bracket syntax. Through the built-in syntax template library, expression generation rules are predefined for each target language. For example, the direct mode of user.name is mapped to user.name in Java and to user.Name in C# (following the Pascal naming convention). At the same time, necessary syntax symbols (such as semicolons and quotation marks) are automatically inserted to ensure that the generated code can be directly compiled or interpreted.
[0038] Traditional solutions require writing independent field access and method call conversion logic for each target language, resulting in bloated and difficult-to-maintain code; the embodiments of this specification implement dynamic mapping through the accessMode and method parameters in the annotation, and only need to maintain a set of core conversion logic, and drive the generation of expressions in different languages through configuration; the embodiments of this specification use a predefined syntax template library to provide code generation rules that conform to the best practices for each access mode (such as direct, JavaBean) of the target language, reducing the workload of manual review and subsequent adjustments, and improving the readability and maintainability of the generated code.
[0039] The class definition in the DSL file is parsed to extract multiple class annotations marked in the class definition. Specifically, the process includes: identifying the type attribute of the class definition. If the class annotation corresponding to the class definition contains multiple target language identifiers, it is determined to be a public type; if it contains only one target language identifier, it is marked as a language-specific type; if the target conversion language is different from the target language identifier of the language-specific type, the compilation process is terminated and a type incompatibility log is generated.
[0040] In one embodiment of the present specification, when parsing a class definition in a DSL file, the first step is to traverse the @DSLClass annotation before the class declaration, extract the values of all language attributes therein (such as language: "java", language: "javascript"), and use them as the target language identifier set. For example, if the class annotation is @DSLClass(language: "java", language: "javascript"), the identifier set includes java and javascript. If there is only a single language attribute in the annotation (such as
[0041] @DSLClass(language:"python")), the identifier set only contains python. This process must ensure the integrity and uniqueness of identifiers to avoid duplication or conflict.
[0042] Based on the number of extracted target language identifiers, the type attribute of the class is determined: if the identifier set contains multiple languages (such as Java and JavaScript), the class is marked as a public type (such as the basic type string); if the identifier set contains only a single language (such as only Java), it is marked as a language-specific type (such as the Java-specific SpringBean class). This determination must be based on a strict set size check to ensure that there is no ambiguity in the division between public types and specific types. For example, the class corresponding to @DSLClass(language:"java",language:"typescript") will be classified as a public type, while
[0043] The class corresponding to @DSLClass(language:"csharp") is a C#-specific type.
[0044] After the user specifies the target conversion language (e.g., Java), the compiler iterates over the type attributes of all class definitions. For language-specific types, if their target language identifiers do not match the user-specified conversion language (e.g., a specific type is marked as CSharp, but the target language is Java), the compilation process is terminated immediately, and a log is generated containing the incorrect class name, target language identifier, and conflict details (e.g., "Class SpringBean is a C#-specific type and is incompatible with the target language Java"). This process must be completed early in the compilation process to ensure that incompatible types do not enter the subsequent code generation phase, thereby avoiding the generation of invalid or incorrect target code.
[0045] In traditional solutions, public types and language-specific types are usually defined through hard coding or configuration files, which can easily lead to type misuse due to human negligence. The embodiments of this specification automatically determine the type scope through the explicit language identifier set in the class annotation, ensuring that public types can be seamlessly reused across multiple languages, while specific types are only effective in their target language environment. In addition, the consistency of types and the target language is forcibly verified during the compilation phase. Once a mismatch is found, the process is immediately terminated and a clear log is generated. The pre-check mechanism significantly shortens the error feedback chain, allowing developers to quickly locate and fix type conflicts in DSL definitions, thereby improving development efficiency.
[0046] Step S103 , extracting a matching specified class annotation set from the class annotation according to the target conversion language and the target language identification information in the class annotation, so as to generate a code file conforming to the syntax of the target conversion language based on the specified class annotation set.
[0047] The specified class annotation set includes class annotations, field annotations, and method annotations.
[0048] In one embodiment of this specification, based on the target conversion language specified by the user (e.g., Java), all annotations containing matching language attributes are filtered from the annotation collection of classes, fields, and methods. For example, if the class annotation contains @DSLClass(language:"java",
[0049] If the constructorMode: "springContainer") is set, the annotation is retained as the basis for class generation. If the field annotation is @field({language: "java", accessMode: "JavaBean"}), the configuration is extracted to generate JavaBean-style field access logic. For common types (such as a string class containing language: "java" and language: "javascript"), only annotation parameters that match the target language (such as Java-related configuration) are retained to ensure that the type definition is legal and usable in the target language.
[0050] Unlike traditional solutions that require separate conversion logic for each language, the embodiments of this specification achieve precise mapping from a single DSL to multiple languages by dynamically filtering annotation parameters. For example, the same DSL class definition uses the language attribute of @DSLClass to distinguish between Java and JavaScript generation logic, eliminating the need to maintain separate converters for the two languages. Centralized annotation configuration significantly reduces code redundancy and improves the efficiency of expanding multi-language support.
[0051] Based on the specified class annotation set, a code file that conforms to the grammar of the target conversion language is generated, specifically comprising: based on the construction pattern identification information, generating an object instantiation expression in the target conversion language, wherein the object instantiation expression is related to the type of the construction pattern identification information; according to the array access pattern identification information, converting the array access syntax in the DSL file into a corresponding array or list access expression in the target conversion language; and according to the object instantiation expression and the array or list access expression, determining a code file that conforms to the grammar of the target language.
[0052] Based on the construction mode identification information, an object instantiation expression in the target conversion language is generated, specifically including: if the construction mode identification information is the default construction mode, an expression is generated that directly calls the target language constructor with the class name; if the construction mode identification information is the container dependency injection mode, an expression is generated that obtains a class instance from a preset container interface, wherein the name and method name of the preset container interface are specified by the container identification information in the class annotation.
[0053] In one embodiment of the present specification, based on the constructorMode identification information in the class annotation, the object instantiation expression of the target language is dynamically generated.
[0054] The constructorMode parameter value determines the instantiation mode of the current class. If the parameter value is default, it enters the default construction logic; if it is springContainer or other container dependency injection mode identifier (such as diContainer), it enters the container dependency injection logic. For example, when parsing to
[0055] When @DSLClass(constructorMode:"springContainer") is specified, it is recognized that the class instance needs to be obtained through the Spring container instead of directly calling the constructor.
[0056] When the construction mode is default, a standard object instantiation expression for the target language is generated. For languages that support explicit new operators (such as Java and C#), a new ClassName() expression is generated; for languages that rely on implicit constructor calls (such as Python and Ruby), a ClassName() expression is generated. In this process, the uri attribute in the class annotation is used to determine the fully qualified name of the class in the target language, such as Java's package path com.example.User, to ensure that the generated class name reference is consistent with the namespace specification of the target language. If the target language requires explicit type declarations (such as TypeScript), generic parameters are automatically supplemented, such as new User <string>().
[0057] When the construction mode is container dependency injection, the container interface identification information (such as containerInterface: "SpringBeanContainer" and method: "get") is extracted from the class annotation and the corresponding instance acquisition expression is generated. For example, for the Spring framework,
[0058] SpringBeanContainer.get(User.class); for .NET Core dependency injection container, generates ServiceProvider.GetService <user>(). If the class annotation does not explicitly specify the container interface and method name, the default dependency injection specification of the target language is used, such as the @Inject annotation in a Java CDI context. The calling syntax is automatically adapted based on the characteristics of the target language, for example, generating asynchronous container calls in JavaScript (such as awaitContainer.resolve('User')) or decorator-based factory methods in Python (such as @inject(User)).
[0059] According to the array access mode identification information, the array access syntax in the DSL file is converted into the corresponding array or list access expression in the target conversion language, specifically including: when the array access mode identification information is the list access mode, the array subscript access syntax in the DSL file is converted into a predefined access method call of the list type in the target conversion language, wherein the name of the access method is defined by the list method identifier in the class annotation.
[0060] In one embodiment of the present specification, the value of the arrayAccessMode parameter is extracted from the class annotation to determine the access mode type of the current array. When the parameter value is arrayList or a similar list access mode identifier, it is recognized that the array needs to be converted to a list type (such as Java's ArrayList or Python's list) in the target language. For example, if the class annotation is
[0061] @DSLClass(arrayAccessMode:"arrayList"), all subsequent array access operations for this class must be processed in list mode. According to the list method identifier specified in the class annotation (such as accessMethod:"get"), the array subscript access syntax in the DSL (such as users[2]) is converted into a list method call expression in the target language. If the class annotation does not explicitly define the method name, the default list access method of the target language is used (such as Java's get() and Python's __getitem__()). For example, users.get(2) is generated in Java, users.ElementAt(2) is generated in C#, and users.fetch(2) is generated in Ruby. During this process, it is necessary to ensure that the generated method name is consistent with the API naming of the standard library or commonly used library of the target language to avoid compilation or runtime exceptions caused by incorrect method names.
[0062] When generating method call expressions, parameter passing is adjusted based on the target language's grammatical rules. For strongly typed languages (such as Java and C#), method calls must strictly match parameter types (e.g., integer indices). Therefore, numerical indices in the DSL are automatically converted to integers in the target language (e.g., Java's int). For dynamically typed languages (e.g., Python and JavaScript), the original numerical types are retained. Furthermore, differences in method call notation in the target language are handled. For example, Java and C# require the use of periods and parentheses (users.get(2)), while Ruby allows parentheses to be omitted (users.get 2). Furthermore, if list access involves chained calls (e.g., multidimensional lists), the aforementioned rules are recursively applied to ensure that nested expressions conform to grammatical specifications.
[0063] Object instantiation expressions and array access expressions are embedded in the syntax framework of the target language to generate a complete code file. Class definitions are organized based on the modularization rules of the target language (such as Java's package declaration, C#'s namespace, and Python's import statement) to ensure that the generated code file can be directly compiled or interpreted. For example, in Java, a class file containing package com.example is generated, and expressions such as new User[5] and users.get(2) are integrated into the method body; in Ruby, type declarations are omitted, and dynamic array assignments (such as users = Array.new(5)) and method call chains are directly generated. The generated code strictly follows the syntax details of the target language, such as indentation, semicolons, and brackets (such as the difference between JavaScript's arrow function and Java's Lambda expression), and format review is performed through the built-in syntax checker to avoid low-level syntax errors.
[0064] Through the above technical solution, the traditional method requires writing independent target language conversion logic for each construction mode (such as new, dependency injection, and singleton), which leads to the technical problem of bloated code. The embodiment of this specification dynamically selects templates through the constructorMode annotation parameter, and there is no need to implement conversion logic for each framework separately. The decoupled design allows new construction modes to be added only by expanding the annotation parameters and template library, without modifying the core generator; in addition, the underlying data structure type is explicitly declared through arrayAccessMode to ensure that the generated access expression is consistent with the best practices of the target language, avoiding performance problems or runtime exceptions caused by data structure mismatch; in addition, traditional code generators often ignore the modularization rules of the target language (such as Python's __init__.py or Go's package management), resulting in the generated files being unable to be directly integrated into the project; when integrating expressions, the embodiment of this specification follows the engineering structure specifications of the target language, such as Maven directory layout and Node.js module export, and automatically generates necessary import / reference statements. This context-aware capability allows the generated code files to be embedded in existing projects without manual adjustment, significantly reducing integration costs.
[0065] Generate a code file that conforms to the target language syntax, specifically including: inserting the corresponding package import statement or module reference statement into the target language code file according to the class unique identification information in the class annotation; if the construction mode identification information is the container dependency injection mode, inserting an expression for obtaining a class instance from a preset dependency injection container into the target language code.
[0066] In one embodiment of the present specification, based on the uri attribute in the class annotation, that is, the class unique identification information, a package import or module reference statement corresponding to the target language is generated. For example, Java's uri:"com.example.User" will be converted to import com.example.User;, and Python's uri:"models.user" will be converted to from models.userimport User. For modular languages, such as JavaScript / TypeScript, reference code is generated according to the module system specification of the target language, such as import{User}from'com / example / User';. In this process, path separators (such as Java's . is converted to the file system's / ), alias conflicts (such as adding an as alias to the same-name class) and default export rules (such as Python's __init__.py implicit export) are automatically processed to ensure that the generated reference statements are legal and executable in the target language.
[0067] When the constructorMode in the class annotation identifies the container dependency injection mode, an expression that obtains an instance from the preset container is inserted into the target code. For example, if the class annotation specifies
[0068] If containerInterface: "SpringBeanContainer" and method: "get", the Java code User user = SpringBeanContainer.get(User.class) is generated; if the target language is C# and the container interface is ServiceProvider, var user = ServiceProvider.GetService is generated. <user>();. For scenarios where the container interface isn't explicitly specified, the target language's custom dependency injection framework automatically adapts to the target language. For example, it generates the @Autowired private User user; annotation for Java Spring and the constructor injection code publicController(User user){...} for .NET Core. The generated expression strictly adheres to the target language's syntax (such as the generic notation <> and type conversion operators) and is consistent with class references in package import statements.
[0069] Through the technical solutions of the embodiments of this specification, traditional code generation solutions usually need to design conversion rules separately for each target language, resulting in a large and difficult to maintain code base; the embodiments of this specification introduce class annotations containing target language identification information to centralize the multi-language adaptation logic to the annotation configuration layer. Developers explicitly declare language features such as construction patterns and array access rules through annotations in DSL. The generator only needs to parse these configurations and call the preset template library, without having to write repeated conversion logic for different languages, which significantly reduces the development and maintenance costs of multi-language support. For example, adding a new language only requires expanding the annotation parameters and template library, rather than reconstructing the entire generator; conventional methods Often rely on implicit rules to infer the behavior of the target language, for example, all classes are assumed to support multiple languages by default, which can easily lead to unusable generated code due to unhandled type conflicts; the embodiment of this specification uses the language identifier in the class annotation to force the definition of the language scope of the type, and the explicit declaration mechanism avoids the risk of type pollution from the source, ensuring that the generated code strictly follows the type system and grammar specifications of the target language; traditional converters often use hard-coded logic to implement when dealing with language feature differences, resulting in the coupling of templates and generation logic; the embodiment of this specification separates the annotation parsing and code generation stages, abstracts the grammar details into a configurable template library, makes the grammar rules dynamically extensible, and adds a new The collection type only needs to add the corresponding template without modifying the core generation logic, thereby improving the flexibility and maintainability of the system; conventional solutions usually find errors through compiler or runtime testing after the code is generated, resulting in high debugging costs; the embodiment of this specification verifies the integrity of the class annotations during the parsing phase, and the pre-verification mechanism advances the error feedback from runtime to compile time, allowing developers to quickly locate problems in the DSL definition, greatly improving development efficiency and the reliability of generated code; traditional multi-language development requires developers to be familiar with the syntax and framework details of all target languages, and the learning cost is extremely high; the embodiment of this specification uses a DSL syntax close to TypeScript ( Such as class definition, method signature) abstract language differences. Developers only need to master the DSL annotation rules to generate multi-language code, and encapsulate the language details in the generator, allowing developers to focus on business logic definition, significantly reducing the technical threshold for cross-language development; conventional generators are often deeply coupled with specific frameworks, resulting in the need to rewrite the generation logic when switching frameworks. The embodiments of this specification abstract framework dependencies into configurable items through annotation parameters (such as containerInterface, method). The parameterized design enables the generator to flexibly adapt to different technology stacks, avoiding the reconstruction of generation logic due to framework upgrades or replacements, and improving the life cycle and scope of application of the solution.
[0070] In one embodiment of this specification, object types are defined through declarative syntax, and annotation configuration for multi-language adaptation is used to achieve the conversion of a unified DSL into code in different target languages during the compilation phase. DSL uses TypeScript syntax as the basic syntax specification, with class (Class) as the basic abstract unit. Each class definition only contains the class name, field declaration, and method signature declaration, and does not involve specific method implementation logic. Its function is similar to that of a C++ header file. Fields must clearly declare types (such as string, number), and methods must define parameter types and return value types. For example, when defining a user class, you only need to declare the fields it contains, such as id (string type), name (string type), and method signatures such as getUserInfo(), without having to write the internal implementation code of the method.
[0071] Multi-language adaptation is achieved by adding annotations that mark each class, field, method, and parameter with the target language. The annotation must include a language attribute to specify the target language (such as Java or JavaScript), and set differentiated parameters based on the characteristics of the target language. For example, in class-level annotations, the uri attribute is used to specify the fully qualified class name in the target language (such as com.xxx.User in Java), the constructorMode defines the object instantiation method (such as default construction and Spring container retrieval), and the arrayAccessMode controls array access syntax (such as [] subscript or get() method call).
[0072] When the compiler parses the DSL, it first extracts all type definitions and associated annotations to build a cross-language semantic mapping relationship. For each target language, the following steps are performed: Filter type definitions that are only applicable to the current language based on the language attribute in the annotation. For example, the common type string works on both the front-end and back-end, while the Java-specific ArrayList class is only generated on the back-end. Convert the DSL syntax structure into a target language expression based on the annotation configuration. For example, field access is converted to a direct attribute reference (user.id), a Getter method call (user.getId()), or a Hashmap value (user.get("id")) based on the accessMode parameter; array access selects users[2] or users.get(2) based on arrayAccessMode. Cross-language method name mapping and call method conversion are achieved through method annotations. For example, the substr method in the DSL is mapped to a Java substring method call or a JavaScript substr method call; for the length attribute, it is converted to a length() method call in Java and directly accessed as a field in JavaScript.
[0073] Common types (such as the basic string and number types) need only be defined once in the DSL, with implementation details adapted to different target languages through multi-language annotations. For example, the string class is mapped to java.lang.String in Java, and its length field is converted to a length() method through annotations. In JavaScript, it is directly mapped to the native string type, with length accessed directly as a property. Language-specific types (such as Java's ArrayList) are declared only in the corresponding language's annotations, ensuring that only code suitable for that language is generated during compilation.
[0074] The compiler performs strong type verification and language compatibility checks during the conversion process. For example, when a hashCode method marked only with language: "java" is called in a DSL, if the target language is JavaScript, the compiler will throw an error that the method does not exist; if the field access mode is set to JavaBean but the getter / setter method name is not explicitly specified, the default method name is automatically generated according to the camel case rule (such as getId corresponding to the id field). The final generated code is deeply integrated with the target language framework. For example, Java backend code can implement dependency injection through SpringBeanContainer annotations, and the front-end JavaScript code generates a model that conforms to the model.
[0075] Block-based, standardized class definitions. The compiler automatically handles package imports (such as Java's import statement) or module references (such as JavaScript's require) based on the uri attribute in the annotation, ensuring that the generated code can be directly embedded in the target technology stack.
[0076] The following is an example of a class annotation provided in the embodiments of this specification.
[0077] @DSLClass(language:"java",uri:"com.xxx.xx..",constructorMode:
[0078] "",arrayAcessMode="")
[0079] export class ClassName{}
[0080] When converting to the target language, class creation expressions and array access expressions are generated based on the annotations set on the class. The URI is the unique identifier of the class in the target language. For example, if the language is Java, the URI refers to the namespace of the class.
[0081] The default object creation method is as follows:
[0082] @DSLClass(language:"java",constructorMode:"default")
[0083] export class User{}
[0084] The object creation expression is User user = new User();
[0085] In the SpringContainer object creation method, instances of some classes in the Java backend are managed by the spring container:
[0086] @DSLClass(constructorMode:"springContainer")
[0087] export class UserService{}
[0088] The object creation expression is: UserService service=
[0089] SpringBeanContainer.get(UserService.class)
[0090] Array subscript access is as follows:
[0091] @DSLClass(constructorMode:"array",arrayAccessMode:"array")
[0092] export class Array{}
[0093] An example of an object creation expression is User[]users=new User[5]; an example of an array subscript access expression is users[2]; and list subscript access is as follows:
[0094] @DSLClass(arrayAccess:"arrayList",uri:
[0095] "java.util.ArrayList")
[0096] export class ArrayList{}
[0097] The array subscript access expression is users.get(2).
[0098] In addition, you can set the field access method in the field annotation. When converting to the target language, the field access expression is generated according to the set field access method. For example, the User class contains an id field. The access method is extensible. The following are some common access methods:
[0099] The first is direct access, which is also the default field access method. The annotation is:
[0100] @field({language:"java",accessMode:"direct"})
[0101] id:string
[0102] Get the field value expression user.id and set the field value expression user.id = "abc";
[0103] The second is the JavaBean method:
[0104] @field({language:"java",accessMode:"JavaBean",getter:"getId",setter:"setId"}
[0105] id:string
[0106] In this mode, you can set getter and setter methods. If not, the default JavaBean rules are used.
[0107] Get the field value expression user.getId(), set the field value expression user.setId("abc");
[0108] Another example is the hashmap method:
[0109] @field({language:"java",accessMode:"hashmap")
[0110] id:string
[0111] In low-code, data is generally stored in a Hashmap, such as the one that gets the field value using the expression user.get("id") and sets the field value using the expression user.set("id","abc");
[0112] The following is an example of a field conversion method:
[0113]
[0114] Taking string as an example, string in TypeScript has a length attribute, but there is no length attribute in Java. However, there is a length method, which can be mapped to the specified method in the annotation configuration. For example, if there is an expression "abc".length in DSL, it will be converted to "abc".length() based on the configuration when compiled into Java.
[0115] Method annotation, taking string as an example, the example is as follows:
[0116]
[0117] Regarding method-to-field conversion, JavaScript string doesn't have a length method, but rather a length field. When converting to JavaScript, these methods are converted to field calls. Regarding method name replacement, substr is a JavaScript method, and Java has a corresponding method, substring. Methods in the string class are a collection of Java and JavaScript methods, and most methods are convertible between them. Some methods are language-specific, such as hashCode, which exists only in Java and sets Java language properties. These methods cannot be used in JavaScript. During compilation, a check is performed to ensure that the runtime environment and method match.
[0118] The embodiment of this specification also provides a code conversion device based on a domain specific language, such as Figure 2 As shown, the device includes: at least one processor; and a memory communicatively connected to the at least one processor; wherein the memory stores instructions that can be executed by the at least one processor, and the instructions are executed by the at least one processor to enable the at least one processor to perform the above method.
[0119] The embodiments of this specification also provide a non-volatile computer storage medium storing computer executable instructions, wherein the computer executable instructions are configured to execute the above method.
[0120] The various embodiments in this specification are described in a progressive manner. Similar portions between the various embodiments can be referenced to each other, and each embodiment focuses on the differences from the other embodiments. In particular, the device, apparatus, and non-volatile computer storage medium embodiments are generally similar to the method embodiments, so their descriptions are relatively simplified. For relevant details, refer to the descriptions of the method embodiments.
[0121] The foregoing description of this specification describes specific embodiments. Other embodiments are within the scope of the appended claims. In some cases, the actions or steps recited in the claims can be performed in an order different from that described in the embodiments and still achieve the desired results. Furthermore, the processes depicted in the accompanying drawings do not necessarily require the specific order shown or the sequential order to achieve the desired results. In certain embodiments, multitasking and parallel processing are also possible or may be advantageous.
[0122] The devices and media provided in the embodiments of this specification correspond one-to-one to the methods. Therefore, the devices and media also have similar beneficial technical effects to their corresponding methods. Since the beneficial technical effects of the methods have been described in detail above, the beneficial technical effects of the devices and media will not be repeated here.
[0123] Those skilled in the art will appreciate that the embodiments of this specification may be provided as methods, systems, or computer program products. Therefore, this specification may take the form of a complete hardware embodiment, a complete software embodiment, or an embodiment combining software and hardware. Furthermore, this specification may take the form of a computer program product implemented on one or more computer-usable storage media (including but not limited to magnetic disk storage, CD-ROM, optical storage, etc.) containing computer-usable program code.
[0124] This specification is described with reference to the flowcharts and / or block diagrams of the methods, devices (systems), and computer program products according to the embodiments of this specification. It should be understood that each process and / or box in the flowchart and / or block diagram, as well as the combination of processes and / or boxes in the flowchart and / or block diagram, can be implemented by computer program instructions. These computer program instructions can be provided to a processor of a general-purpose computer, a special-purpose computer, an embedded processor, or other programmable data processing device to produce a machine, so that the instructions executed by the processor of the computer or other programmable data processing device generate instructions for implementing the processes in the flowchart and / or block diagram. Figure 1 a process or multiple processes and / or boxes Figure 1 A device that provides the functions specified in a block or multiple blocks.
[0125] These computer program instructions may also be stored in a computer readable memory that can direct a computer or other programmable data processing device to work in a specific manner, so that the instructions stored in the computer readable memory produce an article of manufacture comprising an instruction device, which implements the process Figure 1 a process or multiple processes and / or boxes Figure 1 The function specified in one or more boxes.
[0126] These computer program instructions can also be loaded onto a computer or other programmable data processing device so that a series of operational steps are executed on the computer or other programmable device to produce a computer-implemented process, thereby providing the instructions executed on the computer or other programmable device for implementing the process. Figure 1 a process or multiple processes and / or boxes Figure 1 A step that specifies a function in one or more boxes.
[0127] In a typical configuration, a computing device includes one or more processors (CPUs), input / output interfaces, network interfaces, and memory.
[0128] Memory may include non-permanent storage in a computer-readable medium, random access memory (RAM) and / or non-volatile memory in the form of read-only memory (ROM) or flash RAM. Memory is an example of a computer-readable medium.
[0129] Computer-readable media includes permanent and non-permanent, removable and non-removable media that can be implemented by any method or technology to store information. The information can be computer-readable instructions, data structures, program modules or other data. Examples of computer storage media include, but are not limited to, phase change memory (PRAM), static random access memory (SRAM), dynamic random access memory (DRAM), other types of random access memory (RAM), read-only memory (ROM), electrically erasable programmable read-only memory (EEPROM), flash memory or other memory technology, compact disc read-only memory (CD-ROM), digital versatile disc (DVD) or other optical storage, magnetic cassettes, magnetic tape, magnetic disk storage or other magnetic storage devices or any other non-transmission media that can be used to store information that can be accessed by a computing device. As defined herein, computer-readable media does not include transitory computer-readable media (transitory media), such as modulated data signals and carrier waves.
[0130] It should also be noted that the terms "comprises," "includes," or any other variations thereof are intended to encompass non-exclusive inclusion, such that a process, method, commodity, or apparatus that includes a list of elements includes not only those elements but also other elements not explicitly listed, or includes elements inherent to such process, method, commodity, or apparatus. In the absence of further limitations, an element defined by the phrase "comprising a..." does not preclude the presence of other identical elements in the process, method, commodity, or apparatus that includes the element.
[0131] The foregoing description is merely one or more embodiments of this specification and is not intended to limit this specification. It will be apparent to those skilled in the art that various modifications and variations may be made to one or more embodiments of this specification. Any modifications, equivalent substitutions, or improvements made within the spirit and principles of one or more embodiments of this specification are intended to be within the scope of the claims of this specification.< / user> < / user> < / string>
Claims
1. A code conversion method based on a domain-specific language, characterized in that: The method comprises: Receive a DSL file and a target transformation language input by a user, wherein the DSL file includes at least one class definition, and the class definition includes a class name, a field declaration, and a method signature declaration; Parsing the DSL file to extract multiple class annotations marked in the class definition, wherein the class annotations include target language identification information, class unique identification information, construction mode identification information, and array access mode identification information; According to the target conversion language and the target language identification information in the class annotation, a matching specified class annotation set is extracted from the class annotation to generate a code file that conforms to the syntax of the target conversion language based on the specified class annotation set, wherein the specified class annotation set includes class annotations, field annotations and method annotations.
2. The code conversion method based on a domain specific language according to claim 1, characterized in that Based on the specified class annotation set, a code file that conforms to the grammar of the target conversion language is generated, specifically including: Based on the construction pattern identification information, generating an object instantiation expression in the target conversion language, wherein the object instantiation expression is related to the type of the construction pattern identification information; Converting the array access syntax in the DSL file into a corresponding array or list access expression in the target conversion language according to the array access mode identification information; A code file conforming to the target language syntax is determined according to the object instantiation expression and the array or list access expression.
3. The code conversion method based on domain specific language according to claim 1, characterized in that: Parse the class definition in the DSL file to extract multiple class annotations marked in the class definition, specifically including: Extracting a field annotation annotated on a field declaration in the class definition, wherein the field annotation includes target language identification information and field access mode identification information; Extracting a method annotation annotated on a method signature declaration in the class definition, wherein the method annotation includes target language identification information and method mapping identification information; Extracting construction mode identification information from the class definition, wherein the construction mode identification information includes a default construction mode and a container dependency injection mode.
4. The code conversion method based on domain specific language according to claim 3, characterized in that: Generating an object instantiation expression in the target conversion language based on the construction pattern identification information specifically includes: If the construction mode identification information is the default construction mode, an expression is generated that directly calls the target language constructor using the class name; If the construction mode identification information is the container dependency injection mode, an expression is generated to obtain a class instance from a preset container interface, wherein the name and method name of the preset container interface are specified by the container identification information in the class annotation.
5. The code conversion method based on domain specific language according to claim 3, characterized in that: After extracting a matching specified class annotation set from the class annotations, the method further includes: Based on the field access mode identification information, convert the field access syntax in the DSL file into a field expression corresponding to the target conversion language, wherein the field expression includes a field direct access expression, a predefined method call expression, or a key-value pair container access expression; According to the method mapping identification information, the method name in the method call expression in the DSL file is replaced with the corresponding preset method name in the target conversion language, and the order of method parameters is adjusted to match the syntax of the target conversion language.
6. The code conversion method based on domain specific language according to claim 2, characterized in that: According to the array access mode identification information, the array access syntax in the DSL file is converted into a corresponding array or list access expression in the target conversion language, specifically including: When the array access mode identification information is a list access mode, the array subscript access syntax in the DSL file is converted into a predefined access method call of the list type in the target conversion language, wherein the name of the access method is defined by the list method identifier in the class annotation.
7. The code conversion method based on domain specific language according to claim 1, characterized in that: Parse the class definition in the DSL file to extract multiple class annotations marked in the class definition, specifically including: Identify the type attribute of the class definition. If the class annotation corresponding to the class definition contains multiple target language identifiers, it is determined to be a public type; if it contains only one target language identifier, it is marked as a language-specific type. If the target conversion language is different from the target language identifier of the language-specific type, the compilation process is terminated and a type incompatibility log is generated.
8. The code conversion method based on domain specific language according to claim 1, characterized in that: Generate code files that conform to the target language syntax, including: Inserting a corresponding package import statement or module reference statement into the target language code file according to the class unique identification information in the class annotation; If the construction mode identification information is the container dependency injection mode, an expression for obtaining a class instance from a preset dependency injection container is inserted into the target language code.
9. A code conversion device based on a domain-specific language, characterized in that The device comprises: at least one processor; and, a memory communicatively connected to the at least one processor; wherein, The memory stores instructions that can be executed by the at least one processor. The instructions are executed by the at least one processor to enable the at least one processor to perform the method according to any one of claims 1 to 8.
10. A non-volatile computer storage medium storing computer executable instructions, characterized in that: The computer executable instructions are configured to execute the method according to any one of claims 1 to 8.
Citation Information
Cited By
File generation method in processor development process and related products
CN121807270A
Zero-intrusion-oriented compiling period type conversion generation method
CN121979502A
Zero-invasive compile-time type conversion generation method
CN121979502B