Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | /* * This file is released under the MIT license. * Copyright (c) 2017, 2022, Mike Lischke * * See LICENSE file for more info. */ import * as fs from "fs-extra"; import * as path from "path"; import { WebviewProvider, IWebviewMessage } from "./WebviewProvider"; import { FrontendUtils } from "../FrontendUtils"; import { window, workspace, Uri, TextEditor, Webview } from "vscode"; import { IATNGraphData, IATNGraphLayoutNode, IATNGraphRendererData, IATNStateSaveMessage, } from "../../webview-scripts/types"; import { ATNStateType } from "antlr4ts/atn"; interface IATNStatePosition { fx?: number; fy?: number; } // ATN graph state info for a single rule. interface IATNStateEntry { scale: number; translation: { x: number | undefined; y: number | undefined }; statePositions: { [key: number]: IATNStatePosition; }; } interface IATNStateMap { [key: string]: IATNStateEntry; } interface IATNFileStateMap { [key: string]: IATNStateMap; } export class ATNGraphProvider extends WebviewProvider { // All ATN state entries per file, per rule. Initially filled from the extension code. public static cachedATNTransformations: IATNFileStateMap = {}; public static addStatesForGrammar(root: string, grammar: string): void { const hash = FrontendUtils.hashForPath(grammar); const atnCacheFile = path.join(root, "cache", hash + ".atn"); Iif (fs.existsSync(atnCacheFile)) { const data = fs.readFileSync(atnCacheFile, { encoding: "utf-8" }); try { const fileEntry = JSON.parse(data) as IATNStateMap; ATNGraphProvider.cachedATNTransformations[hash] = fileEntry; } catch (e) { // Ignore cache loading errors. } } } public generateContent(webview: Webview, uri: Uri): string { const graphData = this.prepareRenderData(uri); const rendererScriptPath = FrontendUtils.getOutPath("src/webview-scripts/ATNGraphRenderer.js", this.context, webview); const exportScriptPath = FrontendUtils.getOutPath("src/webview-scripts/GraphExport.js", this.context, webview); const graphLibPath = FrontendUtils.getNodeModulesPath(webview, "d3/dist/d3.js", this.context); const name = graphData.ruleName ?? ""; const nonce = this.generateNonce(); return `<!DOCTYPE html> <html style="width: 100%, height: 100%"> <head> <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> ${this.generateContentSecurityPolicy(webview, nonce)} ${this.getStyles(webview)} <base target="_blank"> <script nonce="${nonce}" src="${graphLibPath}"></script> <script nonce="${nonce}"> let atnGraphRenderer; let graphExport; </script> </head> <body> <div class="header"> <span class="atn-graph-color"> <span class="graph-initial">Ⓡ</span>ule </span> ${name} <span class="rule-index">(rule index: ${this.currentRuleIndex ?? "?"})</span> <span class="action-box"> Reset display <a onClick="atnGraphRenderer.resetTransformation();"> <span class="atn-graph-color" style="font-size: 120%; font-weight: 800; cursor: pointer; vertical-align: middle;">↺</span></a> Save to file<a onClick="graphExport.exportToSVG('atn', '${name}');"> <span class="atn-graph-save-image" /> </a> </span> </div> <svg> <defs> <filter id="white-glow" x="-150%" y="-150%" width="300%" height="300%"> <feFlood result="flood" flood-color="#ffffff" flood-opacity="0.15" /> <feComposite in="flood" result="mask" in2="SourceGraphic" operator="in" /> <feMorphology in="mask" result="dilated" operator="dilate" radius="5" /> <feGaussianBlur in="dilated" result="blurred" stdDeviation="5" /> <feMerge> <feMergeNode in="blurred" /> <feMergeNode in="SourceGraphic" /> </feMerge> </filter> <filter id="black-glow" x="-1000%" y="-1000%" width="2000%" height="2000%"> <feFlood result="flood" flood-color="#000000" flood-opacity="0.15" /> <feComposite in="flood" result="mask" in2="SourceGraphic" operator="in" /> <feMorphology in="mask" result="dilated" operator="dilate" radius="4" /> <feGaussianBlur in="dilated" result="blurred" stdDeviation="5" /> <feMerge> <feMergeNode in="blurred" /> <feMergeNode in="SourceGraphic" /> </feMerge> </filter> <marker id="transitionEndCircle" viewBox="0 -5 10 10" refX="31" refY="0" markerWidth="7" markerHeight="7" orient="auto" class="marker"> <path d="M0,-4L10,0L0,4" /> </marker> <marker id="transitionEndRect" viewBox="0 -5 10 10" refX="10" refY="0" markerWidth="7" markerHeight="7" orient="auto" class="marker"> <path d="M0,-4L10,0L0,4" /> </marker> </defs> </svg> <script nonce="${nonce}" type="module"> import { ATNGraphRenderer } from "${rendererScriptPath}"; import { GraphExport, vscode } from "${exportScriptPath}"; graphExport = new GraphExport(); atnGraphRenderer = new ATNGraphRenderer(vscode); atnGraphRenderer.render(${JSON.stringify(graphData)}); </script> </body> </html> `; } /** * Called when the webview must be updated. This can happen when: * - The user switched to another editor, which holds an ANTLR4 grammar. * - The user moved the caret in an editor holding a grammar. * - New data was generated for the grammar in that editor. * * @param editor The editor that holds a grammar. * @param forced If true update regardless of the selected rule (e.g. when new ATN data was generated). */ public update(editor: TextEditor, forced = false): void { // Keep track of the currently selected rule in the given editor and trigger a visual update // if the ATN graph is currently visible. const caret = editor.selection.active; const [selectedRule, selectedRuleIndex] = this.backend.ruleFromPosition(editor.document.fileName, caret.character, caret.line + 1); Iif (this.currentRule !== selectedRule || forced) { this.currentRule = selectedRule; this.currentRuleIndex = selectedRuleIndex; super.update(editor); } } protected handleMessage(message: IWebviewMessage): boolean { const saveMessage = message as IATNStateSaveMessage; Iif (saveMessage.command === "saveATNState") { // This is the bounce back from the script code for our call to `cacheATNLayout` triggered from // the `update()` function. const hash = FrontendUtils.hashForPath(saveMessage.uri.fsPath); const basePath = path.dirname(saveMessage.uri.fsPath); const atnCachePath = path.join(basePath, ".antlr/cache"); let fileEntry = ATNGraphProvider.cachedATNTransformations[hash]; Iif (!fileEntry) { fileEntry = {}; } const { x: translateX, y: translateY, k: scale } = saveMessage.transform; // Convert the given translation back to what it was before applying the scaling, as that is what we need // to specify when we restore the translation. const ruleEntry: IATNStateEntry = { scale, translation: { x: translateX / scale, y: translateY / scale }, statePositions: {}, }; for (const node of saveMessage.nodes) { ruleEntry.statePositions[node.id] = { fx: node.fx === null ? undefined : node.fx, fy: node.fy === null ? undefined : node.fy, }; } fileEntry[saveMessage.rule] = ruleEntry; ATNGraphProvider.cachedATNTransformations[hash] = fileEntry; fs.ensureDirSync(atnCachePath); try { fs.writeFileSync(path.join(atnCachePath, hash + ".atn"), JSON.stringify(fileEntry), { encoding: "utf-8" }); } catch (error) { void window.showErrorMessage(`Couldn't write ATN state data for: ${saveMessage.uri.fsPath} (${hash})`); } return true; } return false; } protected updateContent(uri: Uri): boolean { const graphData = this.prepareRenderData(uri); this.sendMessage(uri, { command: "updateATNTreeData", graphData, }); return true; } private prepareRenderData(uri: Uri): IATNGraphRendererData { const ruleName = this.currentRule ? this.currentRule.replace(/\$/g, "$$") : undefined; const configuration = workspace.getConfiguration("antlr4.atn"); const maxLabelCount = configuration.get<number>("maxLabelCount", 3); const hash = FrontendUtils.hashForPath(uri.fsPath); const fileTransformations = ATNGraphProvider.cachedATNTransformations[hash] ?? {}; let initialScale = 0.5; let initialTranslation = {}; const setPosition = (node: IATNGraphLayoutNode, position?: IATNStatePosition): void => { // If no transformation data is available, give the start and end nodes a fixed vertical // position and a horizontal initial position (which is not the same as a fixed position) // to get the graph rendered near the svg center. // The same positions are used when the user resets the transformation. const fx = position?.fx; const fy = position?.fy; switch (node.type) { case ATNStateType.RULE_START: { node.fy = fy ?? 0; if (fx !== undefined) { node.fx = fx; } else { node.x = -1000; } break; } case ATNStateType.RULE_STOP: { node.fy = fy ?? 0; if (fx !== undefined) { node.fx = fx; } else { node.x = 1000; } break; } default: { node.fx = position?.fx; node.fy = position?.fy; break; } } }; let graphData: IATNGraphData | undefined; Iif (ruleName) { try { graphData = this.backend.getATNGraph(uri.fsPath, ruleName); Iif (graphData) { const ruleTransformation = fileTransformations[ruleName]; if (ruleTransformation) { initialScale = ruleTransformation.scale; initialTranslation = ruleTransformation.translation; for (const node of graphData.nodes as IATNGraphLayoutNode[]) { setPosition(node, ruleTransformation.statePositions[node.id]); } } else { for (const node of graphData.nodes as IATNGraphLayoutNode[]) { setPosition(node); } } } } catch (e) { // Ignore errors. } } const result = { uri, ruleName, maxLabelCount, graphData, initialScale, initialTranslation, }; return result; } } |