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.

984 lines
39 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. alignComments: boolean;
  264. constructor(isRegional: boolean, isAll: boolean, mode: string, keyWords: Array<string>, alignComments: boolean = false) {
  265. this.isRegional = isRegional;
  266. this.isAll = isAll;
  267. this.mode = mode;
  268. this.keyWords = keyWords;
  269. this.alignComments = alignComments;
  270. }
  271. }
  272. export class BeautifierSettings {
  273. RemoveComments: boolean;
  274. RemoveAsserts: boolean;
  275. CheckAlias: boolean;
  276. SignAlignSettings: signAlignSettings;
  277. KeywordCase: string;
  278. TypeNameCase: string;
  279. Indentation: string;
  280. NewLineSettings: NewLineSettings;
  281. EndOfLine: string;
  282. AddNewLine: boolean;
  283. constructor(removeComments: boolean, removeReport: boolean, checkAlias: boolean,
  284. signAlignSettings: signAlignSettings, keywordCase: string, typeNameCase: string, indentation: string,
  285. newLineSettings: NewLineSettings, endOfLine: string, addNewLine: boolean) {
  286. this.RemoveComments = removeComments;
  287. this.RemoveAsserts = removeReport;
  288. this.CheckAlias = checkAlias;
  289. this.SignAlignSettings = signAlignSettings;
  290. this.KeywordCase = keywordCase;
  291. this.TypeNameCase = typeNameCase;
  292. this.Indentation = indentation;
  293. this.NewLineSettings = newLineSettings;
  294. this.EndOfLine = endOfLine;
  295. this.AddNewLine = addNewLine;
  296. }
  297. }
  298. 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"];
  299. let TypeNames: Array<string> = ["BOOLEAN", "BIT", "CHARACTER", "INTEGER", "TIME", "NATURAL", "POSITIVE", "STD_LOGIC", "STD_LOGIC_VECTOR", "STD_ULOGIC", "STD_ULOGIC_VECTOR", "STRING"];
  300. export function beautify(input: string, settings: BeautifierSettings) {
  301. input = input.replace(/\r\n/g, "\n");
  302. input = input.replace(/\n/g, "\r\n");
  303. var arr = input.split("\r\n");
  304. var comments = EscapeComments(arr);
  305. var backslashes = escapeText(arr, "\\\\[^\\\\]+\\\\", ILBackslash);
  306. let quotes = escapeText(arr, '"([^"]+)"', ILQuote);
  307. let singleQuotes = escapeText(arr, "'[^']'", ILSingleQuote);
  308. RemoveLeadingWhitespaces(arr);
  309. input = arr.join("\r\n");
  310. if (settings.RemoveComments) {
  311. input = input.replace(/\r\n[ \t]*@@comments[0-9]+[ \t]*\r\n/g, '\r\n');
  312. input = input.replace(/@@comments[0-9]+/g, '');
  313. comments = [];
  314. }
  315. input = SetKeywordCase(input, "uppercase", KeyWords);
  316. input = SetKeywordCase(input, "uppercase", TypeNames);
  317. input = RemoveExtraNewLines(input);
  318. input = input.replace(/[\t ]+/g, ' ');
  319. input = input.replace(/\([\t ]+/g, '\(');
  320. input = input.replace(/[ ]+;/g, ';');
  321. input = input.replace(/:[ ]*(PROCESS|ENTITY)/gi, ':$1');
  322. arr = input.split("\r\n");
  323. if (settings.RemoveAsserts) {
  324. RemoveAsserts(arr);//RemoveAsserts must be after EscapeQuotes
  325. }
  326. ReserveSemicolonInKeywords(arr);
  327. input = arr.join("\r\n");
  328. input = input.replace(/\b(PORT|GENERIC)\b\s+MAP/g, '$1 MAP');
  329. input = input.replace(/\b(PORT|PROCESS|GENERIC)\b[\s]*\(/g, '$1 (');
  330. let newLineSettings = settings.NewLineSettings;
  331. if (newLineSettings != null) {
  332. input = SetNewLinesAfterSymbols(input, newLineSettings);
  333. arr = input.split("\r\n");
  334. ApplyNoNewLineAfter(arr, newLineSettings.noNewLineAfter);
  335. input = arr.join("\r\n");
  336. }
  337. input = input.replace(/([a-zA-Z0-9\); ])\);(@@comments[0-9]+)?@@end/g, '$1\r\n);$2@@end');
  338. input = input.replace(/[ ]?([&=:\-\+|\*]|[<>]+)[ ]?/g, ' $1 ');
  339. input = input.replace(/(\d+e) +([+\-]) +(\d+)/g, '$1$2$3');// fix exponential notation format broken by previous step
  340. input = input.replace(/[ ]?([,])[ ]?/g, '$1 ');
  341. input = input.replace(/[ ]?(['"])(THEN)/g, '$1 $2');
  342. input = input.replace(/[ ]?(\?)?[ ]?(<|:|>|\/)?[ ]+(=)?[ ]?/g, ' $1$2$3 ');
  343. input = input.replace(/(IF)[ ]?([\(\)])/g, '$1 $2');
  344. input = input.replace(/([\(\)])[ ]?(THEN)/gi, '$1 $2');
  345. input = input.replace(/(^|[\(\)])[ ]?(AND|OR|XOR|XNOR)[ ]*([\(])/g, '$1 $2 $3');
  346. input = input.replace(/ ([\-\*\/=+<>])[ ]*([\-\*\/=+<>]) /g, " $1$2 ");
  347. //input = input.replace(/\r\n[ \t]+--\r\n/g, "\r\n");
  348. input = input.replace(/[ ]+/g, ' ');
  349. input = input.replace(/[ \t]+\r\n/g, "\r\n");
  350. input = input.replace(/\r\n\r\n\r\n/g, '\r\n');
  351. input = input.replace(/[\r\n\s]+$/g, '');
  352. input = input.replace(/[ \t]+\)/g, ')');
  353. input = input.replace(/\s*\)\s+RETURN\s+([\w]+;)/g, '\r\n) RETURN $1');//function(..)\r\nreturn type; -> function(..\r\n)return type;
  354. 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;
  355. let keywordAndSignRegex = new RegExp("(\\b" + KeyWords.join("\\b|\\b") + "\\b) +([\\-+]) +(\\w)", "g");
  356. input = input.replace(keywordAndSignRegex, "$1 $2$3");// `WHEN - 2` -> `WHEN -2`
  357. input = input.replace(/([,|]) +([+\-]) +(\w)/g, '$1 $2$3');// `1, - 2)` -> `1, -2)`
  358. input = input.replace(/(\() +([+\-]) +(\w)/g, '$1$2$3');// `( - 2)` -> `(-2)`
  359. arr = input.split("\r\n");
  360. let result: (FormattedLine | FormattedLine[])[] = [];
  361. beautify3(arr, result, settings, 0, 0);
  362. var alignSettings = settings.SignAlignSettings;
  363. if (alignSettings != null && alignSettings.isAll) {
  364. AlignSigns(result, 0, result.length - 1, alignSettings.mode, alignSettings.alignComments);
  365. }
  366. arr = FormattedLineToString(result, settings.Indentation);
  367. input = arr.join("\r\n");
  368. input = input.replace(/@@RETURN/g, "RETURN");
  369. input = SetKeywordCase(input, settings.KeywordCase, KeyWords);
  370. input = SetKeywordCase(input, settings.TypeNameCase, TypeNames);
  371. input = replaceEscapedWords(input, quotes, ILQuote);
  372. input = replaceEscapedWords(input, singleQuotes, ILSingleQuote);
  373. input = replaceEscapedComments(input, comments, ILCommentPrefix);
  374. input = replaceEscapedWords(input, backslashes, ILBackslash);
  375. input = input.replace(new RegExp(ILSemicolon, "g"), ";");
  376. input = input.replace(/@@[a-z]+/g, "");
  377. var escapedTexts = new RegExp("[" + ILBackslash + ILQuote + ILSingleQuote + "]", "g");
  378. input = input.replace(escapedTexts, "");
  379. input = input.replace(/\r\n/g, settings.EndOfLine);
  380. if (settings.AddNewLine && !input.endsWith(settings.EndOfLine)) {
  381. input += settings.EndOfLine;
  382. }
  383. return input;
  384. }
  385. function replaceEscapedWords(input: string, arr: Array<string>, prefix: string): string {
  386. for (var i = 0; i < arr.length; i++) {
  387. var text = arr[i];
  388. var regex = new RegExp("(" + prefix + "){" + text.length + "}");
  389. input = input.replace(regex, text);
  390. }
  391. return input;
  392. }
  393. function replaceEscapedComments(input: string, arr: Array<string>, prefix: string): string {
  394. for (var i = 0; i < arr.length; i++) {
  395. input = input.replace(prefix + i, arr[i]);
  396. }
  397. return input;
  398. }
  399. function RemoveLeadingWhitespaces(arr: Array<string>) {
  400. for (var i = 0; i < arr.length; i++) {
  401. arr[i] = arr[i].replace(/^\s+/, "");
  402. }
  403. }
  404. export class FormattedLine {
  405. Line: string;
  406. Indent: number;
  407. constructor(line: string, indent: number) {
  408. this.Line = line;
  409. this.Indent = indent;
  410. }
  411. }
  412. export function FormattedLineToString(arr: (FormattedLine | FormattedLine[])[], indentation: string): Array<string> {
  413. let result: Array<string> = [];
  414. if (arr == null) {
  415. return result;
  416. }
  417. if (indentation == null) {
  418. indentation = "";
  419. }
  420. arr.forEach(i => {
  421. if (i instanceof FormattedLine) {
  422. if (i.Line.length > 0) {
  423. result.push((Array(i.Indent + 1).join(indentation)) + i.Line);
  424. }
  425. else {
  426. result.push("");
  427. }
  428. }
  429. else {
  430. result = result.concat(FormattedLineToString(i, indentation));
  431. }
  432. });
  433. return result;
  434. }
  435. function GetCloseparentheseEndIndex(inputs: Array<string>, startIndex: number): number {
  436. let openParentheseCount: number = 0;
  437. let closeParentheseCount: number = 0;
  438. for (let i = startIndex; i < inputs.length; i++) {
  439. let input = inputs[i];
  440. openParentheseCount += input.count("(");
  441. closeParentheseCount += input.count(")");
  442. if (openParentheseCount > 0
  443. && openParentheseCount <= closeParentheseCount) {
  444. return i;
  445. }
  446. }
  447. return startIndex;
  448. }
  449. export function beautifyPortGenericBlock(inputs: Array<string>, result: (FormattedLine | FormattedLine[])[], settings: BeautifierSettings, startIndex: number, parentEndIndex: number, indent: number, mode: string): [number, number] {
  450. let firstLine: string = inputs[startIndex];
  451. let regex: RegExp = new RegExp("[\\w\\s:]*(" + mode + ")([\\s]|$)");
  452. if (!firstLine.regexStartsWith(regex)) {
  453. return [startIndex, parentEndIndex];
  454. }
  455. let firstLineHasParenthese: boolean = firstLine.indexOf("(") >= 0;
  456. let hasParenthese: boolean = firstLineHasParenthese;
  457. let blockBodyStartIndex = startIndex;
  458. let secondLineHasParenthese: boolean = startIndex + 1 < inputs.length && inputs[startIndex + 1].startsWith("(");
  459. if (secondLineHasParenthese) {
  460. hasParenthese = true;
  461. blockBodyStartIndex++;
  462. }
  463. let endIndex: number = hasParenthese ? GetCloseparentheseEndIndex(inputs, startIndex) : startIndex;
  464. if (endIndex != startIndex && firstLineHasParenthese) {
  465. inputs[startIndex] = inputs[startIndex].replace(/\b(PORT|GENERIC|PROCEDURE)\b([\w ]+)\(([\w\(\) ]+)/, '$1$2(\r\n$3');
  466. let newInputs = inputs[startIndex].split("\r\n");
  467. if (newInputs.length == 2) {
  468. inputs[startIndex] = newInputs[0];
  469. inputs.splice(startIndex + 1, 0, newInputs[1]);
  470. endIndex++;
  471. parentEndIndex++;
  472. }
  473. }
  474. else if (endIndex > startIndex + 1 && secondLineHasParenthese) {
  475. inputs[startIndex + 1] = inputs[startIndex + 1].replace(/\(([\w\(\) ]+)/, '(\r\n$1');
  476. let newInputs = inputs[startIndex + 1].split("\r\n");
  477. if (newInputs.length == 2) {
  478. inputs[startIndex + 1] = newInputs[0];
  479. inputs.splice(startIndex + 2, 0, newInputs[1]);
  480. endIndex++;
  481. parentEndIndex++;
  482. }
  483. }
  484. if (firstLineHasParenthese && inputs[startIndex].indexOf("MAP") > 0) {
  485. inputs[startIndex] = inputs[startIndex].replace(/([^\w])(MAP)\s+\(/g, '$1$2(');
  486. }
  487. result.push(new FormattedLine(inputs[startIndex], indent));
  488. if (secondLineHasParenthese) {
  489. let secondLineIndent = indent;
  490. if (endIndex == startIndex + 1) {
  491. secondLineIndent++;
  492. }
  493. result.push(new FormattedLine(inputs[startIndex + 1], secondLineIndent));
  494. }
  495. let blockBodyEndIndex = endIndex;
  496. let i = beautify3(inputs, result, settings, blockBodyStartIndex + 1, indent + 1, endIndex);
  497. if (inputs[i].startsWith(")")) {
  498. (<FormattedLine>result[i]).Indent--;
  499. blockBodyEndIndex--;
  500. }
  501. var alignSettings = settings.SignAlignSettings;
  502. if (alignSettings != null) {
  503. if (alignSettings.isRegional && !alignSettings.isAll
  504. && alignSettings.keyWords != null
  505. && alignSettings.keyWords.indexOf(mode) >= 0) {
  506. blockBodyStartIndex++;
  507. AlignSigns(result, blockBodyStartIndex, blockBodyEndIndex, alignSettings.mode, alignSettings.alignComments);
  508. }
  509. }
  510. return [i, parentEndIndex];
  511. }
  512. export function AlignSigns(result: (FormattedLine | FormattedLine[])[], startIndex: number, endIndex: number, mode: string, alignComments: boolean = false) {
  513. AlignSign_(result, startIndex, endIndex, ":", mode);
  514. AlignSign_(result, startIndex, endIndex, ":=", mode);
  515. AlignSign_(result, startIndex, endIndex, "<=", mode);
  516. AlignSign_(result, startIndex, endIndex, "=>", mode);
  517. AlignSign_(result, startIndex, endIndex, "direction", mode);
  518. if (alignComments) {
  519. AlignSign_(result, startIndex, endIndex, "@@comments", mode);
  520. }
  521. }
  522. function indexOfGroup(regex: RegExp, input: string, group: number) {
  523. var match = regex.exec(input);
  524. if (match == null) {
  525. return -1;
  526. }
  527. var index = match.index;
  528. for (let i = 1; i < group; i++) {
  529. index += match[i].length;
  530. }
  531. return index;
  532. }
  533. function AlignSign_(result: (FormattedLine | FormattedLine[])[], startIndex: number, endIndex: number, symbol: string, mode: string) {
  534. let maxSymbolIndex: number = -1;
  535. let symbolIndices = {};
  536. let startLine = startIndex;
  537. let labelAndKeywords: Array<string> = [
  538. "([\\w\\s]*:(\\s)*PROCESS)",
  539. "([\\w\\s]*:(\\s)*POSTPONED PROCESS)",
  540. "([\\w\\s]*:\\s*$)",
  541. "([\\w\\s]*:.*\\s+GENERATE)"
  542. ];
  543. let labelAndKeywordsStr: string = labelAndKeywords.join("|");
  544. let labelAndKeywordsRegex = new RegExp("(" + labelAndKeywordsStr + ")([^\\w]|$)");
  545. for (let i = startIndex; i <= endIndex; i++) {
  546. let line = (<FormattedLine>result[i]).Line;
  547. if (symbol == ":" && line.regexStartsWith(labelAndKeywordsRegex)) {
  548. continue;
  549. }
  550. let regex: RegExp;
  551. if (symbol == "direction") {
  552. regex = new RegExp("(:\\s*)(IN|OUT|INOUT|BUFFER)(\\s+)(\\w)");
  553. }
  554. else {
  555. regex = new RegExp("([\\s\\w\\\\]|^)" + symbol + "([\\s\\w\\\\]|$)");
  556. }
  557. if (line.regexCount(regex) > 1) {
  558. continue;
  559. }
  560. let colonIndex: number;
  561. if (symbol == "direction") {
  562. colonIndex = indexOfGroup(regex, line, 4);
  563. }
  564. else {
  565. colonIndex = line.regexIndexOf(regex);
  566. }
  567. if (colonIndex > 0) {
  568. maxSymbolIndex = Math.max(maxSymbolIndex, colonIndex);
  569. symbolIndices[i] = colonIndex;
  570. }
  571. else if ((mode != "local" && !line.startsWith(ILCommentPrefix) && line.length != 0)
  572. || (mode == "local")) {
  573. if (startLine < i - 1) // if cannot find the symbol, a block of symbols ends
  574. {
  575. AlignSign(result, startLine, i - 1, symbol, maxSymbolIndex, symbolIndices);
  576. }
  577. maxSymbolIndex = -1;
  578. symbolIndices = {};
  579. startLine = i;
  580. }
  581. }
  582. if (startLine < endIndex) // if cannot find the symbol, a block of symbols ends
  583. {
  584. AlignSign(result, startLine, endIndex, symbol, maxSymbolIndex, symbolIndices);
  585. }
  586. }
  587. export function AlignSign(result: (FormattedLine | FormattedLine[])[], startIndex: number, endIndex: number, symbol: string, maxSymbolIndex: number = -1, symbolIndices = {}) {
  588. if (maxSymbolIndex < 0) {
  589. return;
  590. }
  591. for (let lineIndex in symbolIndices) {
  592. let symbolIndex = symbolIndices[lineIndex];
  593. if (symbolIndex == maxSymbolIndex) {
  594. continue;
  595. }
  596. let line = (<FormattedLine>result[lineIndex]).Line;
  597. (<FormattedLine>result[lineIndex]).Line = line.substring(0, symbolIndex)
  598. + (Array(maxSymbolIndex - symbolIndex + 1).join(" "))
  599. + line.substring(symbolIndex);
  600. }
  601. }
  602. export function beautifyCaseBlock(inputs: Array<string>, result: (FormattedLine | FormattedLine[])[], settings: BeautifierSettings, startIndex: number, indent: number): number {
  603. if (!inputs[startIndex].regexStartsWith(/(.+:\s*)?(CASE)([\s]|$)/)) {
  604. return startIndex;
  605. }
  606. result.push(new FormattedLine(inputs[startIndex], indent));
  607. let i = beautify3(inputs, result, settings, startIndex + 1, indent + 2);
  608. (<FormattedLine>result[i]).Indent = indent;
  609. return i;
  610. }
  611. function getSemicolonBlockEndIndex(inputs: Array<string>, settings: BeautifierSettings, startIndex: number, parentEndIndex: number): [number, number] {
  612. let endIndex = 0;
  613. let openBracketsCount = 0;
  614. let closeBracketsCount = 0;
  615. for (let i = startIndex; i < inputs.length; i++) {
  616. let input = inputs[i];
  617. let indexOfSemicolon = input.indexOf(";");
  618. let splitIndex = indexOfSemicolon < 0 ? input.length : indexOfSemicolon + 1;
  619. let stringBeforeSemicolon = input.substring(0, splitIndex);
  620. let stringAfterSemicolon = input.substring(splitIndex);
  621. stringAfterSemicolon = stringAfterSemicolon.replace(new RegExp(ILCommentPrefix + "[0-9]+"), "");
  622. openBracketsCount += stringBeforeSemicolon.count("(");
  623. closeBracketsCount += stringBeforeSemicolon.count(")");
  624. if (indexOfSemicolon < 0) {
  625. continue;
  626. }
  627. if (openBracketsCount == closeBracketsCount) {
  628. endIndex = i;
  629. if (stringAfterSemicolon.trim().length > 0 && settings.NewLineSettings.newLineAfter.indexOf(";") >= 0) {
  630. inputs[i] = stringBeforeSemicolon;
  631. inputs.splice(i, 0, stringAfterSemicolon);
  632. parentEndIndex++;
  633. }
  634. break;
  635. }
  636. }
  637. return [endIndex, parentEndIndex];
  638. }
  639. export function beautifyComponentBlock(inputs: Array<string>, result: (FormattedLine | FormattedLine[])[], settings: BeautifierSettings, startIndex: number, parentEndIndex: number, indent: number): [number, number] {
  640. let endIndex = startIndex;
  641. for (let i = startIndex; i < inputs.length; i++) {
  642. if (inputs[i].regexStartsWith(/END(\s|$)/)) {
  643. endIndex = i;
  644. break;
  645. }
  646. }
  647. result.push(new FormattedLine(inputs[startIndex], indent));
  648. if (endIndex != startIndex) {
  649. let actualEndIndex = beautify3(inputs, result, settings, startIndex + 1, indent + 1, endIndex);
  650. let incremental = actualEndIndex - endIndex;
  651. endIndex += incremental;
  652. parentEndIndex += incremental;
  653. }
  654. return [endIndex, parentEndIndex];
  655. }
  656. export function beautifyPackageIsNewBlock(inputs: Array<string>, result: (FormattedLine | FormattedLine[])[], settings: BeautifierSettings, startIndex: number, parentEndIndex: number, indent: number): [number, number] {
  657. let endIndex = startIndex;
  658. for (let i = startIndex; i < inputs.length; i++) {
  659. if (inputs[i].regexIndexOf(/;(\s|$)/) >= 0) {
  660. endIndex = i;
  661. break;
  662. }
  663. }
  664. result.push(new FormattedLine(inputs[startIndex], indent));
  665. if (endIndex != startIndex) {
  666. let actualEndIndex = beautify3(inputs, result, settings, startIndex + 1, indent + 1, endIndex);
  667. let incremental = actualEndIndex - endIndex;
  668. endIndex += incremental;
  669. parentEndIndex += incremental;
  670. }
  671. return [endIndex, parentEndIndex];
  672. }
  673. export function beautifySemicolonBlock(inputs: Array<string>, result: (FormattedLine | FormattedLine[])[], settings: BeautifierSettings, startIndex: number, parentEndIndex: number, indent: number): [number, number] {
  674. let endIndex = startIndex;
  675. [endIndex, parentEndIndex] = getSemicolonBlockEndIndex(inputs, settings, startIndex, parentEndIndex);
  676. result.push(new FormattedLine(inputs[startIndex], indent));
  677. if (endIndex != startIndex) {
  678. beautify3(inputs, result, settings, startIndex + 1, indent + 1, endIndex);
  679. alignSignalAssignmentBlock(settings, inputs, startIndex, endIndex, result);
  680. }
  681. return [endIndex, parentEndIndex];
  682. }
  683. function alignSignalAssignmentBlock(settings: BeautifierSettings, inputs: string[], startIndex: number, endIndex: number, result: (FormattedLine | FormattedLine[])[]) {
  684. if (settings.Indentation.replace(/ +/g, "").length == 0) {
  685. let reg: RegExp = new RegExp("^([\\w\\\\]+[\\s]*<=\\s*)");
  686. let match = reg.exec(inputs[startIndex]);
  687. if (match != null) {
  688. let length = match[0].length;
  689. let prefixLength = length - settings.Indentation.length;
  690. let prefix = new Array(prefixLength + 1).join(" ");
  691. for (let i = startIndex + 1; i <= endIndex; i++) {
  692. let fl = (result[i] as FormattedLine);
  693. fl.Line = prefix + fl.Line;
  694. }
  695. }
  696. }
  697. }
  698. export function beautify3(inputs: Array<string>, result: (FormattedLine | FormattedLine[])[], settings: BeautifierSettings, startIndex: number, indent: number, endIndex?: number): number {
  699. let i: number;
  700. let regexOneLineBlockKeyWords: RegExp = new RegExp(/(PROCEDURE)[^\w](?!.+[^\w]IS([^\w]|$))/);//match PROCEDURE..; but not PROCEDURE .. IS;
  701. let regexFunctionMultiLineBlockKeyWords: RegExp = new RegExp(/(FUNCTION|IMPURE FUNCTION)[^\w](?=.+[^\w]IS([^\w]|$))/);//match FUNCTION .. IS; but not FUNCTION
  702. let blockMidKeyWords: Array<string> = ["BEGIN"];
  703. let blockStartsKeyWords: Array<string> = [
  704. "IF",
  705. "CASE",
  706. "ARCHITECTURE",
  707. "PROCEDURE",
  708. "PACKAGE",
  709. "(([\\w\\s]*:)?(\\s)*PROCESS)",// with label
  710. "(([\\w\\s]*:)?(\\s)*POSTPONED PROCESS)",// with label
  711. "(.*\\s*PROTECTED)",
  712. "(COMPONENT)",
  713. "(ENTITY(?!.+;))",
  714. "FOR",
  715. "WHILE",
  716. "LOOP",
  717. "(.*\\s*GENERATE)",
  718. "(CONTEXT[\\w\\s\\\\]+IS)",
  719. "(CONFIGURATION(?!.+;))",
  720. "BLOCK",
  721. "UNITS",
  722. "\\w+\\s+\\w+\\s+IS\\s+RECORD"];
  723. let blockEndsKeyWords: Array<string> = ["END", ".*\\)\\s*RETURN\\s+[\\w]+;"];
  724. let indentedEndsKeyWords: Array<string> = [ILIndentedReturnPrefix + "RETURN\\s+\\w+;"];
  725. let blockEndsWithSemicolon: Array<string> = [
  726. "(WITH\\s+[\\w\\s\\\\]+SELECT)",
  727. "([\\w\\\\]+[\\s]*<=)",
  728. "([\\w\\\\]+[\\s]*:=)",
  729. "FOR\\s+[\\w\\s,]+:\\s*\\w+\\s+USE",
  730. "REPORT"
  731. ];
  732. let newLineAfterKeyWordsStr: string = blockStartsKeyWords.join("|");
  733. let regexBlockMidKeyWords: RegExp = blockMidKeyWords.convertToRegexBlockWords();
  734. let regexBlockStartsKeywords: RegExp = new RegExp("([\\w]+\\s*:\\s*)?(" + newLineAfterKeyWordsStr + ")([^\\w]|$)")
  735. let regexBlockEndsKeyWords: RegExp = blockEndsKeyWords.convertToRegexBlockWords();
  736. let regexBlockIndentedEndsKeyWords: RegExp = indentedEndsKeyWords.convertToRegexBlockWords();
  737. let regexblockEndsWithSemicolon: RegExp = blockEndsWithSemicolon.convertToRegexBlockWords();
  738. let regexMidKeyWhen: RegExp = "WHEN".convertToRegexBlockWords();
  739. let regexMidKeyElse: RegExp = "ELSE|ELSIF".convertToRegexBlockWords();
  740. if (endIndex == null) {
  741. endIndex = inputs.length - 1;
  742. }
  743. for (i = startIndex; i <= endIndex; i++) {
  744. if (indent < 0) {
  745. indent = 0;
  746. }
  747. let input: string = inputs[i].trim();
  748. if (input.regexStartsWith(regexBlockIndentedEndsKeyWords)) {
  749. result.push(new FormattedLine(input, indent));
  750. return i;
  751. }
  752. if (input.regexStartsWith(/COMPONENT\s/)) {
  753. let modeCache = Mode;
  754. Mode = FormatMode.EndsWithSemicolon;
  755. [i, endIndex] = beautifyComponentBlock(inputs, result, settings, i, endIndex, indent);
  756. Mode = modeCache;
  757. continue;
  758. }
  759. if (input.regexStartsWith(/PACKAGE[\s\w]+IS\s+NEW/)) {
  760. let modeCache = Mode;
  761. Mode = FormatMode.EndsWithSemicolon;
  762. [i, endIndex] = beautifyPackageIsNewBlock(inputs, result, settings, i, endIndex, indent);
  763. Mode = modeCache;
  764. continue;
  765. }
  766. if (input.regexStartsWith(/\w+\s*:\s*ENTITY/)) {
  767. let modeCache = Mode;
  768. Mode = FormatMode.EndsWithSemicolon;
  769. [i, endIndex] = beautifySemicolonBlock(inputs, result, settings, i, endIndex, indent);
  770. Mode = modeCache;
  771. continue;
  772. }
  773. if (Mode != FormatMode.EndsWithSemicolon && input.regexStartsWith(regexblockEndsWithSemicolon)) {
  774. let modeCache = Mode;
  775. Mode = FormatMode.EndsWithSemicolon;
  776. [i, endIndex] = beautifySemicolonBlock(inputs, result, settings, i, endIndex, indent);
  777. Mode = modeCache;
  778. continue;
  779. }
  780. if (input.regexStartsWith(/(.+:\s*)?(CASE)([\s]|$)/)) {
  781. let modeCache = Mode;
  782. Mode = FormatMode.CaseWhen;
  783. i = beautifyCaseBlock(inputs, result, settings, i, indent);
  784. Mode = modeCache;
  785. continue;
  786. }
  787. if (input.regexStartsWith(/.*?\:\=\s*\($/)) {
  788. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, ":=");
  789. continue;
  790. }
  791. if (input.regexStartsWith(/[\w\s:]*\bPORT\b([\s]|$)/)) {
  792. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "PORT");
  793. continue;
  794. }
  795. if (input.regexStartsWith(/TYPE\s+\w+\s+IS\s+\(/)) {
  796. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "IS");
  797. continue;
  798. }
  799. if (input.regexStartsWith(/[\w\s:]*GENERIC([\s]|$)/)) {
  800. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "GENERIC");
  801. continue;
  802. }
  803. if (input.regexStartsWith(/[\w\s:]*PROCEDURE[\s\w]+\($/)) {
  804. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "PROCEDURE");
  805. if (inputs[i].regexStartsWith(/.*\)[\s]*IS/)) {
  806. i = beautify3(inputs, result, settings, i + 1, indent + 1);
  807. }
  808. continue;
  809. }
  810. if (input.regexStartsWith(/FUNCTION[^\w]/)
  811. && input.regexIndexOf(/[^\w]RETURN[^\w]/) < 0) {
  812. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "FUNCTION");
  813. if (!inputs[i].regexStartsWith(regexBlockEndsKeyWords)) {
  814. i = beautify3(inputs, result, settings, i + 1, indent + 1);
  815. } else {
  816. (<FormattedLine>result[i]).Indent++;
  817. }
  818. continue;
  819. }
  820. if (input.regexStartsWith(/IMPURE FUNCTION[^\w]/)
  821. && input.regexIndexOf(/[^\w]RETURN[^\w]/) < 0) {
  822. [i, endIndex] = beautifyPortGenericBlock(inputs, result, settings, i, endIndex, indent, "IMPURE FUNCTION");
  823. if (!inputs[i].regexStartsWith(regexBlockEndsKeyWords)) {
  824. if (inputs[i].regexStartsWith(regexBlockIndentedEndsKeyWords)) {
  825. (<FormattedLine>result[i]).Indent++;
  826. } else {
  827. i = beautify3(inputs, result, settings, i + 1, indent + 1);
  828. }
  829. } else {
  830. (<FormattedLine>result[i]).Indent++;
  831. }
  832. continue;
  833. }
  834. result.push(new FormattedLine(input, indent));
  835. if (startIndex != 0
  836. && (input.regexStartsWith(regexBlockMidKeyWords)
  837. || (Mode != FormatMode.EndsWithSemicolon && input.regexStartsWith(regexMidKeyElse))
  838. || (Mode == FormatMode.CaseWhen && input.regexStartsWith(regexMidKeyWhen)))) {
  839. (<FormattedLine>result[i]).Indent--;
  840. }
  841. else if (startIndex != 0
  842. && (input.regexStartsWith(regexBlockEndsKeyWords))) {
  843. (<FormattedLine>result[i]).Indent--;
  844. return i;
  845. }
  846. if (input.regexStartsWith(regexOneLineBlockKeyWords)) {
  847. continue;
  848. }
  849. if (input.regexStartsWith(regexFunctionMultiLineBlockKeyWords)
  850. || input.regexStartsWith(regexBlockStartsKeywords)) {
  851. i = beautify3(inputs, result, settings, i + 1, indent + 1);
  852. }
  853. }
  854. i--;
  855. return i;
  856. }
  857. function ReserveSemicolonInKeywords(arr: Array<string>) {
  858. for (let i = 0; i < arr.length; i++) {
  859. if (arr[i].match(/FUNCTION|PROCEDURE/) != null) {
  860. arr[i] = arr[i].replace(/;/g, ILSemicolon);
  861. }
  862. }
  863. }
  864. export function ApplyNoNewLineAfter(arr: Array<string>, noNewLineAfter: Array<string>) {
  865. if (noNewLineAfter == null) {
  866. return;
  867. }
  868. for (let i = 0; i < arr.length; i++) {
  869. noNewLineAfter.forEach(n => {
  870. let regex = new RegExp("(" + n.toUpperCase + ")[ a-z0-9]+[a-z0-9]+");
  871. if (arr[i].regexIndexOf(regex) >= 0) {
  872. arr[i] += "@@singleline";
  873. }
  874. });
  875. }
  876. }
  877. export function RemoveAsserts(arr: Array<string>) {
  878. let need_semi: boolean = false;
  879. let inAssert: boolean = false;
  880. let n: number = 0;
  881. for (let i = 0; i < arr.length; i++) {
  882. let has_semi: boolean = arr[i].indexOf(";") >= 0;
  883. if (need_semi) {
  884. arr[i] = '';
  885. }
  886. n = arr[i].indexOf("ASSERT ");
  887. if (n >= 0) {
  888. inAssert = true;
  889. arr[i] = '';
  890. }
  891. if (!has_semi) {
  892. if (inAssert) {
  893. need_semi = true;
  894. }
  895. }
  896. else {
  897. need_semi = false;
  898. }
  899. }
  900. }
  901. function escapeText(arr: Array<string>, regex: string, escapedChar: string): Array<string> {
  902. let quotes: Array<string> = [];
  903. let regexEpr = new RegExp(regex, "g");
  904. for (let i = 0; i < arr.length; i++) {
  905. let matches = arr[i].match(regexEpr);
  906. if (matches != null) {
  907. for (var j = 0; j < matches.length; j++) {
  908. var match = matches[j];
  909. arr[i] = arr[i].replace(match, escapedChar.repeat(match.length));
  910. quotes.push(match);
  911. }
  912. }
  913. }
  914. return quotes;
  915. }
  916. function RemoveExtraNewLines(input: any) {
  917. input = input.replace(/(?:\r\n|\r|\n)/g, '\r\n');
  918. input = input.replace(/ \r\n/g, '\r\n');
  919. input = input.replace(/\r\n\r\n\r\n/g, '\r\n');
  920. return input;
  921. }