You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

870 lines
33 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. let isTesting = false;
  2. const ILEscape = "@@";
  3. const ILCommentPrefix = ILEscape + "comments";
  4. const ILQuotesPrefix = ILEscape + "quotes";
  5. const ILSingleQuotesPrefix = ILEscape + "singlequotes";
  6. const ILBackslashesPrefix = ILEscape + "backslash";
  7. enum FormatMode {
  8. Default,
  9. EndsWithSemicolon,
  10. CaseWhen,
  11. IfElse,
  12. PortGeneric,
  13. }
  14. let Mode: FormatMode = FormatMode.Default;
  15. export class NewLineSettings {
  16. newLineAfter: Array<string>;
  17. noNewLineAfter: Array<string>;
  18. constructor() {
  19. this.newLineAfter = [];
  20. this.noNewLineAfter = [];
  21. }
  22. newLineAfterPush(keyword: string) {
  23. this.newLineAfter.push(keyword);
  24. }
  25. noNewLineAfterPush(keyword: string) {
  26. this.noNewLineAfter.push(keyword);
  27. }
  28. push(keyword: string, addNewLine: string) {
  29. let str = addNewLine.toLowerCase();
  30. if (str == "none") {
  31. return;
  32. }
  33. else if (!str.startsWith("no")) {
  34. this.newLineAfterPush(keyword);
  35. }
  36. else {
  37. this.noNewLineAfterPush(keyword);
  38. }
  39. }
  40. }
  41. function ConstructNewLineSettings(dict): NewLineSettings {
  42. let settings: NewLineSettings = new NewLineSettings();
  43. for (let key in dict) {
  44. settings.push(key, dict[key]);
  45. }
  46. return settings;
  47. }
  48. declare global {
  49. interface String {
  50. regexIndexOf: (pattern: RegExp, startIndex?: number) => number;
  51. regexLastIndexOf: (pattern: RegExp, startIndex: number) => number;
  52. reverse: () => string;
  53. regexStartsWith: (pattern: RegExp) => boolean;
  54. count: (text: string) => number;
  55. regexCount: (pattern: RegExp) => number;
  56. convertToRegexBlockWords: () => RegExp;
  57. }
  58. interface Array<T> {
  59. convertToRegexBlockWords: () => RegExp;
  60. }
  61. }
  62. String.prototype.regexCount = function (pattern): number {
  63. if (pattern.flags.indexOf("g") < 0) {
  64. pattern = new RegExp(pattern.source, pattern.flags + "g");
  65. }
  66. return (this.match(pattern) || []).length;
  67. }
  68. String.prototype.count = function (text): number {
  69. return this.split(text).length - 1;
  70. }
  71. String.prototype.regexStartsWith = function (pattern): boolean {
  72. var searchResult = this.search(pattern);
  73. return searchResult == 0;
  74. }
  75. String.prototype.regexIndexOf = function (pattern, startIndex) {
  76. startIndex = startIndex || 0;
  77. var searchResult = this.substr(startIndex).search(pattern);
  78. return (-1 === searchResult) ? -1 : searchResult + startIndex;
  79. }
  80. String.prototype.regexLastIndexOf = function (pattern, startIndex) {
  81. startIndex = startIndex === undefined ? this.length : startIndex;
  82. var searchResult = this.substr(0, startIndex).reverse().regexIndexOf(pattern, 0);
  83. return (-1 === searchResult) ? -1 : this.length - ++searchResult;
  84. }
  85. String.prototype.reverse = function () {
  86. return this.split('').reverse().join('');
  87. }
  88. String.prototype.convertToRegexBlockWords = function (): RegExp {
  89. let result: RegExp = new RegExp("(" + this + ")([^\\w]|$)");
  90. return result;
  91. }
  92. Array.prototype.convertToRegexBlockWords = function (): RegExp {
  93. let wordsStr: string = this.join("|");
  94. let result: RegExp = new RegExp("(" + wordsStr + ")([^\\w]|$)");
  95. return result;
  96. }
  97. function wordWrap() {
  98. var d = document.getElementById("result");
  99. if (d.className == "") {
  100. d.className = "wordwrap";
  101. } else {
  102. d.className = "";
  103. }
  104. }
  105. function getHTMLInputElement(id: string): HTMLInputElement {
  106. return <HTMLInputElement>document.getElementById(id);
  107. }
  108. function noFormat() {
  109. let elements: Array<string> = [
  110. "remove_comments",
  111. "remove_lines",
  112. "remove_report",
  113. "check_alias",
  114. "sign_align_in",
  115. "sign_align_port",
  116. "sign_align_generic",
  117. "sign_align_function",
  118. "sign_align_procedure",
  119. "sign_align_all",
  120. "new_line_after",
  121. "use_space",
  122. "customise_indentation",
  123. "compress",
  124. "mix_letter"
  125. ];
  126. var isDisabled = getHTMLInputElement("no_format").checked;
  127. elements.forEach(element => {
  128. var htmlElement = getHTMLInputElement(element + "_div");
  129. try {
  130. getHTMLInputElement(element).disabled = isDisabled;
  131. }
  132. catch{ }
  133. if (isDisabled) {
  134. htmlElement.className += " disabled";
  135. }
  136. else {
  137. htmlElement.className = htmlElement.className.replace(/\bdisabled\b/g, "");
  138. }
  139. });
  140. let radioButtons = <HTMLCollectionOf<HTMLInputElement>>document.getElementsByTagName("input");
  141. for (let i = 0; i < radioButtons.length; i++) {
  142. if ((<HTMLInputElement>radioButtons[i]).type == "radio") {
  143. (<HTMLInputElement>radioButtons[i]).disabled = isDisabled;
  144. }
  145. }
  146. getHTMLInputElement("cust_indent").disabled = isDisabled;
  147. }
  148. function Compress(input: string) {
  149. input = input.replace(/\r\n/g, '');
  150. input = input.replace(/[\t ]+/g, ' ');
  151. input = input.replace(/[ ]?([&=:\-<>\+|])[ ]?/g, '$1');
  152. return input;
  153. }
  154. function MixLetters(input: string) {
  155. let arr = input.split("");
  156. for (var k = 0; k < arr.length; k++) {
  157. if (arr[k] === arr[k].toUpperCase() && Math.random() > 0.5) {
  158. arr[k] = arr[k].toLowerCase();
  159. } else if (Math.random() > 0.5) {
  160. arr[k] = arr[k].toUpperCase();
  161. }
  162. }
  163. return arr.join("");
  164. }
  165. function EscapeComments(arr: Array<string>): Array<string> {
  166. var comments = [];
  167. var count = 0;
  168. for (var i = 0; i < arr.length; i++) {
  169. var line: string = arr[i];
  170. var commentStartIndex = line.indexOf("--");
  171. if (commentStartIndex >= 0) {
  172. comments.push(line.substr(commentStartIndex));
  173. arr[i] = line.substr(0, commentStartIndex) + ILCommentPrefix + count;
  174. count++;
  175. }
  176. }
  177. return comments
  178. }
  179. function ToLowerCases(arr: Array<string>) {
  180. for (var i = 0; i < arr.length; i++) {
  181. arr[i] = arr[i].toLowerCase();
  182. }
  183. }
  184. function ToUpperCases(arr: Array<string>) {
  185. for (var i = 0; i < arr.length; i++) {
  186. arr[i] = arr[i].toUpperCase();
  187. }
  188. }
  189. function ToCamelCases(arr: Array<string>) {
  190. for (var i = 0; i < arr.length; i++) {
  191. arr[i] = arr[i].charAt(0) + arr[i].slice(1).toLowerCase();
  192. }
  193. }
  194. function ReplaceKeyWords(text: string, keywords: Array<string>): string {
  195. for (var k = 0; k < keywords.length; k++) {
  196. text = text.replace(new RegExp("([^a-zA-Z0-9_@]|^)" + keywords[k] + "([^a-zA-Z0-9_]|$)", 'gi'), "$1" + keywords[k] + "$2");
  197. }
  198. return text;
  199. }
  200. function SetKeywordCase(input: string, keywordcase: string, keywords: string[], typenames: string[]): string {
  201. let inputcase: string = keywordcase.toLowerCase();
  202. switch (keywordcase.toLowerCase()) {
  203. case "lowercase":
  204. ToLowerCases(keywords);
  205. ToLowerCases(typenames);
  206. break;
  207. case "defaultcase":
  208. ToCamelCases(keywords);
  209. ToCamelCases(typenames);
  210. break;
  211. case "uppercase":
  212. ToUpperCases(keywords);
  213. ToUpperCases(typenames);
  214. }
  215. input = ReplaceKeyWords(input, keywords);
  216. input = ReplaceKeyWords(input, typenames);
  217. return input;
  218. }
  219. export function SetNewLinesAfterSymbols(text: string, newLineSettings: NewLineSettings): string {
  220. if (newLineSettings == null) {
  221. return text;
  222. }
  223. if (newLineSettings.newLineAfter != null) {
  224. newLineSettings.newLineAfter.forEach(symbol => {
  225. let regex: RegExp = new RegExp("(" + symbol.toUpperCase() + ")[ ]?([^ \r\n@])", "g");
  226. text = text.replace(regex, '$1\r\n$2');
  227. if (symbol.toUpperCase() == "PORT") {
  228. text = text.replace(/PORT\s+MAP/, "PORT MAP");
  229. }
  230. });
  231. }
  232. if (newLineSettings.noNewLineAfter != null) {
  233. newLineSettings.noNewLineAfter.forEach(symbol => {
  234. let regex: RegExp = new RegExp("(" + symbol.toUpperCase() + ")[ \r\n]+([^@])", "g");
  235. text = text.replace(regex, '$1 $2');
  236. });
  237. }
  238. return text;
  239. }
  240. export class BeautifierSettings {
  241. RemoveComments: boolean;
  242. RemoveAsserts: boolean;
  243. CheckAlias: boolean;
  244. SignAlignRegional: boolean;
  245. SignAlignAll: boolean;
  246. SignAlignKeyWords: Array<string>;
  247. KeywordCase: string;
  248. Indentation: string;
  249. NewLineSettings: NewLineSettings
  250. constructor(removeComments: boolean, removeReport: boolean, checkAlias: boolean,
  251. signAlign: boolean, signAlignAll: boolean, keywordCase: string, indentation: string,
  252. newLineSettings: NewLineSettings) {
  253. this.RemoveComments = removeComments;
  254. this.RemoveAsserts = removeReport;
  255. this.CheckAlias = checkAlias;
  256. this.SignAlignRegional = signAlign;
  257. this.SignAlignAll = signAlignAll;
  258. this.KeywordCase = keywordCase;
  259. this.Indentation = indentation;
  260. this.NewLineSettings = newLineSettings;
  261. }
  262. }
  263. let KeyWords: Array<string> = ["ABS", "ACCESS", "AFTER", "ALIAS", "ALL", "AND", "ARCHITECTURE", "ARRAY", "ASSERT", "ATTRIBUTE", "BEGIN", "BLOCK", "BODY", "BUFFER", "BUS", "CASE", "COMPONENT", "CONFIGURATION", "CONSTANT", "CONTEXT", "COVER", "DISCONNECT", "DOWNTO", "DEFAULT", "ELSE", "ELSIF", "END", "ENTITY", "EXIT", "FAIRNESS", "FILE", "FOR", "FORCE", "FUNCTION", "GENERATE", "GENERIC", "GROUP", "GUARDED", "IF", "IMPURE", "IN", "INERTIAL", "INOUT", "IS", "LABEL", "LIBRARY", "LINKAGE", "LITERAL", "LOOP", "MAP", "MOD", "NAND", "NEW", "NEXT", "NOR", "NOT", "NULL", "OF", "ON", "OPEN", "OR", "OTHERS", "OUT", "PACKAGE", "PORT", "POSTPONED", "PROCEDURE", "PROCESS", "PROPERTY", "PROTECTED", "PURE", "RANGE", "RECORD", "REGISTER", "REJECT", "RELEASE", "REM", "REPORT", "RESTRICT", "RESTRICT_GUARANTEE", "RETURN", "ROL", "ROR", "SELECT", "SEQUENCE", "SEVERITY", "SHARED", "SIGNAL", "SLA", "SLL", "SRA", "SRL", "STRONG", "SUBTYPE", "THEN", "TO", "TRANSPORT", "TYPE", "UNAFFECTED", "UNITS", "UNTIL", "USE", "VARIABLE", "VMODE", "VPROP", "VUNIT", "WAIT", "WHEN", "WHILE", "WITH", "XNOR", "XOR"];
  264. let TypeNames: Array<string> = ["BOOLEAN", "BIT", "CHARACTER", "INTEGER", "TIME", "NATURAL", "POSITIVE", "STRING"];
  265. export function beautify(input: string, settings: BeautifierSettings) {
  266. input = input.replace(/\r\n/g, "\n");
  267. input = input.replace(/\n/g, "\r\n");
  268. var arr = input.split("\r\n");
  269. var comments = EscapeComments(arr);
  270. var backslashes = escapeBackslashes(arr);
  271. RemoveLeadingWhitespaces(arr);
  272. input = arr.join("\r\n");
  273. if (settings.RemoveComments) {
  274. input = input.replace(/\r\n[ \t]*@@comments[0-9]+[ \t]*\r\n/g, '\r\n');
  275. input = input.replace(/@@comments[0-9]+/g, '');
  276. comments = [];
  277. }
  278. input = RemoveExtraNewLines(input);
  279. input = input.replace(/[\t ]+/g, ' ');
  280. input = input.replace(/\([\t ]+/g, '\(');
  281. input = input.replace(/[ ]+;/g, ';');
  282. input = input.replace(/:[ ]*(PROCESS|ENTITY)/gi, ':$1');
  283. arr = input.split("\r\n");
  284. let quotes = EscapeQuotes(arr);
  285. let singleQuotes = EscapeSingleQuotes(arr);
  286. input = arr.join("\r\n");
  287. input = SetKeywordCase(input, "uppercase", KeyWords, TypeNames);
  288. arr = input.split("\r\n");
  289. if (settings.RemoveAsserts) {
  290. RemoveAsserts(arr);//RemoveAsserts must be after EscapeQuotes
  291. }
  292. ReserveSemicolonInKeywords(arr);
  293. input = arr.join("\r\n");
  294. input = input.replace(/(PORT|GENERIC)\s+MAP/g, '$1 MAP');
  295. input = input.replace(/(PORT|PROCESS|GENERIC)[\s]*\(/g, '$1 (');
  296. input = SetNewLinesAfterSymbols(input, settings.NewLineSettings);
  297. arr = input.split("\r\n");
  298. ApplyNoNewLineAfter(arr, settings.NewLineSettings.noNewLineAfter);
  299. input = arr.join("\r\n");
  300. input = input.replace(/([a-zA-Z0-9\); ])\);(@@comments[0-9]+)?@@end/g, '$1\r\n);$2@@end');
  301. input = input.replace(/[ ]?([&=:\-<>\+|\*])[ ]?/g, ' $1 ');
  302. input = input.replace(/(\d+e) +([+\-]) +(\d+)/g, '$1$2$3');// Fix exponential notation format broken by previous step
  303. input = input.replace(/[ ]?([,])[ ]?/g, '$1 ');
  304. input = input.replace(/[ ]?(['"])(THEN)/g, '$1 $2');
  305. input = input.replace(/[ ]?(\?)?[ ]?(<|:|>|\/)?[ ]+(=)?[ ]?/g, ' $1$2$3 ');
  306. input = input.replace(/(IF)[ ]?([\(\)])/g, '$1 $2');
  307. input = input.replace(/([\(\)])[ ]?(THEN)/gi, '$1 $2');
  308. input = input.replace(/(^|[\(\)])[ ]?(AND|OR|XOR|XNOR)[ ]*([\(])/g, '$1 $2 $3');
  309. input = input.replace(/ ([\-\*\/=+<>])[ ]*([\-\*\/=+<>]) /g, " $1$2 ");
  310. //input = input.replace(/\r\n[ \t]+--\r\n/g, "\r\n");
  311. input = input.replace(/[ ]+/g, ' ');
  312. input = input.replace(/[ \t]+\r\n/g, "\r\n");
  313. input = input.replace(/\r\n\r\n\r\n/g, '\r\n');
  314. input = input.replace(/[\r\n\s]+$/g, '');
  315. input = input.replace(/[ \t]+\)/g, ')');
  316. input = input.replace(/\s*\)\s+RETURN\s+([\w]+;)/g, '\r\n) RETURN $1');//function(..\r\n)return type; -> function(..\r\n)return type;
  317. arr = input.split("\r\n");
  318. let result: (FormattedLine | FormattedLine[])[] = [];
  319. beautify3(arr, result, settings, 0, 0);
  320. if (settings.SignAlignAll) {
  321. AlignSigns(result, 0, result.length - 1);
  322. }
  323. arr = FormattedLineToString(result, settings.Indentation);
  324. input = arr.join("\r\n");
  325. input = SetKeywordCase(input, settings.KeywordCase, KeyWords, TypeNames);
  326. input = replaceEscapedWords(input, quotes, ILQuotesPrefix);
  327. input = replaceEscapedWords(input, singleQuotes, ILSingleQuotesPrefix);
  328. input = replaceEscapedWords(input, comments, ILCommentPrefix);
  329. input = replaceEscapedWords(input, backslashes, ILBackslashesPrefix);
  330. input = input.replace(/@@semicolon/g, ";");
  331. input = input.replace(/@@[a-z]+/g, "");
  332. return input;
  333. }
  334. function replaceEscapedWords(input: string, arr: Array<string>, prefix: string): string {
  335. for (var i = 0; i < arr.length; i++) {
  336. input = input.replace(prefix + i, arr[i]);
  337. }
  338. return input;
  339. }
  340. function escapeBackslashes(arr: Array<string>) {
  341. var escaped = [];
  342. var count = 0;
  343. for (var i = 0; i < arr.length; i++) {
  344. var sequence = arr[i].match(/\\[^\\]+\\/g);
  345. if (sequence != null) {
  346. for (var j = 0; j < sequence.length; j++) {
  347. arr[i] = arr[i].replace(sequence[j], ILBackslashesPrefix + count);
  348. escaped[count++] = sequence[j];
  349. }
  350. }
  351. }
  352. return escaped;
  353. }
  354. function RemoveLeadingWhitespaces(arr: Array<string>) {
  355. for (var i = 0; i < arr.length; i++) {
  356. arr[i] = arr[i].replace(/^\s+/, "");
  357. }
  358. }
  359. export class FormattedLine {
  360. Line: string;
  361. Indent: number;
  362. constructor(line: string, indent: number) {
  363. this.Line = line;
  364. this.Indent = indent;
  365. }
  366. }
  367. export function FormattedLineToString(arr: (FormattedLine | FormattedLine[])[], indentation: string): Array<string> {
  368. let result: Array<string> = [];
  369. if (arr == null) {
  370. return result;
  371. }
  372. arr.forEach(i => {
  373. if (i instanceof FormattedLine) {
  374. if (i.Line.length > 0) {
  375. result.push((Array(i.Indent + 1).join(indentation)) + i.Line);
  376. }
  377. else {
  378. result.push("");
  379. }
  380. }
  381. else {
  382. result = result.concat(FormattedLineToString(i, indentation));
  383. }
  384. });
  385. return result;
  386. }
  387. function GetCloseparentheseEndIndex(inputs: Array<string>, startIndex: number): number {
  388. let openParentheseCount: number = 0;
  389. let closeParentheseCount: number = 0;
  390. for (let i = startIndex; i < inputs.length; i++) {
  391. let input = inputs[i];
  392. openParentheseCount += input.count("(");
  393. closeParentheseCount += input.count(")");
  394. if (openParentheseCount > 0
  395. && openParentheseCount <= closeParentheseCount) {
  396. return i;
  397. }
  398. }
  399. return startIndex;
  400. }
  401. export function beautifyPortGenericBlock(inputs: Array<string>, result: (FormattedLine | FormattedLine[])[], settings: BeautifierSettings, startIndex: number, parentEndIndex: number, indent: number, mode: string): [number, number] {
  402. let firstLine: string = inputs[startIndex];
  403. let regex: RegExp = new RegExp("[\\w\\s:]*(" + mode + ")([\\s]|$)");
  404. if (!firstLine.regexStartsWith(regex)) {
  405. return [startIndex, parentEndIndex];
  406. }
  407. let firstLineHasParenthese: boolean = firstLine.indexOf("(") >= 0;
  408. let hasParenthese: boolean = firstLineHasParenthese;
  409. let blockBodyStartIndex = startIndex;
  410. let secondLineHasParenthese: boolean = startIndex + 1 < inputs.length && inputs[startIndex + 1].startsWith("(");
  411. if (secondLineHasParenthese) {
  412. hasParenthese = true;
  413. blockBodyStartIndex++;
  414. }
  415. let endIndex: number = hasParenthese ? GetCloseparentheseEndIndex(inputs, startIndex) : startIndex;
  416. if (endIndex != startIndex && firstLineHasParenthese) {
  417. inputs[startIndex] = inputs[startIndex].replace(/(PORT|GENERIC|PROCEDURE)([\w ]+)\(([\w\(\) ]+)/, '$1$2(\r\n$3');
  418. let newInputs = inputs[startIndex].split("\r\n");
  419. if (newInputs.length == 2) {
  420. inputs[startIndex] = newInputs[0];
  421. inputs.splice(startIndex + 1, 0, newInputs[1]);
  422. endIndex++;
  423. parentEndIndex++;
  424. }
  425. }
  426. else if (endIndex > startIndex + 1 && secondLineHasParenthese) {
  427. inputs[startIndex + 1] = inputs[startIndex + 1].replace(/\(([\w\(\) ]+)/, '(\r\n$1');
  428. let newInputs = inputs[startIndex + 1].split("\r\n");
  429. if (newInputs.length == 2) {
  430. inputs[startIndex + 1] = newInputs[0];
  431. inputs.splice(startIndex + 2, 0, newInputs[1]);
  432. endIndex++;
  433. parentEndIndex++;
  434. }
  435. }
  436. if (firstLineHasParenthese && inputs[startIndex].indexOf("MAP") > 0) {
  437. inputs[startIndex] = inputs[startIndex].replace(/([^\w])(MAP)\s+\(/g, '$1$2(');
  438. }
  439. result.push(new FormattedLine(inputs[startIndex], indent));
  440. if (secondLineHasParenthese) {
  441. let secondLineIndent = indent;
  442. if (endIndex == startIndex + 1) {
  443. secondLineIndent++;
  444. }
  445. result.push(new FormattedLine(inputs[startIndex + 1], secondLineIndent));
  446. }
  447. let blockBodyEndIndex = endIndex;
  448. let i = beautify3(inputs, result, settings, blockBodyStartIndex + 1, indent + 1, endIndex);
  449. if (inputs[i].startsWith(")")) {
  450. (<FormattedLine>result[i]).Indent--;
  451. blockBodyEndIndex--;
  452. }
  453. if (settings.SignAlignRegional && !settings.SignAlignAll
  454. && settings.SignAlignKeyWords != null
  455. && settings.SignAlignKeyWords.indexOf(mode) >= 0) {
  456. blockBodyStartIndex++;
  457. AlignSigns(result, blockBodyStartIndex, blockBodyEndIndex);
  458. }
  459. return [i, parentEndIndex];
  460. }
  461. export function AlignSigns(result: (FormattedLine | FormattedLine[])[], startIndex: number, endIndex: number) {
  462. AlignSign_(result, startIndex, endIndex, ":");
  463. AlignSign_(result, startIndex, endIndex, ":=");
  464. AlignSign_(result, startIndex, endIndex, "=>");
  465. AlignSign_(result, startIndex, endIndex, "<=");
  466. }
  467. function AlignSign_(result: (FormattedLine | FormattedLine[])[], startIndex: number, endIndex: number, symbol: string) {
  468. let maxSymbolIndex: number = -1;
  469. let symbolIndices = {};
  470. let startLine = startIndex;
  471. let labelAndKeywords: Array<string> = [
  472. "([\\w\\s]*:(\\s)*PROCESS)",
  473. "([\\w\\s]*:(\\s)*POSTPONED PROCESS)",
  474. "([\\w\\s]*:\\s*$)",
  475. "([\\w\\s]*:.*\\s+GENERATE)"
  476. ];
  477. let labelAndKeywordsStr: string = labelAndKeywords.join("|");
  478. let labelAndKeywordsRegex = new RegExp("(" + labelAndKeywordsStr + ")([^\\w]|$)");
  479. for (let i = startIndex; i <= endIndex; i++) {
  480. let line = (<FormattedLine>result[i]).Line;
  481. if (symbol == ":" && line.regexStartsWith(labelAndKeywordsRegex)) {
  482. continue;
  483. }
  484. let regex: RegExp = new RegExp("([\\s\\w\\\\]|^)" + symbol + "([\\s\\w\\\\]|$)");
  485. if (line.regexCount(regex) > 1) {
  486. continue;
  487. }
  488. let colonIndex = line.regexIndexOf(regex);
  489. if (colonIndex > 0) {
  490. maxSymbolIndex = Math.max(maxSymbolIndex, colonIndex);
  491. symbolIndices[i] = colonIndex;
  492. }
  493. else if (!line.startsWith(ILCommentPrefix) && line.length != 0) {
  494. if (startLine < i - 1) // if cannot find the symbol, a block of symbols ends
  495. {
  496. AlignSign(result, startLine, i - 1, symbol, maxSymbolIndex, symbolIndices);
  497. }
  498. maxSymbolIndex = -1;
  499. symbolIndices = {};
  500. startLine = i;
  501. }
  502. }
  503. if (startLine < endIndex) // if cannot find the symbol, a block of symbols ends
  504. {
  505. AlignSign(result, startLine, endIndex, symbol, maxSymbolIndex, symbolIndices);
  506. }
  507. }
  508. export function AlignSign(result: (FormattedLine | FormattedLine[])[], startIndex: number, endIndex: number, symbol: string, maxSymbolIndex: number = -1, symbolIndices = {}) {
  509. if (maxSymbolIndex < 0) {
  510. return;
  511. }
  512. for (let lineIndex in symbolIndices) {
  513. let symbolIndex = symbolIndices[lineIndex];
  514. if (symbolIndex == maxSymbolIndex) {
  515. continue;
  516. }
  517. let line = (<FormattedLine>result[lineIndex]).Line;
  518. (<FormattedLine>result[lineIndex]).Line = line.substring(0, symbolIndex)
  519. + (Array(maxSymbolIndex - symbolIndex + 1).join(" "))
  520. + line.substring(symbolIndex);
  521. }
  522. }
  523. export function beautifyCaseBlock(inputs: Array<string>, result: (FormattedLine | FormattedLine[])[], settings: BeautifierSettings, startIndex: number, indent: number): number {
  524. if (!inputs[startIndex].regexStartsWith(/(.+:\s*)?(CASE)([\s]|$)/)) {
  525. return startIndex;
  526. }
  527. result.push(new FormattedLine(inputs[startIndex], indent));
  528. let i = beautify3(inputs, result, settings, startIndex + 1, indent + 2);
  529. (<FormattedLine>result[i]).Indent = indent;
  530. return i;
  531. }
  532. function getSemicolonBlockEndIndex(inputs: Array<string>, settings: BeautifierSettings, startIndex: number, parentEndIndex: number): [number, number] {
  533. let endIndex = 0;
  534. let openBracketsCount = 0;
  535. let closeBracketsCount = 0;
  536. for (let i = startIndex; i < inputs.length; i++) {
  537. let input = inputs[i];
  538. let indexOfSemicolon = input.indexOf(";");
  539. let splitIndex = indexOfSemicolon < 0 ? input.length : indexOfSemicolon + 1;
  540. let stringBeforeSemicolon = input.substring(0, splitIndex);
  541. let stringAfterSemicolon = input.substring(splitIndex);
  542. stringAfterSemicolon = stringAfterSemicolon.replace(new RegExp(ILCommentPrefix + "[0-9]+"), "");
  543. openBracketsCount += stringBeforeSemicolon.count("(");
  544. closeBracketsCount += stringBeforeSemicolon.count(")");
  545. if (indexOfSemicolon < 0) {
  546. continue;
  547. }
  548. if (openBracketsCount == closeBracketsCount) {
  549. endIndex = i;
  550. if (stringAfterSemicolon.trim().length > 0 && settings.NewLineSettings.newLineAfter.indexOf(";") >= 0) {
  551. inputs[i] = stringBeforeSemicolon;
  552. inputs.splice(i, 0, stringAfterSemicolon);
  553. parentEndIndex++;
  554. }
  555. break;
  556. }
  557. }
  558. return [endIndex, parentEndIndex];
  559. }
  560. export function beautifyComponentBlock(inputs: Array<string>, result: (FormattedLine | FormattedLine[])[], settings: BeautifierSettings, startIndex: number, parentEndIndex: number, indent: number): [number, number] {
  561. let endIndex = startIndex;
  562. for (let i = startIndex; i < inputs.length; i++) {
  563. if (inputs[i].regexStartsWith(/END(\s|$)/)) {
  564. endIndex = i;
  565. break;
  566. }
  567. }
  568. result.push(new FormattedLine(inputs[startIndex], indent));
  569. if (endIndex != startIndex) {
  570. let actualEndIndex = beautify3(inputs, result, settings, startIndex + 1, indent + 1, endIndex);
  571. let incremental = actualEndIndex - endIndex;
  572. endIndex += incremental;
  573. parentEndIndex += incremental;
  574. }
  575. return [endIndex, parentEndIndex];
  576. }
  577. export function beautifySemicolonBlock(inputs: Array<string>, result: (FormattedLine | FormattedLine[])[], settings: BeautifierSettings, startIndex: number, parentEndIndex: number, indent: number): [number, number] {
  578. let endIndex = startIndex;
  579. [endIndex, parentEndIndex] = getSemicolonBlockEndIndex(inputs, settings, startIndex, parentEndIndex);
  580. result.push(new FormattedLine(inputs[startIndex], indent));
  581. if (endIndex != startIndex) {
  582. let i = beautify3(inputs, result, settings, startIndex + 1, indent + 1, endIndex);
  583. }
  584. return [endIndex, parentEndIndex];
  585. }
  586. export function beautify3(inputs: Array<string>, result: (FormattedLine | FormattedLine[])[], settings: BeautifierSettings, startIndex: number, indent: number, endIndex?: number): number {
  587. let i: number;
  588. let regexOneLineBlockKeyWords: RegExp = new RegExp(/(PROCEDURE)[^\w](?!.+[^\w]IS([^\w]|$))/);//match PROCEDURE..; but not PROCEDURE .. IS;
  589. let regexFunctionMultiLineBlockKeyWords: RegExp = new RegExp(/(FUNCTION|IMPURE FUNCTION)[^\w](?=.+[^\w]IS([^\w]|$))/);//match FUNCTION .. IS; but not FUNCTION
  590. let blockMidKeyWords: Array<string> = ["BEGIN"];
  591. let blockStartsKeyWords: Array<string> = [
  592. "IF",
  593. "CASE",
  594. "ARCHITECTURE",
  595. "PROCEDURE",
  596. "PACKAGE",
  597. "(([\\w\\s]*:)?(\\s)*PROCESS)",// with label
  598. "(([\\w\\s]*:)?(\\s)*POSTPONED PROCESS)",// with label
  599. "(.*\\s*PROTECTED)",
  600. "(COMPONENT)",
  601. "(ENTITY(?!.+;))",
  602. "FOR",
  603. "WHILE",
  604. "LOOP",
  605. "(.*\\s*GENERATE)",
  606. "(CONTEXT[\\w\\s\\\\]+IS)",
  607. "(CONFIGURATION(?!.+;))",
  608. "BLOCK",
  609. "UNITS",
  610. "\\w+\\s+\\w+\\s+IS\\s+RECORD"];
  611. let blockEndsKeyWords: Array<string> = ["END", ".*\\)\\s*RETURN\\s+[\\w]+;"];
  612. let blockEndsWithSemicolon: Array<string> = [
  613. "(WITH\\s+[\\w\\s\\\\]+SELECT)",
  614. "([\\w\\\\]+[\\s]*<=)",
  615. "([\\w\\\\]+[\\s]*:=)",
  616. "FOR\\s+[\\w\\s,]+:\\s*\\w+\\s+USE",
  617. "REPORT"
  618. ];
  619. let newLineAfterKeyWordsStr: string = blockStartsKeyWords.join("|");
  620. let regexBlockMidKeyWords: RegExp = blockMidKeyWords.convertToRegexBlockWords();
  621. let regexBlockStartsKeywords: RegExp = new RegExp("([\\w]+\\s*:\\s*)?(" + newLineAfterKeyWordsStr + ")([^\\w]|$)")
  622. let regexBlockEndsKeyWords: RegExp = blockEndsKeyWords.convertToRegexBlockWords()
  623. let regexblockEndsWithSemicolon: RegExp = blockEndsWithSemicolon.convertToRegexBlockWords();
  624. let regexMidKeyWhen: RegExp = "WHEN".convertToRegexBlockWords();
  625. let regexMidKeyElse: RegExp = "ELSE|ELSIF".convertToRegexBlockWords();
  626. if (endIndex == null) {
  627. endIndex = inputs.length - 1;
  628. }
  629. for (i = startIndex; i <= endIndex; i++) {
  630. if (indent < 0) {
  631. indent = 0;
  632. }
  633. let input: string = inputs[i].trim();
  634. if (input.regexStartsWith(/COMPONENT\s/)) {
  635. let modeCache = Mode;
  636. Mode = FormatMode.EndsWithSemicolon;
  637. [i, endIndex] = beautifyComponentBlock(inputs, result, settings, i, endIndex, indent);
  638. Mode = modeCache;
  639. continue;
  640. }
  641. if (input.regexStartsWith(/\w+\s*:\s*ENTITY/)) {
  642. let modeCache = Mode;
  643. Mode = FormatMode.EndsWithSemicolon;
  644. [i, endIndex] = beautifySemicolonBlock(inputs, result, settings, i, endIndex, indent);
  645. Mode = modeCache;
  646. continue;
  647. }
  648. if (Mode != FormatMode.EndsWithSemicolon && input.regexStartsWith(regexblockEndsWithSemicolon)) {
  649. let modeCache = Mode;
  650. Mode = FormatMode.EndsWithSemicolon;
  651. [i, endIndex] = beautifySemicolonBlock(inputs, result, settings, i, endIndex, indent);
  652. Mode = modeCache;
  653. continue;
  654. }
  655. if (input.regexStartsWith(/(.+:\s*)?(CASE)([\s]|$)/)) {
  656. let modeCache = Mode;
  657. Mode = FormatMode.CaseWhen;
  658. i = beautifyCaseBlock(inputs, result, settings, i, indent);
  659. Mode = modeCache;
  660. continue;
  661. }
  662. if (input.regexStartsWith(/[\w\s:]*PORT([\s]|$)/)) {
  663. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "PORT");
  664. continue;
  665. }
  666. if (input.regexStartsWith(/TYPE\s+\w+\s+IS\s+\(/)) {
  667. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "IS");
  668. continue;
  669. }
  670. if (input.regexStartsWith(/[\w\s:]*GENERIC([\s]|$)/)) {
  671. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "GENERIC");
  672. continue;
  673. }
  674. if (input.regexStartsWith(/[\w\s:]*PROCEDURE[\s\w]+\($/)) {
  675. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "PROCEDURE");
  676. if (inputs[i].regexStartsWith(/.*\)[\s]*IS/)) {
  677. i = beautify3(inputs, result, settings, i + 1, indent + 1);
  678. }
  679. continue;
  680. }
  681. if (input.regexStartsWith(/FUNCTION[^\w]/)
  682. && input.regexIndexOf(/[^\w]RETURN[^\w]/) < 0) {
  683. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "FUNCTION");
  684. if (!inputs[i].regexStartsWith(regexBlockEndsKeyWords)) {
  685. i = beautify3(inputs, result, settings, i + 1, indent + 1);
  686. } else {
  687. (<FormattedLine>result[i]).Indent++;
  688. }
  689. continue;
  690. }
  691. if (input.regexStartsWith(/IMPURE FUNCTION[^\w]/)
  692. && input.regexIndexOf(/[^\w]RETURN[^\w]/) < 0) {
  693. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "IMPURE FUNCTION");
  694. if (!inputs[i].regexStartsWith(regexBlockEndsKeyWords)) {
  695. i = beautify3(inputs, result, settings, i + 1, indent + 1);
  696. } else {
  697. (<FormattedLine>result[i]).Indent++;
  698. }
  699. continue;
  700. }
  701. result.push(new FormattedLine(input, indent));
  702. if (startIndex != 0
  703. && (input.regexStartsWith(regexBlockMidKeyWords)
  704. || (Mode != FormatMode.EndsWithSemicolon && input.regexStartsWith(regexMidKeyElse))
  705. || (Mode == FormatMode.CaseWhen && input.regexStartsWith(regexMidKeyWhen)))) {
  706. (<FormattedLine>result[i]).Indent--;
  707. }
  708. else if (startIndex != 0
  709. && (input.regexStartsWith(regexBlockEndsKeyWords))) {
  710. (<FormattedLine>result[i]).Indent--;
  711. return i;
  712. }
  713. if (input.regexStartsWith(regexOneLineBlockKeyWords)) {
  714. continue;
  715. }
  716. if (input.regexStartsWith(regexFunctionMultiLineBlockKeyWords)
  717. || input.regexStartsWith(regexBlockStartsKeywords)) {
  718. i = beautify3(inputs, result, settings, i + 1, indent + 1);
  719. }
  720. }
  721. i--;
  722. return i;
  723. }
  724. function ReserveSemicolonInKeywords(arr: Array<string>) {
  725. for (let i = 0; i < arr.length; i++) {
  726. if (arr[i].match(/FUNCTION|PROCEDURE/) != null) {
  727. arr[i] = arr[i].replace(/;/g, '@@semicolon');
  728. }
  729. }
  730. }
  731. export function ApplyNoNewLineAfter(arr: Array<string>, noNewLineAfter: Array<string>) {
  732. if (noNewLineAfter == null) {
  733. return;
  734. }
  735. for (let i = 0; i < arr.length; i++) {
  736. noNewLineAfter.forEach(n => {
  737. let regex = new RegExp("(" + n.toUpperCase + ")[ a-z0-9]+[a-z0-9]+");
  738. if (arr[i].regexIndexOf(regex) >= 0) {
  739. arr[i] += "@@singleline";
  740. }
  741. });
  742. }
  743. }
  744. export function RemoveAsserts(arr: Array<string>) {
  745. let need_semi: boolean = false;
  746. let inAssert: boolean = false;
  747. let n: number = 0;
  748. for (let i = 0; i < arr.length; i++) {
  749. let has_semi: boolean = arr[i].indexOf(";") >= 0;
  750. if (need_semi) {
  751. arr[i] = '';
  752. }
  753. n = arr[i].indexOf("ASSERT ");
  754. if (n >= 0) {
  755. inAssert = true;
  756. arr[i] = '';
  757. }
  758. if (!has_semi) {
  759. if (inAssert) {
  760. need_semi = true;
  761. }
  762. }
  763. else {
  764. need_semi = false;
  765. }
  766. }
  767. }
  768. function EscapeQuotes(arr: Array<string>): Array<string> {
  769. let quotes: Array<string> = [];
  770. let quotesIndex = 0;
  771. for (let i = 0; i < arr.length; i++) {
  772. let quote = arr[i].match(/"([^"]+)"/g);
  773. if (quote != null) {
  774. for (var j = 0; j < quote.length; j++) {
  775. arr[i] = arr[i].replace(quote[j], ILQuotesPrefix + quotesIndex);
  776. quotes[quotesIndex++] = quote[j];
  777. }
  778. }
  779. }
  780. return quotes;
  781. }
  782. function EscapeSingleQuotes(arr: Array<string>): Array<string> {
  783. let quotes: Array<string> = [];
  784. let quotesIndex = 0;
  785. for (let i = 0; i < arr.length; i++) {
  786. let quote = arr[i].match(/'[^']'/g);
  787. if (quote != null) {
  788. for (var j = 0; j < quote.length; j++) {
  789. arr[i] = arr[i].replace(quote[j], ILSingleQuotesPrefix + quotesIndex);
  790. quotes[quotesIndex++] = quote[j];
  791. }
  792. }
  793. }
  794. return quotes;
  795. }
  796. function RemoveExtraNewLines(input: any) {
  797. input = input.replace(/(?:\r\n|\r|\n)/g, '\r\n');
  798. input = input.replace(/ \r\n/g, '\r\n');
  799. input = input.replace(/\r\n\r\n\r\n/g, '\r\n');
  800. return input;
  801. }