tcunitsearch.pas 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. {
  2. This file is part of the Free Component Library (FCL)
  3. Copyright (c) 2018 by Michael Van Canneyt
  4. Unit tests for Pascal-to-Javascript converter class.
  5. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. **********************************************************************
  11. Examples:
  12. ./testpas2js --suite=TestCLI_UnitSearch.
  13. ./testpas2js --suite=TestUS_Program
  14. ./testpas2js --suite=TestUS_UsesEmptyFileFail
  15. }
  16. unit TCUnitSearch;
  17. {$mode objfpc}{$H+}
  18. interface
  19. uses
  20. Classes, SysUtils, contnrs,
  21. fpcunit, testregistry,
  22. PScanner, PasTree,
  23. {$IFDEF CheckPasTreeRefCount}PasResolveEval,{$ENDIF}
  24. Pas2jsFileUtils, Pas2jsCompiler, Pas2JSPCUCompiler, Pas2jsFileCache, Pas2jsLogger,
  25. tcmodules;
  26. type
  27. { TTestCompiler }
  28. TTestCompiler = class(TPas2jsPCUCompiler)
  29. private
  30. FExitCode: longint;
  31. protected
  32. function GetExitCode: Longint; override;
  33. procedure SetExitCode(Value: Longint); override;
  34. end;
  35. { TCLIFile }
  36. TCLIFile = class
  37. public
  38. Filename: string;
  39. Source: string;
  40. Age: TPas2jsFileAgeTime;
  41. Attr: TPas2jsFileAttr;
  42. constructor Create(const aFilename, Src: string; aAge: TPas2jsFileAgeTime;
  43. aAttr: TPas2jsFileAttr);
  44. end;
  45. { TCLILogMsg }
  46. TCLILogMsg = class
  47. public
  48. Msg: string;
  49. MsgTxt: string;
  50. MsgType: TMessageType;
  51. MsgNumber: integer;
  52. MsgFile: string;
  53. MsgLine: integer;
  54. MsgCol: integer;
  55. end;
  56. { TCustomTestCLI }
  57. TCustomTestCLI = class(TTestCase)
  58. private
  59. FCurDate: TDateTime;
  60. FErrorCol: integer;
  61. FErrorFile: string;
  62. FErrorLine: integer;
  63. FErrorMsg: string;
  64. FErrorNumber: integer;
  65. FWorkDir: string;
  66. FCompilerExe: string;
  67. FCompiler: TTestCompiler;
  68. FDefaultFileAge: longint;
  69. FFiles: TObjectList; // list of TCLIFile
  70. FLogMsgs: TObjectList; // list ot TCLILogMsg
  71. FParams: TStringList;
  72. {$IFDEF EnablePasTreeGlobalRefCount}
  73. FElementRefCountAtSetup: int64;
  74. {$ENDIF}
  75. function GetExitCode: integer;
  76. function GetFiles(Index: integer): TCLIFile;
  77. function GetLogMsgs(Index: integer): TCLILogMsg;
  78. procedure SetExitCode(const AValue: integer);
  79. procedure SetWorkDir(const AValue: string);
  80. protected
  81. procedure SetUp; override;
  82. procedure TearDown; override;
  83. procedure DoLog(Sender: TObject; const Msg: String);
  84. Function OnReadDirectory(Dir: TPas2jsCachedDirectory): boolean; virtual;
  85. Function OnReadFile(aFilename: string; var aSource: string): boolean; virtual;
  86. procedure OnWriteFile(aFilename: string; Source: string); virtual;
  87. procedure WriteSources;
  88. procedure CheckDiff(Msg, Expected, Actual: string); virtual;
  89. public
  90. constructor Create; override;
  91. destructor Destroy; override;
  92. procedure Compile(const Args: array of string; ExpectedExitCode: longint = 0);
  93. property Compiler: TTestCompiler read FCompiler;
  94. property CompilerExe: string read FCompilerExe write FCompilerExe;
  95. property Params: TStringList read FParams;
  96. property Files[Index: integer]: TCLIFile read GetFiles; // files an directories
  97. function FileCount: integer;
  98. function FindFile(Filename: string): TCLIFile; // files and directories
  99. function ExpandFilename(const Filename: string): string;
  100. function AddFile(Filename, Source: string): TCLIFile;
  101. function AddFile(Filename: string; const SourceLines: array of string): TCLIFile;
  102. function AddUnit(Filename: string; const Intf, Impl: array of string): TCLIFile;
  103. function AddDir(Filename: string): TCLIFile;
  104. procedure AssertFileExists(Filename: string);
  105. property WorkDir: string read FWorkDir write SetWorkDir;
  106. property DefaultFileAge: longint read FDefaultFileAge write FDefaultFileAge;
  107. property ExitCode: integer read GetExitCode write SetExitCode;
  108. property LogMsgs[Index: integer]: TCLILogMsg read GetLogMsgs;
  109. function GetLogCount: integer;
  110. property ErrorMsg: string read FErrorMsg write FErrorMsg;
  111. property ErrorFile: string read FErrorFile write FErrorFile;
  112. property ErrorLine: integer read FErrorLine write FErrorLine;
  113. property ErrorCol: integer read FErrorCol write FErrorCol;
  114. property ErrorNumber: integer read FErrorNumber write FErrorNumber;
  115. property CurDate: TDateTime read FCurDate write FCurDate;
  116. end;
  117. { TTestCLI_UnitSearch }
  118. TTestCLI_UnitSearch = class(TCustomTestCLI)
  119. protected
  120. procedure CheckLinklibProgramSrc(Msg,Header: string);
  121. procedure CheckFullSource(Msg, Filename, ExpectedSrc: string);
  122. published
  123. procedure TestUS_CreateRelativePath;
  124. procedure TestUS_Program;
  125. procedure TestUS_UsesEmptyFileFail;
  126. procedure TestUS_Program_o;
  127. procedure TestUS_Program_FU;
  128. procedure TestUS_Program_FU_o;
  129. procedure TestUS_Program_FE_o;
  130. procedure TestUS_PlatformModule_Program;
  131. // include files
  132. procedure TestUS_IncludeSameDir;
  133. Procedure TestUS_Include_NestedDelphi;
  134. Procedure TestUS_Include_NestedObjFPC;
  135. // uses 'in' modifier
  136. procedure TestUS_UsesInFile;
  137. procedure TestUS_UsesInFile_Duplicate;
  138. procedure TestUS_UsesInFile_IndirectDuplicate;
  139. procedure TestUS_UsesInFile_WorkNotEqProgDir;
  140. procedure TestUS_UsesInFileTwice;
  141. procedure TestUS_UseUnitTwiceFail;
  142. procedure TestUS_UseUnitTwiceViaNameSpace;
  143. // namespace
  144. Procedure TestUS_DefaultNameSpaceLast;
  145. Procedure TestUS_DefaultNameSpaceAfterNameSpace;
  146. Procedure TestUS_NoNameSpaceBeforeDefaultNameSpace;
  147. Procedure TestUS_NoNameSpaceAndDefaultNameSpace;
  148. // linklib
  149. procedure TestUS_ProgramLinklib;
  150. procedure TestUS_UnitLinklib;
  151. end;
  152. function LinesToStr(const Lines: array of string): string;
  153. implementation
  154. function LinesToStr(const Lines: array of string): string;
  155. var
  156. i: Integer;
  157. begin
  158. Result:='';
  159. for i:=low(Lines) to high(Lines) do
  160. Result:=Result+Lines[i]+LineEnding;
  161. end;
  162. { TCLIFile }
  163. constructor TCLIFile.Create(const aFilename, Src: string;
  164. aAge: TPas2jsFileAgeTime; aAttr: TPas2jsFileAttr);
  165. begin
  166. Filename:=aFilename;
  167. Source:=Src;
  168. Age:=aAge;
  169. Attr:=aAttr;
  170. end;
  171. { TTestCompiler }
  172. function TTestCompiler.GetExitCode: Longint;
  173. begin
  174. Result:=FExitCode;
  175. end;
  176. procedure TTestCompiler.SetExitCode(Value: Longint);
  177. begin
  178. FExitCode:=Value;
  179. end;
  180. { TCustomTestCLI }
  181. function TCustomTestCLI.GetFiles(Index: integer): TCLIFile;
  182. begin
  183. Result:=TCLIFile(FFiles[Index]);
  184. end;
  185. function TCustomTestCLI.GetExitCode: integer;
  186. begin
  187. Result:=Compiler.ExitCode;
  188. end;
  189. function TCustomTestCLI.GetLogMsgs(Index: integer): TCLILogMsg;
  190. begin
  191. Result:=TCLILogMsg(FLogMsgs[Index]);
  192. end;
  193. procedure TCustomTestCLI.SetExitCode(const AValue: integer);
  194. begin
  195. Compiler.ExitCode:=AValue;
  196. end;
  197. procedure TCustomTestCLI.SetWorkDir(const AValue: string);
  198. var
  199. NewValue: String;
  200. begin
  201. NewValue:=IncludeTrailingPathDelimiter(ExpandFileNamePJ(ResolveDots(AValue)));
  202. if FWorkDir=NewValue then Exit;
  203. FWorkDir:=NewValue;
  204. end;
  205. procedure TCustomTestCLI.SetUp;
  206. begin
  207. {$IFDEF EnablePasTreeGlobalRefCount}
  208. FElementRefCountAtSetup:=TPasElement.GlobalRefCount;
  209. {$ENDIF}
  210. inherited SetUp;
  211. FDefaultFileAge:=DateTimeToFileDate(Now);
  212. WorkDir:=ExtractFilePath(ParamStr(0));
  213. {$IFDEF Windows}
  214. CompilerExe:='P:\bin\pas2js.exe';
  215. {$ELSE}
  216. CompilerExe:='/usr/bin/pas2js';
  217. {$ENDIF}
  218. FCompiler:=TTestCompiler.Create;
  219. //FCompiler.ConfigSupport:=TPas2JSFileConfigSupport.Create(FCompiler);
  220. Compiler.Log.OnLog:=@DoLog;
  221. Compiler.FileCache.OnReadDirectory:=@OnReadDirectory;
  222. Compiler.FileCache.OnReadFile:=@OnReadFile;
  223. Compiler.FileCache.OnWriteFile:=@OnWriteFile;
  224. end;
  225. procedure TCustomTestCLI.TearDown;
  226. {$IFDEF CheckPasTreeRefCount}
  227. var
  228. El: TPasElement;
  229. i: integer;
  230. {$ENDIF}
  231. begin
  232. FreeAndNil(FCompiler);
  233. FParams.Clear;
  234. FFiles.Clear;
  235. FLogMsgs.Clear;
  236. FErrorMsg:='';
  237. FErrorFile:='';
  238. FErrorLine:=0;
  239. FErrorCol:=0;
  240. FErrorNumber:=0;
  241. inherited TearDown;
  242. {$IFDEF EnablePasTreeGlobalRefCount}
  243. if FElementRefCountAtSetup<>TPasElement.GlobalRefCount then
  244. begin
  245. writeln('TCustomTestCLI.TearDown GlobalRefCount Was='+IntToStr(FElementRefCountAtSetup)+' Now='+IntToStr(TPasElement.GlobalRefCount));
  246. {$IFDEF CheckPasTreeRefCount}
  247. El:=TPasElement.FirstRefEl;
  248. while El<>nil do
  249. begin
  250. writeln(' ',GetObjName(El),' RefIds.Count=',El.RefIds.Count,':');
  251. for i:=0 to El.RefIds.Count-1 do
  252. writeln(' ',El.RefIds[i]);
  253. El:=El.NextRefEl;
  254. end;
  255. {$ENDIF}
  256. Halt;
  257. Fail('TCustomTestCLI.TearDown Was='+IntToStr(FElementRefCountAtSetup)+' Now='+IntToStr(TPasElement.GlobalRefCount));
  258. end;
  259. {$ENDIF}
  260. end;
  261. procedure TCustomTestCLI.DoLog(Sender: TObject; const Msg: String);
  262. var
  263. LogMsg: TCLILogMsg;
  264. begin
  265. {$IF defined(VerbosePasResolver) or defined(VerbosePCUFiler)}
  266. writeln('TCustomTestCLI.DoLog ',Msg,' File=',Compiler.Log.LastMsgFile,' Line=',Compiler.Log.LastMsgLine);
  267. {$ENDIF}
  268. LogMsg:=TCLILogMsg.Create;
  269. LogMsg.Msg:=Msg;
  270. LogMsg.MsgTxt:=Compiler.Log.LastMsgTxt;
  271. LogMsg.MsgType:=Compiler.Log.LastMsgType;
  272. LogMsg.MsgFile:=Compiler.Log.LastMsgFile;
  273. LogMsg.MsgLine:=Compiler.Log.LastMsgLine;
  274. LogMsg.MsgCol:=Compiler.Log.LastMsgCol;
  275. LogMsg.MsgNumber:=Compiler.Log.LastMsgNumber;
  276. FLogMsgs.Add(LogMsg);
  277. if (LogMsg.MsgType<=mtError) then
  278. begin
  279. if (ErrorFile='')
  280. or ((ErrorLine<1) and (LogMsg.MsgLine>0)) then
  281. begin
  282. ErrorMsg:=LogMsg.MsgTxt;
  283. ErrorFile:=LogMsg.MsgFile;
  284. ErrorLine:=LogMsg.MsgLine;
  285. ErrorCol:=LogMsg.MsgCol;
  286. end;
  287. end;
  288. end;
  289. function TCustomTestCLI.OnReadDirectory(Dir: TPas2jsCachedDirectory): boolean;
  290. var
  291. i: Integer;
  292. aFile: TCLIFile;
  293. Path: String;
  294. begin
  295. Path:=Dir.Path;
  296. //writeln('TCustomTestCLI.ReadDirectory START ',Path,' ',Dir.Count);
  297. Dir.Add('.',DefaultFileAge,faDirectory,4096);
  298. Dir.Add('..',DefaultFileAge,faDirectory,4096);
  299. for i:=0 to FileCount-1 do
  300. begin
  301. aFile:=Files[i];
  302. if CompareFilenames(ExtractFilePath(aFile.Filename),Path)<>0 then continue;
  303. //writeln('TCustomTestCLI.ReadDirectory ',aFile.Filename);
  304. Dir.Add(ExtractFileName(aFile.Filename),aFile.Age,aFile.Attr,length(aFile.Source));
  305. end;
  306. //writeln('TCustomTestCLI.ReadDirectory END ',Path,' ',Dir.Count);
  307. Result:=true;
  308. end;
  309. function TCustomTestCLI.OnReadFile(aFilename: string; var aSource: string
  310. ): boolean;
  311. var
  312. aFile: TCLIFile;
  313. begin
  314. aFile:=FindFile(aFilename);
  315. //writeln('TCustomTestCLI.ReadFile ',aFilename,' Found=',aFile<>nil);
  316. if aFile=nil then exit(false);
  317. if (faDirectory and aFile.Attr)>0 then
  318. begin
  319. {$IF defined(VerbosePasResolver) or defined(VerbosePCUFiler)}
  320. writeln('[20180224000557] TCustomTestCLI.OnReadFile ',aFilename);
  321. {$ENDIF}
  322. EPas2jsFileCache.Create('TCustomTestCLI.OnReadFile: reading directory '+aFilename);
  323. end;
  324. aSource:=aFile.Source;
  325. //writeln('TCustomTestCLI.OnReadFile ',aFile.Filename,' "',LeftStr(aFile.Source,50),'"');
  326. Result:=true;
  327. end;
  328. procedure TCustomTestCLI.OnWriteFile(aFilename: string; Source: string);
  329. var
  330. aFile: TCLIFile;
  331. {$IF defined(VerboseUnitQueue) or defined(VerbosePCUFiler)}
  332. //i: Integer;
  333. {$ENDIF}
  334. begin
  335. aFile:=FindFile(aFilename);
  336. {$IF defined(VerboseUnitQueue) or defined(VerbosePCUFiler)}
  337. writeln('TCustomTestCLI.WriteFile ',aFilename,' Found=',aFile<>nil,' SrcLen=',length(Source));
  338. {$ENDIF}
  339. if aFile<>nil then
  340. begin
  341. if (faDirectory and aFile.Attr)>0 then
  342. begin
  343. {$IF defined(VerboseUnitQueue) or defined(VerbosePCUFiler)}
  344. writeln('[20180223175616] TCustomTestCLI.OnWriteFile ',aFilename);
  345. {$ENDIF}
  346. raise EPas2jsFileCache.Create('unable to write file to directory "'+aFilename+'"');
  347. end;
  348. end else
  349. begin
  350. {$IF defined(VerboseUnitQueue) or defined(VerbosePCUFiler)}
  351. //writeln('TCustomTestCLI.OnWriteFile FFiles: ',FFiles.Count);
  352. //for i:=0 to FFiles.Count-1 do
  353. //begin
  354. // aFile:=TCLIFile(FFiles[i]);
  355. // writeln(' ',i,': Filename=',aFile.Filename,' ',CompareFilenames(aFile.Filename,aFilename),' Dir=',(aFile.Attr and faDirectory)>0,' Len=',length(aFile.Source));
  356. //end;
  357. {$ENDIF}
  358. aFile:=TCLIFile.Create(aFilename,'',0,0);
  359. FFiles.Add(aFile);
  360. end;
  361. aFile.Source:=Source;
  362. aFile.Attr:=faNormal;
  363. aFile.Age:=DateTimeToFileDate(CurDate);
  364. writeln('TCustomTestCLI.OnWriteFile ',aFile.Filename,' Found=',FindFile(aFilename)<>nil,' "',LeftStr(aFile.Source,50),'" ');
  365. //writeln('TCustomTestCLI.OnWriteFile ',aFile.Source);
  366. end;
  367. procedure TCustomTestCLI.WriteSources;
  368. var
  369. i, j, aRow, aCol: Integer;
  370. aFile: TCLIFile;
  371. SrcLines: TStringList;
  372. Line, aFilename: String;
  373. IsSrc: Boolean;
  374. begin
  375. writeln('TCustomTestCLI.WriteSources START');
  376. aFilename:=ErrorFile;
  377. aRow:=ErrorLine;
  378. aCol:=ErrorCol;
  379. SrcLines:=TStringList.Create;
  380. try
  381. for i:=0 to FileCount-1 do
  382. begin
  383. aFile:=Files[i];
  384. if (faDirectory and aFile.Attr)>0 then continue;
  385. writeln('Testcode:-File="',aFile.Filename,'"----------------------------------:');
  386. SrcLines.Text:=aFile.Source;
  387. IsSrc:=ExtractFilename(aFile.Filename)=ExtractFileName(aFilename);
  388. for j:=1 to SrcLines.Count do
  389. begin
  390. Line:=SrcLines[j-1];
  391. if IsSrc and (j=aRow) then
  392. begin
  393. write('*');
  394. Line:=LeftStr(Line,aCol-1)+'|'+copy(Line,aCol,length(Line));
  395. end;
  396. writeln(Format('%:4d: ',[j]),Line);
  397. end;
  398. end;
  399. finally
  400. SrcLines.Free;
  401. end;
  402. end;
  403. procedure TCustomTestCLI.CheckDiff(Msg, Expected, Actual: string);
  404. // search diff, ignore changes in spaces
  405. var
  406. s: string;
  407. begin
  408. if CheckSrcDiff(Expected,Actual,s) then exit;
  409. Fail(Msg+': '+s);
  410. end;
  411. constructor TCustomTestCLI.Create;
  412. begin
  413. inherited Create;
  414. FFiles:=TObjectList.Create(true);
  415. FLogMsgs:=TObjectList.Create(true);
  416. FParams:=TStringList.Create;
  417. CurDate:=Now;
  418. end;
  419. destructor TCustomTestCLI.Destroy;
  420. begin
  421. FreeAndNil(FFiles);
  422. FreeAndNil(FLogMsgs);
  423. FreeAndNil(FParams);
  424. inherited Destroy;
  425. end;
  426. procedure TCustomTestCLI.Compile(const Args: array of string;
  427. ExpectedExitCode: longint);
  428. var
  429. i: Integer;
  430. begin
  431. AssertEquals('Initial System.ExitCode',0,system.ExitCode);
  432. for i:=low(Args) to High(Args) do
  433. Params.Add(Args[i]);
  434. try
  435. try
  436. //writeln('TCustomTestCLI.Compile WorkDir=',WorkDir);
  437. Compiler.Run(CompilerExe,WorkDir,Params,true);
  438. except
  439. on E: ECompilerTerminate do
  440. begin
  441. {$IF defined(VerbosePasResolver) or defined(VerbosePCUFiler)}
  442. writeln('TCustomTestCLI.Compile ',E.ClassName,':',E.Message);
  443. {$ENDIF}
  444. end;
  445. on E: Exception do
  446. begin
  447. {$IF defined(VerbosePasResolver) or defined(VerbosePCUFiler)}
  448. writeln('TCustomTestCLI.Compile ',E.ClassName,':',E.Message);
  449. {$ENDIF}
  450. Fail('TCustomTestCLI.Compile '+E.ClassName+':'+E.Message);
  451. end;
  452. end;
  453. finally
  454. Compiler.Log.CloseOutputFile;
  455. end;
  456. if ExpectedExitCode<>ExitCode then
  457. begin
  458. WriteSources;
  459. AssertEquals('ExitCode',ExpectedExitCode,ExitCode);
  460. end;
  461. end;
  462. function TCustomTestCLI.FileCount: integer;
  463. begin
  464. Result:=FFiles.Count;
  465. end;
  466. function TCustomTestCLI.FindFile(Filename: string): TCLIFile;
  467. var
  468. i: Integer;
  469. begin
  470. Filename:=ExpandFilename(Filename);
  471. for i:=0 to FileCount-1 do
  472. if CompareFilenames(Files[i].Filename,Filename)=0 then
  473. exit(Files[i]);
  474. Result:=nil;
  475. end;
  476. function TCustomTestCLI.ExpandFilename(const Filename: string): string;
  477. begin
  478. Result:=SetDirSeparators(Filename);
  479. if not FilenameIsAbsolute(Result) then
  480. Result:=WorkDir+Result;
  481. Result:=ResolveDots(Result);
  482. end;
  483. function TCustomTestCLI.AddFile(Filename, Source: string): TCLIFile;
  484. begin
  485. Filename:=ExpandFilename(Filename);
  486. {$IFDEF VerbosePCUFiler}
  487. writeln('TCustomTestCLI.AddFile ',Filename);
  488. {$ENDIF}
  489. Result:=FindFile(Filename);
  490. if Result<>nil then
  491. raise Exception.Create('[20180224001050] TCustomTestCLI.AddFile already exists: '+Filename);
  492. Result:=TCLIFile.Create(Filename,Source,DefaultFileAge,faNormal);
  493. FFiles.Add(Result);
  494. AddDir(ExtractFilePath(Filename));
  495. end;
  496. function TCustomTestCLI.AddFile(Filename: string;
  497. const SourceLines: array of string): TCLIFile;
  498. begin
  499. Result:=AddFile(Filename,LinesToStr(SourceLines));
  500. end;
  501. function TCustomTestCLI.AddUnit(Filename: string; const Intf,
  502. Impl: array of string): TCLIFile;
  503. var
  504. Name: String;
  505. begin
  506. Name:=ExtractFilenameOnly(Filename);
  507. Result:=AddFile(Filename,
  508. 'unit '+Name+';'+LineEnding
  509. +'interface'+LineEnding
  510. +LinesToStr(Intf)
  511. +'implementation'+LineEnding
  512. +LinesToStr(Impl)
  513. +'end.'+LineEnding);
  514. end;
  515. function TCustomTestCLI.AddDir(Filename: string): TCLIFile;
  516. var
  517. p: Integer;
  518. Dir: String;
  519. aFile: TCLIFile;
  520. begin
  521. Result:=nil;
  522. Filename:=IncludeTrailingPathDelimiter(ExpandFilename(Filename));
  523. p:=length(Filename);
  524. while p>1 do
  525. begin
  526. if Filename[p]=PathDelim then
  527. begin
  528. Dir:=LeftStr(Filename,p-1);
  529. aFile:=FindFile(Dir);
  530. if Result=nil then
  531. Result:=aFile;
  532. if aFile=nil then
  533. begin
  534. {$IFDEF VerbosePCUFiler}
  535. writeln('TCustomTestCLI.AddDir add Dir=',Dir);
  536. {$ENDIF}
  537. FFiles.Add(TCLIFile.Create(Dir,'',DefaultFileAge,faDirectory));
  538. end
  539. else if (aFile.Attr and faDirectory)=0 then
  540. begin
  541. {$IFDEF VerbosePCUFiler}
  542. writeln('[20180224001036] TCustomTestCLI.AddDir file exists: Dir=',Dir);
  543. {$ENDIF}
  544. raise EPas2jsFileCache.Create('[20180224001036] TCustomTestCLI.AddDir Dir='+Dir);
  545. end;
  546. dec(p);
  547. end else
  548. dec(p);
  549. end;
  550. end;
  551. procedure TCustomTestCLI.AssertFileExists(Filename: string);
  552. var
  553. aFile: TCLIFile;
  554. begin
  555. aFile:=FindFile(Filename);
  556. AssertNotNull('File not found: '+Filename,aFile);
  557. end;
  558. function TCustomTestCLI.GetLogCount: integer;
  559. begin
  560. Result:=FLogMsgs.Count;
  561. end;
  562. { TTestCLI_UnitSearch }
  563. procedure TTestCLI_UnitSearch.CheckLinklibProgramSrc(Msg, Header: string);
  564. var
  565. aFile: TCLIFile;
  566. begin
  567. aFile:=FindFile('test1.js');
  568. if aFile=nil then
  569. Fail(Msg+' file not found test1.js');
  570. CheckDiff(Msg,
  571. LinesToStr([
  572. #$EF#$BB#$BF+Header,
  573. 'rtl.module("program",["system"],function () {',
  574. ' "use strict";',
  575. ' var $mod = this;',
  576. ' $mod.$main = function () {',
  577. ' };',
  578. '});',
  579. 'rtl.run();',
  580. '',
  581. '']),
  582. aFile.Source);
  583. end;
  584. procedure TTestCLI_UnitSearch.CheckFullSource(Msg, Filename, ExpectedSrc: string
  585. );
  586. var
  587. aFile: TCLIFile;
  588. begin
  589. aFile:=FindFile(Filename);
  590. if aFile=nil then
  591. Fail(Msg+' file not found "'+Filename+'"');
  592. CheckDiff(Msg,ExpectedSrc,aFile.Source);
  593. end;
  594. procedure TTestCLI_UnitSearch.TestUS_CreateRelativePath;
  595. procedure DoTest(Filename, BaseDirectory, Expected: string;
  596. UsePointDirectory: boolean = false);
  597. var
  598. Actual: String;
  599. begin
  600. ForcePathDelims(Filename);
  601. ForcePathDelims(BaseDirectory);
  602. ForcePathDelims(Expected);
  603. if not TryCreateRelativePath(Filename,BaseDirectory,UsePointDirectory,true,Actual) then
  604. Actual:=Filename;
  605. AssertEquals('TryCreateRelativePath(File='+Filename+',Base='+BaseDirectory+')',
  606. Expected,Actual);
  607. end;
  608. begin
  609. DoTest('/a','/a','');
  610. DoTest('/a','/a','.',true);
  611. DoTest('/a','/a/','');
  612. DoTest('/a/b','/a/b','');
  613. DoTest('/a/b','/a/b/','');
  614. DoTest('/a','/a/','');
  615. DoTest('/a','','/a');
  616. DoTest('/a/b','/a','b');
  617. DoTest('/a/b','/a/','b');
  618. DoTest('/a/b','/a//','b');
  619. DoTest('/a','/a/b','..');
  620. DoTest('/a','/a/b/','..');
  621. DoTest('/a','/a/b//','..');
  622. DoTest('/a/','/a/b','..');
  623. DoTest('/a','/a/b/c','../..');
  624. DoTest('/a','/a/b//c','../..');
  625. DoTest('/a','/a//b/c','../..');
  626. DoTest('/a','/a//b/c/','../..');
  627. DoTest('/a','/b','/a');
  628. DoTest('~/bin','/','~/bin');
  629. DoTest('$(HOME)/bin','/','$(HOME)/bin');
  630. {$IFDEF MSWindows}
  631. DoTest('D:\a\b\c.pas','D:\a\d\','..\b\c.pas');
  632. {$ENDIF}
  633. end;
  634. procedure TTestCLI_UnitSearch.TestUS_Program;
  635. begin
  636. AddUnit('system.pp',[''],['']);
  637. AddFile('test1.pas',[
  638. 'begin',
  639. 'end.']);
  640. Compile(['test1.pas','-va']);
  641. AssertNotNull('test1.js not found',FindFile('test1.js'));
  642. end;
  643. procedure TTestCLI_UnitSearch.TestUS_UsesEmptyFileFail;
  644. begin
  645. AddFile('system.pp','');
  646. AddFile('test1.pas',[
  647. 'begin',
  648. 'end.']);
  649. Compile(['test1.pas'],ExitCodeSyntaxError);
  650. AssertEquals('ErrorMsg','Expected "unit"',ErrorMsg);
  651. end;
  652. procedure TTestCLI_UnitSearch.TestUS_Program_o;
  653. begin
  654. AddUnit('system.pp',[''],['']);
  655. AddFile('test1.pas',[
  656. 'begin',
  657. 'end.']);
  658. Compile(['test1.pas','-obla.js']);
  659. AssertNotNull('bla.js not found',FindFile('bla.js'));
  660. end;
  661. procedure TTestCLI_UnitSearch.TestUS_Program_FU;
  662. begin
  663. AddUnit('system.pp',[''],['']);
  664. AddFile('test1.pas',[
  665. 'begin',
  666. 'end.']);
  667. AddDir('lib');
  668. Compile(['test1.pas','-FUlib']);
  669. AssertNotNull('lib/test1.js not found',FindFile('lib/test1.js'));
  670. end;
  671. procedure TTestCLI_UnitSearch.TestUS_Program_FU_o;
  672. begin
  673. AddUnit('system.pp',[''],['']);
  674. AddFile('test1.pas',[
  675. 'begin',
  676. 'end.']);
  677. AddDir('lib');
  678. Compile(['test1.pas','-FUlib','-ofoo.js']);
  679. AssertNotNull('lib/system.js not found',FindFile('lib/system.js'));
  680. AssertNotNull('foo.js not found',FindFile('foo.js'));
  681. end;
  682. procedure TTestCLI_UnitSearch.TestUS_Program_FE_o;
  683. begin
  684. AddUnit('system.pp',[''],['']);
  685. AddFile('test1.pas',[
  686. 'begin',
  687. 'end.']);
  688. AddDir('lib');
  689. Compile(['test1.pas','-FElib','-ofoo.js']);
  690. AssertNotNull('lib/system.js not found',FindFile('lib/system.js'));
  691. AssertNotNull('foo.js not found',FindFile('foo.js'));
  692. end;
  693. procedure TTestCLI_UnitSearch.TestUS_PlatformModule_Program;
  694. begin
  695. AddUnit('system.pp',[''],['']);
  696. AddFile('test1.pas',[
  697. 'begin',
  698. 'end.']);
  699. Compile(['-Tmodule','-va','test1.pas']);
  700. CheckFullSource('TestUS_PlatformModule_Library','test1.js',
  701. LinesToStr([
  702. #$EF#$BB#$BF+'rtl.module("program",["system"],function () {',
  703. ' "use strict";',
  704. ' var $mod = this;',
  705. ' $mod.$main = function () {',
  706. ' };',
  707. '});',
  708. 'rtl.run();',
  709. '']));
  710. end;
  711. procedure TTestCLI_UnitSearch.TestUS_IncludeSameDir;
  712. begin
  713. AddUnit('system.pp',[''],['']);
  714. AddFile('sub/defines.inc',[
  715. '{$Define foo}',
  716. '']);
  717. AddUnit('sub/unit1.pas',
  718. ['{$I defines.inc}',
  719. '{$ifdef foo}',
  720. 'var a: longint;',
  721. '{$endif}'],
  722. ['']);
  723. AddFile('test1.pas',[
  724. 'uses unit1;',
  725. 'begin',
  726. ' a:=3;',
  727. 'end.']);
  728. AddDir('lib');
  729. Compile(['test1.pas','-Fusub','-FElib','-ofoo.js']);
  730. end;
  731. procedure TTestCLI_UnitSearch.TestUS_Include_NestedDelphi;
  732. begin
  733. AddUnit('system.pp',[''],['']);
  734. AddFile('sub/inc1.inc',[
  735. 'type number = longint;',
  736. '{$I sub/deep/inc2.inc}',
  737. '']);
  738. AddFile('sub/deep/inc2.inc',[
  739. 'type numero = number;',
  740. '{$I sub/inc3.inc}',
  741. '']);
  742. AddFile('sub/inc3.inc',[
  743. 'type nummer = numero;',
  744. '']);
  745. AddFile('test1.pas',[
  746. '{$mode delphi}',
  747. '{$i sub/inc1.inc}',
  748. 'var',
  749. ' n: nummer;',
  750. 'begin',
  751. 'end.']);
  752. Compile(['test1.pas','-Jc']);
  753. end;
  754. procedure TTestCLI_UnitSearch.TestUS_Include_NestedObjFPC;
  755. begin
  756. AddUnit('system.pp',[''],['']);
  757. AddFile('sub/inc1.inc',[
  758. 'type number = longint;',
  759. '{$I deep/inc2.inc}',
  760. '']);
  761. AddFile('sub/deep/inc2.inc',[
  762. 'type numero = number;',
  763. '{$I ../inc3.inc}',
  764. '']);
  765. AddFile('sub/inc3.inc',[
  766. 'type nummer = numero;',
  767. '']);
  768. AddFile('test1.pas',[
  769. '{$mode objfpc}',
  770. '{$i sub/inc1.inc}',
  771. 'var',
  772. ' n: nummer;',
  773. 'begin',
  774. 'end.']);
  775. Compile(['test1.pas','-Jc']);
  776. end;
  777. procedure TTestCLI_UnitSearch.TestUS_UsesInFile;
  778. begin
  779. AddUnit('system.pp',[''],['']);
  780. AddUnit('unit1.pas',
  781. ['uses bird in ''unit2.pas'';',
  782. 'var a: longint;'],
  783. ['']);
  784. AddUnit('unit2.pas',
  785. ['var b: longint;'],
  786. ['']);
  787. AddFile('test1.pas',[
  788. 'uses foo in ''unit1.pas'', bar in ''unit2.pas'';',
  789. 'begin',
  790. ' bar.b:=foo.a;',
  791. ' a:=b;',
  792. 'end.']);
  793. Compile(['test1.pas','-Jc']);
  794. end;
  795. procedure TTestCLI_UnitSearch.TestUS_UsesInFile_Duplicate;
  796. begin
  797. // check if using two different units with same name
  798. AddUnit('system.pp',[''],['']);
  799. AddUnit('unit1.pas',
  800. ['var a: longint;'],
  801. ['']);
  802. AddUnit('sub'+PathDelim+'unit1.pas',
  803. ['var b: longint;'],
  804. ['']);
  805. AddFile('test1.pas',[
  806. 'uses foo in ''unit1.pas'', bar in ''sub/unit1.pas'';',
  807. 'begin',
  808. ' bar.b:=foo.a;',
  809. ' a:=b;',
  810. 'end.']);
  811. Compile(['test1.pas','-Jc'],ExitCodeSyntaxError);
  812. AssertEquals('ErrorMsg','Duplicate file found: "'+WorkDir+'sub'+PathDelim+'unit1.pas" and "'+WorkDir+'unit1.pas"',ErrorMsg);
  813. end;
  814. procedure TTestCLI_UnitSearch.TestUS_UsesInFile_IndirectDuplicate;
  815. begin
  816. // check if using two different units with same name
  817. AddUnit('system.pp',[''],['']);
  818. AddUnit('unit1.pas',
  819. ['var a: longint;'],
  820. ['']);
  821. AddUnit('sub'+PathDelim+'unit1.pas',
  822. ['var b: longint;'],
  823. ['']);
  824. AddUnit('unit2.pas',
  825. ['uses unit1 in ''unit1.pas'';'],
  826. ['']);
  827. AddFile('test1.pas',[
  828. 'uses unit2, foo in ''sub/unit1.pas'';',
  829. 'begin',
  830. 'end.']);
  831. Compile(['test1.pas','-Jc'],ExitCodeSyntaxError);
  832. AssertEquals('ErrorMsg','Duplicate file found: "'+WorkDir+'unit1.pas" and "'+WorkDir+'sub'+PathDelim+'unit1.pas"',ErrorMsg);
  833. end;
  834. procedure TTestCLI_UnitSearch.TestUS_UsesInFile_WorkNotEqProgDir;
  835. begin
  836. AddUnit('system.pp',[''],['']);
  837. AddUnit('sub/unit2.pas',
  838. ['var a: longint;'],
  839. ['']);
  840. AddUnit('sub/unit1.pas',
  841. ['uses unit2;'],
  842. ['']);
  843. AddFile('sub/test1.pas',[
  844. 'uses foo in ''unit1.pas'';',
  845. 'begin',
  846. 'end.']);
  847. Compile(['sub/test1.pas','-Jc']);
  848. end;
  849. procedure TTestCLI_UnitSearch.TestUS_UsesInFileTwice;
  850. begin
  851. AddUnit('system.pp',[''],['']);
  852. AddUnit('unit1.pas',
  853. ['var a: longint;'],
  854. ['']);
  855. AddFile('test1.pas',[
  856. 'uses foo in ''unit1.pas'', bar in ''unit1.pas'';',
  857. 'begin',
  858. ' bar.a:=foo.a;',
  859. ' a:=a;',
  860. 'end.']);
  861. Compile(['test1.pas','-Jc']);
  862. end;
  863. procedure TTestCLI_UnitSearch.TestUS_UseUnitTwiceFail;
  864. begin
  865. AddUnit('system.pp',[''],['']);
  866. AddUnit('sub.unit1.pas',
  867. ['var a: longint;'],
  868. ['']);
  869. AddFile('test1.pas',[
  870. 'uses sub.Unit1, sub.unit1;',
  871. 'begin',
  872. ' a:=a;',
  873. 'end.']);
  874. Compile(['test1.pas','-FNsub','-Jc'],ExitCodeSyntaxError);
  875. AssertEquals('ErrorMsg','Duplicate identifier "sub.unit1"',ErrorMsg);
  876. end;
  877. procedure TTestCLI_UnitSearch.TestUS_UseUnitTwiceViaNameSpace;
  878. begin
  879. AddUnit('system.pp',[''],['']);
  880. AddUnit('sub.unit1.pas',
  881. ['var a: longint;'],
  882. ['']);
  883. AddFile('test1.pas',[
  884. 'uses unit1, sub.unit1;',
  885. 'begin',
  886. ' unit1.a:=sub.unit1.a;',
  887. ' a:=a;',
  888. 'end.']);
  889. Compile(['test1.pas','-FNsub','-Jc']);
  890. end;
  891. procedure TTestCLI_UnitSearch.TestUS_DefaultNameSpaceLast;
  892. begin
  893. AddUnit('system.pp',[''],['']);
  894. AddUnit('Unit2.pas',
  895. ['var i: longint;'],
  896. ['']);
  897. AddUnit('NS1.Unit2.pas',
  898. ['var j: longint;'],
  899. ['']);
  900. AddFile('test1.pas',[
  901. 'uses unIt2;',
  902. 'var',
  903. ' k: longint;',
  904. 'begin',
  905. ' k:=i;',
  906. 'end.']);
  907. Compile(['test1.pas','','-Jc']);
  908. end;
  909. procedure TTestCLI_UnitSearch.TestUS_DefaultNameSpaceAfterNameSpace;
  910. begin
  911. AddUnit('system.pp',[''],['']);
  912. AddUnit('prg.Unit2.pas',
  913. ['var j: longint;'],
  914. ['']);
  915. AddUnit('sub.Unit2.pas',
  916. ['var i: longint;'],
  917. ['']);
  918. AddFile('prg.test1.pas',[
  919. 'uses unIt2;',
  920. 'var',
  921. ' k: longint;',
  922. 'begin',
  923. ' k:=i;',
  924. 'end.']);
  925. Compile(['prg.test1.pas','-FNsub','-Jc']);
  926. end;
  927. procedure TTestCLI_UnitSearch.TestUS_NoNameSpaceBeforeDefaultNameSpace;
  928. begin
  929. AddUnit('system.pp',[''],['']);
  930. AddUnit('prg.Unit2.pas',
  931. ['var j: longint;'],
  932. ['']);
  933. AddUnit('Unit2.pas',
  934. ['var i: longint;'],
  935. ['']);
  936. AddFile('prg.test1.pas',[
  937. 'uses unIt2;',
  938. 'var',
  939. ' k: longint;',
  940. 'begin',
  941. ' k:=i;',
  942. 'end.']);
  943. Compile(['prg.test1.pas','','-Jc']);
  944. end;
  945. procedure TTestCLI_UnitSearch.TestUS_NoNameSpaceAndDefaultNameSpace;
  946. begin
  947. AddUnit('system.pp',[''],['']);
  948. AddUnit('UnitA.pas',
  949. ['type TBool = boolean;'],
  950. ['']);
  951. AddUnit('ThirdParty.UnitB.pas',
  952. ['uses UnitA;',
  953. 'type TAlias = TBool;'],
  954. ['']);
  955. AddUnit('MyProject.UnitA.pas',
  956. [
  957. 'uses ThirdParty.UnitB;',
  958. 'var a: TAlias;'],
  959. ['']);
  960. AddFile('MyProject.Main.pas',[
  961. 'uses MyProject.UnitA;',
  962. 'var',
  963. ' b: boolean;',
  964. 'begin',
  965. ' b:=a;',
  966. 'end.']);
  967. Compile(['MyProject.Main.pas','','-Jc']);
  968. end;
  969. procedure TTestCLI_UnitSearch.TestUS_ProgramLinklib;
  970. begin
  971. AddUnit('system.pp',[''],['']);
  972. AddFile('test1.pas',[
  973. '{$linklib Bird}',
  974. 'begin',
  975. 'end.']);
  976. Compile(['-Tnodejs','-va','test1.pas']);
  977. CheckLinklibProgramSrc('TestUS_ProgramLinklib',
  978. LinesToStr([
  979. 'import * as bird from "Bird.js";',
  980. 'pas.$libimports.bird = bird;']));
  981. end;
  982. procedure TTestCLI_UnitSearch.TestUS_UnitLinklib;
  983. begin
  984. AddUnit('system.pp',[''],['']);
  985. AddUnit('UnitB.pas',
  986. ['{$linklib Bird Thunderbird}',
  987. ''],
  988. ['']);
  989. AddFile('test1.pas',[
  990. 'uses UnitB;',
  991. 'begin',
  992. 'end.']);
  993. Compile(['-Tnodejs','-va','test1.pas']);
  994. CheckLinklibProgramSrc('TestUS_UnitLinklib',
  995. LinesToStr([
  996. 'import * as Thunderbird from "Bird.js";',
  997. 'pas.$libimports.Thunderbird = Thunderbird;']));
  998. end;
  999. Initialization
  1000. RegisterTests([TTestCLI_UnitSearch]);
  1001. end.