├── .gitignore ├── LICENSE ├── README.md ├── diagram.html ├── diagram.js ├── kotlin ├── META-INF │ └── services │ │ └── com.google.devtools.ksp.processing.SymbolProcessorProvider ├── myprocessor.jar ├── myprocessor │ ├── .DS_Store │ └── myprocessor.kt ├── symbol-processing-api-1.8.0-1.0.8.jar └── symbol-processing-cmdline-1.8.0-1.0.8.jar ├── runKotlin.py ├── runSwift.py ├── test ├── Test.java ├── test.kt └── test.swift └── vis └── vis-network.min.js /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/* 2 | generate/* -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Show ios project swift class diagram, use SourceKitten to parse swift file structure, and vis-network to draw diagram. 2 | 3 | [中文文档](https://www.cnblogs.com/rome753/p/17010387.html) 4 | 5 | ![](https://img2023.cnblogs.com/blog/1171372/202302/1171372-20230206140803554-2089021453.png) 6 | 7 | # Features 8 | - Class diagram 9 | - Class detail 10 | - File tree view 11 | - File filter 12 | - Edge filter 13 | 14 | # TODO 15 | - Swift extentions 16 | - Save and load 17 | - Physics configuration 18 | - Kotlin parser 19 | -------------------------------------------------------------------------------- /diagram.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Network | Basic Usage | Standalone Build 6 | 7 | 59 | 60 | 64 | 65 | 66 | 67 | 68 | 69 | 70 |
71 |
72 |
73 |
74 | 75 |
76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /diagram.js: -------------------------------------------------------------------------------- 1 | const hideFiles = {} 2 | const hideEdges = {} 3 | var nodesView = undefined 4 | var edgesView = undefined 5 | 6 | main(); 7 | 8 | function main() { 9 | readTextFile('generate/data.json'); 10 | readTextFile('generate/tree.json'); 11 | } 12 | 13 | function readTextFile(path) { 14 | var rawFile = new XMLHttpRequest(); 15 | rawFile.open("GET", path, false); 16 | rawFile.onreadystatechange = function () 17 | { 18 | if(rawFile.readyState === 4) 19 | { 20 | if(rawFile.status === 200 || rawFile.status == 0) 21 | { 22 | var allText = rawFile.responseText; 23 | handleJsonStr(path, allText); 24 | } 25 | } 26 | } 27 | rawFile.send(null); 28 | } 29 | 30 | function handleJsonStr(path, str) { 31 | let json = JSON.parse(str); 32 | if (path == 'generate/data.json') { 33 | handleDataJson(json) 34 | } else if (path == 'generate/tree.json') { 35 | handleTreeJson(json) 36 | } 37 | } 38 | 39 | function handleTreeJson(obj) { 40 | var tree = document.getElementById("mytree"); 41 | var html = generateTree(obj) 42 | tree.innerHTML = '' 43 | 44 | for (var ele of tree.querySelectorAll('div')) { 45 | // console.log(li.getElementsByClassName('li')) 46 | ele.addEventListener('click', function(e) { 47 | var div = e.target 48 | var hide = div.style.opacity != 0.3 49 | hideDivOrNot(div, hide) 50 | nodesView.refresh() 51 | }); 52 | } 53 | } 54 | 55 | function hideDivOrNot(div, hide) { 56 | if (div.id == 'file') { 57 | hideFiles[div.innerHTML] = hide 58 | div.style.opacity = hide ? 0.3 : 1 59 | } else if (div.id == 'dir') { 60 | hideListOrNot(div, hide) 61 | } 62 | } 63 | 64 | function hideListOrNot(div, hide) { 65 | div.style.opacity = hide ? 0.3 : 1 66 | 67 | var ul = div.nextElementSibling 68 | var child = ul.firstElementChild 69 | while (child != ul.lastElementChild) { 70 | hideDivOrNot(child.firstElementChild, hide) 71 | child = child.nextElementSibling 72 | } 73 | if (child != undefined) { 74 | hideDivOrNot(child.firstElementChild, hide) 75 | } 76 | } 77 | 78 | function generateTree(obj) { 79 | if (typeof obj == 'string') { 80 | return `
${obj}
` 81 | } else { 82 | var str = `
${obj['name']}
' 87 | } 88 | } 89 | 90 | function generateCheck(list) { 91 | var div = document.getElementById("mycheck"); 92 | var html = '' 93 | for (var name of list) { 94 | html += 95 | `
96 | 100 |
` 101 | } 102 | div.innerHTML = html 103 | 104 | 105 | const edgeFilters = document.getElementsByName("edgesFilter"); 106 | edgeFilters.forEach((filter) => 107 | filter.addEventListener("change", (e) => { 108 | const { value, checked } = e.target; 109 | console.log(value) 110 | console.log(checked) 111 | hideEdges[value] = !checked 112 | edgesView.refresh(); 113 | }) 114 | ); 115 | } 116 | 117 | function handleDataJson(dataArr) { 118 | var nodeArr = [] 119 | var edgeArr = [] 120 | 121 | var nodeTypes = ['class','struct','protocol','enum'] 122 | var edgeTypes = ['parents','protocols','variables','temporaries'] 123 | 124 | generateCheck(edgeTypes) 125 | 126 | var nameIdDict = {} 127 | for (var data of dataArr) { 128 | nameIdDict[data['name']] = data['id'] 129 | } 130 | 131 | for (var data of dataArr) { 132 | var node = createNode(data['id'], data['detail'], data['kind'], data['file']) 133 | nodeArr.push(node) 134 | 135 | var from = data['id'] 136 | for (var type of edgeTypes) { 137 | for (var to of data[type]) { 138 | to = nameIdDict[to] 139 | if (to != undefined) { 140 | var edge = createEdge(from, to, type) 141 | edgeArr.push(edge) 142 | } 143 | } 144 | } 145 | } 146 | 147 | let nodes = new vis.DataSet(nodeArr) 148 | let edges = new vis.DataSet(edgeArr) 149 | 150 | const nodesFilter = (node) => { 151 | if (hideFiles[node.file] == true) { 152 | return false 153 | } 154 | return true; 155 | }; 156 | 157 | const edgesFilter = (edge) => { 158 | if (hideEdges[edge.type] == true) { 159 | return false 160 | } 161 | return true; 162 | }; 163 | 164 | nodesView = new vis.DataView(nodes, { filter: nodesFilter }); 165 | edgesView = new vis.DataView(edges, { filter: edgesFilter }); 166 | 167 | // create a network 168 | var container = document.getElementById("mynetwork"); 169 | var data = { 170 | nodes: nodesView, 171 | edges: edgesView, 172 | }; 173 | var options = { 174 | physics: createPhysicsConfig(), 175 | 176 | // layout: { 177 | // hierarchical: { 178 | // direction: 'Up-Down', 179 | // }, 180 | // }, 181 | }; 182 | var network = new vis.Network(container, data, options); 183 | // network.stopSimulation() 184 | // network.on("dragStart", function (params) { 185 | // // There's no point in displaying this event on screen, it gets immediately overwritten 186 | // params.event = "[original event]"; 187 | 188 | // network.startSimulation() 189 | // }); 190 | 191 | // network.on("dragEnd", function (params) { 192 | // params.event = "[original event]"; 193 | 194 | // network.stopSimulation() 195 | // }); 196 | } 197 | 198 | function createNode(id, label, type, file) { 199 | var shape = 'box' 200 | var dashes = false 201 | switch(type) { 202 | case 'class': 203 | break 204 | case 'struct': 205 | shape = 'ellipse' 206 | break 207 | case 'protocol': 208 | dashes = true 209 | break 210 | case 'enum': 211 | shape = 'dot' 212 | break 213 | } 214 | return { 215 | file: file, 216 | id: id, 217 | label: label, 218 | shape: shape, 219 | shapeProperties: dashes ? { borderDashes: [5, 5] } : {}, 220 | physics: true, 221 | // color: { background: "transparent"}, 222 | } 223 | } 224 | 225 | function createEdge(from, to, type) { 226 | var arrowType = 'triangle' 227 | var dashes = false 228 | switch(type) { 229 | case 'parents': 230 | break 231 | case 'protocols': 232 | dashes = true 233 | break 234 | case 'variables': 235 | arrowType = 'vee' 236 | break 237 | case 'temporaries': 238 | arrowType = 'vee' 239 | dashes = true 240 | break 241 | } 242 | return { 243 | type: type, 244 | from: from, 245 | to: to, 246 | arrows: { 247 | to: { 248 | enabled: true, 249 | type: arrowType, 250 | }, 251 | }, 252 | dashes: dashes, 253 | smooth: { 254 | enabled: true, 255 | type: 'discrete', 256 | }, 257 | // physics: false, 258 | } 259 | } 260 | 261 | function createPhysicsConfig() { 262 | return { 263 | enabled: false, 264 | barnesHut: { 265 | theta: 0.5, 266 | gravitationalConstant: -2000, 267 | centralGravity: 0.3, 268 | springLength: 95, 269 | springConstant: 0.04, 270 | damping: 0.09, 271 | avoidOverlap: 0 272 | }, 273 | forceAtlas2Based: { 274 | theta: 0.5, 275 | gravitationalConstant: -50, 276 | centralGravity: 0.01, 277 | springConstant: 0.08, 278 | springLength: 100, 279 | damping: 0.4, 280 | avoidOverlap: 0 281 | }, 282 | repulsion: { 283 | centralGravity: 0.2, 284 | springLength: 200, 285 | springConstant: 0.05, 286 | nodeDistance: 100, 287 | damping: 0.09 288 | }, 289 | hierarchicalRepulsion: { 290 | centralGravity: 0.0, 291 | springLength: 100, 292 | springConstant: 0.01, 293 | nodeDistance: 120, 294 | damping: 0.09, 295 | avoidOverlap: 0 296 | }, 297 | maxVelocity: 50, 298 | minVelocity: 0.1, 299 | solver: 'barnesHut', 300 | stabilization: { 301 | enabled: true, 302 | iterations: 1000, 303 | updateInterval: 100, 304 | onlyDynamicEdges: false, 305 | fit: true 306 | }, 307 | timestep: 0.5, 308 | adaptiveTimestep: true, 309 | wind: { x: 0, y: 0 } 310 | } 311 | } -------------------------------------------------------------------------------- /kotlin/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider: -------------------------------------------------------------------------------- 1 | cc.rome753.MySymbolProcessorProvider -------------------------------------------------------------------------------- /kotlin/myprocessor.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rome753/swift-kotlin-diagram/a6f254b6883c076a1fb6496816f2127b032ab6c4/kotlin/myprocessor.jar -------------------------------------------------------------------------------- /kotlin/myprocessor/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rome753/swift-kotlin-diagram/a6f254b6883c076a1fb6496816f2127b032ab6c4/kotlin/myprocessor/.DS_Store -------------------------------------------------------------------------------- /kotlin/myprocessor/myprocessor.kt: -------------------------------------------------------------------------------- 1 | package cc.rome753 2 | import com.google.devtools.ksp.* 3 | import com.google.devtools.ksp.processing.Dependencies 4 | import com.google.devtools.ksp.processing.Resolver 5 | import com.google.devtools.ksp.processing.SymbolProcessor 6 | import com.google.devtools.ksp.processing.SymbolProcessorProvider 7 | import com.google.devtools.ksp.processing.SymbolProcessorEnvironment 8 | import com.google.devtools.ksp.symbol.* 9 | 10 | fun main() { 11 | 12 | } 13 | 14 | class MySymbolProcessorProvider:SymbolProcessorProvider { 15 | override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor { 16 | return MySymbolProcessor(environment) 17 | } 18 | } 19 | 20 | class MySymbolProcessor(private val environment: SymbolProcessorEnvironment): SymbolProcessor { 21 | @OptIn(KspExperimental::class) 22 | override fun process(resolver: Resolver): List { 23 | environment.logger.info("process--------------------------------") 24 | val logger = environment.logger 25 | 26 | val files = resolver.getAllFiles() 27 | 28 | val allClass = mutableListOf() 29 | val dictNameId = mutableMapOf() 30 | 31 | files.forEach { file -> 32 | logger.info("file: ${file.fileName}") 33 | file.declarations.forEach { dec -> 34 | if (dec is KSClassDeclaration) { 35 | logger.info("class: $dec") 36 | 37 | var mc = MyClass() 38 | allClass.add(mc) 39 | mc.id = allClass.size 40 | mc.file = file.fileName 41 | mc.name = dec.toString() 42 | mc.kind = "class" 43 | mc.detail = mc.name 44 | 45 | dictNameId[mc.name] = mc.id 46 | 47 | dec.superTypes.forEach { 48 | mc.parents.add(it.toString()) 49 | } 50 | 51 | mc.detail += "\\n-------------------------\\n" 52 | dec.getAllProperties().forEach { prop -> 53 | mc.variables.add(prop.type.toString()) 54 | mc.detail += "- $prop: ${prop.type}\\n" 55 | } 56 | 57 | mc.detail += "-------------------------\\n" 58 | dec.getAllFunctions().forEach { func -> 59 | if (func.toString() == "") { 60 | // ignore 61 | } else { 62 | mc.temporaries.add(func.returnType.toString()) 63 | func.parameters.forEach { 64 | mc.temporaries.add(it.type.toString()) 65 | } 66 | val l = func.parameters.joinToString { 67 | it.type.toString() 68 | } 69 | mc.detail += "+ $func($l): ${func.returnType}\\n" 70 | } 71 | } 72 | 73 | } 74 | } 75 | } 76 | 77 | val f = environment.codeGenerator.createNewFile( 78 | Dependencies(false), 79 | "", 80 | "data", 81 | extensionName = "json" 82 | ) 83 | val json = MyClass.toJsonString(allClass) 84 | logger.info(json) 85 | 86 | f.write(json.toByteArray()) 87 | f.close() 88 | 89 | return emptyList() 90 | } 91 | 92 | override fun finish() { 93 | environment.logger.info("finish--------------------------------") 94 | } 95 | 96 | override fun onError() { 97 | environment.logger.info("onError!!!") 98 | } 99 | } 100 | 101 | class MyClass { 102 | var id = 0 103 | var file = "" 104 | var name = "" 105 | var kind = "" 106 | var detail = "" 107 | var parents = mutableListOf() 108 | var protocols = mutableListOf() 109 | var variables = mutableListOf() 110 | var temporaries = mutableListOf() 111 | 112 | private fun str(k: String, v: Any): String { 113 | return "\"$k\":\"$v\"" 114 | } 115 | 116 | private fun list(k: String, list:MutableList): String { 117 | val l = list.joinToString { 118 | "\"$it\"" 119 | } 120 | return "\"$k\":[$l]" 121 | } 122 | 123 | fun toJsonString(): String { 124 | return "{\"id\": $id, ${str("file", file)}, ${str("name", name)}, ${str("detail", detail)}, ${str("kind", kind)}, ${list("parents", parents)}, ${list("protocols", protocols)}, ${list("variables", variables)}, ${list("temporaries", temporaries)}}" 125 | } 126 | 127 | companion object { 128 | fun toJsonString(list:MutableList): String { 129 | val l = list.joinToString { 130 | it.toJsonString() 131 | } 132 | return "[$l]" 133 | } 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /kotlin/symbol-processing-api-1.8.0-1.0.8.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rome753/swift-kotlin-diagram/a6f254b6883c076a1fb6496816f2127b032ab6c4/kotlin/symbol-processing-api-1.8.0-1.0.8.jar -------------------------------------------------------------------------------- /kotlin/symbol-processing-cmdline-1.8.0-1.0.8.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rome753/swift-kotlin-diagram/a6f254b6883c076a1fb6496816f2127b032ab6c4/kotlin/symbol-processing-cmdline-1.8.0-1.0.8.jar -------------------------------------------------------------------------------- /runKotlin.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import json 4 | import webbrowser 5 | 6 | openBrowser = False 7 | reloadAP = True 8 | 9 | def visit(path): 10 | if os.path.isdir(path): 11 | arr = os.listdir(path) 12 | ret = [] 13 | for name in arr: 14 | p = os.path.join(path, name) 15 | r = visit(p) 16 | if r is not None: 17 | ret.append(r) 18 | return { 19 | 'name': os.path.basename(path), 20 | 'list': ret 21 | } 22 | else: 23 | if path.endswith('.kt'): 24 | print('visit: ' + path) 25 | return os.path.basename(path) 26 | return None 27 | 28 | 29 | if __name__ == '__main__': 30 | argc = len(sys.argv) 31 | print('argv0 ' + sys.argv[0]) 32 | runPath = '' 33 | projPath = '' 34 | if argc < 2: 35 | runPath = os.path.dirname(sys.argv[0]) 36 | projPath = os.path.join(runPath, 'test') 37 | else: 38 | print('argv1 ' + sys.argv[1]) 39 | openBrowser = True 40 | runPath = '.' 41 | projPath = sys.argv[1] 42 | 43 | os.chdir(os.path.join(runPath, 'kotlin')) 44 | 45 | tree = visit(projPath) 46 | 47 | genDir = os.path.join('..', 'generate') 48 | if os.path.exists(genDir) == False: 49 | os.mkdir(genDir) 50 | data = os.path.join(genDir, 'tree.json') 51 | f = open(data, 'w') 52 | f.write(json.dumps(tree)) 53 | f.close() 54 | 55 | if reloadAP: 56 | os.system('kotlinc myprocessor -cp symbol-processing-api-1.8.0-1.0.8.jar -d myprocessor.jar') 57 | os.system('jar uvMf myprocessor.jar META-INF') 58 | 59 | KSP_PLUGIN_OPT = 'plugin:com.google.devtools.ksp.symbol-processing' 60 | KSP_PLUGIN_JAR = 'symbol-processing-cmdline-1.8.0-1.0.8.jar' 61 | KSP_API_JAR = 'symbol-processing-api-1.8.0-1.0.8.jar' 62 | AP = 'myprocessor.jar' 63 | cmd = ('kotlinc ' 64 | '-Xplugin=' + KSP_PLUGIN_JAR + ' ' 65 | '-Xplugin=' + KSP_API_JAR + ' ' 66 | '-Xallow-no-source-files ' 67 | '-P plugin:com.google.devtools.ksp.symbol-processing:apclasspath=' + AP + ' ' 68 | '-P plugin:com.google.devtools.ksp.symbol-processing:projectBaseDir=' + projPath + ' ' 69 | '-P plugin:com.google.devtools.ksp.symbol-processing:incremental=false ' 70 | '-P plugin:com.google.devtools.ksp.symbol-processing:classOutputDir=../generate ' 71 | '-P plugin:com.google.devtools.ksp.symbol-processing:javaOutputDir=../generate ' 72 | '-P plugin:com.google.devtools.ksp.symbol-processing:kotlinOutputDir=../generate ' 73 | '-P plugin:com.google.devtools.ksp.symbol-processing:resourceOutputDir=../generate ' 74 | '-P plugin:com.google.devtools.ksp.symbol-processing:kspOutputDir=../generate ' 75 | '-P plugin:com.google.devtools.ksp.symbol-processing:cachesDir=../generate ' 76 | '' + projPath) 77 | os.system(cmd) 78 | 79 | if openBrowser: 80 | os.chdir('..') 81 | webbrowser.open('http://localhost:8080/diagram.html') 82 | os.system('python3 -m http.server 8080') -------------------------------------------------------------------------------- /runSwift.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import json 4 | import webbrowser 5 | 6 | openBrowser = False 7 | printStructrue = False 8 | 9 | index = 0 10 | dataArr = [] 11 | 12 | def visit(path): 13 | if os.path.isdir(path): 14 | arr = os.listdir(path) 15 | ret = [] 16 | for name in arr: 17 | p = os.path.join(path, name) 18 | r = visit(p) 19 | if r is not None: 20 | ret.append(r) 21 | return { 22 | 'name': os.path.basename(path), 23 | 'list': ret 24 | } 25 | else: 26 | if path.endswith('.swift'): 27 | print('visit: ' + path) 28 | visitFile(path) 29 | return os.path.basename(path) 30 | return None 31 | 32 | 33 | def visitFile(path): 34 | structure = os.popen('sourcekitten structure --file ' + path).read() 35 | if printStructrue: 36 | print(structure) 37 | try: 38 | dict = json.loads(structure) 39 | except Exception as e: 40 | print('Exception in file ' + path) 41 | print(e) 42 | return 43 | 44 | for sub in dict['key.substructure']: 45 | kind = sub['key.kind'] 46 | validKinds = ['source.lang.swift.decl.class', 'source.lang.swift.decl.struct', 'source.lang.swift.decl.protocol', 'source.lang.swift.decl.enum'] 47 | if kind not in validKinds: 48 | continue 49 | global index 50 | index += 1 51 | id = index 52 | data = {} 53 | name = sub['key.name'] 54 | data['id'] = id 55 | data['file'] = os.path.basename(path) 56 | data['name'] = name 57 | data['kind'] = kind.split('.')[-1] 58 | dataArr.append(data) 59 | 60 | parents = [] 61 | data['parents'] = parents 62 | protocols = [] 63 | data['protocols'] = protocols 64 | variables = [] 65 | data['variables'] = variables 66 | temporaries = [] 67 | data['temporaries'] = temporaries 68 | 69 | varDetails = [] 70 | funcDetails = [] 71 | 72 | print('-visit: ' + name) 73 | if 'key.inheritedtypes' in sub: # ParentClass and protocols 74 | i = 0 75 | for s in sub['key.inheritedtypes']: 76 | i += 1 77 | name = s['key.name'] # ParentClass 78 | if i == 1: 79 | j = name.find('<') # ParentClass 80 | if j != -1: 81 | arr = name[j+1:-1].split(', ') 82 | for a in arr: 83 | variables.append(a) 84 | name = name[:j] 85 | parents.append(name) 86 | else: 87 | protocols.append(s['key.name']) 88 | 89 | if 'key.substructure' in sub: # class members 90 | for s in sub['key.substructure']: 91 | if s['key.kind'].startswith('source.lang.swift.decl.var'): # .instance/.static/.class 92 | type = s['key.kind'].split('.')[-1] 93 | type = type if type != 'instance' else '' 94 | typename = '' if 'key.typename' not in s else s['key.typename'] 95 | if typename != '': 96 | if type == '': 97 | variables.append(typename) 98 | else: 99 | temporaries.append(typename) 100 | s1 = '' if typename == '' else ': ' + typename 101 | s2 = '' if type == '' else ' (' + type + ')' 102 | varDetails.append('- ' + s['key.name'] + s1 + s2) 103 | if s['key.kind'] == 'source.lang.swift.expr.call': 104 | name = s['key.name'] 105 | i = name.find('.') 106 | if i != -1: # MyClass.staticFunc 107 | name = name[:i] 108 | variables.append(name) 109 | if s['key.kind'].startswith('source.lang.swift.decl.function.method'): # .instance/.static/.class 110 | type = s['key.kind'].split('.')[-1] 111 | type = type if type != 'instance' else '' 112 | typename = '' if 'key.typename' not in s else s['key.typename'] 113 | if typename != '': 114 | temporaries.append(typename) 115 | 116 | s1 = '' if typename == '' else ': ' + typename 117 | s2 = '' if type == '' else ' (' + type + ')' 118 | funcDetails.append('+ ' + s['key.name'] + s1 + s2) 119 | visitMethod(s, temporaries) 120 | if s['key.kind'] == 'source.lang.swift.decl.enumcase': 121 | varDetails.append('.' + s['key.substructure'][0]['key.name']) 122 | 123 | 124 | s1 = '\n'.join(varDetails) 125 | s2 = '\n'.join(funcDetails) 126 | data['detail'] = '\n-------------------------\n'.join([data['name'], s1, s2]) 127 | 128 | 129 | def visitMethod(sub, temporaries): 130 | if 'key.substructure' in sub: 131 | for s in sub['key.substructure']: 132 | if s['key.kind'] == 'source.lang.swift.decl.var.parameter': 133 | if 'key.typename' in s: 134 | temporaries.append(s['key.typename']) 135 | if s['key.kind'] == 'source.lang.swift.decl.var.local': 136 | if 'key.typename' in s: 137 | temporaries.append(s['key.typename']) 138 | if s['key.kind'] == 'source.lang.swift.expr.call': 139 | name = s['key.name'] 140 | i = name.find('.') 141 | if i != -1: # MyClass.staticFunc 142 | name = name[:i] 143 | temporaries.append(name) 144 | visitMethod(s, temporaries) 145 | 146 | 147 | def replaceName(type, data): 148 | data1 = [] 149 | if type in data: 150 | for name in data[type]: 151 | if name.endswith('?') or name.endswith('!'): # optional 152 | name = name[:-1] 153 | data1.append(name) 154 | data[type] = data1 155 | 156 | 157 | if __name__ == '__main__': 158 | argc = len(sys.argv) 159 | projPath = '' 160 | if argc < 2: 161 | printStructrue = True 162 | projPath = 'test' 163 | else: 164 | openBrowser = True 165 | projPath = sys.argv[1] 166 | 167 | tree = visit(projPath) 168 | genDir = os.path.join(os.path.dirname(sys.argv[0]), 'generate') 169 | if os.path.exists(genDir) == False: 170 | os.mkdir(genDir) 171 | data = os.path.join(genDir, 'tree.json') 172 | f = open(data, 'w') 173 | f.write(json.dumps(tree)) 174 | f.close() 175 | 176 | for data in dataArr: 177 | replaceName('parents', data) 178 | replaceName('protocols', data) 179 | replaceName('variables', data) 180 | replaceName('temporaries', data) 181 | 182 | 183 | data = os.path.join(os.path.dirname(sys.argv[0]), 'generate', 'data.json') 184 | f = open(data, 'w') 185 | f.write(json.dumps(dataArr)) 186 | f.close() 187 | 188 | if openBrowser: 189 | webbrowser.open('http://localhost:8080/diagram.html') 190 | os.system('python3 -m http.server 8080') -------------------------------------------------------------------------------- /test/Test.java: -------------------------------------------------------------------------------- 1 | public class Test { 2 | 3 | static class InnerClass { 4 | int d = 0; 5 | } 6 | 7 | List myList = null; 8 | 9 | int a; 10 | String b; 11 | InnerClass c = new InnerClass(); 12 | 13 | String func1() { 14 | int c = 2; 15 | return "" + c; 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /test/test.kt: -------------------------------------------------------------------------------- 1 | class Demo { 2 | 3 | var a = 20 4 | 5 | var b: Foo 6 | 7 | fun myFun() { 8 | println("this is Demo myFun") 9 | } 10 | 11 | fun myFun1(param0: String, param1: Int): String { 12 | return "" 13 | } 14 | } 15 | 16 | class Foo: Demo { 17 | 18 | } 19 | -------------------------------------------------------------------------------- /test/test.swift: -------------------------------------------------------------------------------- 1 | 2 | class MyClass { 3 | 4 | static func staticFunc1() { 5 | 6 | } 7 | 8 | class func classFunc1() -> Int { 9 | 10 | } 11 | 12 | static var a = 2 13 | class var b: FooClass = nil 14 | 15 | func func1() { 16 | 17 | } 18 | 19 | func func2(param: String) -> String { 20 | return String() 21 | } 22 | 23 | } 24 | 25 | class FooClass { 26 | class func myStaticFunc() -> Int { 27 | return 0 28 | } 29 | } 30 | 31 | protocol MyProtocol { 32 | 33 | } 34 | 35 | struct MyStruct { 36 | 37 | } 38 | 39 | enum MyEnum { 40 | case success 41 | case fail 42 | } 43 | 44 | class MyChildClass: MyClass, MyProtocol { 45 | 46 | var a = FooClass.myStaticFunc() 47 | 48 | var b = MyStruct() 49 | 50 | func myfunc() { 51 | } 52 | } 53 | --------------------------------------------------------------------------------