IsppPreprocessor.pas 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850
  1. {
  2. Inno Setup Preprocessor
  3. Copyright (C) 2001-2002 Alex Yackimoff
  4. Inno Setup
  5. Copyright (C) 1997-2024 Jordan Russell
  6. Portions by Martijn Laan
  7. For conditions of distribution and use, see LICENSE.TXT.
  8. }
  9. unit IsppPreprocessor;
  10. interface
  11. uses Windows, SysUtils, Classes, CompPreprocInt, IniFiles, Registry, IsppIntf,
  12. IsppBase, IsppStack, IsppIdentMan, IsppParser;
  13. {$I ..\Version.inc}
  14. type
  15. TPreprocessor = class;
  16. EPreprocError = class(Exception)
  17. FileName: string;
  18. LineNumber: Integer;
  19. ColumnNumber: Integer;
  20. constructor Create(Preproc: TPreprocessor; const Msg: string);
  21. end;
  22. TConditionalBlockInfo = packed record
  23. BlockState, Fired, HadElse, Reserved: Boolean;
  24. end;
  25. TConditionalVerboseMsg = (cvmIf, cvmElif, cvmElse, cvmEndif);
  26. TConditionalTranslationStack = class(TStack)
  27. private
  28. FPreproc: TPreprocessor;
  29. FCache: Boolean;
  30. FCacheValid: Boolean;
  31. procedure VerboseMsg(Msg: TConditionalVerboseMsg; Eval: Boolean);
  32. protected
  33. function Last: TConditionalBlockInfo;
  34. procedure UpdateLast(const Value: TConditionalBlockInfo);
  35. public
  36. constructor Create(Preproc: TPreprocessor);
  37. procedure IfInstruction(Eval: Boolean);
  38. procedure ElseIfInstruction(Eval: Boolean);
  39. procedure ElseInstruction;
  40. procedure EndIfInstruction;
  41. function Include: Boolean;
  42. procedure Resolved;
  43. end;
  44. TPreprocessorCommand = (pcError, pcIf, pcIfDef, pcIfNDef, pcIfExist,
  45. pcIfNExist, pcElseIf, pcElse, pcEndIf, pcDefine, pcUndef, pcInclude,
  46. pcErrorDir, pcPragma, pcLine, pcImport, pcPrint, pcPrintEnv, pcFile,
  47. pcExecute, pcGlue, pcEndGlue, pcDim, pcProcedure, pcEndProc, pcEndLoop,
  48. pcFor, pcReDim);
  49. TDropGarbageProc = procedure(Item: Pointer);
  50. TIsppMessageType = (imtStatus, imtWarning);
  51. TPreprocessor = class(TObject, IIdentManager)
  52. private
  53. FCompilerParams: TPreprocessScriptParams;
  54. FCompilerPath: string;
  55. FCounter: Integer;
  56. FCurrentFile: Word;
  57. FCurrentLine: Word;
  58. FDefaultScope: TDefineScope;
  59. FFileStack: TStringList; { strs: files being included }
  60. FIncludes: TStringList; { strs: files been included, for error msgs }
  61. FIncludePath: string;
  62. FInsertionPoint: Integer;
  63. FLinePointer: Integer;
  64. FMainCounter: Word;
  65. FOutput: TStringList; { strs: translation }
  66. FQueuedLine: string;
  67. FQueuedLineCount: Integer;
  68. FSourcePath: string;
  69. FStack: TConditionalTranslationStack;
  70. FIdentManager: TIdentManager;
  71. FInProcBody: Boolean;
  72. FInForBody: Boolean;
  73. FProcs: TStringList;
  74. FGarbageCollection: TList;
  75. procedure DropGarbage;
  76. function ProcessInlineDirectives(P: PChar): string;
  77. function ProcessPreprocCommand(Command: TPreprocessorCommand;
  78. var Params: string; ParamsOffset: Integer): Boolean;
  79. procedure PushFile(const FileName: string);
  80. procedure PopFile;
  81. function CheckFile(const FileName: string): Boolean;
  82. function EmitDestination: TStringList;
  83. procedure SendMsg(Msg: string; Typ: TIsppMessageType);
  84. function GetFileName(Code: Integer): string;
  85. function GetLineNumber(Code: Integer): Word;
  86. procedure RaiseErrorEx(const Message: string; Column: Integer);
  87. procedure ExecProc(Body: TStrings);
  88. protected
  89. function GetDefaultScope: TDefineScope;
  90. procedure SetDefaultScope(Scope: TDefineScope);
  91. procedure InternalAddLine(const LineRead: string; FileIndex, LineNo: Word;
  92. NonISS: Boolean);
  93. function InternalQueueLine(const LineRead: string; FileIndex, LineNo: Word;
  94. NonISS: Boolean): Integer;
  95. function ParseFormalParams(Parser: TParser; var ParamList: PParamList): Integer;
  96. { IUnknown }
  97. function QueryInterface(const IID: TGUID; out Obj): HRESULT; stdcall;
  98. function _AddRef: Integer; stdcall;
  99. function _Release: Integer; stdcall;
  100. { IIdentManager }
  101. function LookupPredefined(Name: string; Value: PIsppVariant): Boolean;
  102. function Defined(const Name: String): Boolean;
  103. function GetIdent(const Name: String;
  104. out CallContext: ICallContext): TIdentType;
  105. function TypeOf(const Name: String): Byte;
  106. function DimOf(const Name: String): Integer;
  107. public
  108. FOptions: TISPPOptions;
  109. constructor Create(const CompilerParams: TPreprocessScriptParams;
  110. VarManager: TIdentManager; const Options: TIsppOptions;
  111. const SourcePath: string; const CompilerPath: string; const FileName: string = '');
  112. destructor Destroy; override;
  113. procedure VerboseMsg(Level: Byte; const Msg: string; const Args: array of const);
  114. procedure StatusMsg(const Msg: string; const Args: array of const);
  115. procedure WarningMsg(const Msg: string; const Args: array of const);
  116. function GetNextOutputLine(var LineFilename: string; var LineNumber: Integer;
  117. var LineText: string): Boolean;
  118. procedure GetNextOutputLineReset;
  119. procedure IncludeFile(FileName: string; Builtins, UseIncludePathOnly, ResetCurrentFile: Boolean);
  120. procedure QueueLine(const LineRead: string);
  121. function PrependDirName(const FileName, Dir: string): string;
  122. procedure RegisterFunction(const Name: string; Handler: TIsppFunction; Ext: Longint);
  123. procedure RaiseError(const Message: string);
  124. procedure SaveToFile(const FileName: string);
  125. procedure CollectGarbage(Item: Pointer; Proc: TDropGarbageProc);
  126. procedure UncollectGarbage(Item: Pointer);
  127. property IncludedFiles: TStringList read FIncludes;
  128. property IncludePath: string read FIncludePath write FIncludePath;
  129. property SourcePath: string read FSourcePath;
  130. property StringList: TStringList read FOutput;
  131. property Stack: TConditionalTranslationStack read FStack;
  132. property VarMan: TIdentManager read FIdentManager;
  133. end;
  134. implementation
  135. uses IsppConsts, IsppFuncs, IsppVarUtils, IsppSessions, CTokenizer, PathFunc,
  136. CmnFunc2, FileClass, Struct;
  137. const
  138. PreprocCommands: array[TPreprocessorCommand] of String =
  139. ('', 'if', 'ifdef', 'ifndef', 'ifexist', 'ifnexist', 'elif', 'else',
  140. 'endif', 'define', 'undef', 'include', 'error', 'pragma', 'line', 'import',
  141. 'emit', 'env', 'file', 'expr', 'insert', 'append', 'dim', 'sub', 'endsub',
  142. 'endloop', 'for', 'redim');
  143. PpCmdSynonyms: array[TPreprocessorCommand] of Char =
  144. (#0, '?', #0, #0, #0, #0, #0, '^', '.', ':', #0, '+', #0, #0, #0, #0,
  145. '=', '%', #0, '!', #0, #0, #0, #0, #0, #0, #0, #0);
  146. function GetEnv(const EnvVar: String): String;
  147. function AdjustLength(var S: String; const Res: Cardinal): Boolean;
  148. begin
  149. Result := Integer(Res) < Length(S);
  150. SetLength (S, Res);
  151. end;
  152. var
  153. Res: DWORD;
  154. begin
  155. SetLength(Result, 255);
  156. repeat
  157. Res := GetEnvironmentVariable(PChar(EnvVar), PChar(Result), Length(Result));
  158. if Res = 0 then begin
  159. Result := '';
  160. Break;
  161. end;
  162. until AdjustLength(Result, Res);
  163. end;
  164. function ParsePreprocCommand(var P: PChar; ExtraTerminator: Char): TPreprocessorCommand;
  165. begin
  166. for Result := TPreprocessorCommand(1) to High(TPreprocessorCommand) do
  167. begin
  168. if (P^ = PpCmdSynonyms[Result]) then
  169. Inc(P)
  170. else if (StrLIComp(P, @PreprocCommands[Result][1], Length(PreprocCommands[Result])) = 0) and
  171. CharInSet(P[Length(PreprocCommands[Result])], [#0..#32, ExtraTerminator]) then
  172. Inc(P, Length(PreprocCommands[Result]))
  173. else
  174. Continue;
  175. Exit;
  176. end;
  177. if StrLIComp('echo', P, 4) = 0 then
  178. begin
  179. Result := pcPrint;
  180. Inc(P, 4)
  181. end
  182. else if StrLIComp('call', P, 4) = 0 then
  183. begin
  184. Result := pcExecute;
  185. Inc(P, 4);
  186. end
  187. else
  188. Result := pcError;
  189. end;
  190. { EPreprocError }
  191. constructor EPreprocError.Create(Preproc: TPreprocessor; const Msg: string);
  192. begin
  193. inherited Create(Msg + '.');
  194. FileName := Preproc.GetFileName(-1);
  195. LineNumber := Preproc.GetLineNumber(-1);
  196. end;
  197. { TPreprocessor }
  198. function CheckReservedIdent(const Ident: string): string;
  199. begin
  200. Result := UpperCase(Ident);
  201. if (Result = SLocal) or
  202. (Result = SGlobal) or
  203. (Result = SInt) or
  204. (Result = SStr) or
  205. (Result = SAny) then
  206. raise EParsingError.CreateFmt(SExpectedButFound, [SIdent, '''' + Result + '''']);
  207. Result := Ident;
  208. end;
  209. constructor TPreprocessor.Create(const CompilerParams: TPreprocessScriptParams;
  210. VarManager: TIdentManager; const Options: TIsppOptions;
  211. const SourcePath, CompilerPath, FileName: string);
  212. begin
  213. PushPreproc(Self);
  214. if VarManager = nil then
  215. FIdentManager := TIdentManager.Create(Self, Longint(Self))
  216. else
  217. FIdentManager := VarManager;
  218. FOptions := Options;
  219. FIdentManager._AddRef;
  220. FIdentManager.BeginLocal;
  221. FCompilerParams := CompilerParams;
  222. FCompilerPath := CompilerPath;
  223. FSourcePath := SourcePath;
  224. FFileStack := TStringList.Create;
  225. FIncludes := TStringList.Create;
  226. FIncludes.Add(FileName); //main file - no name
  227. FInsertionPoint := -1;
  228. FOutput := TStringList.Create;
  229. FProcs := TStringList.Create;
  230. FStack := TConditionalTranslationStack.Create(Self);
  231. if VarManager = nil then IsppFuncs.RegisterFunctions(Self);
  232. end;
  233. destructor TPreprocessor.Destroy;
  234. begin
  235. DropGarbage;
  236. if PopPreproc <> Self then
  237. RaiseError('Internal error: FSP');
  238. FStack.Free;
  239. FProcs.Free;
  240. FOutput.Free;
  241. FIncludes.Free;
  242. if FFileStack.Count <> 0 then
  243. RaiseError('Internal error: FNE');
  244. FFileStack.Free;
  245. FIdentManager.EndLocal;
  246. FIdentManager._Release;
  247. end;
  248. function TPreprocessor.GetFileName(Code: Integer): string;
  249. begin
  250. if Code = -1 then
  251. Result := FIncludes[FCurrentFile]
  252. else
  253. Result := FIncludes[Longint(FOutput.Objects[Code]) shr 16];
  254. end;
  255. function TPreprocessor.GetLineNumber(Code: Integer): Word;
  256. begin
  257. if Code = -1 then
  258. Result := FCurrentLine
  259. else
  260. Result := Word(FOutput.Objects[Code]) and $FFFF
  261. end;
  262. function TPreprocessor.GetNextOutputLine(var LineFilename: string; var LineNumber: Integer;
  263. var LineText: string): Boolean;
  264. begin
  265. Result := False;
  266. if FLinePointer < FOutput.Count then
  267. begin
  268. LineFilename := GetFileName(FLinePointer);
  269. LineNumber := GetLineNumber(FLinePointer);
  270. LineText := FOutput[FLinePointer];
  271. Inc(FLinePointer);
  272. Result := True;
  273. end;
  274. end;
  275. procedure TPreprocessor.GetNextOutputLineReset;
  276. begin
  277. FLinePointer := 0;
  278. end;
  279. procedure TPreprocessor.InternalAddLine(const LineRead: string; FileIndex, LineNo: Word;
  280. NonISS: Boolean);
  281. var
  282. IncludeLine: Boolean;
  283. P, P1: PChar;
  284. Command: TPreprocessorCommand;
  285. DirectiveOffset: Integer;
  286. State: Boolean;
  287. S, S1: string;
  288. begin
  289. try
  290. Inc(LineNo);
  291. FCurrentFile := FileIndex;
  292. FCurrentLine := LineNo;
  293. P := PChar(LineRead);
  294. IncludeLine := True;
  295. if P^ <> #0 then
  296. begin
  297. P1 := P;
  298. while CharInSet(P^, [#1..#32]) do Inc(P);
  299. if P^ = '#' then
  300. begin
  301. Inc(P);
  302. while CharInSet(P^, [#1..#32]) do Inc(P);
  303. IncludeLine := FInProcBody;
  304. Command := ParsePreprocCommand(P, #0);
  305. if FInProcBody then
  306. begin
  307. case Command of
  308. pcError: RaiseError(SUnknownPreprocessorDirective);
  309. pcProcedure: RaiseError('Nested procedure declaration not allowed');
  310. pcEndProc:
  311. begin
  312. S := P;
  313. ProcessPreprocCommand(Command, S, P - P1);
  314. IncludeLine := False;
  315. end
  316. else
  317. S := LineRead;
  318. end;
  319. end
  320. else
  321. begin
  322. State := FStack.Include;
  323. DirectiveOffset := P - P1;
  324. //S := Copy(LineRead, DirectiveOffset + 1, MaxInt);
  325. S := P;
  326. case Command of
  327. pcIf..pcIfNExist:
  328. FStack.IfInstruction(FStack.Include and
  329. ProcessPreprocCommand(Command, S, DirectiveOffset));
  330. pcElseIf:
  331. FStack.ElseIfInstruction(FStack.Last.Fired or
  332. (FStack.Include or not FStack.Last.BlockState) and
  333. ProcessPreprocCommand(Command, S, DirectiveOffset));
  334. pcElse: FStack.ElseInstruction;
  335. pcEndIf: FStack.EndIfInstruction
  336. else
  337. if State then
  338. case Command of
  339. pcPrint, pcPrintEnv:
  340. begin
  341. ProcessPreprocCommand(Command, S, DirectiveOffset);
  342. VerboseMsg(8, SLineEmitted, [S]);
  343. IncludeLine := True
  344. end;
  345. pcFile: RaiseError(SFileDirectiveCanBeOnlyInline);
  346. else
  347. ProcessPreprocCommand(Command, S, DirectiveOffset);
  348. end;
  349. end
  350. end;
  351. end
  352. else
  353. if not FInProcBody and not FStack.Include then
  354. IncludeLine := False
  355. else
  356. if ((P^ = '/') and (P[1] = '/')) or
  357. ((P^ = #0) and not (optEmitEmptyLines in FOptions.Options)) then //P^ is #0 if the line was all whitespace
  358. IncludeLine := False
  359. else
  360. if (P^ <> #0) and (P^ <> ';') and not FInProcBody then
  361. S := PChar(ProcessInlineDirectives(P1))
  362. else
  363. S := P1;
  364. end
  365. else
  366. begin
  367. S := '';
  368. IncludeLine := optEmitEmptyLines in FOptions.Options
  369. end;
  370. if IncludeLine then
  371. begin
  372. P := PChar(S);
  373. repeat
  374. P1 := P;
  375. while not CharInSet(P^, [#0, #10, #13]) do Inc(P);
  376. SetString(S1, P1, P - P1);
  377. if FInsertionPoint >= 0 then
  378. begin
  379. EmitDestination.InsertObject(FInsertionPoint, S1,
  380. TObject(FileIndex shl 16 or LineNo));
  381. Inc(FInsertionPoint);
  382. end
  383. else
  384. EmitDestination.AddObject(S1, TObject(FileIndex shl 16 or LineNo));
  385. while CharInSet(P^, [#10, #13]) do Inc(P);
  386. until P^ = #0;
  387. end;
  388. except
  389. on E: EParsingError do
  390. RaiseErrorEx(E.Message, E.Position);
  391. on E: EPreprocError do
  392. raise;
  393. on E: Exception do
  394. RaiseError(E.Message);
  395. end;
  396. end;
  397. function TPreprocessor.ProcessInlineDirectives(P: PChar): string;
  398. var
  399. S: string;
  400. Command: TPreprocessorCommand;
  401. LineStack: TConditionalTranslationStack;
  402. LineStart, P1, DStart, DEnd: PChar;
  403. function ScanForInlineStart(var P, D: PChar): Boolean;
  404. var
  405. I: Integer;
  406. begin
  407. Result := False;
  408. while P^ <> #0 do
  409. begin
  410. if AnsiChar(P^) = FOptions.InlineStart[1] then
  411. begin
  412. D := P;
  413. Result := True;
  414. for I := 2 to Byte(FOptions.InlineStart[0]) do
  415. begin
  416. Inc(D);
  417. if AnsiChar(D^) <> FOptions.InlineStart[I] then
  418. begin
  419. Result := False;
  420. Break;
  421. end;
  422. end;
  423. Inc(D);
  424. end;
  425. if Result then Break;
  426. Inc(P);
  427. end;
  428. end;
  429. function ScanForInlineEnd(var P: PChar): PChar;
  430. var
  431. I: Integer;
  432. begin
  433. Result := nil;
  434. while P^ <> #0 do
  435. begin
  436. if AnsiChar(P^) = FOptions.InlineEnd[1] then
  437. begin
  438. Result := P;
  439. for I := 2 to Byte(FOptions.InlineEnd[0]) do
  440. begin
  441. Inc(P);
  442. if AnsiChar(P^) <> FOptions.InlineEnd[I] then
  443. begin
  444. Result := nil;
  445. Break;
  446. end;
  447. end;
  448. Inc(P);
  449. end;
  450. if Result <> nil then Exit;
  451. Inc(P);
  452. end;
  453. RaiseError(SUnterminatedPreprocessorDirectiv);
  454. end;
  455. begin
  456. LineStack := TConditionalTranslationStack.Create(Self);
  457. try
  458. Result := '';
  459. LineStart := P;
  460. P1 := P;
  461. while ScanForInlineStart(P, DStart) do
  462. begin
  463. SetString(S, P1, P - P1);
  464. if LineStack.Include then Result := Result + S;
  465. Command := ParsePreprocCommand(DStart, Char(FOptions.InlineEnd[1]));
  466. if Command = pcError then
  467. Command := pcPrint;
  468. DEnd := DStart;
  469. SetString(S, DStart, ScanForInlineEnd(DEnd) - DStart);
  470. case Command of
  471. pcError: RaiseError(SUnknownPreprocessorDirective);
  472. pcIf..pcIfNExist:
  473. LineStack.IfInstruction(LineStack.Include and
  474. ProcessPreprocCommand(Command, S, DStart - LineStart));
  475. pcElseIf:
  476. LineStack.ElseIfInstruction(LineStack.Last.Fired or
  477. (LineStack.Include or not LineStack.Last.BlockState) and
  478. ProcessPreprocCommand(Command, S, DStart - LineStart));
  479. pcElse: LineStack.ElseInstruction;
  480. pcEndIf: LineStack.EndIfInstruction;
  481. else
  482. if LineStack.Include then
  483. case Command of
  484. pcInclude, pcGlue..pcEndLoop:
  485. RaiseError(Format(SDirectiveCannotBeInline,
  486. [PreprocCommands[Command]]));
  487. pcPrint, pcPrintEnv, pcFile:
  488. begin
  489. ProcessPreprocCommand(Command, S, DStart - LineStart);
  490. Result := Result + S;
  491. end;
  492. else
  493. ProcessPreprocCommand(Command, S, DStart - LineStart)
  494. end;
  495. end;
  496. P1 := DEnd;
  497. P := DEnd;
  498. //Inc(P);
  499. end;
  500. Result := Result + P1;
  501. LineStack.Resolved;
  502. finally
  503. LineStack.Free
  504. end;
  505. end;
  506. function TPreprocessor.GetDefaultScope: TDefineScope;
  507. begin
  508. if FFileStack.Count > 0 then
  509. Result := TDefineScope(FFileStack.Objects[FFileStack.Count - 1])
  510. else
  511. Result := FDefaultScope;
  512. end;
  513. procedure TPreprocessor.SetDefaultScope(Scope: TDefineScope);
  514. begin
  515. if Scope = dsAny then Scope := dsPublic;
  516. if FFileStack.Count > 0 then
  517. FFileStack.Objects[FFileStack.Count - 1] := TObject(Scope)
  518. else
  519. FDefaultScope := Scope;
  520. end;
  521. type
  522. TParserAccess = class(TParser);
  523. function TPreprocessor.ProcessPreprocCommand(Command: TPreprocessorCommand;
  524. var Params: string; ParamsOffset: Integer): Boolean;
  525. function ParseScope(Parser: TParser; ExpectedTokens: TTokenKinds = [tkIdent]): TDefineScope;
  526. const
  527. ScopeClauses: array[dsPublic..dsPrivate] of string =
  528. ('public', 'protected', 'private');
  529. begin
  530. Parser.NextTokenExpect([tkIdent]);
  531. for Result := Low(ScopeClauses) to High(ScopeClauses) do
  532. if CompareText(Parser.TokenString, ScopeClauses[Result]) = 0 then
  533. begin
  534. Parser.NextTokenExpect(ExpectedTokens);
  535. Exit;
  536. end;
  537. Result := dsAny;
  538. end;
  539. function GetScope(Parser: TParser): TDefineScope;
  540. begin
  541. Result := ParseScope(Parser);
  542. if Result = dsAny then Result := GetDefaultScope;
  543. end;
  544. procedure ParseDim(Parser: TParserAccess; ReDim: Boolean);
  545. var
  546. Name: string;
  547. N, NValues, I: Integer;
  548. Scope: TDefineScope;
  549. Values: array of TIsppVariant;
  550. begin
  551. with Parser do
  552. try
  553. Scope := GetScope(Parser);
  554. Name := CheckReservedIdent(TokenString);
  555. NextTokenExpect([tkOpenBracket]);
  556. N := IntExpr(True);
  557. NValues := 0;
  558. NextTokenExpect([tkCloseBracket]);
  559. if PeekAtNextToken = tkOpenBrace then
  560. begin
  561. NextToken;
  562. SetLength(Values, N);
  563. NValues := 0;
  564. while True do begin
  565. if NValues >= N then
  566. raise EIdentError.CreateFmt(SIndexIsOutOfArraySize, [NValues, Name]);
  567. Values[NValues] := Expr(True);
  568. MakeRValue(Values[NValues]);
  569. Inc(NValues);
  570. if PeekAtNextToken <> tkComma then
  571. Break;
  572. NextToken;
  573. end;
  574. NextTokenExpect([tkCloseBrace]);
  575. end;
  576. FIdentManager.DimVariable(Name, N, Scope, ReDim);
  577. if ReDim and (NValues <> 0) then
  578. Error('Initializers not allowed on #redim of existing array');
  579. for I := 0 to NValues-1 do
  580. FIdentManager.DefineVariable(Name, I, Values[I], Scope);
  581. finally
  582. //Free
  583. end;
  584. end;
  585. procedure ParseDefine(Parser: TParserAccess);
  586. var
  587. Name: string;
  588. Start, P: PChar;
  589. IsMacroDefine: Boolean;
  590. //Ident: string;
  591. //Param: TIsppMacroParam;
  592. ParamList: PParamList;
  593. AParamCount: Byte;
  594. AExpr: string;
  595. VarIndex: Integer;
  596. Scope: TDefineScope;
  597. MacroExprPos: TExprPosition;
  598. begin
  599. with Parser do
  600. begin
  601. Start := FExpr;
  602. Scope := ParseScope(Parser, [tkEOF, tkIdent, tkSemicolon]);
  603. if Scope = dsAny then
  604. Scope := GetDefaultScope
  605. else
  606. if Token <> tkIdent then
  607. begin
  608. SetDefaultScope(Scope);
  609. Exit;
  610. end;
  611. Name := CheckReservedIdent(TokenString);
  612. IsMacroDefine := FExpr^ = '(';
  613. if IsMacroDefine then
  614. begin
  615. NextToken;
  616. AParamCount := ParseFormalParams(Parser, ParamList);
  617. try
  618. Inc(FExpr);
  619. P := FExpr;
  620. MacroExprPos.FileIndex := FCurrentFile;
  621. MacroExprPos.Line := FCurrentLine;
  622. MacroExprPos.Column := (FExpr - Start) + ParamsOffset;
  623. while P^ <> #0 do Inc(P);
  624. SetString(AExpr, FExpr, P - FExpr);
  625. AExpr := Trim(AExpr);
  626. if AExpr = '' then RaiseError(SMacroExpressionExpected);
  627. FIdentManager.DefineMacro(Name, AExpr, MacroExprPos, FOptions.ParserOptions,
  628. Slice(ParamList^, AParamCount), Scope);
  629. finally
  630. Finalize(ParamList^[0], AParamCount);
  631. FreeMem(ParamList)
  632. end;
  633. end
  634. else
  635. begin
  636. VarIndex := -1;
  637. if PeekAtNextToken = tkOpenBracket then
  638. begin
  639. NextToken;
  640. VarIndex := IntExpr(True);
  641. NextTokenExpect([tkCloseBracket]);
  642. end;
  643. case PeekAtNextToken of
  644. opAssign: NextToken;
  645. tkEOF:
  646. begin
  647. FIdentManager.DefineVariable(Name, VarIndex, NULL, Scope);
  648. Exit;
  649. end
  650. end;
  651. FIdentManager.DefineVariable(Name, VarIndex, Evaluate, Scope);
  652. end;
  653. end;
  654. end;
  655. procedure ParseUndef(Parser: TParserAccess);
  656. var
  657. Scope: TDefineScope;
  658. begin
  659. with Parser do
  660. begin
  661. Scope := GetScope(Parser);
  662. FIdentManager.Delete(CheckReservedIdent(TokenString), Scope);
  663. EndOfExpr;
  664. end
  665. end;
  666. procedure IncludeFile(const Params: string);
  667. var
  668. FileName: string;
  669. function TryPascal: Boolean;
  670. begin
  671. Result := not (optPascalStrings in FOptions.ParserOptions.Options);
  672. if Result then
  673. begin
  674. Include(FOptions.ParserOptions.Options, optPascalStrings);
  675. try
  676. try
  677. FileName := ParseStr(Self, Params, ParamsOffset,
  678. @FOptions.ParserOptions);
  679. except
  680. Result := False
  681. end;
  682. finally
  683. Exclude(FOptions.ParserOptions.Options, optPascalStrings);
  684. end;
  685. end
  686. end;
  687. var
  688. IncludePathOnly: Boolean;
  689. begin
  690. FileName := Params;
  691. if Pos(';', FileName) > 0 then
  692. Delete(FileName, Pos(';', FileName), MaxInt);
  693. FileName := Trim(FileName);
  694. if (FileName <> '') and (FileName[1] = '<') and
  695. (FileName[Length(FileName)] = '>') then
  696. begin
  697. FileName := Copy(FileName, 2, Length(FileName) - 2);
  698. IncludePathOnly := True;
  699. end
  700. else
  701. begin
  702. try
  703. FileName := ParseStr(Self, Params, ParamsOffset, @FOptions.ParserOptions);
  704. except
  705. if not TryPascal then
  706. raise
  707. end;
  708. IncludePathOnly := False;
  709. end;
  710. Self.IncludeFile(FileName, False, IncludePathOnly, False);
  711. end;
  712. procedure Pragma(Parser: TParserAccess);
  713. var
  714. P: string;
  715. function StrPragma(AllowEmpty: Boolean): string;
  716. begin
  717. Result := Parser.StrExpr(True);
  718. if (Result = '') and not AllowEmpty then
  719. RaiseError(SNonEmptyStringExpected);
  720. Parser.EndOfExpr;
  721. end;
  722. procedure OptionPragma(var Options: TOptions);
  723. var
  724. C: Char;
  725. V: Boolean;
  726. begin
  727. with Parser do
  728. begin
  729. NextTokenExpect([opSubtract]);
  730. repeat
  731. NextTokenExpect([tkIdent]);
  732. if Length(TokenString) > 1 then
  733. RaiseError(SInvalidOptionName);
  734. C := TokenString[1];
  735. V := NextTokenExpect([opAdd, opSubtract]) = opAdd;
  736. SetOption(Options, C, V);
  737. until NextTokenExpect([tkEOF, opSubtract, tkSemicolon]) <> opSubtract;
  738. end;
  739. end;
  740. var
  741. CatchException: Boolean;
  742. ErrorMsg: string;
  743. begin
  744. CatchException := True;
  745. try
  746. with Parser do
  747. begin
  748. NextTokenExpect([tkIdent]);
  749. P := LowerCase(TokenString);
  750. if P = 'include' then
  751. FIncludePath := StrPragma(True)
  752. else if P = 'inlinestart' then
  753. FOptions.InlineStart := AnsiString(StrPragma(False))
  754. else if P = 'inlineend' then
  755. FOptions.InlineEnd := AnsiString(StrPragma(False))
  756. else if P = 'spansymbol' then
  757. FOptions.SpanSymbol := AnsiChar(StrPragma(False)[1])
  758. else if P = 'parseroption' then
  759. OptionPragma(FOptions.ParserOptions.Options)
  760. else if P = 'option' then
  761. OptionPragma(FOptions.Options)
  762. else if P = 'verboselevel' then
  763. begin
  764. Include(FOptions.Options, optVerbose);
  765. FOptions.VerboseLevel := IntExpr(True);
  766. VerboseMsg(0, SChangedVerboseLevel, [FOptions.VerboseLevel]);
  767. EndOfExpr;
  768. end
  769. else if P = 'warning' then begin
  770. { Also see WarningFunc in IsppFuncs }
  771. WarningMsg(StrPragma(True), [])
  772. end else if P = 'message' then begin
  773. { Also see MessageFunc in IsppFuncs }
  774. StatusMsg(StrPragma(True), [])
  775. end else if P = 'error' then begin
  776. { Also see ErrorFunc in IsppFuncs }
  777. ErrorMsg := StrPragma(True);
  778. if ErrorMsg = '' then ErrorMsg := 'Error';
  779. CatchException := False;
  780. RaiseError(ErrorMsg)
  781. end
  782. else
  783. WarningMsg(SFailedToParsePragmaDirective, []);
  784. end;
  785. except
  786. if CatchException then
  787. WarningMsg(SFailedToParsePragmaDirective, [])
  788. else
  789. raise
  790. end;
  791. end;
  792. function DoFile(FileName: string): string;
  793. function GetTempFileName(const Original: string): string;
  794. var
  795. Path: string;
  796. begin
  797. SetLength(Path, MAX_PATH);
  798. SetLength(Path, GetTempPath(MAX_PATH, PChar(Path)));
  799. SetLength(Result, MAX_PATH);
  800. if Windows.GetTempFileName(PChar(Path), PChar(UpperCase(Original)), 0, PChar(Result)) <> 0 then
  801. SetLength(Result, StrLen(PChar(Result)))
  802. else
  803. RaiseLastOSError;
  804. end;
  805. var
  806. F: TTextFileReader;
  807. ALine: string;
  808. Preprocessor: TPreprocessor;
  809. NewOptions: TIsppOptions;
  810. begin
  811. FileName := PrependDirName(FileName, FSourcePath);
  812. if FileExists(FileName) then
  813. begin
  814. Result := GetTempFileName(ExtractFileName(FileName));
  815. StatusMsg(SProcessingExternalFile, [FileName]);
  816. NewOptions := FOptions;
  817. Preprocessor := TPreprocessor.Create(FCompilerParams, FIdentManager,
  818. NewOptions, FSourcePath, FCompilerPath, FileName);
  819. try
  820. F := TTextFileReader.Create(Filename, fdOpenExisting, faRead, fsRead);
  821. try
  822. while not F.Eof do begin
  823. ALine := F.ReadLine;
  824. Preprocessor.QueueLine(ALine);
  825. end;
  826. finally
  827. F.Free;
  828. end;
  829. Preprocessor.SaveToFile(Result);
  830. QueueFileForDeletion(Result);
  831. VerboseMsg(1, STemporaryFileCreated, [Result]);
  832. finally
  833. Preprocessor.Free;
  834. end;
  835. end
  836. else
  837. RaiseError(Format(SFileNotFound, [FileName]));
  838. end;
  839. procedure ParseFor(Parser: TParserAccess);
  840. var
  841. Condition, Action, Body: PChar;
  842. begin
  843. Parser.NextTokenExpect([tkOpenBrace]);
  844. Parser.Expr(False);
  845. Parser.NextTokenExpect([tkSemicolon]);
  846. { Skip condition and remember it }
  847. Condition := Parser.FExpr;
  848. Parser.Sequentional(False);
  849. Parser.NextTokenExpect([tkSemicolon]);
  850. Action := Parser.FExpr;
  851. Parser.Sequentional(False);
  852. Parser.NextTokenExpect([tkCloseBrace]);
  853. Body := Parser.FExpr;
  854. Parser.Sequentional(False);
  855. Parser.EndOfExpr;
  856. Parser.SetPos(Condition);
  857. while Parser.IntExpr(False) <> 0 do
  858. begin
  859. Parser.SetPos(Body);
  860. Parser.Sequentional(True);
  861. Parser.SetPos(Action);
  862. Parser.Sequentional(True);
  863. Parser.SetPos(Condition);
  864. end;
  865. end;
  866. procedure Glue(LineNo: Integer);
  867. begin
  868. if LineNo > FOutput.Count then
  869. RaiseError(Format(SInsertLineNoTooBig, [LineNo]));
  870. FInsertionPoint := LineNo;
  871. VerboseMsg(2, SChangingInsertionPointToLine, [FInsertionPoint]);
  872. end;
  873. procedure EndGlue;
  874. begin
  875. VerboseMsg(2, SResettingInsertionPoint, []);
  876. FInsertionPoint := -1;
  877. end;
  878. procedure BeginProcDecl(Parser: TParserAccess);
  879. var
  880. ProcName: string;
  881. begin
  882. if FInForBody or FInProcBody then
  883. RaiseError('Nested procedure declaration and compound loops not allowed');
  884. FInProcBody := True;
  885. Parser.NextTokenExpect([tkIdent]);
  886. ProcName := Parser.TokenString;
  887. Parser.EndOfExpr;
  888. FProcs.AddObject(ProcName, TStringList.Create);
  889. EmitDestination.Add('#define private');
  890. end;
  891. procedure EndProcDecl;
  892. begin
  893. if not FInProcBody then
  894. RaiseError('''endproc'' without ''procedure''');
  895. FInProcBody := False;
  896. end;
  897. var
  898. IfCondition: TIsppVariant;
  899. DummyContext: ICallContext;
  900. Parser: TParserAccess;
  901. begin
  902. Result := False;
  903. Parser := TParserAccess.Create(Self, Params, ParamsOffset, @FOptions.ParserOptions);
  904. with Parser do
  905. try
  906. case Command of
  907. pcError: RaiseError(SUnknownPreprocessorDirective);
  908. pcIf, pcElseIf:
  909. begin
  910. IfCondition := Evaluate;
  911. case IfCondition.Typ of
  912. evInt: Result := IfCondition.AsInt <> 0;
  913. evStr: Result := IfCondition.AsStr <> ''
  914. else
  915. WarningMsg(SSpecifiedConditionEvalatedToVoid, []);
  916. Result := False
  917. end;
  918. end;
  919. pcIfdef, pcIfndef:
  920. begin
  921. NextTokenExpect([tkIdent]);
  922. case GetIdent(TokenString, DummyContext) of
  923. itUnknown: Result := Command = pcIfNDef;
  924. itVariable, itMacro: Result := Command = pcIfDef;
  925. itFunc:
  926. begin
  927. Result := Command = pcIfDef;
  928. WarningMsg(SFuncIdentForIfdef, []);
  929. end;
  930. else
  931. begin
  932. Result := Command = pcIfNDef;
  933. WarningMsg(SSpecFuncIdentForIfdef, []);
  934. end;
  935. end;
  936. EndOfExpr;
  937. end;
  938. pcIfExist, pcIfNExist:
  939. Result := FileExists(PrependDirName(StrExpr(False), FSourcePath)) xor (Command = pcIfNExist);
  940. pcDefine: ParseDefine(Parser);
  941. pcDim: ParseDim(Parser, False);
  942. pcReDim: ParseDim(Parser, True);
  943. pcUndef: ParseUndef(Parser);
  944. pcInclude: IncludeFile(Params);
  945. pcErrorDir:
  946. begin
  947. { Also see ErrorFunc in IsppFuncs }
  948. if Params = '' then Params := 'Error';
  949. RaiseError(Params);
  950. end;
  951. pcPragma: Pragma(Parser);
  952. pcPrint: Params := ToStr(Evaluate).AsStr;
  953. pcPrintEnv:
  954. begin
  955. NextTokenExpect([tkIdent]);
  956. Params := GetEnv(TokenString);
  957. EndOfExpr;
  958. end;
  959. pcFile: Params := DoFile(StrExpr(False));
  960. pcExecute: Evaluate;
  961. pcGlue: Glue(IntExpr(False));
  962. pcEndGlue: EndGlue;
  963. pcFor: ParseFor(Parser);
  964. pcProcedure: BeginProcDecl(Parser);
  965. pcEndProc: EndProcDecl;
  966. else
  967. WarningMsg(SDirectiveNotYetSupported, [PreprocCommands[Command]])
  968. end;
  969. finally
  970. Free
  971. end;
  972. end;
  973. function TPreprocessor.InternalQueueLine(const LineRead: string;
  974. FileIndex, LineNo: Word; NonISS: Boolean): Integer; //how many just been added
  975. var
  976. L: Integer;
  977. begin
  978. L := Length(LineRead);
  979. if (L > 2) and (AnsiChar(LineRead[L]) = FOptions.SpanSymbol) and (LineRead[L - 1] <= #32) then
  980. begin
  981. FQueuedLine := FQueuedLine + TrimLeft(Copy(LineRead, 1, L - 1));
  982. Inc(FQueuedLineCount);
  983. Result := 0;
  984. end
  985. else
  986. if FQueuedLineCount > 0 then
  987. begin
  988. InternalAddLine(FQueuedLine + TrimLeft(LineRead), FileIndex, LineNo, NonISS);
  989. FQueuedLine := '';
  990. Result := FQueuedLineCount + 1;
  991. FQueuedLineCount := 0;
  992. end
  993. else
  994. begin
  995. InternalAddLine(LineRead, FileIndex, LineNo, NonISS);
  996. Result := 1;
  997. end;
  998. end;
  999. procedure TPreprocessor.QueueLine(const LineRead: string);
  1000. begin
  1001. Inc(FMainCounter, InternalQueueLine(LineRead, 0, FMainCounter, False));
  1002. end;
  1003. procedure TPreprocessor.RegisterFunction(const Name: string; Handler: TIsppFunction; Ext: Longint);
  1004. begin
  1005. FIdentManager.DefineFunction(Name, Handler, Ext);
  1006. end;
  1007. procedure TPreprocessor.SaveToFile(const FileName: string);
  1008. var
  1009. S: String;
  1010. begin
  1011. S := FOutput.Text;
  1012. if SameText(S, String(AnsiString(S))) then
  1013. FOutput.SaveToFile(FileName)
  1014. else
  1015. FOutput.SaveToFile(FileName, TEncoding.UTF8);
  1016. end;
  1017. function TPreprocessor.CheckFile(const FileName: string): Boolean;
  1018. begin
  1019. Result := FFileStack.IndexOf(ExpandFileName(FileName)) < 0;
  1020. end;
  1021. procedure TPreprocessor.PopFile;
  1022. begin
  1023. FFileStack.Delete(FFileStack.Count - 1);
  1024. end;
  1025. procedure TPreprocessor.PushFile(const FileName: string);
  1026. begin
  1027. FFileStack.AddObject(ExpandFileName(FileName), TObject(dsPublic));
  1028. end;
  1029. procedure TPreprocessor.VerboseMsg(Level: Byte; const Msg: string;
  1030. const Args: array of const);
  1031. begin
  1032. if (optVerbose in FOptions.Options) and (FOptions.VerboseLevel >= Level) then
  1033. StatusMsg(Msg, Args);
  1034. end;
  1035. procedure TPreprocessor.StatusMsg(const Msg: string; const Args: array of const);
  1036. begin
  1037. SendMsg(Format(Msg, Args), imtStatus);
  1038. end;
  1039. procedure TPreprocessor.WarningMsg(const Msg: string; const Args: array of const);
  1040. begin
  1041. SendMsg(Format(Msg, Args), imtWarning);
  1042. end;
  1043. procedure TPreprocessor.SendMsg(Msg: string; Typ: TIsppMessageType);
  1044. const
  1045. MsgPrefixes: array[TIsppMessageType] of string = ('', 'Warning: ');
  1046. var
  1047. LineNumber: Word;
  1048. FileName: String;
  1049. begin
  1050. Msg := MsgPrefixes[Typ] + Msg;
  1051. LineNumber := GetLineNumber(-1);
  1052. if LineNumber <> 0 then begin
  1053. FileName := GetFileName(-1);
  1054. if FileName <> '' then
  1055. Msg := Format('Line %d of %s: %s', [LineNumber, PathExtractName(FileName), Msg])
  1056. else
  1057. Msg := Format('Line %d: %s', [LineNumber, Msg]);
  1058. end;
  1059. FCompilerParams.StatusProc(FCompilerParams.CompilerData, PChar(Msg), Typ = imtWarning);
  1060. end;
  1061. function TPreprocessor.DimOf(const Name: String): Integer;
  1062. begin
  1063. Result := FIdentManager.DimOf(Name)
  1064. end;
  1065. function TPreprocessor.EmitDestination: TStringList;
  1066. begin
  1067. if FInProcBody then
  1068. Result := TStringList(FProcs.Objects[FProcs.Count - 1])
  1069. else
  1070. Result := FOutput;
  1071. end;
  1072. procedure TPreprocessor.ExecProc(Body: TStrings);
  1073. var
  1074. I: Integer;
  1075. begin
  1076. for I := 0 to Body.Count - 1 do
  1077. InternalAddLine(Body[I], Integer(Body.Objects[I]) shr 16,
  1078. Integer(Body.Objects[I]) and $FFFF - 1, False);
  1079. end;
  1080. { TConditionalTranslationStack }
  1081. constructor TConditionalTranslationStack.Create(Preproc: TPreprocessor);
  1082. begin
  1083. inherited Create;
  1084. FPreproc := Preproc;
  1085. FCache := True;
  1086. end;
  1087. procedure TConditionalTranslationStack.IfInstruction(Eval: Boolean);
  1088. var
  1089. A: TConditionalBlockInfo;
  1090. begin
  1091. A.BlockState := Eval;
  1092. A.Fired := Eval;
  1093. A.HadElse := False;
  1094. PushItem(Pointer(A));
  1095. FCacheValid := False;
  1096. VerboseMsg(cvmIf, Eval);
  1097. end;
  1098. procedure TConditionalTranslationStack.ElseIfInstruction(Eval: Boolean);
  1099. var
  1100. A: TConditionalBlockInfo;
  1101. begin
  1102. if AtLeast(1) then
  1103. begin
  1104. A := Last;
  1105. with A do
  1106. begin
  1107. if HadElse then FPreproc.RaiseError(SElifAfterElse);
  1108. BlockState := not Fired and Eval;
  1109. Fired := Fired or Eval;
  1110. FCacheValid := False;
  1111. end;
  1112. UpdateLast(A);
  1113. VerboseMsg(cvmElif, Eval);
  1114. end
  1115. else
  1116. FPreproc.RaiseError(SElseWithoutIf);
  1117. end;
  1118. procedure TConditionalTranslationStack.ElseInstruction;
  1119. var
  1120. A: TConditionalBlockInfo;
  1121. begin
  1122. if AtLeast(1) then
  1123. begin
  1124. A := Last;
  1125. with A do
  1126. begin
  1127. if HadElse then FPreproc.RaiseError(SDoubleElse);
  1128. BlockState := not Fired;
  1129. Fired := True;
  1130. HadElse := True;
  1131. FCacheValid := False;
  1132. end;
  1133. UpdateLast(A);
  1134. VerboseMsg(cvmElse, False);
  1135. end
  1136. else
  1137. FPreproc.RaiseError(SElseWithoutIf);
  1138. end;
  1139. procedure TConditionalTranslationStack.EndIfInstruction;
  1140. begin
  1141. if AtLeast(1) then
  1142. begin
  1143. PopItem;
  1144. FCacheValid := False;
  1145. VerboseMsg(cvmEndif, False);
  1146. end
  1147. else
  1148. FPreproc.RaiseError(SEndifWithoutIf);
  1149. end;
  1150. function TConditionalTranslationStack.Include: Boolean;
  1151. var
  1152. I: Integer;
  1153. begin
  1154. if FCacheValid then
  1155. Result := FCache
  1156. else
  1157. begin
  1158. FCacheValid := True;
  1159. if Count > 0 then
  1160. begin
  1161. Result := False;
  1162. FCache := False;
  1163. for I := Count - 1 downto 0 do
  1164. if not TConditionalBlockInfo(List[I]).BlockState then Exit;
  1165. end;
  1166. Result := True;
  1167. FCache := True;
  1168. end;
  1169. end;
  1170. procedure TConditionalTranslationStack.Resolved;
  1171. begin
  1172. if Count > 0 then FPreproc.RaiseError(SEndifExpected);
  1173. end;
  1174. function TConditionalTranslationStack.Last: TConditionalBlockInfo;
  1175. begin
  1176. Result := TConditionalBlockInfo(Longint(List.Last))
  1177. end;
  1178. procedure TConditionalTranslationStack.UpdateLast(
  1179. const Value: TConditionalBlockInfo);
  1180. begin
  1181. List.Items[List.Count - 1] := Pointer(Value)
  1182. end;
  1183. procedure TConditionalTranslationStack.VerboseMsg(
  1184. Msg: TConditionalVerboseMsg; Eval: Boolean);
  1185. const
  1186. B: array[Boolean] of string = ('false', 'true');
  1187. var
  1188. M: string;
  1189. begin
  1190. case Msg of
  1191. cvmIf: M := SStartingConditionalInclusionIf;
  1192. cvmElif: M := SUpdatingConditionalInclusionElif;
  1193. cvmElse: M := SUpdatingConditionalInclusionElse;
  1194. else
  1195. begin
  1196. FPreproc.VerboseMsg(6, SFinishedConditionalInclusion, []);
  1197. Exit;
  1198. end;
  1199. end;
  1200. FPreproc.VerboseMsg(6, M, []);
  1201. end;
  1202. { TPreprocessor }
  1203. function TPreprocessor._AddRef: Integer;
  1204. begin
  1205. Result := -1
  1206. end;
  1207. function TPreprocessor._Release: Integer;
  1208. begin
  1209. Result := -1;
  1210. end;
  1211. function TPreprocessor.QueryInterface(const IID: TGUID; out Obj): HRESULT;
  1212. begin
  1213. if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE
  1214. end;
  1215. procedure TPreprocessor.RaiseError(const Message: string);
  1216. begin
  1217. RaiseErrorEx(Message, 0);
  1218. end;
  1219. procedure TPreprocessor.RaiseErrorEx(const Message: string; Column: Integer);
  1220. var
  1221. E: EPreprocError;
  1222. begin
  1223. E := EPreprocError.Create(Self, Message);
  1224. E.ColumnNumber := Column;
  1225. raise E;
  1226. end;
  1227. { TPredefinedVarCallContext }
  1228. type
  1229. TPredefinedVarCallContext = class(TInterfacedObject, ICallContext)
  1230. private
  1231. FValue: TIsppVariant;
  1232. public
  1233. constructor Create(const Value: TIsppVariant);
  1234. procedure Add(const Name: String; const Value: TIsppVariant);
  1235. function Call: TIsppVariant; dynamic;
  1236. function GroupingStyle: TArgGroupingStyle;
  1237. procedure Clone(out NewCallContext: ICallContext);
  1238. end;
  1239. TCounterCallContext = class(TPredefinedVarCallContext)
  1240. private
  1241. FCounter: PInteger;
  1242. public
  1243. constructor Create(Counter: PInteger);
  1244. function Call: TIsppVariant; override;
  1245. end;
  1246. TProcCallContext = class(TInterfacedObject, ICallContext)
  1247. private
  1248. FPreproc: TPreprocessor;
  1249. FBody: TStrings;
  1250. FScopeUpdated: Boolean;
  1251. FIndex: Integer;
  1252. procedure UpdateScope;
  1253. public
  1254. constructor Create(Proprocessor: TPreprocessor; ProcBody: TStrings);
  1255. procedure Add(const Name: String; const Value: TIsppVariant);
  1256. function Call: TIsppVariant;
  1257. procedure Clone(out NewContext: ICallContext);
  1258. function GroupingStyle: TArgGroupingStyle;
  1259. end;
  1260. constructor TCounterCallContext.Create(Counter: PInteger);
  1261. begin
  1262. FCounter := Counter;
  1263. end;
  1264. function TCounterCallContext.Call: TIsppVariant;
  1265. begin
  1266. MakeInt(Result, FCounter^);
  1267. Inc(FCounter^);
  1268. end;
  1269. constructor TPredefinedVarCallContext.Create(const Value: TIsppVariant);
  1270. begin
  1271. FValue := Value;
  1272. end;
  1273. procedure TPredefinedVarCallContext.Add(const Name: String;
  1274. const Value: TIsppVariant);
  1275. begin
  1276. raise EIdentError.Create(SParameterlessVariable);
  1277. end;
  1278. function TPredefinedVarCallContext.Call: TIsppVariant;
  1279. begin
  1280. Result := FValue;
  1281. end;
  1282. function TPredefinedVarCallContext.GroupingStyle: TArgGroupingStyle;
  1283. begin
  1284. Result := agsNone;
  1285. end;
  1286. { IIdentManager }
  1287. function LookupAlwaysDefined(const Name: string): Boolean;
  1288. const
  1289. AlwaysDefined: array[0..3] of string =
  1290. ('ISPP_INVOKED', 'WINDOWS', '__WIN32__', 'UNICODE');
  1291. var
  1292. I: Integer;
  1293. begin
  1294. Result := True;
  1295. for I := Low(AlwaysDefined) to High(AlwaysDefined) do
  1296. if CompareText(AlwaysDefined[I], Name) = 0 then Exit;
  1297. Result := False;
  1298. end;
  1299. const
  1300. SCounter = '__COUNTER__';
  1301. function TPreprocessor.Defined(const Name: String): Boolean;
  1302. begin
  1303. Result := LookupAlwaysDefined(Name) or LookupPredefined(Name, nil) or
  1304. (CompareText(Name, SCounter) = 0) or FIdentManager.Defined(Name);
  1305. end;
  1306. function TPreprocessor.GetIdent(const Name: String;
  1307. out CallContext: ICallContext): TIdentType;
  1308. var
  1309. V: TIsppVariant;
  1310. I: Integer;
  1311. begin
  1312. Result := itVariable;
  1313. I := FProcs.IndexOf(Name);
  1314. if I >= 0 then
  1315. begin
  1316. Result := itFunc;
  1317. CallContext := TProcCallContext.Create(Self, TStrings(FProcs.Objects[I]));
  1318. end
  1319. else
  1320. if LookupAlwaysDefined(Name) then
  1321. CallContext := TPredefinedVarCallContext.Create(NULL)
  1322. else
  1323. if LookupPredefined(Name, @V) then
  1324. CallContext := TPredefinedVarCallContext.Create(V)
  1325. else
  1326. if CompareText(Name, SCounter) = 0 then
  1327. CallContext := TCounterCallContext.Create(@FCounter)
  1328. else
  1329. Result := FIdentManager.GetIdent(Name, CallContext)
  1330. end;
  1331. function TPreprocessor.TypeOf(const Name: String): Byte;
  1332. var
  1333. V: TIsppVariant;
  1334. begin
  1335. if LookupAlwaysDefined(Name) then
  1336. Result := TYPE_NULL
  1337. else
  1338. if LookupPredefined(Name, @V) then
  1339. case V.Typ of
  1340. evInt: Result := TYPE_INTEGER;
  1341. evStr: Result := TYPE_STRING
  1342. else
  1343. Result := TYPE_NULL
  1344. end
  1345. else
  1346. if CompareText(Name, SCounter) = 0 then
  1347. Result := TYPE_INTEGER
  1348. else
  1349. Result := FIdentManager.TypeOf(Name)
  1350. end;
  1351. function TPreprocessor.LookupPredefined(Name: string;
  1352. Value: PIsppVariant): Boolean;
  1353. begin
  1354. Result := True;
  1355. Name := UpperCase(Name);
  1356. if Name = '__FILE__' then
  1357. begin
  1358. if Value <> nil then MakeStr(Value^, ExtractFileName(FIncludes[FCurrentFile]))
  1359. end
  1360. else if Name = '__PATHFILENAME__' then
  1361. begin
  1362. if Value <> nil then MakeStr(Value^, FIncludes[FCurrentFile])
  1363. end
  1364. else if Name = '__LINE__' then
  1365. begin
  1366. if Value <> nil then MakeInt(Value^, FCurrentLine)
  1367. end
  1368. else if Name = 'PREPROCVER' then
  1369. begin
  1370. if Value <> nil then MakeInt(Value^, SetupBinVersion)
  1371. end
  1372. else if Name = '__INCLUDE__' then
  1373. begin
  1374. if Value <> nil then MakeStr(Value^, FIncludePath);
  1375. end
  1376. else if (Length(Name) = 9) and (Copy(Name, 1, 6) = '__OPT_') and
  1377. (Copy(Name, 8, 2) = '__') then
  1378. begin
  1379. if Value <> nil then Value^ := NULL;
  1380. Result := GetOption(FOptions.Options, Name[7]);
  1381. end
  1382. else if (Length(Name) = 10) and (Copy(Name, 1, 7) = '__POPT_') and
  1383. (Copy(Name, 9, 2) = '__') then
  1384. begin
  1385. if Value <> nil then Value^ := NULL;
  1386. Result := GetOption(FOptions.ParserOptions.Options, Name[8]);
  1387. end
  1388. else
  1389. Result := False;
  1390. end;
  1391. procedure TPredefinedVarCallContext.Clone(
  1392. out NewCallContext: ICallContext);
  1393. begin
  1394. NewCallContext := Self
  1395. end;
  1396. procedure TPreprocessor.CollectGarbage(Item: Pointer;
  1397. Proc: TDropGarbageProc);
  1398. begin
  1399. if (Item = nil) or (@Proc = nil) then Exit;
  1400. if FGarbageCollection = nil then
  1401. FGarbageCollection := TList.Create;
  1402. FGarbageCollection.Add(Item);
  1403. FGarbageCollection.Add(@Proc);
  1404. end;
  1405. procedure TPreprocessor.UncollectGarbage(Item: Pointer);
  1406. var
  1407. I: Integer;
  1408. begin
  1409. if FGarbageCollection = nil then Exit;
  1410. for I := 0 to FGarbageCollection.Count div 2 - 1 do
  1411. if FGarbageCollection.Items[I * 2] = Item then
  1412. begin
  1413. FGarbageCollection.Items[I * 2] := nil;
  1414. FGarbageCollection.Items[I * 2 + 1] := nil;
  1415. end;
  1416. FGarbageCollection.Pack;
  1417. if FGarbageCollection.Count = 0 then FreeAndNil(FGarbageCollection);
  1418. end;
  1419. procedure TPreprocessor.DropGarbage;
  1420. var
  1421. I: Integer;
  1422. Proc: TDropGarbageProc;
  1423. Item: Pointer;
  1424. begin
  1425. if FGarbageCollection <> nil then
  1426. try
  1427. for I := 0 to FGarbageCollection.Count div 2 - 1 do
  1428. begin
  1429. Item := FGarbageCollection.Items[I * 2];
  1430. Proc := FGarbageCollection.Items[I * 2 + 1];
  1431. try
  1432. if @Proc <> nil then
  1433. try
  1434. Proc(Item);
  1435. except
  1436. end
  1437. else
  1438. if Item <> nil then
  1439. begin
  1440. try
  1441. TObject(Item).Free
  1442. except
  1443. try Dispose(Item) except end;
  1444. end;
  1445. end;
  1446. finally
  1447. FGarbageCollection.Items[I * 2] := nil;
  1448. FGarbageCollection.Items[I * 2 + 1] := nil;
  1449. end;
  1450. end;
  1451. finally
  1452. FreeAndNil(FGarbageCollection);
  1453. end;
  1454. end;
  1455. function TPreprocessor.PrependDirName(const FileName, Dir: string): string;
  1456. var
  1457. P: PChar;
  1458. begin
  1459. P := FCompilerParams.PrependDirNameProc(FCompilerParams.CompilerData,
  1460. PChar(FileName), PChar(Dir), PChar(GetFileName(-1)), GetLineNumber(-1), 0);
  1461. if P = nil then
  1462. RaiseError('PrependDirNameProc failed');
  1463. Result := P;
  1464. end;
  1465. procedure TPreprocessor.IncludeFile(FileName: string;
  1466. Builtins, UseIncludePathOnly, ResetCurrentFile: Boolean);
  1467. function IsDotRelativePath(const Filename: String): Boolean;
  1468. begin
  1469. { Check for '.\' and '..\' }
  1470. if (Length(Filename) >= 2) and (Filename[1] = '.') and PathCharIsSlash(Filename[2]) then
  1471. Result := True
  1472. else if (Length(Filename) >= 3) and (Filename[1] = '.') and (Filename[2] = '.') and
  1473. PathCharIsSlash(Filename[3]) then
  1474. Result := True
  1475. else
  1476. Result := False;
  1477. end;
  1478. procedure AddToPath(var Path: string; const Dir: string);
  1479. begin
  1480. if (Dir <> '') and (Pos(';' + Dir + ';', ';' + Path + ';') = 0) then
  1481. begin
  1482. if Path <> '' then Path := Path + ';';
  1483. Path := Path + Dir;
  1484. end;
  1485. end;
  1486. function RemoveSlash(const S: string): string;
  1487. begin
  1488. Result := S;
  1489. if (Length(Result) > 3) and (Result[Length(Result)] = '\') then
  1490. Delete(Result, Length(Result), 1);
  1491. end;
  1492. function DoSearch(const SearchDirs: String): String;
  1493. var
  1494. FilePart: PChar;
  1495. begin
  1496. SetLength(Result, MAX_PATH);
  1497. SetLength(Result, SearchPath(PChar(SearchDirs), PChar(FileName), nil, MAX_PATH,
  1498. PChar(Result), FilePart));
  1499. end;
  1500. var
  1501. CurPath, SearchDirs, FullFileName: String;
  1502. FileHandle: TPreprocFileHandle;
  1503. I, FileIndex: Integer;
  1504. J: Word;
  1505. LineText: PChar;
  1506. LineTextStr: string;
  1507. begin
  1508. if ResetCurrentFile then begin
  1509. FCurrentFile := 0;
  1510. FCurrentLine := 0;
  1511. end;
  1512. { Expand any prefix on the filename (e.g. 'compiler:') }
  1513. FileName := PrependDirName(FileName, '');
  1514. if IsDotRelativePath(FileName) then
  1515. begin
  1516. { Make filenames beginning with '.\' and '..\' relative to the directory
  1517. containing the current file }
  1518. CurPath := PathExtractPath(FIncludes[FCurrentFile]);
  1519. if CurPath = '' then
  1520. CurPath := FSourcePath;
  1521. FileName := PathCombine(CurPath, FileName);
  1522. end
  1523. else if not PathIsRooted(FileName) then
  1524. begin
  1525. if not UseIncludePathOnly then
  1526. begin
  1527. for I := FFileStack.Count - 1 downto 0 do
  1528. AddToPath(SearchDirs, ExtractFileDir(FFileStack[I]));
  1529. if FIncludes[0] <> '' then
  1530. AddToPath(SearchDirs, ExtractFileDir(FIncludes[0]));
  1531. AddToPath(SearchDirs, RemoveSlash(FSourcePath));
  1532. end;
  1533. AddToPath(SearchDirs, FIncludePath);
  1534. AddToPath(SearchDirs, GetEnv('INCLUDE'));
  1535. if not UseIncludePathOnly then
  1536. AddToPath(SearchDirs, RemoveSlash(FCompilerPath));
  1537. end;
  1538. FullFileName := DoSearch(SearchDirs);
  1539. if FullFileName <> '' then
  1540. begin
  1541. if not CheckFile(FullFileName) then
  1542. RaiseError(Format(SFileIsAlreadyBeingIncluded, [FullFileName]));
  1543. if not Builtins then
  1544. StatusMsg(SIncludingFile, [FullFileName]);
  1545. PushFile(FullFileName);
  1546. try
  1547. FileHandle := FCompilerParams.LoadFileProc(FCompilerParams.CompilerData,
  1548. PChar(FullFileName), PChar(GetFileName(-1)), GetLineNumber(-1), 0);
  1549. if FileHandle < 0 then
  1550. RaiseError('LoadFileProc failed');
  1551. FileIndex := FIncludes.Add(FullFileName);
  1552. FIdentManager.BeginLocal;
  1553. try
  1554. I := 0;
  1555. J := 0;
  1556. while True do
  1557. begin
  1558. LineText := FCompilerParams.LineInProc(FCompilerParams.CompilerData,
  1559. FileHandle, I);
  1560. if LineText = nil then
  1561. Break;
  1562. LineTextStr := LineText;
  1563. Inc(J, InternalQueueLine(LineTextStr, FileIndex, J, False));
  1564. Inc(I);
  1565. end;
  1566. finally
  1567. FIdentManager.EndLocal
  1568. end;
  1569. finally
  1570. PopFile;
  1571. end;
  1572. end
  1573. else
  1574. RaiseError(Format(SFileNotFound, [FileName]));
  1575. end;
  1576. // ParseFormalParams
  1577. // Parser must be behind the opening parenthesis
  1578. function TPreprocessor.ParseFormalParams(Parser: TParser;
  1579. var ParamList: PParamList): Integer;
  1580. var
  1581. Param: TIsppMacroParam;
  1582. Ident: string;
  1583. procedure Grow;
  1584. var
  1585. OldCapacity, NewCapacity: Integer;
  1586. begin
  1587. OldCapacity := ((Result div 4) * 4) * SizeOf(TIsppMacroParam);
  1588. NewCapacity := ((Result div 4 + 1) * 4);
  1589. if NewCapacity > High(Byte) then RaiseError(STooManyFormalParams);
  1590. NewCapacity := NewCapacity * SizeOf(TIsppMacroParam);
  1591. ReallocMem(ParamList, NewCapacity);
  1592. { Initilizing to zeroes is required to prevent compiler's attempts to
  1593. finilize not existing strings }
  1594. FillChar(ParamList^[Result], NewCapacity - OldCapacity, 0)
  1595. end;
  1596. begin
  1597. with Parser do
  1598. begin
  1599. Result := 0;
  1600. ParamList := AllocMem(SizeOf(TIsppMacroParam) * 4);
  1601. while not (PeekAtNextToken in [tkEOF, tkCloseParen]) do
  1602. begin
  1603. Param.Name := '';
  1604. Param.DefValue.AsStr := '';
  1605. FillChar(Param, SizeOf(Param), 0);
  1606. Param.ParamFlags := [];
  1607. if NextTokenExpect([tkIdent, opMul]) = tkIdent then
  1608. begin
  1609. Ident := TokenString;
  1610. if not (PeekAtNextToken in [tkEOF, tkComma, tkCloseParen, opAssign]) then
  1611. begin
  1612. Ident := UpperCase(Ident);
  1613. if Ident = sAny then {do nothing }
  1614. else if Ident = sInt then Param.DefValue.Typ := evInt
  1615. else if Ident = sStr then Param.DefValue.Typ := evStr
  1616. else if Ident = 'FUNC' then
  1617. begin
  1618. Param.DefValue.Typ := evCallContext;
  1619. Include(Param.ParamFlags, pfFunc)
  1620. end
  1621. else if Ident = 'ARRAY' then Param.DefValue.Typ := evCallContext
  1622. else RaiseError(Format(SInvalidTypeId, [Ident]));
  1623. if Param.DefValue.Typ <> evSpecial then
  1624. Include(Param.ParamFlags, pfTypeDefined);
  1625. if NextTokenExpect([tkIdent, opMul]) = opMul then
  1626. begin
  1627. Include(Param.ParamFlags, pfByRef);
  1628. NextTokenExpect([tkIdent]);
  1629. end;
  1630. end;
  1631. end
  1632. else
  1633. begin
  1634. Include(Param.ParamFlags, pfByRef);
  1635. NextTokenExpect([tkIdent]);
  1636. end;
  1637. Ident := TokenString;
  1638. Param.Name := CheckReservedIdent(Ident);
  1639. if PeekAtNextToken = opAssign then
  1640. begin
  1641. if pfByRef in Param.ParamFlags then
  1642. RaiseError(SByRefNoDefault);
  1643. NextToken;
  1644. case Param.DefValue.Typ of
  1645. evSpecial: Param.DefValue := GetRValue(Expr(True));
  1646. evInt: Param.DefValue.AsInt := IntExpr(True);
  1647. evStr: Param.DefValue.AsStr := StrExpr(True);
  1648. end;
  1649. Include(Param.ParamFlags, pfHasDefault);
  1650. end;
  1651. ParamList^[Result] := Param;
  1652. Inc(Result);
  1653. if Result mod 4 = 0 then
  1654. Grow;
  1655. if NextTokenExpect([tkComma, tkCloseParen]) = tkCloseParen then Break;
  1656. end;
  1657. end;
  1658. end;
  1659. { TProcCallContext }
  1660. procedure TProcCallContext.Add(const Name: String;
  1661. const Value: TIsppVariant);
  1662. begin
  1663. UpdateScope;
  1664. if Name <> '' then
  1665. FPreproc.FIdentManager.DefineVariable(Name, -1, Value, dsPrivate);
  1666. FPreproc.FIdentManager.DefineVariable(SLocal, FIndex, Value, dsPrivate);
  1667. Inc(FIndex);
  1668. end;
  1669. function TProcCallContext.Call: TIsppVariant;
  1670. begin
  1671. UpdateScope;
  1672. try
  1673. FPreproc.ExecProc(FBody);
  1674. finally
  1675. FPreproc.FIdentManager.EndLocal
  1676. end;
  1677. end;
  1678. procedure TProcCallContext.Clone(out NewContext: ICallContext);
  1679. begin
  1680. NewContext := TProcCallContext.Create(FPreproc, FBody);
  1681. end;
  1682. constructor TProcCallContext.Create(Proprocessor: TPreprocessor;
  1683. ProcBody: TStrings);
  1684. begin
  1685. FPreproc := Proprocessor;
  1686. FBody := ProcBody
  1687. end;
  1688. function TProcCallContext.GroupingStyle: TArgGroupingStyle;
  1689. begin
  1690. Result := agsParenteses;
  1691. end;
  1692. procedure TProcCallContext.UpdateScope;
  1693. var
  1694. ReDim: Boolean;
  1695. begin
  1696. if not FScopeUpdated then
  1697. begin
  1698. FPreproc.FIdentManager.BeginLocal;
  1699. ReDim := False;
  1700. FPreproc.FIdentManager.DimVariable(SLocal, 16, dsPrivate, ReDim);
  1701. FScopeUpdated := True;
  1702. end;
  1703. end;
  1704. end.