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.

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