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.

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