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.

783 lines
30 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
  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[], typenames: string[]): string {
  134. let inputcase: string = keywordcase.toLowerCase();
  135. switch (keywordcase.toLowerCase()) {
  136. case "lowercase":
  137. ToLowerCases(keywords);
  138. ToLowerCases(typenames);
  139. break;
  140. case "defaultcase":
  141. ToCamelCases(keywords);
  142. ToCamelCases(typenames);
  143. break;
  144. case "uppercase":
  145. ToUpperCases(keywords);
  146. ToUpperCases(typenames);
  147. }
  148. input = ReplaceKeyWords(input, keywords);
  149. input = ReplaceKeyWords(input, typenames);
  150. return input;
  151. }
  152. export function SetNewLinesAfterSymbols(text: string, newLineSettings: NewLineSettings): string {
  153. if (newLineSettings == null) {
  154. return text;
  155. }
  156. if (newLineSettings.newLineAfter != null) {
  157. newLineSettings.newLineAfter.forEach(symbol => {
  158. let regex: RegExp = new RegExp("(" + symbol.toUpperCase() + ")[ ]?([^ \r\n@])", "g");
  159. text = text.replace(regex, '$1\r\n$2');
  160. if (symbol.toUpperCase() == "PORT") {
  161. text = text.replace(/PORT\s+MAP/, "PORT MAP");
  162. }
  163. });
  164. }
  165. if (newLineSettings.noNewLineAfter != null) {
  166. newLineSettings.noNewLineAfter.forEach(symbol => {
  167. let regex: RegExp = new RegExp("(" + symbol.toUpperCase() + ")[ \r\n]+([^@])", "g");
  168. text = text.replace(regex, '$1 $2');
  169. });
  170. }
  171. return text;
  172. }
  173. export class BeautifierSettings {
  174. RemoveComments: boolean;
  175. RemoveAsserts: boolean;
  176. CheckAlias: boolean;
  177. SignAlignRegional: boolean;
  178. SignAlignAll: boolean;
  179. SignAlignKeyWords: Array<string>;
  180. KeywordCase: string;
  181. Indentation: string;
  182. NewLineSettings: NewLineSettings;
  183. EndOfLine: string;
  184. constructor(removeComments: boolean, removeReport: boolean, checkAlias: boolean,
  185. signAlign: boolean, signAlignAll: boolean, keywordCase: string, indentation: string,
  186. newLineSettings: NewLineSettings, endOfLine: string) {
  187. this.RemoveComments = removeComments;
  188. this.RemoveAsserts = removeReport;
  189. this.CheckAlias = checkAlias;
  190. this.SignAlignRegional = signAlign;
  191. this.SignAlignAll = signAlignAll;
  192. this.KeywordCase = keywordCase;
  193. this.Indentation = indentation;
  194. this.NewLineSettings = newLineSettings;
  195. this.EndOfLine = endOfLine;
  196. }
  197. }
  198. 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"];
  199. let TypeNames: Array<string> = ["BOOLEAN", "BIT", "CHARACTER", "INTEGER", "TIME", "NATURAL", "POSITIVE", "STRING"];
  200. export function beautify(input: string, settings: BeautifierSettings) {
  201. input = input.replace(/\r\n/g, "\n");
  202. input = input.replace(/\n/g, "\r\n");
  203. var arr = input.split("\r\n");
  204. var comments = EscapeComments(arr);
  205. var backslashes = escapeText(arr, "\\\\[^\\\\]+\\\\", ILBackslash);
  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 = RemoveExtraNewLines(input);
  214. input = input.replace(/[\t ]+/g, ' ');
  215. input = input.replace(/\([\t ]+/g, '\(');
  216. input = input.replace(/[ ]+;/g, ';');
  217. input = input.replace(/:[ ]*(PROCESS|ENTITY)/gi, ':$1');
  218. arr = input.split("\r\n");
  219. let quotes = escapeText(arr, '"([^"]+)"', ILQuote);
  220. let singleQuotes = escapeText(arr, "'[^']'", ILSingleQuote);
  221. input = arr.join("\r\n");
  222. input = SetKeywordCase(input, "uppercase", KeyWords, TypeNames);
  223. arr = input.split("\r\n");
  224. if (settings.RemoveAsserts) {
  225. RemoveAsserts(arr);//RemoveAsserts must be after EscapeQuotes
  226. }
  227. ReserveSemicolonInKeywords(arr);
  228. input = arr.join("\r\n");
  229. input = input.replace(/(PORT|GENERIC)\s+MAP/g, '$1 MAP');
  230. input = input.replace(/(PORT|PROCESS|GENERIC)[\s]*\(/g, '$1 (');
  231. input = SetNewLinesAfterSymbols(input, settings.NewLineSettings);
  232. arr = input.split("\r\n");
  233. ApplyNoNewLineAfter(arr, settings.NewLineSettings.noNewLineAfter);
  234. input = arr.join("\r\n");
  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\n)return type; -> function(..\r\n)return type;
  252. arr = input.split("\r\n");
  253. let result: (FormattedLine | FormattedLine[])[] = [];
  254. beautify3(arr, result, settings, 0, 0);
  255. if (settings.SignAlignAll) {
  256. AlignSigns(result, 0, result.length - 1);
  257. }
  258. arr = FormattedLineToString(result, settings.Indentation);
  259. input = arr.join("\r\n");
  260. input = SetKeywordCase(input, settings.KeywordCase, KeyWords, TypeNames);
  261. input = replaceEscapedWords(input, quotes, ILQuote);
  262. input = replaceEscapedWords(input, singleQuotes, ILSingleQuote);
  263. input = replaceEscapedComments(input, comments, ILCommentPrefix);
  264. input = replaceEscapedWords(input, backslashes, ILBackslash);
  265. input = input.replace(new RegExp(ILSemicolon, "g"), ";");
  266. input = input.replace(/@@[a-z]+/g, "");
  267. var escapedTexts = new RegExp("[" + ILBackslash + ILQuote + ILSingleQuote + "]", "g");
  268. input = input.replace(escapedTexts, "");
  269. input = input.replace(/\r\n/g, settings.EndOfLine);
  270. return input;
  271. }
  272. function replaceEscapedWords(input: string, arr: Array<string>, prefix: string): string {
  273. for (var i = 0; i < arr.length; i++) {
  274. var text = arr[i];
  275. var regex = new RegExp(prefix + "{" + text.length + "}");
  276. input = input.replace(regex, text);
  277. }
  278. return input;
  279. }
  280. function replaceEscapedComments(input: string, arr: Array<string>, prefix: string): string {
  281. for (var i = 0; i < arr.length; i++) {
  282. input = input.replace(prefix + i, arr[i]);
  283. }
  284. return input;
  285. }
  286. function RemoveLeadingWhitespaces(arr: Array<string>) {
  287. for (var i = 0; i < arr.length; i++) {
  288. arr[i] = arr[i].replace(/^\s+/, "");
  289. }
  290. }
  291. export class FormattedLine {
  292. Line: string;
  293. Indent: number;
  294. constructor(line: string, indent: number) {
  295. this.Line = line;
  296. this.Indent = indent;
  297. }
  298. }
  299. export function FormattedLineToString(arr: (FormattedLine | FormattedLine[])[], indentation: string): Array<string> {
  300. let result: Array<string> = [];
  301. if (arr == null) {
  302. return result;
  303. }
  304. arr.forEach(i => {
  305. if (i instanceof FormattedLine) {
  306. if (i.Line.length > 0) {
  307. result.push((Array(i.Indent + 1).join(indentation)) + i.Line);
  308. }
  309. else {
  310. result.push("");
  311. }
  312. }
  313. else {
  314. result = result.concat(FormattedLineToString(i, indentation));
  315. }
  316. });
  317. return result;
  318. }
  319. function GetCloseparentheseEndIndex(inputs: Array<string>, startIndex: number): number {
  320. let openParentheseCount: number = 0;
  321. let closeParentheseCount: number = 0;
  322. for (let i = startIndex; i < inputs.length; i++) {
  323. let input = inputs[i];
  324. openParentheseCount += input.count("(");
  325. closeParentheseCount += input.count(")");
  326. if (openParentheseCount > 0
  327. && openParentheseCount <= closeParentheseCount) {
  328. return i;
  329. }
  330. }
  331. return startIndex;
  332. }
  333. export function beautifyPortGenericBlock(inputs: Array<string>, result: (FormattedLine | FormattedLine[])[], settings: BeautifierSettings, startIndex: number, parentEndIndex: number, indent: number, mode: string): [number, number] {
  334. let firstLine: string = inputs[startIndex];
  335. let regex: RegExp = new RegExp("[\\w\\s:]*(" + mode + ")([\\s]|$)");
  336. if (!firstLine.regexStartsWith(regex)) {
  337. return [startIndex, parentEndIndex];
  338. }
  339. let firstLineHasParenthese: boolean = firstLine.indexOf("(") >= 0;
  340. let hasParenthese: boolean = firstLineHasParenthese;
  341. let blockBodyStartIndex = startIndex;
  342. let secondLineHasParenthese: boolean = startIndex + 1 < inputs.length && inputs[startIndex + 1].startsWith("(");
  343. if (secondLineHasParenthese) {
  344. hasParenthese = true;
  345. blockBodyStartIndex++;
  346. }
  347. let endIndex: number = hasParenthese ? GetCloseparentheseEndIndex(inputs, startIndex) : startIndex;
  348. if (endIndex != startIndex && firstLineHasParenthese) {
  349. inputs[startIndex] = inputs[startIndex].replace(/(PORT|GENERIC|PROCEDURE)([\w ]+)\(([\w\(\) ]+)/, '$1$2(\r\n$3');
  350. let newInputs = inputs[startIndex].split("\r\n");
  351. if (newInputs.length == 2) {
  352. inputs[startIndex] = newInputs[0];
  353. inputs.splice(startIndex + 1, 0, newInputs[1]);
  354. endIndex++;
  355. parentEndIndex++;
  356. }
  357. }
  358. else if (endIndex > startIndex + 1 && secondLineHasParenthese) {
  359. inputs[startIndex + 1] = inputs[startIndex + 1].replace(/\(([\w\(\) ]+)/, '(\r\n$1');
  360. let newInputs = inputs[startIndex + 1].split("\r\n");
  361. if (newInputs.length == 2) {
  362. inputs[startIndex + 1] = newInputs[0];
  363. inputs.splice(startIndex + 2, 0, newInputs[1]);
  364. endIndex++;
  365. parentEndIndex++;
  366. }
  367. }
  368. if (firstLineHasParenthese && inputs[startIndex].indexOf("MAP") > 0) {
  369. inputs[startIndex] = inputs[startIndex].replace(/([^\w])(MAP)\s+\(/g, '$1$2(');
  370. }
  371. result.push(new FormattedLine(inputs[startIndex], indent));
  372. if (secondLineHasParenthese) {
  373. let secondLineIndent = indent;
  374. if (endIndex == startIndex + 1) {
  375. secondLineIndent++;
  376. }
  377. result.push(new FormattedLine(inputs[startIndex + 1], secondLineIndent));
  378. }
  379. let blockBodyEndIndex = endIndex;
  380. let i = beautify3(inputs, result, settings, blockBodyStartIndex + 1, indent + 1, endIndex);
  381. if (inputs[i].startsWith(")")) {
  382. (<FormattedLine>result[i]).Indent--;
  383. blockBodyEndIndex--;
  384. }
  385. if (settings.SignAlignRegional && !settings.SignAlignAll
  386. && settings.SignAlignKeyWords != null
  387. && settings.SignAlignKeyWords.indexOf(mode) >= 0) {
  388. blockBodyStartIndex++;
  389. AlignSigns(result, blockBodyStartIndex, blockBodyEndIndex);
  390. }
  391. return [i, parentEndIndex];
  392. }
  393. export function AlignSigns(result: (FormattedLine | FormattedLine[])[], startIndex: number, endIndex: number) {
  394. AlignSign_(result, startIndex, endIndex, ":");
  395. AlignSign_(result, startIndex, endIndex, ":=");
  396. AlignSign_(result, startIndex, endIndex, "<=");
  397. AlignSign_(result, startIndex, endIndex, "=>");
  398. AlignSign_(result, startIndex, endIndex, "@@comments");
  399. }
  400. function AlignSign_(result: (FormattedLine | FormattedLine[])[], startIndex: number, endIndex: number, symbol: string) {
  401. let maxSymbolIndex: number = -1;
  402. let symbolIndices = {};
  403. let startLine = startIndex;
  404. let labelAndKeywords: Array<string> = [
  405. "([\\w\\s]*:(\\s)*PROCESS)",
  406. "([\\w\\s]*:(\\s)*POSTPONED PROCESS)",
  407. "([\\w\\s]*:\\s*$)",
  408. "([\\w\\s]*:.*\\s+GENERATE)"
  409. ];
  410. let labelAndKeywordsStr: string = labelAndKeywords.join("|");
  411. let labelAndKeywordsRegex = new RegExp("(" + labelAndKeywordsStr + ")([^\\w]|$)");
  412. for (let i = startIndex; i <= endIndex; i++) {
  413. let line = (<FormattedLine>result[i]).Line;
  414. if (symbol == ":" && line.regexStartsWith(labelAndKeywordsRegex)) {
  415. continue;
  416. }
  417. let regex: RegExp = new RegExp("([\\s\\w\\\\]|^)" + symbol + "([\\s\\w\\\\]|$)");
  418. if (line.regexCount(regex) > 1) {
  419. continue;
  420. }
  421. let colonIndex = line.regexIndexOf(regex);
  422. if (colonIndex > 0) {
  423. maxSymbolIndex = Math.max(maxSymbolIndex, colonIndex);
  424. symbolIndices[i] = colonIndex;
  425. }
  426. else if (!line.startsWith(ILCommentPrefix) && line.length != 0) {
  427. if (startLine < i - 1) // if cannot find the symbol, a block of symbols ends
  428. {
  429. AlignSign(result, startLine, i - 1, symbol, maxSymbolIndex, symbolIndices);
  430. }
  431. maxSymbolIndex = -1;
  432. symbolIndices = {};
  433. startLine = i;
  434. }
  435. }
  436. if (startLine < endIndex) // if cannot find the symbol, a block of symbols ends
  437. {
  438. AlignSign(result, startLine, endIndex, symbol, maxSymbolIndex, symbolIndices);
  439. }
  440. }
  441. export function AlignSign(result: (FormattedLine | FormattedLine[])[], startIndex: number, endIndex: number, symbol: string, maxSymbolIndex: number = -1, symbolIndices = {}) {
  442. if (maxSymbolIndex < 0) {
  443. return;
  444. }
  445. for (let lineIndex in symbolIndices) {
  446. let symbolIndex = symbolIndices[lineIndex];
  447. if (symbolIndex == maxSymbolIndex) {
  448. continue;
  449. }
  450. let line = (<FormattedLine>result[lineIndex]).Line;
  451. (<FormattedLine>result[lineIndex]).Line = line.substring(0, symbolIndex)
  452. + (Array(maxSymbolIndex - symbolIndex + 1).join(" "))
  453. + line.substring(symbolIndex);
  454. }
  455. }
  456. export function beautifyCaseBlock(inputs: Array<string>, result: (FormattedLine | FormattedLine[])[], settings: BeautifierSettings, startIndex: number, indent: number): number {
  457. if (!inputs[startIndex].regexStartsWith(/(.+:\s*)?(CASE)([\s]|$)/)) {
  458. return startIndex;
  459. }
  460. result.push(new FormattedLine(inputs[startIndex], indent));
  461. let i = beautify3(inputs, result, settings, startIndex + 1, indent + 2);
  462. (<FormattedLine>result[i]).Indent = indent;
  463. return i;
  464. }
  465. function getSemicolonBlockEndIndex(inputs: Array<string>, settings: BeautifierSettings, startIndex: number, parentEndIndex: number): [number, number] {
  466. let endIndex = 0;
  467. let openBracketsCount = 0;
  468. let closeBracketsCount = 0;
  469. for (let i = startIndex; i < inputs.length; i++) {
  470. let input = inputs[i];
  471. let indexOfSemicolon = input.indexOf(";");
  472. let splitIndex = indexOfSemicolon < 0 ? input.length : indexOfSemicolon + 1;
  473. let stringBeforeSemicolon = input.substring(0, splitIndex);
  474. let stringAfterSemicolon = input.substring(splitIndex);
  475. stringAfterSemicolon = stringAfterSemicolon.replace(new RegExp(ILCommentPrefix + "[0-9]+"), "");
  476. openBracketsCount += stringBeforeSemicolon.count("(");
  477. closeBracketsCount += stringBeforeSemicolon.count(")");
  478. if (indexOfSemicolon < 0) {
  479. continue;
  480. }
  481. if (openBracketsCount == closeBracketsCount) {
  482. endIndex = i;
  483. if (stringAfterSemicolon.trim().length > 0 && settings.NewLineSettings.newLineAfter.indexOf(";") >= 0) {
  484. inputs[i] = stringBeforeSemicolon;
  485. inputs.splice(i, 0, stringAfterSemicolon);
  486. parentEndIndex++;
  487. }
  488. break;
  489. }
  490. }
  491. return [endIndex, parentEndIndex];
  492. }
  493. export function beautifyComponentBlock(inputs: Array<string>, result: (FormattedLine | FormattedLine[])[], settings: BeautifierSettings, startIndex: number, parentEndIndex: number, indent: number): [number, number] {
  494. let endIndex = startIndex;
  495. for (let i = startIndex; i < inputs.length; i++) {
  496. if (inputs[i].regexStartsWith(/END(\s|$)/)) {
  497. endIndex = i;
  498. break;
  499. }
  500. }
  501. result.push(new FormattedLine(inputs[startIndex], indent));
  502. if (endIndex != startIndex) {
  503. let actualEndIndex = beautify3(inputs, result, settings, startIndex + 1, indent + 1, endIndex);
  504. let incremental = actualEndIndex - endIndex;
  505. endIndex += incremental;
  506. parentEndIndex += incremental;
  507. }
  508. return [endIndex, parentEndIndex];
  509. }
  510. export function beautifySemicolonBlock(inputs: Array<string>, result: (FormattedLine | FormattedLine[])[], settings: BeautifierSettings, startIndex: number, parentEndIndex: number, indent: number): [number, number] {
  511. let endIndex = startIndex;
  512. [endIndex, parentEndIndex] = getSemicolonBlockEndIndex(inputs, settings, startIndex, parentEndIndex);
  513. result.push(new FormattedLine(inputs[startIndex], indent));
  514. if (endIndex != startIndex) {
  515. let i = beautify3(inputs, result, settings, startIndex + 1, indent + 1, endIndex);
  516. }
  517. return [endIndex, parentEndIndex];
  518. }
  519. export function beautify3(inputs: Array<string>, result: (FormattedLine | FormattedLine[])[], settings: BeautifierSettings, startIndex: number, indent: number, endIndex?: number): number {
  520. let i: number;
  521. let regexOneLineBlockKeyWords: RegExp = new RegExp(/(PROCEDURE)[^\w](?!.+[^\w]IS([^\w]|$))/);//match PROCEDURE..; but not PROCEDURE .. IS;
  522. let regexFunctionMultiLineBlockKeyWords: RegExp = new RegExp(/(FUNCTION|IMPURE FUNCTION)[^\w](?=.+[^\w]IS([^\w]|$))/);//match FUNCTION .. IS; but not FUNCTION
  523. let blockMidKeyWords: Array<string> = ["BEGIN"];
  524. let blockStartsKeyWords: Array<string> = [
  525. "IF",
  526. "CASE",
  527. "ARCHITECTURE",
  528. "PROCEDURE",
  529. "PACKAGE",
  530. "(([\\w\\s]*:)?(\\s)*PROCESS)",// with label
  531. "(([\\w\\s]*:)?(\\s)*POSTPONED PROCESS)",// with label
  532. "(.*\\s*PROTECTED)",
  533. "(COMPONENT)",
  534. "(ENTITY(?!.+;))",
  535. "FOR",
  536. "WHILE",
  537. "LOOP",
  538. "(.*\\s*GENERATE)",
  539. "(CONTEXT[\\w\\s\\\\]+IS)",
  540. "(CONFIGURATION(?!.+;))",
  541. "BLOCK",
  542. "UNITS",
  543. "\\w+\\s+\\w+\\s+IS\\s+RECORD"];
  544. let blockEndsKeyWords: Array<string> = ["END", ".*\\)\\s*RETURN\\s+[\\w]+;"];
  545. let blockEndsWithSemicolon: Array<string> = [
  546. "(WITH\\s+[\\w\\s\\\\]+SELECT)",
  547. "([\\w\\\\]+[\\s]*<=)",
  548. "([\\w\\\\]+[\\s]*:=)",
  549. "FOR\\s+[\\w\\s,]+:\\s*\\w+\\s+USE",
  550. "REPORT"
  551. ];
  552. let newLineAfterKeyWordsStr: string = blockStartsKeyWords.join("|");
  553. let regexBlockMidKeyWords: RegExp = blockMidKeyWords.convertToRegexBlockWords();
  554. let regexBlockStartsKeywords: RegExp = new RegExp("([\\w]+\\s*:\\s*)?(" + newLineAfterKeyWordsStr + ")([^\\w]|$)")
  555. let regexBlockEndsKeyWords: RegExp = blockEndsKeyWords.convertToRegexBlockWords()
  556. let regexblockEndsWithSemicolon: RegExp = blockEndsWithSemicolon.convertToRegexBlockWords();
  557. let regexMidKeyWhen: RegExp = "WHEN".convertToRegexBlockWords();
  558. let regexMidKeyElse: RegExp = "ELSE|ELSIF".convertToRegexBlockWords();
  559. if (endIndex == null) {
  560. endIndex = inputs.length - 1;
  561. }
  562. for (i = startIndex; i <= endIndex; i++) {
  563. if (indent < 0) {
  564. indent = 0;
  565. }
  566. let input: string = inputs[i].trim();
  567. if (input.regexStartsWith(/COMPONENT\s/)) {
  568. let modeCache = Mode;
  569. Mode = FormatMode.EndsWithSemicolon;
  570. [i, endIndex] = beautifyComponentBlock(inputs, result, settings, i, endIndex, indent);
  571. Mode = modeCache;
  572. continue;
  573. }
  574. if (input.regexStartsWith(/\w+\s*:\s*ENTITY/)) {
  575. let modeCache = Mode;
  576. Mode = FormatMode.EndsWithSemicolon;
  577. [i, endIndex] = beautifySemicolonBlock(inputs, result, settings, i, endIndex, indent);
  578. Mode = modeCache;
  579. continue;
  580. }
  581. if (Mode != FormatMode.EndsWithSemicolon && input.regexStartsWith(regexblockEndsWithSemicolon)) {
  582. let modeCache = Mode;
  583. Mode = FormatMode.EndsWithSemicolon;
  584. [i, endIndex] = beautifySemicolonBlock(inputs, result, settings, i, endIndex, indent);
  585. Mode = modeCache;
  586. continue;
  587. }
  588. if (input.regexStartsWith(/(.+:\s*)?(CASE)([\s]|$)/)) {
  589. let modeCache = Mode;
  590. Mode = FormatMode.CaseWhen;
  591. i = beautifyCaseBlock(inputs, result, settings, i, indent);
  592. Mode = modeCache;
  593. continue;
  594. }
  595. if (input.regexStartsWith(/[\w\s:]*PORT([\s]|$)/)) {
  596. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "PORT");
  597. continue;
  598. }
  599. if (input.regexStartsWith(/TYPE\s+\w+\s+IS\s+\(/)) {
  600. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "IS");
  601. continue;
  602. }
  603. if (input.regexStartsWith(/[\w\s:]*GENERIC([\s]|$)/)) {
  604. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "GENERIC");
  605. continue;
  606. }
  607. if (input.regexStartsWith(/[\w\s:]*PROCEDURE[\s\w]+\($/)) {
  608. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "PROCEDURE");
  609. if (inputs[i].regexStartsWith(/.*\)[\s]*IS/)) {
  610. i = beautify3(inputs, result, settings, i + 1, indent + 1);
  611. }
  612. continue;
  613. }
  614. if (input.regexStartsWith(/FUNCTION[^\w]/)
  615. && input.regexIndexOf(/[^\w]RETURN[^\w]/) < 0) {
  616. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "FUNCTION");
  617. if (!inputs[i].regexStartsWith(regexBlockEndsKeyWords)) {
  618. i = beautify3(inputs, result, settings, i + 1, indent + 1);
  619. } else {
  620. (<FormattedLine>result[i]).Indent++;
  621. }
  622. continue;
  623. }
  624. if (input.regexStartsWith(/IMPURE FUNCTION[^\w]/)
  625. && input.regexIndexOf(/[^\w]RETURN[^\w]/) < 0) {
  626. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "IMPURE FUNCTION");
  627. if (!inputs[i].regexStartsWith(regexBlockEndsKeyWords)) {
  628. i = beautify3(inputs, result, settings, i + 1, indent + 1);
  629. } else {
  630. (<FormattedLine>result[i]).Indent++;
  631. }
  632. continue;
  633. }
  634. result.push(new FormattedLine(input, indent));
  635. if (startIndex != 0
  636. && (input.regexStartsWith(regexBlockMidKeyWords)
  637. || (Mode != FormatMode.EndsWithSemicolon && input.regexStartsWith(regexMidKeyElse))
  638. || (Mode == FormatMode.CaseWhen && input.regexStartsWith(regexMidKeyWhen)))) {
  639. (<FormattedLine>result[i]).Indent--;
  640. }
  641. else if (startIndex != 0
  642. && (input.regexStartsWith(regexBlockEndsKeyWords))) {
  643. (<FormattedLine>result[i]).Indent--;
  644. return i;
  645. }
  646. if (input.regexStartsWith(regexOneLineBlockKeyWords)) {
  647. continue;
  648. }
  649. if (input.regexStartsWith(regexFunctionMultiLineBlockKeyWords)
  650. || input.regexStartsWith(regexBlockStartsKeywords)) {
  651. i = beautify3(inputs, result, settings, i + 1, indent + 1);
  652. }
  653. }
  654. i--;
  655. return i;
  656. }
  657. function ReserveSemicolonInKeywords(arr: Array<string>) {
  658. for (let i = 0; i < arr.length; i++) {
  659. if (arr[i].match(/FUNCTION|PROCEDURE/) != null) {
  660. arr[i] = arr[i].replace(/;/g, ILSemicolon);
  661. }
  662. }
  663. }
  664. export function ApplyNoNewLineAfter(arr: Array<string>, noNewLineAfter: Array<string>) {
  665. if (noNewLineAfter == null) {
  666. return;
  667. }
  668. for (let i = 0; i < arr.length; i++) {
  669. noNewLineAfter.forEach(n => {
  670. let regex = new RegExp("(" + n.toUpperCase + ")[ a-z0-9]+[a-z0-9]+");
  671. if (arr[i].regexIndexOf(regex) >= 0) {
  672. arr[i] += "@@singleline";
  673. }
  674. });
  675. }
  676. }
  677. export function RemoveAsserts(arr: Array<string>) {
  678. let need_semi: boolean = false;
  679. let inAssert: boolean = false;
  680. let n: number = 0;
  681. for (let i = 0; i < arr.length; i++) {
  682. let has_semi: boolean = arr[i].indexOf(";") >= 0;
  683. if (need_semi) {
  684. arr[i] = '';
  685. }
  686. n = arr[i].indexOf("ASSERT ");
  687. if (n >= 0) {
  688. inAssert = true;
  689. arr[i] = '';
  690. }
  691. if (!has_semi) {
  692. if (inAssert) {
  693. need_semi = true;
  694. }
  695. }
  696. else {
  697. need_semi = false;
  698. }
  699. }
  700. }
  701. function escapeText(arr: Array<string>, regex: string, escapedChar: string): Array<string> {
  702. let quotes: Array<string> = [];
  703. let regexEpr = new RegExp(regex, "g");
  704. for (let i = 0; i < arr.length; i++) {
  705. let matches = arr[i].match(regexEpr);
  706. if (matches != null) {
  707. for (var j = 0; j < matches.length; j++) {
  708. var match = matches[j];
  709. arr[i] = arr[i].replace(match, escapedChar.repeat(match.length));
  710. quotes.push(match);
  711. }
  712. }
  713. }
  714. return quotes;
  715. }
  716. function RemoveExtraNewLines(input: any) {
  717. input = input.replace(/(?:\r\n|\r|\n)/g, '\r\n');
  718. input = input.replace(/ \r\n/g, '\r\n');
  719. input = input.replace(/\r\n\r\n\r\n/g, '\r\n');
  720. return input;
  721. }