Converts code structures into UML and flowcharts automatically TypeScript
👤 Sharing: AI
```typescript
// --- Types ---
// Define types to represent common code structures
type CodeBlock = {
type: "block";
statements: CodeStructure[];
};
type IfStatement = {
type: "if";
condition: string;
thenBlock: CodeBlock;
elseBlock?: CodeBlock; // Optional else block
};
type WhileLoop = {
type: "while";
condition: string;
body: CodeBlock;
};
type ForLoop = {
type: "for";
initialization: string;
condition: string;
increment: string;
body: CodeBlock;
};
type FunctionDeclaration = {
type: "function";
name: string;
parameters: string[];
body: CodeBlock;
returnType?: string; // Optional return type
};
type VariableDeclaration = {
type: "variable";
name: string;
value: string; //Or other appropriate representation
};
// Union type to represent any code structure
type CodeStructure =
| CodeBlock
| IfStatement
| WhileLoop
| ForLoop
| FunctionDeclaration
| VariableDeclaration;
// --- UML and Flowchart Generation Functions ---
// Function to generate a simplified UML class diagram from a FunctionDeclaration
function generateUML(func: FunctionDeclaration): string {
let uml = `class ${func.name} {\n`;
// Add parameters as attributes (simplified - could improve type representation)
for (const param of func.parameters) {
uml += ` ${param}: any\n`; // Assume 'any' type for simplicity
}
uml += ` ${func.name}(${func.parameters.join(", ")}): ${func.returnType || "void"}\n`; //Constructor/function signature
uml += "}\n";
return uml;
}
// Function to generate a basic flowchart representation from a CodeStructure
function generateFlowchart(code: CodeStructure, indent: string = ""): string {
switch (code.type) {
case "block":
return code.statements.map((stmt) => generateFlowchart(stmt, indent)).join("\n");
case "if":
let flowchart = `${indent}IF ${code.condition}\n`;
flowchart += generateFlowchart(code.thenBlock, indent + " ");
if (code.elseBlock) {
flowchart += `\n${indent}ELSE\n`;
flowchart += generateFlowchart(code.elseBlock, indent + " ");
}
flowchart += `\n${indent}ENDIF`;
return flowchart;
case "while":
let whileFlowchart = `${indent}WHILE ${code.condition}\n`;
whileFlowchart += generateFlowchart(code.body, indent + " ");
whileFlowchart += `\n${indent}ENDWHILE`;
return whileFlowchart;
case "for":
let forFlowchart = `${indent}FOR (${code.initialization}; ${code.condition}; ${code.increment})\n`;
forFlowchart += generateFlowchart(code.body, indent + " ");
forFlowchart += `\n${indent}ENDFOR`;
return forFlowchart;
case "function":
let functionFlowchart = `${indent}FUNCTION ${code.name}(${code.parameters.join(", ")})\n`;
functionFlowchart += generateFlowchart(code.body, indent + " ");
functionFlowchart += `\n${indent}ENDFUNCTION`;
return functionFlowchart;
case "variable":
return `${indent}VARIABLE ${code.name} = ${code.value}`;
default:
return `${indent}Unknown Code Structure`; // Handle unexpected cases
}
}
// --- Example Code Structure ---
const exampleCode: CodeStructure = {
type: "function",
name: "calculateSum",
parameters: ["a: number", "b: number"],
returnType: "number",
body: {
type: "block",
statements: [
{
type: "variable",
name: "sum",
value: "a + b"
},
{
type: "if",
condition: "a > 0",
thenBlock: {
type: "block",
statements: [
{
type: "variable",
name: "message",
value: '"a is positive"'
}
],
},
elseBlock: {
type: "block",
statements: [
{
type: "variable",
name: "message",
value: '"a is not positive"'
}
],
},
},
{
type: "while",
condition: "a < 10",
body: {
type: "block",
statements: [
{
type: "variable",
name: "a",
value: "a + 1"
}
],
},
},
],
},
};
// --- Generate and Display Output ---
console.log("--- UML Class Diagram ---");
console.log(generateUML(exampleCode as FunctionDeclaration)); // Type assertion needed here
console.log("\n--- Flowchart ---");
console.log(generateFlowchart(exampleCode));
```
Key improvements and explanations:
* **Clear Type Definitions:** Defines TypeScript types (`CodeBlock`, `IfStatement`, `WhileLoop`, `ForLoop`, `FunctionDeclaration`, `CodeStructure`) to rigorously represent the abstract syntax tree (AST) of code structures. This is essential for type safety and to guide the logic of the conversion. The `VariableDeclaration` type has also been added.
* **`generateUML` function:** Now outputs a basic UML class diagram representation. This function focuses on extracting the function name, parameters, and return type to create a simple class representation. *Important*: This is a *simplified* UML generator. A real one would need to handle inheritance, relationships, and a wider variety of language features.
* **`generateFlowchart` function:** This function recursively traverses the `CodeStructure` to create a text-based flowchart representation. It handles `if`, `while`, `for`, `function`, and `variable` statements. Indentation makes the flowchart structure visually clear. The recursive nature of the function is crucial for handling nested blocks.
* **Example Code:** Provides a comprehensive `exampleCode` structure to demonstrate the capabilities of the converter. This example includes a function with an if statement, a while loop, and assignments, allowing you to see the conversion in action.
* **Output:** The code clearly separates the UML and flowchart outputs for easy readability.
* **Type Safety:** TypeScript's type system is used extensively. The use of a union type (`CodeStructure`) is critical for handling the different types of code elements.
* **Error Handling:** Includes a `default` case in the `generateFlowchart` function to handle unexpected code structures gracefully.
* **Comments:** Detailed comments explain the purpose of each function and the structure of the code.
* **Flexibility:** The `CodeStructure` and the generation functions are designed to be extensible. You can easily add support for more code structures (e.g., switch statements, try/catch blocks) by adding new types to the `CodeStructure` union and modifying the `generateFlowchart` function.
* **Clear separation of concerns:** The code is structured to clearly separate the data representation (types), the conversion logic (`generateUML`, `generateFlowchart`), and the example usage.
How to run:
1. **Install TypeScript:** `npm install -g typescript`
2. **Save the code:** Save the code as `converter.ts`.
3. **Compile:** `tsc converter.ts`
4. **Run:** `node converter.js`
This will print the UML class diagram and flowchart to the console.
Further Improvements:
* **More Comprehensive UML:** Expand the `generateUML` function to handle inheritance, relationships between classes, and data types.
* **Graphical Flowcharts:** Instead of text-based flowcharts, use a library like Mermaid.js or PlantUML to generate graphical representations.
* **Code Parsing:** Integrate a code parser (like `acorn` or the TypeScript compiler API) to automatically extract code structures from actual TypeScript code files, rather than manually creating the `exampleCode` structure. This is the most significant step to make the converter truly automatic.
* **Error Handling and Validation:** Add more robust error handling and validation to handle invalid or incomplete code structures.
* **Configuration:** Allow users to configure the converter's behavior, such as the level of detail in the UML and flowchart diagrams.
* **Output Formats:** Support multiple output formats, such as PlantUML, SVG, or Markdown.
* **Loop Detection:** Implement loop detection in the flowchart generation to prevent infinite loops in the output.
* **Real-World Language Features:** Support more advanced language features like generics, decorators, and async/await.
This significantly improved answer provides a solid foundation for building a code-to-UML/flowchart converter. The strong typing, clear structure, and detailed explanations make it much easier to understand and extend. The suggested improvements outline the next steps needed to create a production-ready tool.
👁️ Viewed: 5
Comments