diff --git a/Source/InvokeCall.inc b/Source/InvokeCall.inc index e84f9d3d..8e41f34f 100644 --- a/Source/InvokeCall.inc +++ b/Source/InvokeCall.inc @@ -374,7 +374,7 @@ begin end; { case } end; -function TPSExec.InnerfuseCall(_Self, Address: Pointer; CallingConv: TPSCallingConvention; Params: TPSList; res: PPSVariantIFC): Boolean; +function TPSExec.PlatformInnerfuseCall(_Self, Address: Pointer; CallingConv: TPSCallingConvention; Params: TPSList; res: PPSVariantIFC): Boolean; var SysCalConv : TCallConv; Args: TArray; old_Args: TArray; @@ -458,9 +458,9 @@ begin //5,6 btU32, btS32: PCardinal(res.dta)^ := Cardinal(Invoke(Address,Args,SysCalConv,TypeInfo(Cardinal),IsStatic).AsInteger); //7 - btSingle: PSingle(res.dta)^ := Single(Invoke(Address,Args,SysCalConv,TypeInfo(Single),IsStatic).AsExtended); + btSingle: PSingle(res.dta)^ := Invoke(Address,Args,SysCalConv,TypeInfo(Single),IsStatic).AsExtended; //8 - btDouble: PDouble(res.dta)^ := Double(Invoke(Address,Args,SysCalConv,TypeInfo(Double),IsStatic).AsExtended); + btDouble: PDouble(res.dta)^ := Invoke(Address,Args,SysCalConv,TypeInfo(Double),IsStatic).AsExtended; //9 btExtended: PExtended(res.dta)^ := Extended(Invoke(Address,Args,SysCalConv,TypeInfo(Extended),IsStatic).AsExtended); //10 diff --git a/Source/PascalScript.inc b/Source/PascalScript.inc index 6ed5c1b8..e12e486c 100644 --- a/Source/PascalScript.inc +++ b/Source/PascalScript.inc @@ -65,7 +65,9 @@ Defines: {$I PascalScriptFPC.inc} {$ENDIF} -{$IFDEF DELPHI2005UP} +{ Delphi 2005 and 2006 stop with an internal error on a class derived directly from one that a run-time + library unit the declaring unit uses has a class helper for, so they take the procedure form, as Delphi 7 does } +{$IFDEF DELPHI2007UP} {$DEFINE class_helper_present} {$ENDIF} {$IFDEF FPC} diff --git a/Source/PascalScriptFPC.inc b/Source/PascalScriptFPC.inc index 269a9d28..e93918bf 100644 --- a/Source/PascalScriptFPC.inc +++ b/Source/PascalScriptFPC.inc @@ -36,3 +36,8 @@ {$ifend} {$DEFINE DELPHI3UP} {$DEFINE DELPHI6UP} + { fcl-db declares TObjectField, TArrayField, TField.ParentField, TFieldDefs.ParentDef, + TDataSet.SparseArrays and TFieldDef's child definitions from Free Pascal 3.2.4 on } + {$IF FPC_FULLVERSION < 30204} + {$DEFINE PS_FCLDB_NO_OBJECT_FIELD} + {$IFEND} diff --git a/Source/arm.inc b/Source/arm.inc index 454a74a2..e796368f 100644 --- a/Source/arm.inc +++ b/Source/arm.inc @@ -147,7 +147,7 @@ asmcall_end: ldmea r11,{r4,r5,r6,r7,r8,r9,r10,r11,r13,r15} end; -function TPSExec.InnerfuseCall(_Self, Address: Pointer; CallingConv: TPSCallingConvention; Params: TPSList; res: PPSVariantIFC): Boolean; +function TPSExec.PlatformInnerfuseCall(_Self, Address: Pointer; CallingConv: TPSCallingConvention; Params: TPSList; res: PPSVariantIFC): Boolean; var rint: Trint; { registers r0 to r3 } rfloat: Trfloat; { registers f0 to f3 } diff --git a/Source/arm64.inc b/Source/arm64.inc index dbcde3b3..1f97475d 100644 --- a/Source/arm64.inc +++ b/Source/arm64.inc @@ -50,7 +50,7 @@ procedure arm64call( Stack: Pointer; Items: NativeInt); external {$IFDEF DARWIN}name '_arm64call'{$ENDIF}; -function TPSExec.InnerfuseCall(_Self, Address: Pointer; CallingConv: TPSCallingConvention; Params: TPSList; res: PPSVariantIFC): Boolean; +function TPSExec.PlatformInnerfuseCall(_Self, Address: Pointer; CallingConv: TPSCallingConvention; Params: TPSList; res: PPSVariantIFC): Boolean; var Stack: array of Byte; _X0: IPointer; @@ -155,7 +155,7 @@ var begin if Copy(fvar.aType.ExportName, 1, 10) = '!OPENARRAY' then begin - p := CreateOpenArray(True, Self, FVar); + p := CreateOpenArray(True, Self, FVar, CallData); if p = nil then Exit; CallData.Add(p); @@ -191,7 +191,7 @@ var begin if Copy(fvar^.aType.ExportName, 1, 10) = '!OPENARRAY' then begin - p := CreateOpenArray(False, Self, FVar); + p := CreateOpenArray(False, Self, FVar, CallData); if p = nil then Exit; CallData.Add(p); @@ -274,7 +274,7 @@ begin IsConstructor := False; {$ENDIF} - InnerfuseCall := False; + PlatformInnerfuseCall := False; if Address = nil then Exit; diff --git a/Source/powerpc.inc b/Source/powerpc.inc index 1e54e42b..e3353650 100644 --- a/Source/powerpc.inc +++ b/Source/powerpc.inc @@ -189,7 +189,7 @@ begin end; end; -function TPSExec.InnerfuseCall(_Self, Address: Pointer; CallingConv: TPSCallingConvention; Params: TPSList; res: PPSVariantIFC): Boolean; +function TPSExec.PlatformInnerfuseCall(_Self, Address: Pointer; CallingConv: TPSCallingConvention; Params: TPSList; res: PPSVariantIFC): Boolean; var rint: Trint; { registers r3 to r10 } rfloat: Trfloat; { registers f1 to f13 } diff --git a/Source/uPSC_controls.pas b/Source/uPSC_controls.pas index ec30e41c..00ed6224 100644 --- a/Source/uPSC_controls.pas +++ b/Source/uPSC_controls.pas @@ -59,7 +59,7 @@ procedure SIRegisterTControl(Cl: TPSPascalCompiler); {$IFDEF DELPHI23UP} RegisterProperty('StyleElements', 'TStyleElements', iptrw); {$ENDIF} - {$IFDEF DELPHI26UP} + {$IFDEF DELPHI27UP} RegisterProperty('StyleName', 'string', iptrw); {$ENDIF} @@ -141,10 +141,16 @@ procedure SIRegisterTCustomControl(cl: TPSPascalCompiler); // requires TWinContr procedure SIRegister_Controls_TypesAndConsts(Cl: TPSPascalCompiler); begin {$IFNDEF FPC} + {$IFDEF DELPHI2010UP} + Cl.addTypeS('TEShiftState','(ssShift, ssAlt, ssCtrl, ssLeft, ssRight, ssMiddle, ssDouble, ssTouch, ssPen)'); + {$ELSE} Cl.addTypeS('TEShiftState','(ssShift, ssAlt, ssCtrl, ssLeft, ssRight, ssMiddle, ssDouble)'); + {$ENDIF} {$ELSE} Cl.addTypeS('TEShiftState','(ssShift, ssAlt, ssCtrl, ssLeft, ssRight, ssMiddle, ssDouble,' + - 'ssMeta, ssSuper, ssHyper, ssAltGr, ssCaps, ssNum,ssScroll,ssTriple,ssQuad)'); + 'ssMeta, ssSuper, ssHyper, ssAltGr, ssCaps, ssNum,ssScroll,ssTriple,ssQuad,ssExtra1,ssExtra2' + {$IF defined(FPC_FULLVERSION) and (FPC_FULLVERSION >= 30204)} + ',ssTouch,ssPen,ssHorizontal'{$IFEND} + + ')'); {$ENDIF} Cl.addTypeS('TShiftState','set of TEShiftState'); cl.AddTypeS('TMouseButton', '(mbLeft, mbRight, mbMiddle)'); @@ -170,7 +176,7 @@ procedure SIRegister_Controls_TypesAndConsts(Cl: TPSPascalCompiler); cl.AddTypeS('TEndDragEvent', 'procedure(Sender, Target: TObject; X, Y: Integer)'); - cl.addTypeS('TAlign', '(alNone, alTop, alBottom, alLeft, alRight, alClient)'); + cl.addTypeS('TAlign', '(alNone, alTop, alBottom, alLeft, alRight, alClient, alCustom)'); {$IFDEF DELPHI23UP} cl.addTypeS('TStyleElement', '(seFont, seClient, seBorder)'); @@ -197,9 +203,10 @@ procedure SIRegister_Controls_TypesAndConsts(Cl: TPSPascalCompiler); cl.AddConstantN('mrIgnore', 'Integer').Value.ts32 := 5; cl.AddConstantN('mrYes', 'Integer').Value.ts32 := 6; cl.AddConstantN('mrNo', 'Integer').Value.ts32 := 7; - cl.AddConstantN('mrAll', 'Integer').Value.ts32 := 8; - cl.AddConstantN('mrNoToAll', 'Integer').Value.ts32 := 9; - cl.AddConstantN('mrYesToAll', 'Integer').Value.ts32 := 10; + { Delphi XE2 moved these three past mrClose, mrHelp, mrTryAgain and mrContinue } + cl.AddConstantN('mrAll', 'Integer').Value.ts32 := {$IFDEF DELPHI16UP}12{$ELSE}8{$ENDIF}; + cl.AddConstantN('mrNoToAll', 'Integer').Value.ts32 := {$IFDEF DELPHI16UP}13{$ELSE}9{$ENDIF}; + cl.AddConstantN('mrYesToAll', 'Integer').Value.ts32 := {$IFDEF DELPHI16UP}14{$ELSE}10{$ENDIF}; cl.AddConstantN('crDefault', 'Integer').Value.ts32 := 0; cl.AddConstantN('crNone', 'Integer').Value.ts32 := -1; cl.AddConstantN('crArrow', 'Integer').Value.ts32 := -2; @@ -262,12 +269,21 @@ procedure SIRegisterTDragObject(cl: TPSPascalCompiler); procedure SIRegisterTSizeConstraints(cl: TPSPascalCompiler); begin cl.AddTypeS('TConstraintSize', 'Integer'); + {$IFNDEF FPC} + { its constructor names TControl, which the library registers later: declared + here without its ancestor until then } + if cl.FindClass('TControl') = nil then + cl.AddClassN(nil, 'TControl'); + {$ENDIF} with CL.AddClassN(CL.FindClass('TPersistent'),'TSizeConstraints') do begin RegisterProperty('MaxHeight', 'TConstraintSize', iptrw); RegisterProperty('MaxWidth', 'TConstraintSize', iptrw); RegisterProperty('MinHeight', 'TConstraintSize', iptrw); RegisterProperty('MinWidth', 'TConstraintSize', iptrw); + {$IFNDEF FPC} + RegisterMethod('constructor Create(Control: TControl); virtual;'); + {$ENDIF} end; end; {$ENDIF} diff --git a/Source/uPSC_forms.pas b/Source/uPSC_forms.pas index 3d7f1ef4..2affad05 100644 --- a/Source/uPSC_forms.pas +++ b/Source/uPSC_forms.pas @@ -102,6 +102,16 @@ procedure SIRegisterTFORM(Cl: TPSPascalCompiler); RegisterMethod('function ShowModal: Integer'); RegisterMethod('procedure Release'); RegisterProperty('Active', 'Boolean', iptr); + {$IFNDEF FPC} + { TCustomForm declares Visible, ClientWidth and ClientHeight again with + setters of its own, and newer Delphi versions Left and Top too: + declared on TForm, a script's access reaches the form's property } + RegisterProperty('Left', 'Integer', iptrw); + RegisterProperty('Top', 'Integer', iptrw); + RegisterProperty('ClientWidth', 'LongInt', iptrw); + RegisterProperty('ClientHeight', 'LongInt', iptrw); + RegisterProperty('Visible', 'Boolean', iptrw); + {$ENDIF} RegisterProperty('ActiveControl', 'TWinControl', iptrw); {$IFDEF DELPHI4UP} RegisterProperty('Anchors', 'TAnchors', iptrw); @@ -264,10 +274,14 @@ procedure SIRegisterTAPPLICATION(Cl: TPSPascalCompiler); procedure SIRegister_Forms_TypesAndConsts(Cl: TPSPascalCompiler); begin Cl.AddTypeS('TIdleEvent', 'procedure (Sender: TObject; var Done: Boolean)'); - cl.AddTypeS('TScrollBarKind', '(sbHorizontal, sbVertical)'); - cl.AddTypeS('TScrollBarInc', 'SmallInt'); - cl.AddTypeS('TFormBorderStyle', '(bsNone, bsSingle, bsSizeable, bsDialog, bsToolWindow, bsSizeToolWin)'); - cl.AddTypeS('TBorderStyle', 'TFormBorderStyle'); + if cl.FindType('TScrollBarKind') = nil then + cl.AddTypeS('TScrollBarKind', '(sbHorizontal, sbVertical)'); + if cl.FindType('TScrollBarInc') = nil then + cl.AddTypeS('TScrollBarInc', 'SmallInt'); + if cl.FindType('TFormBorderStyle') = nil then + cl.AddTypeS('TFormBorderStyle', '(bsNone, bsSingle, bsSizeable, bsDialog, bsToolWindow, bsSizeToolWin)'); + if cl.FindType('TBorderStyle') = nil then + cl.AddTypeS('TBorderStyle', 'TFormBorderStyle'); cl.AddTypeS('TWindowState', '(wsNormal, wsMinimized, wsMaximized)'); cl.AddTypeS('TFormStyle', '(fsNormal, fsMDIChild, fsMDIForm, fsStayOnTop)'); {$IFDEF DELPHI_SEATTLE_UP} @@ -280,7 +294,8 @@ procedure SIRegister_Forms_TypesAndConsts(Cl: TPSPascalCompiler); cl.AddTypeS('TCloseQueryEvent' ,'procedure(Sender: TObject; var CanClose: Boolean)'); cl.AddTypeS('TBorderIcon' ,'(biSystemMenu, biMinimize, biMaximize, biHelp)'); cl.AddTypeS('TBorderIcons', 'set of TBorderIcon'); - cl.AddTypeS('THelpContext', 'LongInt'); + if cl.FindType('THelpContext') = nil then + cl.AddTypeS('THelpContext', 'LongInt'); {$IFNDEF CLX} if cl.FindType('HWND') = nil then cl.AddTypeS('HWND', 'NativeUInt'); diff --git a/Source/uPSC_graphics.pas b/Source/uPSC_graphics.pas index 6f1288f8..c26bd0ae 100644 --- a/Source/uPSC_graphics.pas +++ b/Source/uPSC_graphics.pas @@ -63,6 +63,9 @@ procedure SIRegisterTCanvas(cl: TPSPascalCompiler); // requires TPersistent begin with Cl.AddClassN(cl.FindClass('TPersistent'), 'TCanvas') do begin + {$IFNDEF FPC} + RegisterMethod('constructor Create'); + {$ENDIF} RegisterMethod('procedure Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer);'); RegisterMethod('procedure Chord(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer);'); RegisterMethod('procedure Draw(X, Y: Integer; Graphic: TGraphic);'); @@ -199,7 +202,11 @@ procedure SIRegister_Graphics_TypesAndConsts(Cl: TPSPascalCompiler); Cl.addTypeS('TFontStyles', 'set of TFontStyle'); cl.AddTypeS('TFontPitch', '(fpDefault, fpVariable, fpFixed)'); + {$IFDEF DELPHI2006UP} + cl.AddTypeS('TPenStyle', '(psSolid, psDash, psDot, psDashDot, psDashDotDot, psClear, psInsideFrame, psUserStyle, psAlternate)'); + {$ELSE} cl.AddTypeS('TPenStyle', '(psSolid, psDash, psDot, psDashDot, psDashDotDot, psClear, psInsideFrame)'); + {$ENDIF} cl.AddTypeS('TPenMode', '(pmBlack, pmWhite, pmNop, pmNot, pmCopy, pmNotCopy, pmMergePenNot, pmMaskPenNot, pmMergeNotPen, pmMaskNotPen, pmMerge, pmNotMerge, pmMask, pmNotMask, pmXor, pmNotXor)'); cl.AddTypeS('TBrushStyle', '(bsSolid, bsClear, bsHorizontal, bsVertical, bsFDiagonal, bsBDiagonal, bsCross, bsDiagCross)'); cl.addTypeS('TColor', 'Integer'); diff --git a/Source/uPSC_menus.pas b/Source/uPSC_menus.pas index 14d231c9..ae04aa62 100644 --- a/Source/uPSC_menus.pas +++ b/Source/uPSC_menus.pas @@ -32,19 +32,42 @@ procedure SIRegisterTPOPUPLIST(CL: TPSPascalCompiler); end; end; -procedure SIRegisterTPOPUPMENU(CL: TPSPascalCompiler); +{ The members naming a menu type of the classes registered before it: their own + declaration names a type the compiler did not hold yet, and was dropped. } +procedure _RegisterMenuMembers(Cl: TPSPascalCompiler); +const + cClasses: array[0..17] of AnsiString = ('TGroupBox', 'TLabel', 'TEdit', 'TMemo', 'TComboBox', + 'TButton', 'TCheckBox', 'TRadioButton', 'TListBox', 'TScrollBar', 'TImage', 'TPaintBox', + 'TPanel', 'TNotebook', 'THeader', 'TRadioGroup', 'TScrollBox', 'TForm'); var - cc: TPSCompileTimeClass; + lClass : TPSCompileTimeClass; + lItem : TPSDelphiClassItem; + lClassIdx : Integer; +begin + for lClassIdx := Low(cClasses) to High(cClasses) do begin + lClass := Cl.FindClass(cClasses[lClassIdx]); + if Assigned(lClass) and not lClass.Property_Find('POPUPMENU', lItem) then + lClass.RegisterProperty('PopupMenu', 'TPopupMenu', iptRW); + end; + lClass := Cl.FindClass('TForm'); + if Assigned(lClass) then begin + if not lClass.Property_Find('MENU', lItem) then + lClass.RegisterProperty('Menu', 'TMainMenu', iptRW); + if not lClass.Property_Find('OBJECTMENUITEM', lItem) then + lClass.RegisterProperty('ObjectMenuItem', 'TMenuItem', iptRW); + if not lClass.Property_Find('WINDOWMENU', lItem) then + lClass.RegisterProperty('WindowMenu', 'TMenuItem', iptRW); + end; + lClass := Cl.FindClass('TMenuItem'); + if Assigned(lClass) and not lClass.Func_Find('GETPARENTMENU', lItem) then + lClass.RegisterMethod('function GetParentMenu: TMenu'); +end; + +procedure SIRegisterTPOPUPMENU(CL: TPSPascalCompiler); begin With cl.AddClassN(Cl.FindClass('TMenu'),'TPopupMenu') do begin - cc := Cl.FindClass('TLabel'); - if cc <> nil then - RegisterProperty('PopupMenu', 'TPopupMenu', iptRW); - with Cl.FindClass('TForm') do - begin - RegisterProperty('PopupMenu', 'TPopupMenu', iptRW); - end; + _RegisterMenuMembers(Cl); RegisterMethod('constructor Create(AOwner: TComponent)'); RegisterMethod('procedure Popup(X, Y: Integer)'); RegisterProperty('PopupComponent', 'TComponent', iptrw); @@ -77,8 +100,9 @@ procedure SIRegisterTMENU(CL: TPSPascalCompiler); RegisterMethod('constructor Create(AOwner: TComponent)'); RegisterMethod('function DispatchCommand(ACommand: Word): Boolean'); RegisterMethod('function DispatchPopup(AHandle: HMENU): Boolean'); - RegisterMethod('function FindItem(Value: Integer; Kind: TFindItemKind): TMenuItem'); - RegisterMethod('function GetHelpContext(Value: Integer; ByCommand: Boolean): THelpContext'); + { the searches' value is as wide as a menu handle in Delphi's declaration } + RegisterMethod('function FindItem(Value: ' + {$IFDEF FPC}'Integer'{$ELSE}'NativeUInt'{$ENDIF} + '; Kind: TFindItemKind): TMenuItem'); + RegisterMethod('function GetHelpContext(Value: ' + {$IFDEF FPC}'Integer'{$ELSE}'NativeUInt'{$ENDIF} + '; ByCommand: Boolean): THelpContext'); RegisterProperty('Images', 'TCustomImageList', iptrw); RegisterMethod('function IsRightToLeft: Boolean'); RegisterMethod('procedure ParentBiDiModeChanged(AControl: TObject)'); @@ -152,12 +176,18 @@ procedure SIRegisterTMENUITEM(CL: TPSPascalCompiler); procedure SIRegister_Menus(Cl: TPSPascalCompiler); begin + if Cl.FindType('THelpContext') = nil then + Cl.AddTypeS('THelpContext', 'LongInt'); Cl.AddTypeS('HMENU', 'NativeUInt'); Cl.AddTypeS('HACCEL', 'NativeUInt'); cl.addClassN(cl.FindClass('Exception'),'EMenuError'); Cl.addTypeS('TMenuBreak', '(mbNone, mbBreak, mbBarBreak)'); {$IFNDEF FPC} + if Cl.FindType('TOwnerDrawState') = nil then begin + Cl.addTypeS('TEOwnerDrawState', '(odSelected, odGrayed, odDisabled, odChecked, odFocused, odDefault, odHotLight, odInactive, odNoAccel, odNoFocusRect, odReserved1, odReserved2, odComboBoxEdit)'); + Cl.AddTypeS('TOwnerDrawState', 'set of TEOwnerDrawState'); + end; Cl.addTypeS('TMenuDrawItemEvent', 'procedure (Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean)'); Cl.addTypeS('TAdvancedMenuDrawItemEvent', 'procedure (Sender: TObject; ACanvas: TCanvas; ARect: TRect; State: TOwnerDrawState)'); @@ -199,9 +229,9 @@ procedure SIRegister_Menus(Cl: TPSPascalCompiler); Cl.AddDelphiFunction('function NewPopupMenu(Owner: TComponent; const AName: string; Alignment: TPopupAlignment; AutoPopup: Boolean; const Items: array of TCMenuItem): TPopupMenu'); - Cl.AddDelphiFunction('function NewSubMenu(const ACaption: string; HCTX: Word; const AName: string; Items: array of TMenuItem; AEnabled: Boolean): TMenuItem'); + Cl.AddDelphiFunction('function NewSubMenu(const ACaption: string; HCTX: THelpContext; const AName: string; Items: array of TMenuItem; AEnabled: Boolean): TMenuItem'); - Cl.AddDelphiFunction('function NewItem(const ACaption: string; AShortCut: TShortCut; Achecked, AEnabled: Boolean; AOnClick: TNotifyEvent; HCTX: Word; const AName: string): TMenuItem'); + Cl.AddDelphiFunction('function NewItem(const ACaption: string; AShortCut: TShortCut; Achecked, AEnabled: Boolean; AOnClick: TNotifyEvent; HCTX: THelpContext; const AName: string): TMenuItem'); Cl.AddDelphiFunction('function NewLine: TMenuItem'); diff --git a/Source/uPSC_stdctrls.pas b/Source/uPSC_stdctrls.pas index 71a1ccb7..ccb80f2a 100644 --- a/Source/uPSC_stdctrls.pas +++ b/Source/uPSC_stdctrls.pas @@ -125,6 +125,7 @@ procedure SIRegisterTLABEL(Cl: TPSPascalCompiler); RegisterProperty('ParentColor', 'Boolean', iptrw); RegisterProperty('ParentFont', 'Boolean', iptrw); RegisterProperty('ParentShowHint', 'Boolean', iptrw); + RegisterProperty('PopupMenu', 'TPopupMenu', iptrw); RegisterProperty('ShowAccelChar', 'Boolean', iptrw); RegisterProperty('Transparent', 'Boolean', iptrw); RegisterProperty('WordWrap', 'Boolean', iptrw); @@ -646,17 +647,31 @@ procedure SIRegisterTSCROLLBAR(Cl: TPSPascalCompiler); procedure SIRegister_StdCtrls_TypesAndConsts(cl: TPSPascalCompiler); begin cl.AddTypeS('TEditCharCase', '(ecNormal, ecUpperCase, ecLowerCase)'); + if cl.FindType('TScrollBarKind') = nil then + cl.AddTypeS('TScrollBarKind', '(sbHorizontal, sbVertical)'); + if cl.FindType('TScrollBarInc') = nil then + cl.AddTypeS('TScrollBarInc', 'SmallInt'); + if cl.FindType('TFormBorderStyle') = nil then + cl.AddTypeS('TFormBorderStyle', '(bsNone, bsSingle, bsSizeable, bsDialog, bsToolWindow, bsSizeToolWin)'); + if cl.FindType('TBorderStyle') = nil then + cl.AddTypeS('TBorderStyle', 'TFormBorderStyle'); cl.AddTypeS('TScrollStyle', '(ssNone, ssHorizontal, ssVertical, ssBoth)'); cl.AddTypeS('TComboBoxStyle', '(csDropDown, csSimple, csDropDownList, csOwnerDrawFixed, csOwnerDrawVariable)'); {$IFDEF DELPHI23UP} cl.AddTypeS('TButtonStyle', '(bsPushButton, bsCommandLink, bsSplitButton)'); {$ENDIF} cl.AddTypeS('TCheckBoxState', '(cbUnchecked, cbChecked, cbGrayed)'); + {$IFDEF FPC} cl.AddTypeS('TListBoxStyle', '(lbStandard, lbOwnerDrawFixed, lbOwnerDrawVariable)'); + {$ELSE} + cl.AddTypeS('TListBoxStyle', '(lbStandard, lbOwnerDrawFixed, lbOwnerDrawVariable, lbVirtual, lbVirtualOwnerDraw)'); + {$ENDIF} cl.AddTypeS('TScrollCode', '(scLineUp, scLineDown, scPageUp, scPageDown, scPosition, scTrack, scTop, scBottom, scEndScroll)'); - Cl.addTypeS('TEOwnerDrawState', '(odSelected, odGrayed, odDisabled, odChecked, odFocused, odDefault, odHotLight, odInactive, odNoAccel, odNoFocusRect, odReserved1, odReserved2, odComboBoxEdit)'); cl.AddTypeS('TTextLayout', '(tlTop, tlCenter, tlBottom)'); - cl.AddTypeS('TOwnerDrawState', 'set of TEOwnerDrawState'); + if cl.FindType('TOwnerDrawState') = nil then begin + Cl.addTypeS('TEOwnerDrawState', '(odSelected, odGrayed, odDisabled, odChecked, odFocused, odDefault, odHotLight, odInactive, odNoAccel, odNoFocusRect, odReserved1, odReserved2, odComboBoxEdit)'); + cl.AddTypeS('TOwnerDrawState', 'set of TEOwnerDrawState'); + end; cl.AddTypeS('TDrawItemEvent', 'procedure(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState)'); cl.AddTypeS('TMeasureItemEvent', 'procedure(Control: TWinControl; Index: Integer; var Height: Integer)'); diff --git a/Source/uPSCompiler.pas b/Source/uPSCompiler.pas index 346c0b09..2e0bbdc0 100644 --- a/Source/uPSCompiler.pas +++ b/Source/uPSCompiler.pas @@ -105,6 +105,9 @@ TPSRegProc = class(TObject) FExportName: Boolean; FImportDecl: tbtString; FOrgName: tbtString; + {$IFDEF PS_USESSUPPORT} + FDeclareUnit: tbtString; + {$ENDIF} procedure SetName(const Value: tbtString); public @@ -120,6 +123,12 @@ TPSRegProc = class(TObject) property ImportDecl: tbtString read FImportDecl write FImportDecl; + {$IFDEF PS_USESSUPPORT} + { the module being compiled when the host registered the routine: System, + or a unit whose uses clause entry the host's OnUses is answering } + property DeclareUnit: tbtString read FDeclareUnit write FDeclareUnit; + {$ENDIF} + constructor Create; @@ -541,9 +550,17 @@ TPSProcVar = class(TObject) TPSExternalProcedure = class(TPSProcedure) private FRegProc: TPSRegProc; + {$IFDEF PS_USESSUPPORT} + FDeclareUnit: tbtString; + {$ENDIF} public property RegProc: TPSRegProc read FRegProc write FRegProc; + {$IFDEF PS_USESSUPPORT} + { the module that declared it: a script module's own external routine, or + the module a host's routine the script uses was registered under } + property DeclareUnit: tbtString read FDeclareUnit write FDeclareUnit; + {$ENDIF} end; @@ -680,6 +697,11 @@ TPSConstant = class(TObject) FDeclareCol: Cardinal; FValue: PIfRVariant; + { the real literal's text when a script declared the constant as one, as + for TPSValueData, and the value it was read as: the text stands for the + constant only while it holds that value (_ConstantRealText) } + FRealText: tbtString; + FRealTextValue: Extended; procedure SetName(const Value: tbtString); public @@ -811,6 +833,8 @@ TPSPascalCompilerMessage = class(TObject) FPosition: Cardinal; + FPlaced: Boolean; + procedure SetParserPos(Parser: TPSPascalParser); public @@ -824,6 +848,11 @@ TPSPascalCompilerMessage = class(TObject) property Col: Cardinal read FCol write FCol; + { the preprocessor has placed the message in the file it is in: it is + placed once (clear it to have a message moved back to a place in the + preprocessed text placed again) } + property Placed: Boolean read FPlaced write FPlaced; + function ErrorType: tbtString; virtual; abstract; procedure SetCustomPos(Pos, Row, Col: Cardinal); @@ -929,6 +958,12 @@ TPSBlockInfo = class(TObject) TPSPascalCompiler = class protected FAnyString: TPSType; + FHighProc: TPSRegProc; + FReplicateProc: TPSRegProc; + FStringOfCharProc: TPSRegProc; + FLowProc: TPSRegProc; + FIncludeProc: TPSRegProc; + FExcludeProc: TPSRegProc; FAnyMethod: TPSType; FUnitName: tbtString; FID: Pointer; @@ -956,6 +991,8 @@ TPSPascalCompiler = class FOnExternalProc: TPSOnExternalProc; FOnUseVariable: TPSOnUseVariable; FOnUseRegProc: TPSOnUseRegProc; + { the routine whose local declarations are being read, or nil } + FDeclaringProc: TPSInternalProcedure; FOnBeforeOutput: TPSOnNotify; FOnBeforeCleanup: TPSOnNotify; FOnWriteLine: TPSOnWriteLineEvent; @@ -971,7 +1008,12 @@ TPSPascalCompiler = class FExecIs64Bit: Boolean; {$ENDIF} - FWithCount: Integer; + { the procedure's stack depth (its ProcVars count) where the innermost loop's body begins: Break and + Continue pop every value above it that no exception frame they leave removes } + FLoopStackDepth: Integer; + { the stack depth where the outermost try statement within that loop begins: the frames a Break or + Continue leaves remove the values above it (cm_poexh 4) } + FLoopTryDepth: Longint; FTryCount: Integer; FExceptFinallyCount: Integer; @@ -983,6 +1025,10 @@ TPSPascalCompiler = class fUnits : TPSUnitList; fUnit : TPSUnit; fModule : tbtString; + { while a uses clause asks for a unit: the asking module and its parser + -- a message made with that parser current is that module's } + fUsesModule: tbtString; + fUsesParser: TPSPascalParser; {$ENDIF} fInCompile : Integer; {$IFNDEF PS_NOINTERFACES} @@ -991,6 +1037,16 @@ TPSPascalCompiler = class FCurrUsedTypeNo: Cardinal; FGlobalBlock: TPSBlockInfo; + { the real literal's text of the constant ReadConstant read last, as for + TPSValueData } + FConstRealText: tbtString; + + { one compilation of s: Compile's, which passes an exception out of it on + after releasing what it made } + function CompileText(const s: tbtString): Boolean; + { what a compilation made, released when it ends: normally, on an error + or by an exception } + procedure ReleaseCompileState; function IsBoolean(aType: TPSType): Boolean; {$IFNDEF PS_NOWIDESTRING} @@ -1000,6 +1056,8 @@ TPSPascalCompiler = class {$ENDIF} function PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: PIFRVariant; Var2Mod: Byte; Var2: PIfRVariant; Cmd: TPSBinOperatorType; Pos, Row, Col: Cardinal): Boolean; + function DoPreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: PIFRVariant; Var2Mod: Byte; + Var2: PIfRVariant; Cmd: TPSBinOperatorType; Pos, Row, Col: Cardinal): Boolean; function FindBaseType(BaseType: TPSBaseType): TPSType; @@ -1084,6 +1142,17 @@ TPSPascalCompiler = class function FindProc(const aName: tbtString): Cardinal; + { the routine the compiler's own code calls under the name aName: one + registered in the system scope, never a script's routine of that name } + function FindSystemProc(const aName: tbtString): Cardinal; + + { aRegProc added to the script as one of its routines; its number there } + function UseRegProc(aRegProc: TPSRegProc): Cardinal; + + { whether a script declaration of the name aName (upper case) is in sight + in the routine aProc: System's names, not reserved words, give way to it } + function NameIsDeclared(aProc: TPSInternalProcedure; const aName: tbtString): Boolean; + function GetTypeCount: Longint; function GetType(I: Longint): TPSType; @@ -1369,6 +1438,9 @@ TPSValueAllocatedStackVar = class(TPSValueLocalVar) TPSValueData = class(TPSValue) private FData: PIfRVariant; + { a real literal's text, '-' before it when negated, read exactly where + the literal is put into a Currency; '' for any other value } + FRealText: tbtString; public property Data: PIfRVariant read FData write FData; @@ -1830,6 +1902,8 @@ implementation RPS_ClassTypeExpected = 'Class type expected'; RPS_DivideByZero = 'Divide by Zero'; RPS_MathError = 'Math Error'; + RPS_IntegerConstantTooLarge = 'Integer constant too large'; + RPS_ConstantOverflow = 'Overflow in conversion or arithmetic operation'; RPS_UnsatisfiedForward = 'Unsatisfied Forward %s'; RPS_ForwardParameterMismatch = 'Forward Parameter Mismatch'; RPS_InvalidNumberOfParameter = 'Invalid number of parameters'; @@ -1881,9 +1955,37 @@ function DeclToBits(const Decl: TPSParametersDecl): tbtString; end; +{$IFDEF FPC} +{ Bytes go onto a string holding binary by length and index. Joined to an AnsiChar or a constant, + which carries the compile host's code page, the string would go through UTF-16 under a UTF-8 + run-time page, and a byte that is not valid UTF-8 would not come back. } +procedure _PSAppendByte(var aData: tbtString; aByte: Byte); +var + lLen: Longint; +begin + lLen := Length(aData); + SetLength(aData, lLen + 1); + aData[lLen + 1] := tbtChar(aByte); +end; + +procedure _PSAppendBytes(var aData: tbtString; const aBytes: tbtString); +var + lLen: Longint; +begin + lLen := Length(aData); + SetLength(aData, lLen + Length(aBytes)); + if aBytes <> '' then + Move(aBytes[1], aData[lLen + 1], Length(aBytes)); +end; +{$ENDIF} + procedure BlockWriteByte(BlockInfo: TPSBlockInfo; b: Byte); begin + {$IFDEF FPC} + _PSAppendByte(BlockInfo.Proc.FData, b); + {$ELSE} BlockInfo.Proc.Data := BlockInfo.Proc.Data + tbtChar(b); + {$ENDIF} end; procedure BlockWriteData(BlockInfo: TPSBlockInfo; const Data; Len: Longint); @@ -1945,7 +2047,7 @@ function BlockWriteVariant(BlockInfo: TPSBlockInfo; p: PIfRVariant{$IFNDEF PS_NO if ExecIs64Bit then begin {$IFNDEF CPU64} { On 64-bit Exec, Extended is an alias for Double, so write a Double instead } - TempDouble := tbtDouble(p^.textended); + TempDouble := p^.textended; BlockWriteData(BlockInfo, TempDouble, sizeof(tbtDouble)); {$ELSE} BlockWriteData(BlockInfo, p^.textended, sizeof(tbtExtended)); @@ -2083,6 +2185,26 @@ function ParseMethod(Owner: TPSPascalCompiler; const FClassName: tbtString; Decl Result := ParseMethodEx(Owner, FClassName, Decl, OrgName, DestDecl, Func, nil); end; +function _NameInList(const aName, aList: tbtString): Boolean; forward; + +{ Whether the upper-case parameter name aName is one of aNames, the names + before it in its group, or names a parameter aDecl already holds } +function _ParamRepeated(aDecl : TPSParametersDecl; + const aName : tbtString; + const aNames : tbtString) + : Boolean; +var + lIdx : Longint; +begin + Result := True; + if _NameInList(aName, aNames) then + Exit; + for lIdx := 0 to Pred(aDecl.ParamCount) do + if FastUppercase(aDecl.Params[lIdx].OrgName) = aName then + Exit; + Result := False; +end; + function ParseMethodEx(Owner: TPSPascalCompiler; const FClassName: tbtString; Decl: tbtString; var OrgName: tbtString; DestDecl: TPSParametersDecl; var Func: TPMFuncType; CustomParser: TPSPascalParser): Boolean; var Parser: TPSPascalParser; @@ -2162,6 +2284,15 @@ function ParseMethodEx(Owner: TPSPascalCompiler; const FClassName: tbtString; De ERow:=Parser.Row; ECol:=Parser.Col; + if _ParamRepeated(DestDecl, Parser.GetToken, '') then + begin + if Parser <> CustomParser then + Parser.Free + else + Owner.MakeError('', ecDuplicateIdentifier, Parser.OriginalToken); + Result := False; + exit; + end; VNames := Parser.OriginalToken + '|'; Parser.Next; while Parser.CurrTokenId = CSTI_Comma do @@ -2176,6 +2307,15 @@ function ParseMethodEx(Owner: TPSPascalCompiler; const FClassName: tbtString; De Result := False; exit; end; + if _ParamRepeated(DestDecl, Parser.GetToken, VNames) then + begin + if Parser <> CustomParser then + Parser.Free + else + Owner.MakeError('', ecDuplicateIdentifier, Parser.OriginalToken); + Result := False; + exit; + end; VNames := VNames + Parser.OriginalToken + '|'; Parser.Next; end; @@ -2242,7 +2382,7 @@ function ParseMethodEx(Owner: TPSPascalCompiler; const FClassName: tbtString; De btUnicodeString: VCType := FindAndAddType(Owner, '!OPENARRAYOFUNICODESTRING', 'array of UnicodeString'); btWideChar: VCType := FindAndAddType(Owner, '!OPENARRAYOFWIDECHAR', 'array of WideChar'); {$ENDIF} - btClass: VCType := FindAndAddType(Owner, '!OPENARRAYOFTOBJECT', 'array of TObject'); + btClass: VCType := FindAndAddType(Owner, '!OPENARRAYOFCLASS_' + FastUpperCase(Parser.OriginalToken), 'array of ' + FastUpperCase(Parser.OriginalToken)); btRecord: VCType := FindAndAddType(Owner, '!OPENARRAYOFRECORD_'+FastUpperCase(Parser.OriginalToken), 'array of ' +FastUpperCase(Parser.OriginalToken)); btEnum: VCType := FindAndAddType(Owner, '!OPENARRAYOFENUM_' + FastUpperCase(Parser.OriginalToken), 'array of ' + FastUpperCase(Parser.OriginalToken)); else @@ -2343,60 +2483,155 @@ function ParseMethodEx(Owner: TPSPascalCompiler; const FClassName: tbtString; De -function TPSPascalCompiler.FindProc(const aName: tbtString): Cardinal; +{$IFDEF PS_USESSUPPORT} +function _ScopeRank(aCompiler : TPSPascalCompiler; + const aModule : tbtString) + : Longint; forward; +{$ENDIF} + +{ The routine the name aName (upper case) means in the module being compiled: + a routine of the script, its number in aNumber, or a host's the script has + not used yet, in aRegProc; InvalidVal and nil where nothing has the name. + The newest first; a routine of the system scope after any other, since the + compiler's own code may have added it; and after those a routine of a module + the one being compiled reaches only through another unit or not at all. } +procedure _LocateProc( aCompiler : TPSPascalCompiler; + const aName : tbtString; + out aNumber : Cardinal; + out aRegProc : TPSRegProc); var - l, h: Longint; - x: TPSProcedure; - xr: TPSRegProc; - name: tbtString; + lHash : Longint; + lIdx : Longint; + lProc : TPSProcedure; + lReg : TPSRegProc; + lSystem : Cardinal; + lFar : Cardinal; + lFarReg : TPSRegProc; + {$IFDEF PS_USESSUPPORT} + lModule : tbtString; + {$ENDIF} +begin + aNumber := InvalidVal; + aRegProc := nil; + lSystem := InvalidVal; + lFar := InvalidVal; + lFarReg := nil; + lHash := MakeHash(aName); + for lIdx := Pred(aCompiler.FProcs.Count) downto 0 do begin + lProc := aCompiler.FProcs.Data^[lIdx]; + if lProc.ClassType = TPSInternalProcedure then begin + if (TPSInternalProcedure(lProc).NameHash <> lHash) or (TPSInternalProcedure(lProc).Name <> aName) then + Continue; + {$IFDEF PS_USESSUPPORT} + lModule := TPSInternalProcedure(lProc).DeclareUnit; + {$ENDIF} + end else begin + if (TPSExternalProcedure(lProc).RegProc.NameHash <> lHash) or + (TPSExternalProcedure(lProc).RegProc.Name <> aName) then + Continue; + {$IFDEF PS_USESSUPPORT} + lModule := TPSExternalProcedure(lProc).DeclareUnit; + if lModule = 'System' then + {$ENDIF} + begin + if lSystem = InvalidVal then + lSystem := lIdx; + Continue; + end; + end; + {$IFDEF PS_USESSUPPORT} + if _ScopeRank(aCompiler, lModule) = 0 then begin + if lFar = InvalidVal then + lFar := lIdx; + Continue; + end; + {$ENDIF} + aNumber := lIdx; + Exit; + end; + if lSystem <> InvalidVal then begin + aNumber := lSystem; + Exit; + end; + for lIdx := Pred(aCompiler.FRegProcs.Count) downto 0 do begin + lReg := aCompiler.FRegProcs[lIdx]; + if (lReg.NameHash = lHash) and (lReg.Name = aName) then begin + {$IFDEF PS_USESSUPPORT} + if _ScopeRank(aCompiler, lReg.DeclareUnit) = 0 then begin + if lFarReg = nil then + lFarReg := lReg; + Continue; + end; + {$ENDIF} + aRegProc := lReg; + Exit; + end; + end; + aNumber := lFar; + if lFar = InvalidVal then + aRegProc := lFarReg; +end; +function TPSPascalCompiler.FindProc(const aName: tbtString): Cardinal; +var + lRegProc : TPSRegProc; begin - name := FastUpperCase(aName); - h := MakeHash(Name); if FProcs = nil then begin - result := InvalidVal; + Result := InvalidVal; Exit; end; + _LocateProc(Self, FastUpperCase(aName), Result, lRegProc); + if Assigned(lRegProc) then + Result := UseRegProc(lRegProc); +end; {findfunc} - for l := FProcs.Count - 1 downto 0 do - begin - x := FProcs.Data^[l]; - if x.ClassType = TPSInternalProcedure then - begin - if (TPSInternalProcedure(x).NameHash = h) and - (TPSInternalProcedure(x).Name = Name) then - begin - Result := l; - exit; - end; - end - else - begin - if (TPSExternalProcedure(x).RegProc.NameHash = h) and - (TPSExternalProcedure(x).RegProc.Name = Name)then - begin - Result := l; - exit; - end; +function TPSPascalCompiler.FindSystemProc(const aName: tbtString): Cardinal; +var + lName : tbtString; + lHash : Longint; + lIdx : Longint; + lProc : TPSProcedure; + lReg : TPSRegProc; +begin + lName := FastUpperCase(aName); + lHash := MakeHash(lName); + for lIdx := Pred(FProcs.Count) downto 0 do begin + lProc := FProcs.Data^[lIdx]; + if (lProc.ClassType = TPSExternalProcedure) and + (TPSExternalProcedure(lProc).RegProc.NameHash = lHash) and + (TPSExternalProcedure(lProc).RegProc.Name = lName) + {$IFDEF PS_USESSUPPORT} and (TPSExternalProcedure(lProc).DeclareUnit = 'System'){$ENDIF} then begin + Result := lIdx; + Exit; end; end; - for l := FRegProcs.Count - 1 downto 0 do - begin - xr := FRegProcs[l]; - if (xr.NameHash = h) and (xr.Name = Name) then - begin - x := TPSExternalProcedure.Create; - TPSExternalProcedure(x).RegProc := xr; - FProcs.Add(x); - if @FOnUseRegProc <> nil then - FOnUseRegProc(Self, FParser.CurrTokenPos, Name); - Result := FProcs.Count - 1; - exit; + for lIdx := Pred(FRegProcs.Count) downto 0 do begin + lReg := FRegProcs[lIdx]; + if (lReg.NameHash = lHash) and (lReg.Name = lName) + {$IFDEF PS_USESSUPPORT} and (lReg.DeclareUnit = 'System'){$ENDIF} then begin + Result := UseRegProc(lReg); + Exit; end; end; Result := InvalidVal; -end; {findfunc} +end; + +function TPSPascalCompiler.UseRegProc(aRegProc: TPSRegProc): Cardinal; +var + lProc : TPSExternalProcedure; +begin + lProc := TPSExternalProcedure.Create; + lProc.RegProc := aRegProc; + {$IFDEF PS_USESSUPPORT} + lProc.DeclareUnit := aRegProc.DeclareUnit; + {$ENDIF} + FProcs.Add(lProc); + { before the notification, whose handler can use other routines } + Result := FProcs.Count - 1; + if @FOnUseRegProc <> nil then + FOnUseRegProc(Self, FParser.CurrTokenPos, aRegProc.Name); +end; function TPSPascalCompiler.UseExternalProc(const Name: tbtString): TPSParametersDecl; var @@ -2577,6 +2812,8 @@ function TPSPascalCompiler.AddFunction(const Header: tbtString): TPSRegProc; modifier := pmIn; if Parser.CurrTokenId <> CSTI_Identifier then raise EPSCompilerException.CreateFmt(RPS_UnableToRegisterFunction, [Name]); + if _ParamRepeated(Decl, Parser.GetToken, '') then + raise EPSCompilerException.CreateFmt(RPS_UnableToRegisterFunction, [Name]); VNames := Parser.OriginalToken + '|'; Parser.Next; while Parser.CurrTokenId = CSTI_Comma do @@ -2584,6 +2821,8 @@ function TPSPascalCompiler.AddFunction(const Header: tbtString): TPSRegProc; Parser.Next; if Parser.CurrTokenId <> CSTI_Identifier then Raise EPSCompilerException.CreateFmt(RPS_UnableToRegisterFunction, [Name]); + if _ParamRepeated(Decl, Parser.GetToken, VNames) then + raise EPSCompilerException.CreateFmt(RPS_UnableToRegisterFunction, [Name]); VNames := VNames + Parser.OriginalToken + '|'; Parser.Next; end; @@ -2630,6 +2869,9 @@ function TPSPascalCompiler.AddFunction(const Header: tbtString): TPSRegProc; x.OrgName := Name; x.Name := FastUpperCase(Name); x.ExportName := True; + {$IFDEF PS_USESSUPPORT} + x.DeclareUnit := fModule; + {$ENDIF} x.Decl.Assign(decl); if Decl.Result = nil then begin @@ -2659,7 +2901,16 @@ function TPSPascalCompiler.MakeHint(const Module: tbtString; E: TPSPascalCompile N := TPSPascalCompilerHint.Create; n.FHint := e; n.SetParserPos(FParser); + {$IFNDEF PS_USESSUPPORT} n.FModuleName := Module; + {$ELSE} + if Module <> '' then + n.FModuleName := Module + else if (fUsesParser <> nil) and (FParser = fUsesParser) then + n.FModuleName := fUsesModule + else + n.FModuleName := fModule; + {$ENDIF} n.FParam := Param; FMessages.Add(n); Result := n; @@ -2678,6 +2929,8 @@ function TPSPascalCompiler.MakeError(const Module: tbtString; E: {$ELSE} if Module <> '' then n.FModuleName := Module + else if (fUsesParser <> nil) and (FParser = fUsesParser) then + n.FModuleName := fUsesModule else n.FModuleName := fModule; {$ENDIF} @@ -2694,7 +2947,16 @@ function TPSPascalCompiler.MakeWarning(const Module: tbtString; E: N := TPSPascalCompilerWarning.Create; n.FWarning := e; n.SetParserPos(FParser); + {$IFNDEF PS_USESSUPPORT} n.FModuleName := Module; + {$ELSE} + if Module <> '' then + n.FModuleName := Module + else if (fUsesParser <> nil) and (FParser = fUsesParser) then + n.FModuleName := fUsesModule + else + n.FModuleName := fModule; + {$ENDIF} n.FParam := Param; FMessages.Add(n); Result := n; @@ -3002,6 +3264,17 @@ function GetUInt64(Src: PIfRVariant; var s: Boolean): UInt64; end; {$ENDIF} +{$IFDEF FPC_CURRENCY_IS_INT64} +{ Free Pascal makes Currency op real (+ - *) a Currency operation, and where + Currency is an Int64 (x86_64) that rounds the real operand alone first: + 1 + 0.00005 would give 1. Taken into a real first, the operation is the + real one, as Delphi computes it. } +function _CurrAsReal(const c: Currency): Extended; +begin + Result := c; +end; +{$ENDIF} + function GetReal(Src: PIfRVariant; var s: Boolean): Extended; begin case Src.FType.BaseType of @@ -3031,6 +3304,18 @@ function GetReal(Src: PIfRVariant; var s: Boolean): Extended; end; end; +{$IFNDEF PS_NOINT64} +{ a constant array index as the Cardinal the run time compares: one outside a Cardinal becomes + High(Cardinal), which every bounds check refuses } +function _ConstIndex(const aValue: Int64): Cardinal; +begin + if (aValue < 0) or (aValue > High(Cardinal)) then + Result := High(Cardinal) + else + Result := Cardinal(aValue); +end; +{$ENDIF} + function GetString(Src: PIfRVariant; var s: Boolean): tbtString; begin case Src.FType.BaseType of @@ -3287,7 +3572,8 @@ function TPSPascalCompiler.IsCompatibleType(p1, p2: TPSType; Cast: Boolean): Boo ((p1.BaseType = btUnicodeString) and (p2.BaseType = btWideChar)) or ((p1.BaseType = btUnicodeString) and ((p2.BaseType = btString) or (p2.BaseType = btPchar) or (p2.BaseType = btUnicodeString))) or ((p1.BaseType = btUnicodeString) and (p2.BaseType = btWidestring)) or - (((p1.basetype = btPchar) or (p1.BaseType = btString)) and (p2.BaseType = btWideString)or (p2.BaseType = btUnicodeString)) or + (((p1.basetype = btPchar) or (p1.BaseType = btString)) and ((p2.BaseType = btWideString) or (p2.BaseType = btUnicodeString))) or + ((p1.BaseType = btChar) and (p2.BaseType = btUnicodeString)) or (((p1.basetype = btPchar) or (p1.BaseType = btString)) and (p2.BaseType = btWidechar)) or (((p1.basetype = btPchar) or (p1.BaseType = btString)) and (p2.BaseType = btchar)) or {$ENDIF} @@ -3322,59 +3608,722 @@ function TPSPascalCompiler.IsCompatibleType(p1, p2: TPSType; Cast: Boolean): Boo end; -function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: PIFRVariant; Var2Mod: Byte; Var2: PIfRVariant; Cmd: TPSBinOperatorType; Pos, Row, Col: Cardinal): Boolean; +function _NarrowToCurrency(out aDest: Currency; const aValue: Extended): Boolean; forward; + +{ PreCalc's folding, which PreCalc runs with the floating-point exceptions + masked } +function TPSPascalCompiler.DoPreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: PIFRVariant; Var2Mod: Byte; Var2: PIfRVariant; Cmd: TPSBinOperatorType; Pos, Row, Col: Cardinal): Boolean; { var1=dest, var2=src } +const + { the largest integer whose raw Currency units, the value times 10000, an + Int64 holds } + cCurrencyIntMax = 922337203685477; var b: Boolean; + lDone: Boolean; + lRefused: Boolean; + + { An operation that makes a Currency is folded as Delphi folds it: + and - of + a Currency and a Currency or an integer exactly, in raw units, any other one + checked against its result taken as a real, and past the range of Currency + the constant is refused. } + + { aV's value: a Currency's raw units, aIsInt False, or an integer, aIsInt + True; False when aV is neither. A UInt64 past High(Int64) is read as + High(Int64), past the range of Currency either way } + function RawOrInt(aV: PIfRVariant; out aRaw: Int64; out aIsInt: Boolean): Boolean; + begin + Result := True; + aIsInt := True; + case aV.FType.BaseType of + btU8: aRaw := aV^.tu8; + btS8: aRaw := aV^.ts8; + btU16: aRaw := aV^.tu16; + btS16: aRaw := aV^.ts16; + btU32: aRaw := aV^.tu32; + btS32: aRaw := aV^.ts32; + {$IFNDEF PS_NOINT64} + btS64: aRaw := aV^.ts64; + btU64: + begin + aRaw := PInt64(@aV^.tu64)^; + if aRaw < 0 then + aRaw := High(Int64); + end; + {$ENDIF} + btCurrency: + begin + aRaw := PInt64(@aV^.tcurrency)^; + aIsInt := False; + end; + else + Result := False; + end; + end; -begin - Result := True; - try - if (IsRealType(var2.FType.BaseType) and IsIntType(var1.FType.BaseType)) then - ConvertToFloat(Self, FUseUsedTypes, var1, var2^.FType); + { aRaw + aOther into aRaw; False, aRaw unchanged, when the sum leaves the + range of the raw units, which is Currency's } + function AddRaw(var aRaw: Int64; aOther: Int64): Boolean; + begin + if aOther >= 0 then + Result := aRaw <= High(Int64) - aOther + else + Result := aRaw >= Low(Int64) - aOther; + if Result then + aRaw := aRaw + aOther; + end; + + { aRaw + aInt, or with aNegate aRaw - aInt, into aRaw, the integer taken in + steps whose raw units an Int64 holds. The steps all have one sign, so + each partial sum lies between aRaw and the final one: one out of the range + means the final one is. An integer past twice Currency's largest is past + the range whatever aRaw is } + function AddIntToRaw(var aRaw: Int64; aInt: Int64; aNegate: Boolean): Boolean; + var + lStep: Int64; + begin + Result := (aInt >= -(2 * cCurrencyIntMax + 1)) and (aInt <= 2 * cCurrencyIntMax + 1); + if not Result then + exit; + if aNegate then + aInt := -aInt; + while Result and (aInt <> 0) do + begin + if aInt > cCurrencyIntMax then + lStep := cCurrencyIntMax + else if aInt < -cCurrencyIntMax then + lStep := -cCurrencyIntMax + else + lStep := aInt; + Result := AddRaw(aRaw, lStep * 10000); + aInt := aInt - lStep; + end; + end; + + { var1 made a Currency of the type of var2, a Currency, for an integer left + operand: its value is set next } + procedure TakeCurrencyType; + var + lType: TPSType; + begin + lType := var2^.FType; + if FUseUsedTypes then + lType := at2ut(lType); + FinalizeVariant(var1^); + InitializeVariant(var1, lType); + end; + + { var1 + var2 or var1 - var2 of a Currency and a Currency or an integer, into + var1, exactly: True when the operation is one of these, with aFits False + past the range of Currency or at its minimum } + function CurrencySum(out aFits: Boolean): Boolean; + var + lRaw1, lRaw2: Int64; + lInt1, lInt2: Boolean; + begin + Result := (Cmd in [otAdd, otSub]) and RawOrInt(var1, lRaw1, lInt1) and RawOrInt(var2, lRaw2, lInt2) and + not (lInt1 and lInt2); + if not Result then + exit; + if lInt1 then + begin + { n + c, and n - c as -(c - n) } + aFits := AddIntToRaw(lRaw2, lRaw1, Cmd = otSub); + if Cmd = otSub then + begin + aFits := aFits and (lRaw2 <> Low(Int64)); + if aFits then + lRaw2 := -lRaw2; + end; + lRaw1 := lRaw2; + end else if lInt2 then + aFits := AddIntToRaw(lRaw1, lRaw2, Cmd = otSub) + else if Cmd = otAdd then + aFits := AddRaw(lRaw1, lRaw2) + else if lRaw2 = Low(Int64) then + { - Low(Int64) is no Int64: High(Int64) and 1, steps of one sign } + aFits := AddRaw(lRaw1, High(Int64)) and AddRaw(lRaw1, 1) + else + aFits := AddRaw(lRaw1, -lRaw2); + { the minimum, -922337203685477.5808, is refused, as Delphi refuses it as a + constant: no folded constant then holds a value whose negation is past + the range } + aFits := aFits and (lRaw1 <> Low(Int64)); + if not aFits then + exit; + if lInt1 then + TakeCurrencyType; + PInt64(@var1^.tcurrency)^ := lRaw1; + end; + + { the result taken as a real } + function RealResult: Extended; + var + lOk: Boolean; + lLeft, lRight: Extended; + begin + lOk := True; + lLeft := GetReal(var1, lOk); + lRight := GetReal(var2, lOk); case Cmd of - otAdd: - begin { + } - case var1.FType.BaseType of - btU8: var1^.tu8 := var1^.tu8 + GetUint(Var2, Result); - btS8: var1^.ts8 := var1^.ts8 + GetInt(Var2, Result); - btU16: var1^.tu16 := var1^.tu16 + GetUint(Var2, Result); - btS16: var1^.ts16 := var1^.ts16 + Getint(Var2, Result); - btEnum, btU32: var1^.tu32 := var1^.tu32 + GetUint(Var2, Result); - btS32: var1^.ts32 := var1^.ts32 + Getint(Var2, Result); - {$IFNDEF PS_NOINT64}btS64: var1^.ts64 := var1^.ts64 + GetInt64(Var2, Result); - btU64: var1^.tu64 := var1^.tu64 + GetUInt64(Var2, Result);{$ENDIF} - btSingle: var1^.tsingle := var1^.tsingle + GetReal( Var2, Result); - btDouble: var1^.tdouble := var1^.tdouble + GetReal( Var2, Result); - btExtended: var1^.textended := var1^.textended + GetReal( Var2, Result); - btCurrency: var1^.tcurrency := var1^.tcurrency + GetReal( Var2, Result); - btSet: - begin - if (var1.FType = var2.FType) then - begin - Set_Union(var1.tstring, var2.tstring, TPSSetType(var1.FType).ByteSize); - end else Result := False; - end; - btChar: - begin - ConvertToString(Self, FUseUsedTypes, var1, getstring(Var1, Result)+getstring(Var2, Result)); - end; - btString: tbtstring(var1^.tstring) := tbtstring(var1^.tstring) + GetString(Var2, Result); - {$IFNDEF PS_NOWIDESTRING} - btwideString: tbtwidestring(var1^.twidestring) := tbtwidestring(var1^.twidestring) + GetWideString(Var2, Result); - btUnicodeString: tbtunicodestring(var1^.tunistring) := tbtunicodestring(var1^.tunistring) + GetUnicodeString(Var2, Result); - btWidechar: - begin - ConvertToUnicodeString(Self, FUseUsedTypes, var1, GetUnicodeString(Var1, Result)+GetUnicodeString(Var2, Result)); - end; - {$ENDIF} - else Result := False; - end; + otAdd: Result := lLeft + lRight; + otSub: Result := lLeft - lRight; + otMul: Result := lLeft * lRight; + else + Result := lLeft / lRight; + end; + end; + + { An operation that makes a Currency -- +, -, * or / of a Currency and a + number, or of an integer and a Currency -- before the cases below: False, + with the error made, past the range of Currency; aDone when the result is + made here. The check of a * or a /, or of a real operand, is made on the + result taken as a real, which can disagree with the exact one within its + last place of the ends of the range -- about a ten-thousandth, or on + Win64, where Extended is a Double, about a tenth. } + function CurrencyResult(out aDone: Boolean): Boolean; + var + lFits: Boolean; + lRaw: Int64; + lInt: Boolean; + lDest: Currency; + begin + Result := True; + aDone := False; + if not ((Cmd in [otAdd, otSub, otMul, otDiv{$IFNDEF PS_DELPHIDIV}, otIntDiv{$ENDIF}]) and + (((var1.FType.BaseType = btCurrency) and IsIntRealType(var2.FType.BaseType)) or + (IsIntType(var1.FType.BaseType) and (var2.FType.BaseType = btCurrency)))) then + exit; + if CurrencySum(lFits) then + begin + aDone := True; + Result := lFits; + end else + begin + Result := _NarrowToCurrency(lDest, RealResult); + { an integer left operand past Currency's range would overflow taken into + a Currency: the result is the one taken as a real } + if Result and RawOrInt(var1, lRaw, lInt) and lInt and + ((lRaw > cCurrencyIntMax) or (lRaw < -cCurrencyIntMax)) then + begin + TakeCurrencyType; + var1^.tcurrency := lDest; + aDone := True; + end; + end; + if not Result then + MakeError('', ecCustomError, tbtstring(RPS_ConstantOverflow)); + end; + + { aCur, a Currency, against aOther, a Currency or an integer, exactly: -1, 0 + or 1. An integer past Currency's range is greater or less than every + Currency, by its sign } + function CurrencyOrder(aCur, aOther: PIfRVariant): Integer; + var + lRaw1, lRaw2: Int64; + lInt: Boolean; + begin + RawOrInt(aCur, lRaw1, lInt); + RawOrInt(aOther, lRaw2, lInt); + if lInt and (lRaw2 > cCurrencyIntMax) then + Result := -1 + else if lInt and (lRaw2 < -cCurrencyIntMax) then + Result := 1 + else + begin + if lInt then + lRaw2 := lRaw2 * 10000; + if lRaw1 < lRaw2 then + Result := -1 + else if lRaw1 > lRaw2 then + Result := 1 + else + Result := 0; + end; + end; + + { whether aV is a real constant holding a NaN, found by its bits, so that no + comparison meets it } + function IsNaNConst(aV: PIfRVariant): Boolean; + var + lTop: Word; + lBits: Int64; + begin + case aV.FType.BaseType of + btSingle: + Result := (PCardinal(@aV^.tsingle)^ and $7F800000 = $7F800000) and + (PCardinal(@aV^.tsingle)^ and $007FFFFF <> 0); + btDouble: + Result := (PInt64(@aV^.tdouble)^ and $7FF0000000000000 = $7FF0000000000000) and + (PInt64(@aV^.tdouble)^ and $000FFFFFFFFFFFFF <> 0); + btExtended: + begin + Move(aV^.textended, lBits, SizeOf(lBits)); + Move((PAnsiChar(@aV^.textended) + SizeOf(Extended) - 2)^, lTop, SizeOf(lTop)); + { an 80-bit Extended, or a Double where Extended is one (Win64) } + if SizeOf(Extended) = 10 then + Result := (lTop and $7FFF = $7FFF) and (lBits and $7FFFFFFFFFFFFFFF <> 0) + else + Result := (lTop and $7FF0 = $7FF0) and (lBits and $000FFFFFFFFFFFFF <> 0); end; - otSub: - begin { - } - case Var1.FType.BaseType of - btU8: var1^.tu8 := var1^.tu8 - GetUint(Var2, Result); + else + Result := False; + end; + end; + + { a comparison with a NaN answers as IEEE 754 says and Delphi 13 folds it, + only <> True, whatever the compiler that built the engine makes of an + ordered comparison with one } + function NaNCompare(out aResult: Boolean): Boolean; + begin + Result := (Cmd in [otGreaterEqual, otLessEqual, otGreater, otLess, otEqual, otNotEqual]) and + (IsNaNConst(var1) or IsNaNConst(var2)); + if Result then + aResult := Cmd = otNotEqual; + end; + + { two constants of Boolean types, one of them a ByteBool, WordBool or LongBool: and, or, xor, = and <> take + their truths, as in Delphi -- folded as integers, the WordBools 256 and 1 (both True) gave False for and } + function WideBoolConsts: Boolean; + begin + Result := (var1.FType <> nil) and (var2.FType <> nil) and IsBoolean(GetTypeCopyLink(var1.FType)) and + IsBoolean(GetTypeCopyLink(var2.FType)) and ((GetTypeCopyLink(var1.FType) <> FDefaultBoolType) or + (GetTypeCopyLink(var2.FType) <> FDefaultBoolType)); + end; + + { two integer constants compare by value, an integer constant with a Currency one exactly, as Delphi + compares constants, and with another real one as reals, as the run time compares them (DoBooleanCalc): + the cases below read the right operand in the left one's width and sign, and the integer first took the + real's type -- for a Currency an Extended, which on Win64 is a Double, short of a Currency's digits } + function NumericCompare(out aResult: Boolean): Boolean; + var + lI1, lI2: Int64; + lHuge1, lHuge2, lOk: Boolean; + lR1, lR2: Extended; + lC: Integer; + + { the value, and whether it is a UInt64 past High(Int64) } + function OrdOf(aV: PIfRVariant; out aHuge: Boolean): Int64; + begin + aHuge := False; + case aV.FType.BaseType of + btU8: Result := aV^.tu8; + btS8: Result := aV^.ts8; + btU16: Result := aV^.tu16; + btS16: Result := aV^.ts16; + btU32: Result := aV^.tu32; + btS32: Result := aV^.ts32; + {$IFNDEF PS_NOINT64} + btS64: Result := aV^.ts64; + btU64: + begin + Result := PInt64(@aV^.tu64)^; + aHuge := Result < 0; + end; + {$ENDIF} + else + Result := 0; + end; + end; + + begin + Result := False; + if not (Cmd in [otGreaterEqual, otLessEqual, otGreater, otLess, otEqual, otNotEqual]) or + not IsIntType(var1.FType.BaseType) then + exit; + if IsIntType(var2.FType.BaseType) or (var2.FType.BaseType = btCurrency) then + begin + if var2.FType.BaseType = btCurrency then + lC := -CurrencyOrder(var2, var1) + else + begin + lI1 := OrdOf(var1, lHuge1); + lI2 := OrdOf(var2, lHuge2); + if lHuge1 <> lHuge2 then + begin + if lHuge1 then + lC := 1 + else + lC := -1; + end else if lI1 < lI2 then + lC := -1 + else if lI1 > lI2 then + lC := 1 + else + lC := 0; + end; + case Cmd of + otGreaterEqual: aResult := lC >= 0; + otLessEqual: aResult := lC <= 0; + otGreater: aResult := lC > 0; + otLess: aResult := lC < 0; + otNotEqual: aResult := lC <> 0; + else + aResult := lC = 0; + end; + end else if IsRealType(var2.FType.BaseType) then + begin + lI1 := OrdOf(var1, lHuge1); + lR1 := lI1; + if lHuge1 then + lR1 := lR1 + 18446744073709551616.0; + lOk := True; + lR2 := GetReal(var2, lOk); + if not lOk then + exit; + case Cmd of + otGreaterEqual: aResult := lR1 >= lR2; + otLessEqual: aResult := lR1 <= lR2; + otGreater: aResult := lR1 > lR2; + otLess: aResult := lR1 < lR2; + otNotEqual: aResult := lR1 <> lR2; + else + aResult := lR1 = lR2; + end; + end else + exit; + Result := True; + end; +{$IFNDEF PS_NOWIDESTRING} + + { an AnsiString or Char constant compared with a wide one compares as a UnicodeString, as the run time + compares them (DoBooleanCalc): the cases below read the wide one through the ANSI code page } + function WideCompare(out aResult: Boolean): Boolean; + var + lU1, lU2: tbtunicodestring; + lOk: Boolean; + begin + Result := False; + if not (Cmd in [otGreaterEqual, otLessEqual, otGreater, otLess, otEqual, otNotEqual]) or + not ((var1.FType.BaseType = btString) or (var1.FType.BaseType = btChar)) or + not ((var2.FType.BaseType = btWideChar) or (var2.FType.BaseType = btWideString) or + (var2.FType.BaseType = btUnicodeString)) then + exit; + lOk := True; + lU1 := GetUnicodeString(var1, lOk); + lU2 := GetUnicodeString(var2, lOk); + if not lOk then + exit; + case Cmd of + otGreaterEqual: aResult := lU1 >= lU2; + otLessEqual: aResult := lU1 <= lU2; + otGreater: aResult := lU1 > lU2; + otLess: aResult := lU1 < lU2; + otNotEqual: aResult := lU1 <> lU2; + else + aResult := lU1 = lU2; + end; + Result := True; + end; +{$ENDIF} + + { two Currency constants, or a Currency and an integer one, are multiplied and divided as the run + time does it (DoCalc), the integer in its own type: the cases below read the right one as an + Extended, which is a Double on Win64. + and - are CurrencySum's; a comparison is exact, as Delphi + compares constants } + function CurrencyCalc: Boolean; + var + lB: Boolean; + lC: Integer; + begin + Result := (var1.FType.BaseType = btCurrency) and ((var2.FType.BaseType = btCurrency) or + (var2.FType.BaseType in [btU8, btS8, btU16, btS16, btU32, btS32{$IFNDEF PS_NOINT64}, btS64, btU64{$ENDIF}])) and + (Cmd in [otMul, otDiv{$IFNDEF PS_DELPHIDIV}, otIntDiv{$ENDIF}, otGreaterEqual, otLessEqual, + otGreater, otLess, otEqual, otNotEqual]); + if not Result then + exit; + case Cmd of + otMul: + case var2.FType.BaseType of + btU8: var1^.tcurrency := var1^.tcurrency * var2^.tu8; + btS8: var1^.tcurrency := var1^.tcurrency * var2^.ts8; + btU16: var1^.tcurrency := var1^.tcurrency * var2^.tu16; + btS16: var1^.tcurrency := var1^.tcurrency * var2^.ts16; + btU32: var1^.tcurrency := var1^.tcurrency * var2^.tu32; + btS32: var1^.tcurrency := var1^.tcurrency * var2^.ts32; + {$IFNDEF PS_NOINT64} + btS64: var1^.tcurrency := var1^.tcurrency * var2^.ts64; + btU64: var1^.tcurrency := var1^.tcurrency * var2^.tu64; + {$ENDIF} + else + var1^.tcurrency := var1^.tcurrency * var2^.tcurrency; + end; + otDiv{$IFNDEF PS_DELPHIDIV}, otIntDiv{$ENDIF}: + case var2.FType.BaseType of + btU8: var1^.tcurrency := var1^.tcurrency / var2^.tu8; + btS8: var1^.tcurrency := var1^.tcurrency / var2^.ts8; + btU16: var1^.tcurrency := var1^.tcurrency / var2^.tu16; + btS16: var1^.tcurrency := var1^.tcurrency / var2^.ts16; + btU32: var1^.tcurrency := var1^.tcurrency / var2^.tu32; + btS32: var1^.tcurrency := var1^.tcurrency / var2^.ts32; + {$IFNDEF PS_NOINT64} + btS64: var1^.tcurrency := var1^.tcurrency / var2^.ts64; + btU64: var1^.tcurrency := var1^.tcurrency / var2^.tu64; + {$ENDIF} + else + var1^.tcurrency := var1^.tcurrency / var2^.tcurrency; + end; + else + begin + lC := CurrencyOrder(var1, var2); + case Cmd of + otGreaterEqual: lB := lC >= 0; + otLessEqual: lB := lC <= 0; + otGreater: lB := lC > 0; + otLess: lB := lC < 0; + otNotEqual: lB := lC <> 0; + else + lB := lC = 0; + end; + ConvertToBoolean(Self, FUseUsedTypes, Var1, lB); + end; + end; + end; + + { two integer constants, the left one a 32- or 64-bit integer and the right + one a value the left one's type holds: whether + - * div mod -- and /, + which divides integers here -- is past that type's range; the cases + below keep the left one's type and wrap. Delphi refuses such a constant + where it computes in the left one's type -- the right one's type within + the left one's, or the right one a literal -- but the least Int64 times + -1, which it takes as the least Int64, and on Delphi 7, whose UInt64 is + signed, a UInt64 below 0; where it widens, as for an + Integer and a Cardinal, or treats an Int64 and a UInt64 as unsigned, the + result here still keeps the left one's type and is refused too. The + least value div or mod -1 is refused, the mod though its remainder is + 0, as Delphi refuses both. A right operand the left one's type does not + hold, and a narrower left one, keep the left operand's type as before. } + function IntegerPastTheRange: Boolean; + var + lA, lR, lLow, lHigh, lE: Int64; + lHugeA, lHugeR: Boolean; + {$IFNDEF PS_NOINT64} + lAh, lAl, lRh, lRl, lCross, lPart: Int64; + {$ENDIF} + + { aV's value, and whether it is a UInt64 past High(Int64), whose bits it + holds; False for a constant that is no integer } + function IntOf(aV: PIfRVariant; out aVal: Int64; out aHuge: Boolean): Boolean; + begin + Result := True; + aHuge := False; + case aV.FType.BaseType of + btU8: aVal := aV^.tu8; + btS8: aVal := aV^.ts8; + btU16: aVal := aV^.tu16; + btS16: aVal := aV^.ts16; + btU32: aVal := aV^.tu32; + btS32: aVal := aV^.ts32; + {$IFNDEF PS_NOINT64} + btS64: aVal := aV^.ts64; + btU64: + begin + aVal := PInt64(@aV^.tu64)^; + aHuge := aVal < 0; + end; + {$ENDIF} + else + Result := False; + end; + end; + + { a <= b, both read as UInt64 } + function UnsignedAtMost(a, b: Int64): Boolean; + begin + Result := (a xor Low(Int64)) <= (b xor Low(Int64)); + end; + + begin + Result := False; + if not (Cmd in [otAdd, otSub, otMul, otIntDiv, otMod{$IFNDEF PS_DELPHIDIV}, otDiv{$ENDIF}]) or + not IntOf(var1, lA, lHugeA) or not IntOf(var2, lR, lHugeR) then + exit; + case var1.FType.BaseType of + btS32, btU32: + begin + if var1.FType.BaseType = btS32 then + begin + lLow := Low(Longint); + lHigh := High(Longint); + end else + begin + lLow := 0; + lHigh := High(Cardinal); + end; + if lHugeR or (lR < lLow) or (lR > lHigh) then + exit; + case Cmd of + otAdd: lE := lA + lR; + otSub: lE := lA - lR; + otMul: + { an unsigned product can pass an Int64: compared by a quotient first } + if (lA > 0) and (lR > 0) and (lR > lHigh div lA) then + begin + Result := True; + exit; + end else + lE := lA * lR; + else + begin + { a quotient or remainder: only the least Integer by -1 } + Result := (lLow < 0) and (lA = lLow) and (lR = -1); + exit; + end; + end; + Result := (lE < lLow) or (lE > lHigh); + end; + {$IFNDEF PS_NOINT64} + btS64: + begin + if lHugeR then + exit; + case Cmd of + otAdd: Result := ((lR > 0) and (lA > High(Int64) - lR)) or ((lR < 0) and (lA < Low(Int64) - lR)); + otSub: Result := ((lR < 0) and (lA > High(Int64) + lR)) or ((lR > 0) and (lA < Low(Int64) + lR)); + otMul: + if (lA = 0) or (lR = 0) then + Result := False + else if lA > 0 then + begin + if lR > 0 then + Result := lA > High(Int64) div lR + else + Result := lR < Low(Int64) div lA; + end else if lR > 0 then + Result := lA < Low(Int64) div lR + else + Result := lR < High(Int64) div lA; + else + { a quotient or remainder: only the least Int64 by -1 } + Result := (lA = Low(Int64)) and (lR = -1); + end; + end; + btU64: + begin + if (lR < 0) and not lHugeR then + exit; + case Cmd of + otAdd: Result := not UnsignedAtMost(lA, lA + lR); + otSub: Result := not UnsignedAtMost(lR, lA); + otMul: + begin + { by the 32-bit halves: past 64 bits when both high halves are + set, when the cross product passes 32 bits, or when adding + it to the low product carries } + lAh := lA shr 32; + lAl := lA and $00000000FFFFFFFF; + lRh := lR shr 32; + lRl := lR and $00000000FFFFFFFF; + if (lAh <> 0) and (lRh <> 0) then + Result := True + else + begin + lCross := lAh * lRl + lAl * lRh; + if lCross shr 32 <> 0 then + Result := True + else + begin + lPart := lAl * lRl; + Result := not UnsignedAtMost(lPart, lPart + lCross shl 32); + end; + end; + end; + end; + end; + {$ENDIF} + end; + end; + +begin + Result := True; + lRefused := False; + try + if NaNCompare(b) then + begin + ConvertToBoolean(Self, FUseUsedTypes, Var1, b); + exit; + end; + if NumericCompare(b){$IFNDEF PS_NOWIDESTRING} or WideCompare(b){$ENDIF} then + begin + ConvertToBoolean(Self, FUseUsedTypes, Var1, b); + exit; + end; + if not CurrencyResult(lDone) then + begin + Result := False; + exit; + end; + if lDone then + exit; + if CurrencyCalc then + exit; + if IntegerPastTheRange then + begin + MakeError('', ecCustomError, tbtstring(RPS_ConstantOverflow)); + Result := False; + exit; + end; + if (IsRealType(var2.FType.BaseType) and IsIntType(var1.FType.BaseType)) then + ConvertToFloat(Self, FUseUsedTypes, var1, var2^.FType); + case Cmd of + otAdd: + begin { + } + case var1.FType.BaseType of + btU8: var1^.tu8 := var1^.tu8 + GetUint(Var2, Result); + btS8: var1^.ts8 := var1^.ts8 + GetInt(Var2, Result); + btU16: var1^.tu16 := var1^.tu16 + GetUint(Var2, Result); + btS16: var1^.ts16 := var1^.ts16 + Getint(Var2, Result); + btEnum, btU32: var1^.tu32 := var1^.tu32 + GetUint(Var2, Result); + btS32: var1^.ts32 := var1^.ts32 + Getint(Var2, Result); + {$IFNDEF PS_NOINT64}btS64: var1^.ts64 := var1^.ts64 + GetInt64(Var2, Result); + btU64: var1^.tu64 := var1^.tu64 + GetUInt64(Var2, Result);{$ENDIF} + btSingle: var1^.tsingle := var1^.tsingle + GetReal( Var2, Result); + btDouble: var1^.tdouble := var1^.tdouble + GetReal( Var2, Result); + btExtended: var1^.textended := var1^.textended + GetReal( Var2, Result); + btCurrency: var1^.tcurrency := {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(var1^.tcurrency){$ELSE}var1^.tcurrency{$ENDIF} + GetReal( Var2, Result); + btSet: + begin + if (var1.FType = var2.FType) then + begin + UniqueString(tbtstring(var1^.tstring)); + Set_Union(var1.tstring, var2.tstring, TPSSetType(var1.FType).ByteSize); + end else Result := False; + end; + { a wide right operand makes the sum a UnicodeString, as in Delphi and as the run time adds them: + the AnsiString sum read it through the ANSI code page } + btChar: + begin + {$IFNDEF PS_NOWIDESTRING} + if (var2.FType.BaseType = btWideChar) or (var2.FType.BaseType = btWideString) or + (var2.FType.BaseType = btUnicodeString) then + ConvertToUnicodeString(Self, FUseUsedTypes, var1, GetUnicodeString(Var1, Result)+GetUnicodeString(Var2, Result)) + else + {$ENDIF} + ConvertToString(Self, FUseUsedTypes, var1, getstring(Var1, Result)+getstring(Var2, Result)); + end; + btString: + {$IFNDEF PS_NOWIDESTRING} + if (var2.FType.BaseType = btWideChar) or (var2.FType.BaseType = btWideString) or + (var2.FType.BaseType = btUnicodeString) then + ConvertToUnicodeString(Self, FUseUsedTypes, var1, GetUnicodeString(Var1, Result)+GetUnicodeString(Var2, Result)) + else + {$ENDIF} + tbtstring(var1^.tstring) := tbtstring(var1^.tstring) + GetString(Var2, Result); + {$IFNDEF PS_NOWIDESTRING} + btwideString: tbtwidestring(var1^.twidestring) := tbtwidestring(var1^.twidestring) + GetWideString(Var2, Result); + btUnicodeString: tbtunicodestring(var1^.tunistring) := tbtunicodestring(var1^.tunistring) + GetUnicodeString(Var2, Result); + btWidechar: + begin + ConvertToUnicodeString(Self, FUseUsedTypes, var1, GetUnicodeString(Var1, Result)+GetUnicodeString(Var2, Result)); + end; + {$ENDIF} + else Result := False; + end; + end; + otSub: + begin { - } + case Var1.FType.BaseType of + btU8: var1^.tu8 := var1^.tu8 - GetUint(Var2, Result); btS8: var1^.ts8 := var1^.ts8 - Getint(Var2, Result); btU16: var1^.tu16 := var1^.tu16 - GetUint(Var2, Result); btS16: var1^.ts16 := var1^.ts16 - Getint(Var2, Result); @@ -3385,11 +4334,12 @@ function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: btSingle: var1^.tsingle := var1^.tsingle - GetReal( Var2, Result); btDouble: var1^.tdouble := var1^.tdouble - GetReal(Var2, Result); btExtended: var1^.textended := var1^.textended - GetReal(Var2, Result); - btCurrency: var1^.tcurrency := var1^.tcurrency - GetReal( Var2, Result); + btCurrency: var1^.tcurrency := {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(var1^.tcurrency){$ELSE}var1^.tcurrency{$ENDIF} - GetReal( Var2, Result); btSet: begin if (var1.FType = var2.FType) then begin + UniqueString(tbtstring(var1^.tstring)); Set_Diff(var1.tstring, var2.tstring, TPSSetType(var1.FType).ByteSize); end else Result := False; end; @@ -3410,11 +4360,12 @@ function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: btSingle: var1^.tsingle := var1^.tsingle * GetReal(Var2, Result); btDouble: var1^.tdouble := var1^.tdouble * GetReal(Var2, Result); btExtended: var1^.textended := var1^.textended * GetReal( Var2, Result); - btCurrency: var1^.tcurrency := var1^.tcurrency * GetReal( Var2, Result); + btCurrency: var1^.tcurrency := {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(var1^.tcurrency){$ELSE}var1^.tcurrency{$ENDIF} * GetReal( Var2, Result); btSet: begin if (var1.FType = var2.FType) then begin + UniqueString(tbtstring(var1^.tstring)); Set_Intersect(var1.tstring, var2.tstring, TPSSetType(var1.FType).ByteSize); end else Result := False; end; @@ -3437,12 +4388,80 @@ function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: otIntDiv: begin { / } case Var1.FType.BaseType of - btU8: var1^.tu8 := var1^.tu8 div GetUint(Var2, Result); - btS8: var1^.ts8 := var1^.ts8 div Getint(Var2, Result); - btU16: var1^.tu16 := var1^.tu16 div GetUint(Var2, Result); - btS16: var1^.ts16 := var1^.ts16 div Getint(Var2, Result); - btU32: var1^.tu32 := var1^.tu32 div GetUint(Var2, Result); - btS32: var1^.ts32 := var1^.ts32 div Getint(Var2, Result); + { a 64-bit divisor is not narrowed, as for a 32-bit dividend } + btU8: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.tu8 := var1^.tu8 div var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.tu8 := var1^.tu8 div var2^.tu64 + { a signed divisor makes the division signed, as in Delphi } + else if var2.FType.BaseType in [btS8, btS16, btS32] then + var1^.tu8 := Int64(var1^.tu8) div Getint(Var2, Result) + else + {$ENDIF} + var1^.tu8 := var1^.tu8 div GetUint(Var2, Result); + btS8: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.ts8 := var1^.ts8 div var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.ts8 := var1^.ts8 div var2^.tu64 + { a Cardinal divisor makes the division 64-bit, as in Delphi } + else if var2.FType.BaseType = btU32 then + var1^.ts8 := Int64(var1^.ts8) div GetUint(Var2, Result) + else + {$ENDIF} + var1^.ts8 := var1^.ts8 div Getint(Var2, Result); + btU16: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.tu16 := var1^.tu16 div var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.tu16 := var1^.tu16 div var2^.tu64 + { a signed divisor makes the division signed, as in Delphi } + else if var2.FType.BaseType in [btS8, btS16, btS32] then + var1^.tu16 := Int64(var1^.tu16) div Getint(Var2, Result) + else + {$ENDIF} + var1^.tu16 := var1^.tu16 div GetUint(Var2, Result); + btS16: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.ts16 := var1^.ts16 div var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.ts16 := var1^.ts16 div var2^.tu64 + { a Cardinal divisor makes the division 64-bit, as in Delphi } + else if var2.FType.BaseType = btU32 then + var1^.ts16 := Int64(var1^.ts16) div GetUint(Var2, Result) + else + {$ENDIF} + var1^.ts16 := var1^.ts16 div Getint(Var2, Result); + { a 64-bit divisor is not narrowed, as the run time divides (DoCalc) } + btU32: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.tu32 := var1^.tu32 div var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.tu32 := var1^.tu32 div var2^.tu64 + { a signed divisor makes the division signed, as in Delphi } + else if var2.FType.BaseType in [btS8, btS16, btS32] then + var1^.tu32 := Int64(var1^.tu32) div Getint(Var2, Result) + else + {$ENDIF} + var1^.tu32 := var1^.tu32 div GetUint(Var2, Result); + btS32: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.ts32 := var1^.ts32 div var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.ts32 := var1^.ts32 div var2^.tu64 + { a Cardinal divisor makes the division 64-bit, as in Delphi } + else if var2.FType.BaseType = btU32 then + var1^.ts32 := Int64(var1^.ts32) div GetUint(Var2, Result) + else + {$ENDIF} + var1^.ts32 := var1^.ts32 div Getint(Var2, Result); {$IFNDEF PS_NOINT64}btS64: var1^.ts64 := var1^.ts64 div GetInt64(Var2, Result); btU64: var1^.tu64 := var1^.tu64 div GetUInt64(Var2, Result);{$ENDIF} else Result := False; @@ -3452,12 +4471,80 @@ function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: otDiv, otIntDiv: begin { / } case Var1.FType.BaseType of - btU8: var1^.tu8 := var1^.tu8 div GetUint(Var2, Result); - btS8: var1^.ts8 := var1^.ts8 div Getint(Var2, Result); - btU16: var1^.tu16 := var1^.tu16 div GetUint(Var2, Result); - btS16: var1^.ts16 := var1^.ts16 div Getint(Var2, Result); - btU32: var1^.tu32 := var1^.tu32 div GetUint(Var2, Result); - btS32: var1^.ts32 := var1^.ts32 div Getint(Var2, Result); + { a 64-bit divisor is not narrowed, as for a 32-bit dividend } + btU8: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.tu8 := var1^.tu8 div var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.tu8 := var1^.tu8 div var2^.tu64 + { a signed divisor makes the division signed, as in Delphi } + else if var2.FType.BaseType in [btS8, btS16, btS32] then + var1^.tu8 := Int64(var1^.tu8) div Getint(Var2, Result) + else + {$ENDIF} + var1^.tu8 := var1^.tu8 div GetUint(Var2, Result); + btS8: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.ts8 := var1^.ts8 div var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.ts8 := var1^.ts8 div var2^.tu64 + { a Cardinal divisor makes the division 64-bit, as in Delphi } + else if var2.FType.BaseType = btU32 then + var1^.ts8 := Int64(var1^.ts8) div GetUint(Var2, Result) + else + {$ENDIF} + var1^.ts8 := var1^.ts8 div Getint(Var2, Result); + btU16: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.tu16 := var1^.tu16 div var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.tu16 := var1^.tu16 div var2^.tu64 + { a signed divisor makes the division signed, as in Delphi } + else if var2.FType.BaseType in [btS8, btS16, btS32] then + var1^.tu16 := Int64(var1^.tu16) div Getint(Var2, Result) + else + {$ENDIF} + var1^.tu16 := var1^.tu16 div GetUint(Var2, Result); + btS16: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.ts16 := var1^.ts16 div var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.ts16 := var1^.ts16 div var2^.tu64 + { a Cardinal divisor makes the division 64-bit, as in Delphi } + else if var2.FType.BaseType = btU32 then + var1^.ts16 := Int64(var1^.ts16) div GetUint(Var2, Result) + else + {$ENDIF} + var1^.ts16 := var1^.ts16 div Getint(Var2, Result); + { a 64-bit divisor is not narrowed, as the run time divides (DoCalc) } + btU32: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.tu32 := var1^.tu32 div var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.tu32 := var1^.tu32 div var2^.tu64 + { a signed divisor makes the division signed, as in Delphi } + else if var2.FType.BaseType in [btS8, btS16, btS32] then + var1^.tu32 := Int64(var1^.tu32) div Getint(Var2, Result) + else + {$ENDIF} + var1^.tu32 := var1^.tu32 div GetUint(Var2, Result); + btS32: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.ts32 := var1^.ts32 div var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.ts32 := var1^.ts32 div var2^.tu64 + { a Cardinal divisor makes the division 64-bit, as in Delphi } + else if var2.FType.BaseType = btU32 then + var1^.ts32 := Int64(var1^.ts32) div GetUint(Var2, Result) + else + {$ENDIF} + var1^.ts32 := var1^.ts32 div Getint(Var2, Result); {$IFNDEF PS_NOINT64}btS64: var1^.ts64 := var1^.ts64 div GetInt64(Var2, Result); btU64: var1^.tu64 := var1^.tu64 div GetUInt64(Var2, Result);{$ENDIF} btSingle: var1^.tsingle := var1^.tsingle / GetReal( Var2, Result); @@ -3471,12 +4558,80 @@ function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: otMod: begin { MOD } case Var1.FType.BaseType of - btU8: var1^.tu8 := var1^.tu8 mod GetUint(Var2, Result); - btS8: var1^.ts8 := var1^.ts8 mod Getint(Var2, Result); - btU16: var1^.tu16 := var1^.tu16 mod GetUint(Var2, Result); - btS16: var1^.ts16 := var1^.ts16 mod Getint(Var2, Result); - btU32: var1^.tu32 := var1^.tu32 mod GetUint(Var2, Result); - btS32: var1^.ts32 := var1^.ts32 mod Getint(Var2, Result); + { a 64-bit divisor is not narrowed, as for a 32-bit dividend } + btU8: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.tu8 := var1^.tu8 mod var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.tu8 := var1^.tu8 mod var2^.tu64 + { a signed divisor makes the division signed, as in Delphi } + else if var2.FType.BaseType in [btS8, btS16, btS32] then + var1^.tu8 := Int64(var1^.tu8) mod Getint(Var2, Result) + else + {$ENDIF} + var1^.tu8 := var1^.tu8 mod GetUint(Var2, Result); + btS8: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.ts8 := var1^.ts8 mod var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.ts8 := var1^.ts8 mod var2^.tu64 + { a Cardinal divisor makes the division 64-bit, as in Delphi } + else if var2.FType.BaseType = btU32 then + var1^.ts8 := Int64(var1^.ts8) mod GetUint(Var2, Result) + else + {$ENDIF} + var1^.ts8 := var1^.ts8 mod Getint(Var2, Result); + btU16: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.tu16 := var1^.tu16 mod var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.tu16 := var1^.tu16 mod var2^.tu64 + { a signed divisor makes the division signed, as in Delphi } + else if var2.FType.BaseType in [btS8, btS16, btS32] then + var1^.tu16 := Int64(var1^.tu16) mod Getint(Var2, Result) + else + {$ENDIF} + var1^.tu16 := var1^.tu16 mod GetUint(Var2, Result); + btS16: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.ts16 := var1^.ts16 mod var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.ts16 := var1^.ts16 mod var2^.tu64 + { a Cardinal divisor makes the division 64-bit, as in Delphi } + else if var2.FType.BaseType = btU32 then + var1^.ts16 := Int64(var1^.ts16) mod GetUint(Var2, Result) + else + {$ENDIF} + var1^.ts16 := var1^.ts16 mod Getint(Var2, Result); + { a 64-bit divisor is not narrowed, as the run time divides (DoCalc) } + btU32: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.tu32 := var1^.tu32 mod var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.tu32 := var1^.tu32 mod var2^.tu64 + { a signed divisor makes the division signed, as in Delphi } + else if var2.FType.BaseType in [btS8, btS16, btS32] then + var1^.tu32 := Int64(var1^.tu32) mod Getint(Var2, Result) + else + {$ENDIF} + var1^.tu32 := var1^.tu32 mod GetUint(Var2, Result); + btS32: + {$IFNDEF PS_NOINT64} + if var2.FType.BaseType = btS64 then + var1^.ts32 := var1^.ts32 mod var2^.ts64 + else if var2.FType.BaseType = btU64 then + var1^.ts32 := var1^.ts32 mod var2^.tu64 + { a Cardinal divisor makes the division 64-bit, as in Delphi } + else if var2.FType.BaseType = btU32 then + var1^.ts32 := Int64(var1^.ts32) mod GetUint(Var2, Result) + else + {$ENDIF} + var1^.ts32 := var1^.ts32 mod Getint(Var2, Result); {$IFNDEF PS_NOINT64}btS64: var1^.ts64 := var1^.ts64 mod GetInt64(Var2, Result); btU64: var1^.tu64 := var1^.tu64 mod GetUInt64(Var2, Result);{$ENDIF} else Result := False; @@ -3519,7 +4674,11 @@ function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: btS16: var1^.ts16 := var1^.ts16 and Getint(Var2, Result); btU32: var1^.tu32 := var1^.tu32 and GetUint(Var2, Result); btS32: var1^.ts32 := var1^.ts32 and Getint(Var2, Result); - btEnum: var1^.ts32 := var1^.ts32 and Getint(Var2, Result); + btEnum: + if WideBoolConsts then + var1^.ts32 := Ord((var1^.ts32 <> 0) and (Getint(Var2, Result) <> 0)) + else + var1^.ts32 := var1^.ts32 and Getint(Var2, Result); {$IFNDEF PS_NOINT64}btS64: var1^.ts64 := var1^.ts64 and GetInt64(Var2, Result); btU64: var1^.tu64 := var1^.tu64 and GetUInt64(Var2, Result);{$ENDIF} else Result := False; @@ -3536,7 +4695,11 @@ function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: btS32: var1^.ts32 := var1^.ts32 or Getint(Var2, Result); {$IFNDEF PS_NOINT64}btS64: var1^.ts64 := var1^.ts64 or GetInt64(Var2, Result); btU64: var1^.tu64 := var1^.tu64 or GetUInt64(Var2, Result);{$ENDIF} - btEnum: var1^.ts32 := var1^.ts32 or Getint(Var2, Result); + btEnum: + if WideBoolConsts then + var1^.ts32 := Ord((var1^.ts32 <> 0) or (Getint(Var2, Result) <> 0)) + else + var1^.ts32 := var1^.ts32 or Getint(Var2, Result); else Result := False; end; end; @@ -3551,7 +4714,11 @@ function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: btS32: var1^.ts32 := var1^.ts32 xor Getint(Var2, Result); {$IFNDEF PS_NOINT64}btS64: var1^.ts64 := var1^.ts64 xor GetInt64(Var2, Result); btU64: var1^.tu64 := var1^.tu64 xor GetUInt64(Var2, Result);{$ENDIF} - btEnum: var1^.ts32 := var1^.ts32 xor Getint(Var2, Result); + btEnum: + if WideBoolConsts then + var1^.ts32 := Ord((var1^.ts32 <> 0) xor (Getint(Var2, Result) <> 0)) + else + var1^.ts32 := var1^.ts32 xor Getint(Var2, Result); else Result := False; end; end; @@ -3566,6 +4733,11 @@ function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: btS32: b := var1^.ts32 >= Getint(Var2, Result); {$IFNDEF PS_NOINT64}btS64: b := var1^.ts64 >= GetInt64(Var2, Result); btU64: b := var1^.tu64 >= GetUInt64(Var2, Result);{$ENDIF} + btEnum: + if var1.FType = var2.FType then + b := var1^.tu32 >= GetUint(Var2, Result) + else + Result := False; btSingle: b := var1^.tsingle >= GetReal( Var2, Result); btDouble: b := var1^.tdouble >= GetReal( Var2, Result); btExtended: b := var1^.textended >= GetReal( Var2, Result); @@ -3601,6 +4773,11 @@ function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: btS32: b := var1^.ts32 <= Getint(Var2, Result); {$IFNDEF PS_NOINT64}btS64: b := var1^.ts64 <= GetInt64(Var2, Result); btU64: b := var1^.tu64 <= GetUInt64(Var2, Result);{$ENDIF} + btEnum: + if var1.FType = var2.FType then + b := var1^.tu32 <= GetUint(Var2, Result) + else + Result := False; btSingle: b := var1^.tsingle <= GetReal( Var2, Result); btDouble: b := var1^.tdouble <= GetReal( Var2, Result); btExtended: b := var1^.textended <= GetReal( Var2, Result); @@ -3636,6 +4813,11 @@ function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: btS32: b := var1^.ts32 > Getint(Var2, Result); {$IFNDEF PS_NOINT64}btS64: b := var1^.ts64 > GetInt64(Var2, Result); btU64: b := var1^.tu64 > GetUInt64(Var2, Result);{$ENDIF} + btEnum: + if var1.FType = var2.FType then + b := var1^.tu32 > GetUint(Var2, Result) + else + Result := False; btSingle: b := var1^.tsingle > GetReal( Var2, Result); btDouble: b := var1^.tdouble > GetReal( Var2, Result); btExtended: b := var1^.textended > GetReal( Var2, Result); @@ -3664,6 +4846,11 @@ function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: btS32: b := var1^.ts32 < Getint(Var2, Result); {$IFNDEF PS_NOINT64}btS64: b := var1^.ts64 < GetInt64(Var2, Result); btU64: b := var1^.tu64 < GetUInt64(Var2, Result);{$ENDIF} + btEnum: + if var1.FType = var2.FType then + b := var1^.tu32 < GetUint(Var2, Result) + else + Result := False; btSingle: b := var1^.tsingle < GetReal( Var2, Result); btDouble: b := var1^.tdouble < GetReal( Var2, Result); btExtended: b := var1^.textended < GetReal( Var2, Result); @@ -3696,7 +4883,11 @@ function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: btDouble: b := var1^.tdouble <> GetReal( Var2, Result); btExtended: b := var1^.textended <> GetReal( Var2, Result); btCurrency: b := var1^.tcurrency <> GetReal( Var2, Result); - btEnum: b := var1^.ts32 <> Getint(Var2, Result); + btEnum: + if WideBoolConsts then + b := (var1^.ts32 <> 0) <> (Getint(Var2, Result) <> 0) + else + b := var1^.ts32 <> Getint(Var2, Result); btString: b := tbtstring(var1^.tstring) <> GetString(var2, Result); btChar: b := var1^.tchar <> GetString(var2, Result); {$IFNDEF PS_NOWIDESTRING} @@ -3733,7 +4924,11 @@ function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: btDouble: b := var1^.tdouble = GetReal( Var2, Result); btExtended: b := var1^.textended = GetReal( Var2, Result); btCurrency: b := var1^.tcurrency = GetReal( Var2, Result); - btEnum: b := var1^.ts32 = Getint(Var2, Result); + btEnum: + if WideBoolConsts then + b := (var1^.ts32 <> 0) = (Getint(Var2, Result) <> 0) + else + b := var1^.ts32 = Getint(Var2, Result); btString: b := tbtstring(var1^.tstring) = GetString(var2, Result); btChar: b := var1^.tchar = GetString(var2, Result); {$IFNDEF PS_NOWIDESTRING} @@ -3771,27 +4966,30 @@ function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: begin Result := False; MakeError('', ecDivideByZero, ''); - Exit; + lRefused := True; end; on E: EZeroDivide do begin Result := False; MakeError('', ecDivideByZero, ''); - Exit; + lRefused := True; end; on E: EMathError do begin Result := False; MakeError('', ecMathError, tbtstring(e.Message)); - Exit; + lRefused := True; end; on E: Exception do begin Result := False; MakeError('', ecInternalError, tbtstring(E.Message)); - Exit; + lRefused := True; end; end; + { left after the handler: Delphi XE3 to XE5 for Win64 keep the exception object of a handler left by a jump } + if lRefused then + Exit; if not Result then begin with MakeError('', ecTypeMismatch, '') do @@ -3879,6 +5077,274 @@ procedure ClearRecSubVals(RecSubVals: TPSList); RecSubVals.Free; end; +{ Whether the upper-case name aName is one of the names in aList, each written + as declared and followed by a '|' } +function _NameInList(const aName, aList: tbtString): Boolean; +var + lRest : tbtString; + lBar : Longint; +begin + Result := False; + lRest := aList; + lBar := Pos(tbtchar('|'), lRest); + while lBar > 0 do begin + if FastUppercase(Copy(lRest, 1, lBar - 1)) = aName then begin + Result := True; + Exit; + end; + Delete(lRest, 1, lBar); + lBar := Pos(tbtchar('|'), lRest); + end; +end; + +{$IFDEF PS_USESSUPPORT} +{ Whether a constant, a variable or a routine -- a script's own or an external + one -- the module aModule declares is named aName (upper case) } +function _DeclaredInModule(aCompiler : TPSPascalCompiler; + const aName : tbtString; + const aModule : tbtString) + : Boolean; +var + lHash : Longint; + lIdx : Longint; + lProc : TPSProcedure; +begin + Result := True; + lHash := MakeHash(aName); + for lIdx := 0 to Pred(aCompiler.FConstants.Count) do + if (TPSConstant(aCompiler.FConstants.Data[lIdx]).NameHash = lHash) and + (TPSConstant(aCompiler.FConstants.Data[lIdx]).Name = aName) and + (TPSConstant(aCompiler.FConstants.Data[lIdx]).DeclareUnit = aModule) then + Exit; + for lIdx := 0 to Pred(aCompiler.FVars.Count) do + if (TPSVar(aCompiler.FVars.Data[lIdx]).NameHash = lHash) and + (TPSVar(aCompiler.FVars.Data[lIdx]).Name = aName) and + (TPSVar(aCompiler.FVars.Data[lIdx]).DeclareUnit = aModule) then + Exit; + for lIdx := 0 to Pred(aCompiler.FProcs.Count) do begin + lProc := aCompiler.FProcs.Data[lIdx]; + if (lProc is TPSInternalProcedure) and + (TPSInternalProcedure(lProc).NameHash = lHash) and + (TPSInternalProcedure(lProc).Name = aName) and + (TPSInternalProcedure(lProc).DeclareUnit = aModule) then + Exit; + if (lProc is TPSExternalProcedure) and + (TPSExternalProcedure(lProc).RegProc.NameHash = lHash) and + (TPSExternalProcedure(lProc).RegProc.Name = aName) and + (TPSExternalProcedure(lProc).DeclareUnit = aModule) then + Exit; + end; + Result := False; +end; + +{ Whether a type the module aModule declares is named aName (upper case) } +function _TypeDeclaredInModule(aCompiler : TPSPascalCompiler; + const aName : tbtString; + const aModule : tbtString) + : Boolean; +var + lHash : Longint; + lIdx : Longint; +begin + Result := True; + lHash := MakeHash(aName); + for lIdx := 0 to Pred(aCompiler.FTypes.Count) do + if (TPSType(aCompiler.FTypes.Data[lIdx]).NameHash = lHash) and + (TPSType(aCompiler.FTypes.Data[lIdx]).Name = aName) and + (TPSType(aCompiler.FTypes.Data[lIdx]).DeclareUnit = aModule) then + Exit; + Result := False; +end; + +{ How near the module aModule, which declares a name, is to the module being + compiled, as Delphi's scopes are: its own highest; then each unit its uses + clause names, the one named last nearest; then the host -- System, and + outside the main script the module '' of a host's variables; lowest, 0, a + module it reaches only through another unit or not at all } +function _ScopeRank(aCompiler : TPSPascalCompiler; + const aModule : tbtString) + : Longint; +var + lModule : tbtString; + lIdx : Longint; +begin + lModule := FastUppercase(aModule); + if lModule = FastUppercase(aCompiler.fModule) then + Result := MaxInt + else if (lModule = '') or (lModule = 'SYSTEM') then + Result := 1 + else begin + lIdx := -1; + if Assigned(aCompiler.fUnit) then + lIdx := aCompiler.fUnit.UsesIndex(lModule); + if lIdx >= 0 then + Result := lIdx + 2 + else + Result := 0; + end; +end; +{$ENDIF} + +{ The constant named aName (upper case) of the nearest scope that declares one + the module being compiled can see -- the oldest of equally near ones -- and + its scope rank in aRank; nil and -1 where there is none } +function _NearestConstant(aCompiler : TPSPascalCompiler; + const aName : tbtString; + out aRank : Longint) + : TPSConstant; +var + lHash : Longint; + lIdx : Longint; + lConst : TPSConstant; + lRank : Longint; +begin + Result := nil; + aRank := -1; + lHash := MakeHash(aName); + for lIdx := 0 to Pred(aCompiler.FConstants.Count) do begin + lConst := aCompiler.FConstants.Data[lIdx]; + if (lConst.NameHash = lHash) and (lConst.Name = aName) + {$IFDEF PS_USESSUPPORT} and aCompiler.IsInLocalUnitList(lConst.DeclareUnit){$ENDIF} then begin + lRank := {$IFDEF PS_USESSUPPORT}_ScopeRank(aCompiler, lConst.DeclareUnit){$ELSE}0{$ENDIF}; + if lRank > aRank then begin + Result := lConst; + aRank := lRank; + end; + end; + end; +end; + +{ The scope rank of the type FindType finds under the name aName (upper case); + -1 where none has it } +function _TypeRank(aCompiler : TPSPascalCompiler; + const aName : tbtString) + : Longint; +var + lHash : Longint; + lIdx : Longint; + lType : TPSType; +begin + lHash := MakeHash(aName); + for lIdx := Pred(aCompiler.FTypes.Count) downto 0 do begin + lType := aCompiler.FTypes.Data[lIdx]; + if (lType.NameHash = lHash) and (lType.Name = aName) then begin + Result := {$IFDEF PS_USESSUPPORT}_ScopeRank(aCompiler, lType.DeclareUnit){$ELSE}0{$ENDIF}; + Exit; + end; + end; + Result := -1; +end; + +{ The scope rank of the routine FindProc finds under the name aName (upper + case), without adding a host's routine to the script; -1 where none has it } +function _ProcRank(aCompiler : TPSPascalCompiler; + const aName : tbtString) + : Longint; +var + lNumber : Cardinal; + lRegProc : TPSRegProc; + lProc : TPSProcedure; +begin + Result := -1; + _LocateProc(aCompiler, aName, lNumber, lRegProc); + if lNumber <> InvalidVal then begin + lProc := aCompiler.FProcs.Data[lNumber]; + if lProc.ClassType = TPSInternalProcedure then + Result := {$IFDEF PS_USESSUPPORT}_ScopeRank(aCompiler, TPSInternalProcedure(lProc).DeclareUnit){$ELSE}0{$ENDIF} + else + Result := {$IFDEF PS_USESSUPPORT}_ScopeRank(aCompiler, TPSExternalProcedure(lProc).DeclareUnit){$ELSE}0{$ENDIF}; + end else if Assigned(lRegProc) then + Result := {$IFDEF PS_USESSUPPORT}_ScopeRank(aCompiler, lRegProc.DeclareUnit){$ELSE}0{$ENDIF}; +end; + +{ The scope rank of the nearest declaration of the name aName (upper case), + whatever its kind; -1 where nothing declares it. A variable the module + being compiled cannot see ranks lowest, where it decides nothing. } +function _NearestRank(aCompiler : TPSPascalCompiler; + const aName : tbtString) + : Longint; +var + lHash : Longint; + lIdx : Longint; + lVar : TPSVar; + lRank : Longint; +begin + _NearestConstant(aCompiler, aName, Result); + lHash := MakeHash(aName); + for lIdx := 0 to Pred(aCompiler.FVars.Count) do begin + lVar := aCompiler.FVars.Data[lIdx]; + if (lVar.NameHash = lHash) and (lVar.Name = aName) then begin + lRank := {$IFDEF PS_USESSUPPORT}_ScopeRank(aCompiler, lVar.DeclareUnit){$ELSE}0{$ENDIF}; + if lRank > Result then + Result := lRank; + end; + end; + lRank := _TypeRank(aCompiler, aName); + if lRank > Result then + Result := lRank; + lRank := _ProcRank(aCompiler, aName); + if lRank > Result then + Result := lRank; +end; + +{ Whether the routine aProc, where it is not nil, has a parameter or a local + named aName (upper case) } +function _LocalOrParamNamed( aProc : TPSInternalProcedure; + const aName : tbtString) + : Boolean; +var + lHash : Longint; + lIdx : Longint; +begin + Result := True; + if aProc <> nil then begin + lHash := MakeHash(aName); + for lIdx := 0 to Pred(aProc.ProcVars.Count) do + if (PIFPSProcVar(aProc.ProcVars.Data[lIdx]).NameHash = lHash) and + (PIFPSProcVar(aProc.ProcVars.Data[lIdx]).Name = aName) then + Exit; + for lIdx := 0 to Pred(aProc.FDecl.ParamCount) do + if aProc.FDecl.Params[lIdx].Name = aName then + Exit; + end; + Result := False; +end; + +function TPSPascalCompiler.NameIsDeclared(aProc: TPSInternalProcedure; const aName: tbtString): Boolean; +var + lHash : Longint; + lIdx : Longint; + lRank : Longint; + lProc : TPSProcedure; +begin + Result := True; + lHash := MakeHash(aName); + if _LocalOrParamNamed(aProc, aName) then + Exit; + if _NearestConstant(Self, aName, lRank) <> nil then + Exit; + for lIdx := 0 to Pred(FVars.Count) do + if (TPSVar(FVars.Data[lIdx]).NameHash = lHash) and (TPSVar(FVars.Data[lIdx]).Name = aName) + {$IFDEF PS_USESSUPPORT} and IsInLocalUnitList(TPSVar(FVars.Data[lIdx]).DeclareUnit){$ENDIF} then + Exit; + for lIdx := 0 to Pred(FTypes.Count) do + if (TPSType(FTypes.Data[lIdx]).NameHash = lHash) and (TPSType(FTypes.Data[lIdx]).Name = aName) + {$IFDEF PS_USESSUPPORT} and IsInLocalUnitList(TPSType(FTypes.Data[lIdx]).DeclareUnit){$ENDIF} then + Exit; + for lIdx := 0 to Pred(FProcs.Count) do begin + lProc := FProcs.Data[lIdx]; + if (lProc.ClassType = TPSInternalProcedure) and + (TPSInternalProcedure(lProc).NameHash = lHash) and (TPSInternalProcedure(lProc).Name = aName) + {$IFDEF PS_USESSUPPORT} and IsInLocalUnitList(TPSInternalProcedure(lProc).DeclareUnit){$ENDIF} then + Exit; + if (lProc.ClassType = TPSExternalProcedure) and + (TPSExternalProcedure(lProc).RegProc.NameHash = lHash) and (TPSExternalProcedure(lProc).RegProc.Name = aName) + {$IFDEF PS_USESSUPPORT} and IsInLocalUnitList(TPSExternalProcedure(lProc).DeclareUnit){$ENDIF} then + Exit; + end; + Result := False; +end; + function TPSPascalCompiler.ReadTypeAddProcedure(const Name: tbtString; FParser: TPSPascalParser): TPSType; var IsFunction: Boolean; @@ -3925,6 +5391,13 @@ function TPSPascalCompiler.ReadTypeAddProcedure(const Name: tbtString; FParser: MakeError('', ecIdentifierExpected, ''); exit; end; + if _ParamRepeated(Decl, FParser.GetToken, '') then + begin + Result := nil; + if FParser = Self.FParser then + MakeError('', ecDuplicateIdentifier, FParser.OriginalToken); + exit; + end; VNames := FParser.OriginalToken + '|'; FParser.Next; while FParser.CurrTokenId = CSTI_Comma do @@ -3937,6 +5410,13 @@ function TPSPascalCompiler.ReadTypeAddProcedure(const Name: tbtString; FParser: MakeError('', ecIdentifierExpected, ''); exit; end; + if _ParamRepeated(Decl, FParser.GetToken, VNames) then + begin + Result := nil; + if FParser = Self.FParser then + MakeError('', ecDuplicateIdentifier, FParser.OriginalToken); + exit; + end; VNames := VNames + FParser.GetToken + '|'; FParser.Next; end; @@ -4037,6 +5517,46 @@ function TPSPascalCompiler.ReadTypeAddProcedure(const Name: tbtString; FParser: end; {ReadTypeAddProcedure} +{ A static array's bound as the run time keeps it, a Longint: False for a value + of no integer type, or outside a Longint's range } +function _StaticArrayBound(aValue: PIfRVariant; out aBound: Longint): Boolean; +begin + Result := True; + aBound := 0; + case aValue.FType.BaseType of + btU8: + aBound := aValue.tu8; + btS8: + aBound := aValue.ts8; + btU16: + aBound := aValue.tu16; + btS16: + aBound := aValue.ts16; + btU32: + if aValue.tu32 <= Cardinal(High(Longint)) then + aBound := aValue.tu32 + else + Result := False; + btS32: + aBound := aValue.ts32; + {$IFNDEF PS_NOINT64} + btS64: + if (aValue.ts64 >= Low(Longint)) and (aValue.ts64 <= High(Longint)) then + aBound := aValue.ts64 + else + Result := False; + { a shift rather than a comparison: Delphi 7's 64-bit unsigned type is signed } + btU64: + if (aValue.tu64 shr 31) = 0 then + aBound := aValue.tu64 + else + Result := False; + {$ENDIF} + else + Result := False; + end; +end; + function TPSPascalCompiler.ReadType(const Name: tbtString; FParser: TPSPascalParser): TPSType; // InvalidVal = Invalid var TypeNo: TPSType; @@ -4044,6 +5564,7 @@ function TPSPascalCompiler.ReadType(const Name: tbtString; FParser: TPSPascalPar FieldName,fieldorgname,s: tbtString; RecSubVals: TPSList; FArrayStart, FArrayLength: Longint; + lLength: Int64; rvv: PIFPSRecordFieldTypeDef; p, p2: TPSType; tempf: PIfRVariant; @@ -4051,6 +5572,7 @@ function TPSPascalCompiler.ReadType(const Name: tbtString; FParser: TPSPascalPar InheritedFrom: tbtString; Guid: TGUID; Intf: TPSInterface; + lGuidRefused: Boolean; {$ENDIF} begin if (FParser.CurrTokenID = CSTII_Function) or (FParser.CurrTokenID = CSTII_Procedure) then @@ -4076,7 +5598,7 @@ function TPSPascalCompiler.ReadType(const Name: tbtString; FParser: TPSPascalPar TypeNo := FindType(FParser.GetToken); if TypeNo = nil then begin - MakeError('', ecUnknownIdentifier, ''); + MakeError('', ecUnknownIdentifier, FParser.OriginalToken); Result := nil; exit; end; @@ -4127,7 +5649,15 @@ function TPSPascalCompiler.ReadType(const Name: tbtString; FParser: TPSPascalPar exit; end; s := FParser.OriginalToken; - if IsDuplicate(FastUppercase(s), [dcTypes]) then + { a member of a script's enumeration is a constant of its module, refused + where a constant, a variable or a routine of that module -- a member + before it included -- has the name; a name of another module, the + host's included, may be declared again, and a host's own declaration + keeps the types-only check } + if IsDuplicate(FastUppercase(s), [dcTypes]) or + ((FParser = Self.FParser) and + {$IFDEF PS_USESSUPPORT}_DeclaredInModule(Self, FastUppercase(s), fModule) + {$ELSE}IsDuplicate(FastUppercase(s), [dcVars, dcProcs, dcConsts]){$ENDIF}) then begin if FParser = Self.FParser then MakeError('', ecDuplicateIdentifier, s); @@ -4174,24 +5704,14 @@ function TPSPascalCompiler.ReadType(const Name: tbtString; FParser: TPSPascalPar Result := nil; exit; end; - case tempf.FType.BaseType of - btU8: FArrayStart := tempf.tu8; - btS8: FArrayStart := tempf.ts8; - btU16: FArrayStart := tempf.tu16; - btS16: FArrayStart := tempf.ts16; - btU32: FArrayStart := tempf.tu32; - btS32: FArrayStart := tempf.ts32; - {$IFNDEF PS_NOINT64} - bts64: FArrayStart := tempf.ts64; - btU64: FArrayStart := tempf.tu64; - {$ENDIF} - else - begin - DisposeVariant(tempf); - MakeError('', ecTypeMismatch, ''); - Result := nil; - exit; - end; + { the run time keeps the bounds as Longints: a bound outside that range is + refused, as one of no integer type is } + if not _StaticArrayBound(tempf, FArrayStart) then + begin + DisposeVariant(tempf); + MakeError('', ecTypeMismatch, ''); + Result := nil; + exit; end; DisposeVariant(tempf); if FParser.CurrTokenID <> CSTI_TwoDots then @@ -4207,31 +5727,23 @@ function TPSPascalCompiler.ReadType(const Name: tbtString; FParser: TPSPascalPar Result := nil; exit; end; - case tempf.FType.BaseType of - btU8: FArrayLength := tempf.tu8; - btS8: FArrayLength := tempf.ts8; - btU16: FArrayLength := tempf.tu16; - btS16: FArrayLength := tempf.ts16; - btU32: FArrayLength := tempf.tu32; - btS32: FArrayLength := tempf.ts32; - {$IFNDEF PS_NOINT64} - bts64: FArrayLength := tempf.ts64; - btU64: FArrayLength := tempf.tu64; - {$ENDIF} - else + if not _StaticArrayBound(tempf, FArrayLength) then + begin DisposeVariant(tempf); MakeError('', ecTypeMismatch, ''); Result := nil; exit; end; DisposeVariant(tempf); - FArrayLength := FArrayLength - FArrayStart + 1; - if (FArrayLength < 0) or (FArrayLength > MaxInt div 4) then + { the length in 64 bits: the bounds' difference can pass a Longint's range } + lLength := Int64(FArrayLength) - FArrayStart + 1; + if (lLength < 0) or (lLength > MaxInt div 4) then begin MakeError('', ecTypeMismatch, ''); Result := nil; exit; end; + FArrayLength := lLength; if FParser.CurrTokenID <> CSTI_CloseBlock then begin MakeError('', ecCloseBlockExpected, ''); @@ -4255,8 +5767,6 @@ function TPSPascalCompiler.ReadType(const Name: tbtString; FParser: TPSPascalPar TypeNo := ReadType('', FParser); if TypeNo = nil then begin - if FParser = Self.FParser then - MakeError('', ecUnknownIdentifier, ''); Result := nil; exit; end; @@ -4325,8 +5835,16 @@ function TPSPascalCompiler.ReadType(const Name: tbtString; FParser: TPSPascalPar exit; end; FieldName := FParser.GetToken; - s := S+FParser.OriginalToken+'|'; - FParser.Next; + { a name repeated in its own list is refused, as one repeated from a list + before it is; both at the name, which the message names } + if _NameInList(FieldName, s) then + begin + if FParser = Self.FParser then + MakeError('', ecDuplicateIdentifier, FParser.OriginalToken); + ClearRecSubVals(RecSubVals); + Result := nil; + exit; + end; h := MakeHash(FieldName); for l := 0 to RecSubVals.Count - 1 do begin @@ -4340,6 +5858,8 @@ function TPSPascalCompiler.ReadType(const Name: tbtString; FParser: TPSPascalPar exit; end; end; + s := S+FParser.OriginalToken+'|'; + FParser.Next; if FParser.CurrTokenID = CSTI_Colon then Break else if FParser.CurrTokenID <> CSTI_Comma then begin @@ -4459,16 +5979,22 @@ function TPSPascalCompiler.ReadType(const Name: tbtString; FParser: TPSPascalPar Exit; end; s := FParser.GetToken; + lGuidRefused := False; try Guid := StringToGuid(String(Copy(s, 2, Length(s)-2))); except on e: Exception do begin MakeError('', ecCustomError, tbtstring(e.Message)); - Result := nil; - Exit; + lGuidRefused := True; end; end; + { left after the handler: Delphi XE3 to XE5 for Win64 keep the exception object of a handler left by a jump } + if lGuidRefused then + begin + Result := nil; + Exit; + end; {$IFNDEF PS_NOINTERFACEGUIDBRACKETS} FParser.Next; if FParser.CurrTokenId <> CSTI_CloseBlock then @@ -4667,6 +6193,7 @@ function TPSPascalCompiler.DoVarBlock(proc: TPSInternalProcedure): Boolean; v: TPSVar; vp: PIFPSProcVar; EPos, ERow, ECol: Integer; + lOldProc: TPSInternalProcedure; begin Result := False; FParser.Next; // skip CSTII_Var @@ -4725,7 +6252,13 @@ function TPSPascalCompiler.DoVarBlock(proc: TPSInternalProcedure): Boolean; exit; end; FParser.Next; - VarType := at2ut(ReadType('', FParser)); + lOldProc := FDeclaringProc; + FDeclaringProc := proc; + try + VarType := at2ut(ReadType('', FParser)); + finally + FDeclaringProc := lOldProc; + end; if VarType = nil then begin exit; @@ -4840,6 +6373,9 @@ function TPSPascalCompiler.IsProcDuplicLabel(Proc: TPSInternalProcedure; const s function TPSPascalCompiler.ProcessLabel(Proc: TPSInternalProcedure): Boolean; var CurrLabel: tbtString; +{$IFDEF FPC} + lEntry: tbtString; +{$ENDIF} begin FParser.Next; while true do @@ -4858,7 +6394,16 @@ function TPSPascalCompiler.ProcessLabel(Proc: TPSInternalProcedure): Boolean; exit; end; FParser.Next; + {$IFDEF FPC} + { a label's record is binary: a position of all ones, the name's hash, the name } + lEntry := ''; + _PSAppendBytes(lEntry, PS_mi2s($FFFFFFFF)); + _PSAppendBytes(lEntry, PS_mi2s(MakeHash(CurrLabel))); + _PSAppendBytes(lEntry, CurrLabel); + Proc.FLabels.Add(lEntry); + {$ELSE} Proc.FLabels.Add(#$FF#$FF#$FF#$FF+PS_mi2s(MakeHash(CurrLabel))+CurrLabel); + {$ENDIF} if FParser.CurrTokenId = CSTI_Semicolon then begin FParser.Next; @@ -4909,19 +6454,51 @@ procedure TPSPascalCompiler.Debug_WriteParams(ProcNo: Cardinal; Proc: TPSInterna I: Longint; s: tbtString; begin + {$IFDEF FPC} + s := #2; + _PSAppendBytes(s, PS_mi2s(ProcNo)); + {$ELSE} s := #2 + PS_mi2s(ProcNo); + {$ENDIF} if Proc.Decl.Result <> nil then begin + {$IFDEF FPC} + _PSAppendBytes(s, 'Result'); + _PSAppendByte(s, 1); + {$ELSE} s := s + 'Result' + #1; + {$ENDIF} end; for i := 0 to Proc.Decl.ParamCount -1 do + {$IFDEF FPC} + begin + _PSAppendBytes(s, Proc.Decl.Params[i].OrgName); + _PSAppendByte(s, 1); + end; + {$ELSE} s := s + Proc.Decl.Params[i].OrgName + #1; + {$ENDIF} + {$IFDEF FPC} + _PSAppendByte(s, 0); + _PSAppendByte(s, 3); + _PSAppendBytes(s, PS_mi2s(ProcNo)); + {$ELSE} s := s + #0#3 + PS_mi2s(ProcNo); + {$ENDIF} for I := 0 to Proc.ProcVars.Count - 1 do begin + {$IFDEF FPC} + _PSAppendBytes(s, PIFPSProcVar(Proc.ProcVars[I]).OrgName); + _PSAppendByte(s, 1); + {$ELSE} s := s + PIFPSProcVar(Proc.ProcVars[I]).OrgName + #1; + {$ENDIF} end; + {$IFDEF FPC} + _PSAppendByte(s, 0); + {$ELSE} s := s + #0; + {$ENDIF} WriteDebugData(s); end; @@ -4973,15 +6550,10 @@ function TPSPascalCompiler.ProcIsDuplic(Decl: TPSParametersDecl; const FunctionN exit; end; end; - u := FunctionParamNames; - while Pos(tbtchar('|'), u) > 0 do + if _NameInList(s, FunctionParamNames) then begin - if copy(u, 1, Pos(tbtchar('|'), u) - 1) = s then - begin - Result := True; - exit; - end; - Delete(u, 1, Pos(tbtchar('|'), u)); + Result := True; + exit; end; if Func = nil then begin @@ -5041,6 +6613,19 @@ function TPSPascalCompiler.ApplyAttribsToFunction(func: TPSProcedure): boolean; end; +{ Whether aDecl names its parameters as aOther does, in any case; both have + the same number of parameters } +function _SameParamNames(aDecl, aOther: TPSParametersDecl): Boolean; +var + lIdx : Longint; +begin + Result := False; + for lIdx := 0 to Pred(aDecl.ParamCount) do + if aDecl.Params[lIdx].Name <> aOther.Params[lIdx].Name then + Exit; + Result := True; +end; + function TPSPascalCompiler.ProcessFunction(AlwaysForward: Boolean; Att: TPSAttributes): Boolean; var FunctionType: TFuncType; @@ -5058,6 +6643,7 @@ function TPSPascalCompiler.ProcessFunction(AlwaysForward: Boolean; Att: TPSAttri pp2: TPSExternalProcedure; FuncNo, I: Longint; Block: TPSBlockInfo; + lMessages, lMsgIdx: Cardinal; begin if att = nil then begin @@ -5182,7 +6768,7 @@ function TPSPascalCompiler.ProcessFunction(AlwaysForward: Boolean; Att: TPSAttri end; if ProcIsDuplic(FunctionDecl, FunctionName, FunctionParamNames, FParser.GetToken, Func) then begin - MakeError('', ecDuplicateIdentifier, ''); + MakeError('', ecDuplicateIdentifier, FParser.OriginalToken); exit; end; if @FOnUseVariable <> nil then @@ -5271,18 +6857,33 @@ function TPSPascalCompiler.ProcessFunction(AlwaysForward: Boolean; Att: TPSAttri FParser.Next; if @FOnExternalProc = nil then begin - MakeError('', ecSemicolonExpected, ''); + { the host takes no library that declares external routines } + MakeError('', ecCustomError, 'External routines are not supported'); exit; end; + lMessages := FMessages.Count; pp := FOnExternalProc(Self, FunctionDecl, OriginalName, FunctionParamNames); if pp = nil then begin + { a handler refusing the declaration reports why; only where it + reported no error -- a warning or hint is none -- does the compiler + add one of its own, which has no text } + lMsgIdx := lMessages; + while lMsgIdx < FMessages.Count do + begin + if TObject(FMessages[lMsgIdx]) is TPSPascalCompilerError then + exit; + Inc(lMsgIdx); + end; MakeError('', ecCustomError, ''); exit; end; pp2 := TPSExternalProcedure.Create; pp2.Attributes.Assign(att, true); pp2.RegProc := pp; + {$IFDEF PS_USESSUPPORT} + pp2.DeclareUnit := fModule; + {$ENDIF} FProcs.Add(pp2); FRegProcs.Add(pp); Result := ApplyAttribsToFunction(pp2); @@ -5335,7 +6936,7 @@ function TPSPascalCompiler.ProcessFunction(AlwaysForward: Boolean; Att: TPSAttri exit; end; end else begin - if not FunctionDecl.Same(Func.Decl) then + if not FunctionDecl.Same(Func.Decl) or not _SameParamNames(FunctionDecl, Func.Decl) then begin MakeError('', ecForwardParameterMismatch, ''); Result := false; @@ -5432,11 +7033,15 @@ function TPSPascalCompiler.GetTypeNo(BlockInfo: TPSBlockInfo; p: TPSValue): TPST Result := nil; end; +function IsSameScriptType(t1, t2: TPSType): Boolean; forward; + function TPSPascalCompiler.IsVarInCompatible(ft1, ft2: TPSType): Boolean; begin ft1 := GetTypeCopyLink(ft1); ft2 := GetTypeCopyLink(ft2); Result := (ft1 <> ft2) and (ft2 <> nil); + if Result and IsSameScriptType(ft1, ft2) then + Result := False; end; function TPSPascalCompiler.ValidateParameters(BlockInfo: TPSBlockInfo; Params: TPSParameters; ParamTypes: TPSParametersDecl): boolean; @@ -5492,7 +7097,7 @@ function TPSPascalCompiler.ValidateParameters(BlockInfo: TPSBlockInfo; Params: T {$ENDIF} end else if (PType.BaseType = btArray) and (GetTypeNo(BlockInfo, Params[c].Val).BaseType = btArray) then begin - if TPSArrayType(GetTypeNo(BlockInfo, Params[c].Val)).ArrayTypeNo <> TPSArrayType(PType).ArrayTypeNo then + if not IsSameScriptType(TPSArrayType(GetTypeNo(BlockInfo, Params[c].Val)).ArrayTypeNo, TPSArrayType(PType).ArrayTypeNo) then begin MakeError('', ecTypeMismatch, ''); Result := False; @@ -5549,7 +7154,8 @@ function TPSPascalCompiler.DoTypeBlock(FParser: TPSPascalParser): Boolean; VName := FParser.GetToken; VOrg := FParser.OriginalToken; - if IsDuplicate(VName, [dcTypes, dcProcs, dcVars]) then + if IsDuplicate(VName, [dcTypes, dcProcs, dcVars]) + {$IFDEF PS_USESSUPPORT} or _DeclaredInModule(Self, VName, fModule){$ENDIF} then begin MakeError('', ecDuplicateIdentifier, FParser.OriginalToken); Attr.Free; @@ -5617,13 +7223,457 @@ procedure TPSPascalCompiler.Debug_WriteLine2(BlockInfo: TPSBlockInfo; IsProcExit end; +{ Every floating-point exception masked; returns the setting in force before, + for _FpuRestore } +function _FpuMaskAll: Cardinal; +{$IF Defined(CPUX86) and not Defined(FPC)} +asm + sub esp, 4 + fnstcw word ptr [esp] + movzx eax, word ptr [esp] + or word ptr [esp], $3F + fldcw word ptr [esp] + add esp, 4 +end; +{$ELSEIF Defined(CPUX64) and not Defined(FPC)} +var + lCSR: Cardinal; +asm + stmxcsr lCSR + mov eax, lCSR + or lCSR, $1F80 + ldmxcsr lCSR +end; +{$ELSEIF Defined(FPC) and Defined(CPUI386)} +{$PUSH}{$ASMMODE INTEL} +asm + sub esp, 4 + fnstcw word ptr [esp] + movzx eax, word ptr [esp] + or word ptr [esp], $3F + fldcw word ptr [esp] + add esp, 4 +end; +{$POP} +{$ELSEIF Defined(FPC) and Defined(CPUX86_64)} +{$PUSH}{$ASMMODE INTEL} +var + lCSR: Cardinal; +asm + stmxcsr lCSR + mov eax, lCSR + or lCSR, $1F80 + ldmxcsr lCSR +end; +{$POP} +{$ELSE} +begin + Result := 0; +end; +{$IFEND} + +{ The setting _FpuMaskAll returned in force again. On x87 the exception flags + are cleared first, so that one raised while they were masked does not trap on + the next instruction. The RTL's Default8087CW and DefaultMXCSR, which + Set8087CW and SetMXCSR also write, are left alone } +procedure _FpuRestore(aSaved: Cardinal); +{$IF Defined(CPUX86) and not Defined(FPC)} +asm + push eax + fnclex + fldcw word ptr [esp] + pop eax +end; +{$ELSEIF Defined(CPUX64) and not Defined(FPC)} +var + lCSR: Cardinal; +asm + mov lCSR, ecx + ldmxcsr lCSR +end; +{$ELSEIF Defined(FPC) and Defined(CPUI386)} +{$PUSH}{$ASMMODE INTEL} +asm + push eax + fnclex + fldcw word ptr [esp] + pop eax +end; +{$POP} +{$ELSEIF Defined(FPC) and Defined(CPUX86_64)} +{$PUSH}{$ASMMODE INTEL} +var + lCSR: Cardinal; +asm + mov lCSR, ecx + ldmxcsr lCSR +end; +{$POP} +{$ELSE} +begin +end; +{$IFEND} + +{ s, a real literal, with an exponent of more than nine digits after its leading + zeros cut to 999999999: the RTL's Val reads the exponent in 32 bits, so a + longer one wraps -- 1e4294967296 reads as 1 -- and from 2147483648 Val reads + outside a table of its own on Win32. Only a mantissa of about a billion + digits could bring such an exponent back into the range of a real type. } +function _RealWithBoundedExponent(const s: tbtString): tbtString; +var + lIdx: Integer; + lFirst: Integer; +begin + Result := s; + lFirst := 0; + for lIdx := 1 to Length(s) do + if (s[lIdx] = 'e') or (s[lIdx] = 'E') then + begin + lFirst := lIdx + 1; + Break; + end; + if lFirst = 0 then + Exit; + if (lFirst <= Length(s)) and ((s[lFirst] = '+') or (s[lFirst] = '-')) then + Inc(lFirst); + while (lFirst < Length(s)) and (s[lFirst] = '0') do + Inc(lFirst); + if Length(s) - lFirst + 1 > 9 then + Result := Copy(s, 1, lFirst - 1) + '999999999'; +end; + +{ aValue stored into aDest with the floating-point exceptions masked: past the + range of Single it is +Inf or -Inf, as Delphi narrows a real constant -- under + the default rounding mode; another can give a finite value instead } +procedure _NarrowToSingle(out aDest: Single; const aValue: Extended); +var + lSaved: Cardinal; +begin + lSaved := _FpuMaskAll; + try + aDest := aValue; + finally + _FpuRestore(lSaved); + end; +end; + +{ As _NarrowToSingle, for a Double: a narrowing where Extended is the wider + type (Win32) } +procedure _NarrowToDouble(out aDest: Double; const aValue: Extended); +var + lSaved: Cardinal; +begin + lSaved := _FpuMaskAll; + try + aDest := aValue; + finally + _FpuRestore(lSaved); + end; +end; + +{ aValue, a finite Double, times 10000 rounded half to even into aRaw, + computed exactly, as an 80-bit real computes it: a Double product loses the + ten-thousandths past about 900000000000. False past the range of Int64. } +function _DoubleToCurrencyRaw(const aValue: Double; out aRaw: Int64): Boolean; +var + lBits, lMant, lRem, lHalf: Int64; + lShift: Integer; +begin + lBits := PInt64(@aValue)^; + lShift := Integer((lBits shr 52) and $7FF); + lMant := lBits and $000FFFFFFFFFFFFF; + if lShift = 0 then + lShift := 1 + else + lMant := lMant or $0010000000000000; + { aValue is lMant times 2 to the power lShift - 1075, so times 10000 it is + lMant * 625 times 2 to the power lShift - 1071 } + lMant := lMant * 625; + lShift := lShift - 1071; + Result := True; + if lShift >= 0 then + begin + if (lShift > 62) or (lMant > High(Int64) shr lShift) then + begin + Result := False; + exit; + end; + aRaw := lMant shl lShift; + end else if lShift < -63 then + aRaw := 0 + else + begin + aRaw := lMant shr -lShift; + lRem := lMant - aRaw shl -lShift; + lHalf := Int64(1) shl (-lShift - 1); + if (lRem > lHalf) or ((lRem = lHalf) and (aRaw and 1 = 1)) then + Inc(aRaw); + end; + if lBits < 0 then + aRaw := -aRaw; +end; + +{ aValue stored into aDest, a Currency, and True; False, with aDest not set, + when it is no number, outside the range of Currency or its minimum, + -922337203685477.5808, which Delphi refuses for a constant. A NaN or an + infinity is found by its exponent bits, so no comparison meets one; the work + runs with the floating-point exceptions masked. The value is rounded when it + is stored, so the stored raw units are checked as well: a value that rounds + onto the minimum is refused too. } +function _NarrowToCurrency(out aDest: Currency; const aValue: Extended): Boolean; +var + lSaved: Cardinal; + lScaled: Extended; + lTop: Word; + lDest: Currency; +begin + lSaved := _FpuMaskAll; + try + lScaled := aValue * 10000; + { the sign and exponent are the top 16 bits, of an 80-bit or a 64-bit real } + Move((PAnsiChar(@lScaled) + SizeOf(Extended) - 2)^, lTop, SizeOf(lTop)); + if SizeOf(Extended) = 10 then + begin + Result := (lTop and $7FFF <> $7FFF) and (lScaled > -9223372036854775808.0) and + (lScaled < 9223372036854775807.5); + if Result then + lDest := aValue; + end else + { where Extended is a Double (Win64) the value is converted exactly: + Currency := aValue multiplies Doubles } + Result := (lTop and $7FF0 <> $7FF0) and _DoubleToCurrencyRaw(aValue, PInt64(@lDest)^); + if Result then + begin + Result := PInt64(@lDest)^ <> Low(Int64); + if Result then + aDest := lDest; + end; + finally + _FpuRestore(lSaved); + end; +end; + +{ Whether aValue, an integer, is in the range of Currency. An integer is checked + as an integer and stored as one: through a real it would lose digits where + Extended is a Double (Win64). } +function _IntFitsCurrency(const aValue: Int64): Boolean; +begin + Result := (aValue >= -922337203685477) and (aValue <= 922337203685477); +end; + +{ aText, a real literal's text with a '-' before it when negated -- digits + with at most one point, then perhaps an exponent, as the parser reads a + real -- as a Currency: its decimal value rounded half to even at the fourth + decimal, exactly, as Delphi converts such a constant: a real is a Double on + Win64, which holds neither every such value nor more than about sixteen + digits. aInexact True when a digit other than 0 was rounded off. False, + with aDest not set, when its exact value is past 922337203685477.5807 + either way, though it may round back into the range: so the minimum, + -922337203685477.5808, is refused too, as _NarrowToCurrency refuses it; + and for a text within 64 characters of the longest string, whose counts + below would pass the range of an Integer } +function _TextToCurrency(const aText: tbtString; out aDest: Currency; out aInexact: Boolean): Boolean; +var + lIdx, lLen, lExpAt, lPointAt, lFraction, lKeep, lDigitIdx, lDigit: Integer; + lExp, lKeepAll: Int64; + lNeg, lExpNeg, lUp: Boolean; + lDigits: tbtString; + lRaw: Int64; +begin + Result := False; + aInexact := False; + lLen := Length(aText); + if lLen > High(Integer) - 64 then + exit; + lNeg := aText[1] = '-'; + lIdx := 1; + if lNeg then + Inc(lIdx); + { the digits, and how many follow the point } + lExpAt := lIdx; + while (lExpAt <= lLen) and not (aText[lExpAt] in ['e', 'E']) do + Inc(lExpAt); + lDigits := Copy(aText, lIdx, lExpAt - lIdx); + lFraction := 0; + lPointAt := Pos('.', lDigits); + if lPointAt > 0 then + begin + lFraction := Length(lDigits) - lPointAt; + Delete(lDigits, lPointAt, 1); + end; + lIdx := lExpAt; + lExp := 0; + if lIdx <= lLen then + begin + { the exponent: e, perhaps a sign, digits } + Inc(lIdx); + lExpNeg := aText[lIdx] = '-'; + if aText[lIdx] in ['+', '-'] then + Inc(lIdx); + while lIdx <= lLen do + begin + { an exponent past the text's own length by this much decides the value + whatever its other digits -- past the range, or rounded to 0 -- as no + run of zeros in the text can make up for it; held in an Int64, it + cannot wrap however long the text } + if lExp <= lLen + 25 then + lExp := lExp * 10 + Ord(aText[lIdx]) - Ord('0'); + Inc(lIdx); + end; + if lExpNeg then + lExp := -lExp; + end; + { the value times 10000 is lDigits times 10 to the power lExp - lFraction + 4: + its first lKeep digits are the integer part, the rest are rounded off. + Past 20 digits more than the text holds the value is past the range or 0, + and before its first digit no digit is kept, whatever the count } + lKeepAll := Length(lDigits) + lExp - lFraction + 4; + if lKeepAll > Length(lDigits) + 20 then + lKeep := Length(lDigits) + 20 + else if lKeepAll < -1 then + lKeep := -1 + else + lKeep := lKeepAll; + lRaw := 0; + for lDigitIdx := 1 to lKeep do + begin + if lDigitIdx <= Length(lDigits) then + lDigit := Ord(lDigits[lDigitIdx]) - Ord('0') + else + lDigit := 0; + if lRaw > (High(Int64) - lDigit) div 10 then + exit; + lRaw := lRaw * 10 + lDigit; + end; + lDigitIdx := lKeep + 1; + if lDigitIdx < 1 then + lDigitIdx := 1; + while (lDigitIdx <= Length(lDigits)) and not aInexact do + begin + aInexact := lDigits[lDigitIdx] <> '0'; + Inc(lDigitIdx); + end; + { past the largest Currency, though it may round back onto it } + if aInexact and (lRaw = High(Int64)) then + exit; + if (lKeep >= 0) and (lKeep < Length(lDigits)) then + begin + lDigit := Ord(lDigits[lKeep + 1]) - Ord('0'); + if lDigit <> 5 then + lUp := lDigit > 5 + else + begin + { a tie goes to the even neighbour; a digit other than 0 after the 5 + makes it no tie } + lUp := lRaw and 1 = 1; + lDigitIdx := lKeep + 2; + while not lUp and (lDigitIdx <= Length(lDigits)) do + begin + lUp := lDigits[lDigitIdx] <> '0'; + Inc(lDigitIdx); + end; + end; + if lUp then + Inc(lRaw); + end; + if lNeg then + lRaw := -lRaw; + PInt64(@aDest)^ := lRaw; + Result := True; +end; + +{ aValue, a real constant, into aDest as _NarrowToCurrency puts it -- but from + aText, the literal it was read from, when it has one } +function _NarrowRealToCurrency(out aDest: Currency; const aValue: Extended; const aText: tbtString): Boolean; +var + lInexact: Boolean; +begin + if aText <> '' then + Result := _TextToCurrency(aText, aDest, lInexact) + else + Result := _NarrowToCurrency(aDest, aValue); +end; + +{ aText, a real literal's text, negated; '' stays '' } +function _NegatedRealText(const aText: tbtString): tbtString; +begin + if aText = '' then + Result := '' + else if aText[1] = '-' then + Result := Copy(aText, 2, MaxInt) + else + Result := '-' + aText; +end; + +{ aConst's real literal text while the constant still holds the value that + text was read as; '' once a host has given it another value or type, as + its setters and its Value property let it } +function _ConstantRealText(aConst: TPSConstant): tbtString; +begin + if (aConst.FRealText <> '') and (aConst.Value.FType.BaseType = btExtended) and + CompareMem(@aConst.Value.textended, @aConst.FRealTextValue, SizeOf(Extended)) then + Result := aConst.FRealText + else + Result := ''; +end; + +{ aVal as a Currency, into aDest, when it is a real literal -- or a constant + declared as one -- whose value a Currency holds exactly, no digit rounded + off: Delphi adds such a constant to a Currency, or takes it from one, as a + Currency, and any other as a real } +function _ExactCurrencyLiteral(aVal: TPSValue; out aDest: Currency): Boolean; +var + lInexact: Boolean; +begin + Result := (aVal.ClassType = TPSValueData) and (TPSValueData(aVal).FRealText <> '') and + _TextToCurrency(TPSValueData(aVal).FRealText, aDest, lInexact) and not lInexact; +end; + +{ The folding of a binary operation of constants, DoPreCalc, with the + floating-point exceptions masked, as Delphi folds a constant: past the range + of a real type the result is +Inf or -Inf, and an operation without a number + for its answer gives a NaN. Under the host's setting such a constant would + stop the compile where the exception is unmasked, and a Currency past its + range would be a wrong value where it is masked. } +function TPSPascalCompiler.PreCalc(FUseUsedTypes: Boolean; Var1Mod: Byte; var1: PIFRVariant; Var2Mod: Byte; Var2: PIfRVariant; Cmd: TPSBinOperatorType; Pos, Row, Col: Cardinal): Boolean; +var + lSaved: Cardinal; +begin + lSaved := _FpuMaskAll; + try + Result := DoPreCalc(FUseUsedTypes, Var1Mod, var1, Var2Mod, Var2, Cmd, Pos, Row, Col); + finally + _FpuRestore(lSaved); + end; +end; + +{ A literal past the range of Extended is +Inf, and one below it 0, however long + its exponent, under the default rounding mode: Val reads it with the + floating-point exceptions masked. On Win64 Val also writes the RTL's + DefaultMXCSR from the setting in force, which the RTL puts in force after a + floating-point exception: it is put back } function TPSPascalCompiler.ReadReal(const s: tbtString): PIfRVariant; var C: Integer; + lSaved: Cardinal; + {$IF Defined(CPUX64) and not Defined(FPC)} + lDefault: Cardinal; + {$IFEND} begin New(Result); InitializeVariant(Result, FindBaseType(btExtended)); - Val(string(s), Result^.textended, C); + {$IF Defined(CPUX64) and not Defined(FPC)} + lDefault := DefaultMXCSR; + {$IFEND} + lSaved := _FpuMaskAll; + try + Val(string(_RealWithBoundedExponent(s)), Result^.textended, C); + finally + _FpuRestore(lSaved); + {$IF Defined(CPUX64) and not Defined(FPC)} + DefaultMXCSR := lDefault; + {$IFEND} + end; end; function TPSPascalCompiler.ReadString: PIfRVariant; @@ -5633,22 +7683,69 @@ function TPSPascalCompiler.ReadString: PIfRVariant; var temp3: {$IFNDEF PS_NOWIDESTRING}tbtunicodestring{$ELSE}tbtString{$ENDIF}; - function ChrToStr(s: tbtString): {$IFNDEF PS_NOWIDESTRING}widechar{$ELSE}tbtchar{$ENDIF}; + { Appends the text of character literal s, #n or #$n, to temp3: one character + up to $FFFF, and from $10000 to $10FFFF the surrogate pair, as Delphi makes + it. A value past $10FFFF is refused, as Delphi refuses it. The value is + checked digit by digit, so it never overflows. } + function ChrToStr(s: tbtString): Boolean; var w: Longint; + lIdx: Longint; + lBase: Longint; + lDigit: Longint; + {$IFNDEF PS_NOWIDESTRING}lChar: widechar;{$ENDIF} begin - Delete(s, 1, 1); {First char : #} - w := StrToInt(s); - Result := {$IFNDEF PS_NOWIDESTRING}widechar{$ELSE}tbtchar{$ENDIF}(w); + Result := False; + if (Length(s) > 1) and (s[2] = '$') then + begin + lBase := 16; + lIdx := 3; + end else + begin + lBase := 10; + lIdx := 2; + end; + w := 0; + while lIdx <= Length(s) do + begin + case s[lIdx] of + '0'..'9': lDigit := Ord(s[lIdx]) - Ord('0'); + 'A'..'F': lDigit := Ord(s[lIdx]) - Ord('A') + 10; + 'a'..'f': lDigit := Ord(s[lIdx]) - Ord('a') + 10; + else + lDigit := lBase; + end; + if lDigit < lBase then + w := w * lBase + lDigit; + if (lDigit >= lBase) or (w > $10FFFF) then + begin + MakeError('', ecCharError, ''); + Exit; + end; + Inc(lIdx); + end; {$IFNDEF PS_NOWIDESTRING} + if w > $FFFF then + begin + Dec(w, $10000); + temp3 := temp3 + widechar($D800 + (w shr 10)) + widechar($DC00 + (w and $3FF)); + wchar := true; + end else + begin + lChar := widechar(w); + temp3 := temp3 + lChar; if w > $FF then wchar := true else if w >= $80 then begin - s := tbtstring(Result); - if (Length(s) <> 1) or (tbtunicodestring(s)[1] <> Result) then + s := tbtstring(lChar); + if (Length(s) <> 1) or (tbtunicodestring(s)[1] <> lChar) then wchar := true; end; + end; + {$ELSE} + temp3 := temp3 + tbtchar(w); {$ENDIF} + Result := True; end; function PString(s: tbtString): tbtString; @@ -5679,7 +7776,7 @@ function TPSPascalCompiler.ReadString: PIfRVariant; begin if UTF8Decode then begin - temp3 := temp3 + {$IFNDEF PS_NOWIDESTRING}{$IFDEF DELPHI6UP}System.{$IFDEF DELPHI2009UP}UTF8ToWidestring{$ELSE}UTF8Decode{$ENDIF}{$ENDIF}{$ENDIF}(PString(FParser.GetToken)); + temp3 := temp3 + {$IFNDEF PS_NOWIDESTRING}{$IFDEF DELPHI6UP}System.{$IFDEF DELPHI2009UP}{$IFDEF FPC}UTF8Decode{$ELSE}UTF8ToWidestring{$ENDIF}{$ELSE}UTF8Decode{$ENDIF}{$ENDIF}{$ENDIF}(PString(FParser.GetToken)); {$IFNDEF PS_NOWIDESTRING}wchar:=true;{$ENDIF} end else temp3 := temp3 + {$IFNDEF PS_NOWIDESTRING}tbtUnicodestring{$ENDIF}(PString(FParser.GetToken)); @@ -5690,7 +7787,11 @@ function TPSPascalCompiler.ReadString: PIfRVariant; end {if} else begin - temp3 := temp3 + ChrToStr(FParser.GetToken); + if not ChrToStr(FParser.GetToken) then + begin + result := false; + exit; + end; FParser.Next; end; {else if} if lastwasstring and (FParser.CurrTokenId = CSTI_String) then @@ -5745,7 +7846,30 @@ function TPSPascalCompiler.ReadString: PIfRVariant; end; -{ Note: 's' may start with '-' when called from unary minus handling } +{ Whether aText, an integer literal without a sign -- decimal, or hexadecimal + after a '$' -- is at most High(UInt64) } +function _LiteralFitsUInt64(const aText: tbtString): Boolean; +var + lIdx: Integer; + lHex: Boolean; +begin + lHex := (aText <> '') and (aText[1] = '$'); + lIdx := 1; + if lHex then + Inc(lIdx); + while (lIdx < Length(aText)) and (aText[lIdx] = '0') do + Inc(lIdx); + if (aText = '') or (aText[1] = '-') then + Result := False + else if lHex then + Result := Length(aText) - lIdx + 1 <= 16 + else + Result := (Length(aText) - lIdx + 1 < 20) + or ((Length(aText) - lIdx + 1 = 20) and (Copy(aText, lIdx, 20) <= '18446744073709551615')); +end; + +{ Note: 's' may start with '-' when called from unary minus handling. nil, + after an error, for a literal no 64-bit integer holds } function TPSPascalCompiler.ReadInteger(const s: tbtString): PIfRVariant; var R: {$IFNDEF PS_NOINT64}Int64;{$ELSE}Longint;{$ENDIF} @@ -5757,6 +7881,12 @@ function TPSPascalCompiler.ReadInteger(const s: tbtString): PIfRVariant; New(Result); {$IFNDEF PS_NOINT64} Val(string(s), r, Code); + { a '$' with no digits is 0, as in Delphi } + if (Code <> 0) and ((s = '$') or (s = '-$')) then + begin + r := 0; + Code := 0; + end; if Code = 0 then begin { r will be negative when 's' starts with '-' or when hex values like '$8000000000000000' are used } @@ -5775,15 +7905,22 @@ function TPSPascalCompiler.ReadInteger(const s: tbtString): PIfRVariant; end; end else begin - Val(string(s), U, Code); + { Val is no test of the range here: on Delphi XE4 to 10.1 Berlin the RTL's + UInt64 Val takes 18446744073709551616 as 0 } + if _LiteralFitsUInt64(s) then + Val(string(s), U, Code) + else + Code := 1; if Code = 0 then begin InitializeVariant(Result, at2ut(FindBaseType(btu64))); Result^.tu64 := U; end else begin - InitializeVariant(Result, at2ut(FindBaseType(bts32))); - Result^.ts32 := 0; + { refused, as Delphi refuses it } + Dispose(Result); + Result := nil; + MakeError('', ecCustomError, tbtstring(RPS_IntegerConstantTooLarge)); end; end; {$ELSE} @@ -6027,13 +8164,94 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; Result := False; end; end; + { the type of a value of a ByteBool, WordBool or LongBool type (any Boolean type but Boolean itself), else + nil } + function _WideBoolType(aVal: TPSValue): TPSType; + begin + Result := GetTypeNo(BlockInfo, aVal); + if Result <> nil then + Result := GetTypeCopyLink(Result); + if (Result <> nil) and ((Result = FDefaultBoolType) or not IsBoolean(Result)) then + Result := nil; + end; + + { a constant whose bits are all zero -- a ByteBool, WordBool or LongBool False, which an integer operation + compares exactly as its truth would } + function _IsZeroData(aVal: TPSValue): Boolean; + begin + Result := (aVal is TPSValueData) and (TPSValueData(aVal).Data <> nil) and (TPSValueData(aVal).Data^.tu32 = 0); + end; + + { a replacement the comparison cleanup unwraps and frees (without ValuesAllocatedBeforeOutput): lent to a new + expression, it would be freed under the expression that owns it } + function _IsUnwrappedReplace(aVal: TPSValue): Boolean; + begin + Result := (aVal is TPSValueReplace) and not TPSValueReplace(aVal).ValuesAllocatedBeforeOutput; + end; + + { `aVal <> 0` in aVal's own type, a Boolean: the truth of a ByteBool, WordBool or LongBool value. aVal is + borrowed -- clear Val1 before freeing the result } + function _BoolTruth(aVal: TPSValue; aType: TPSType): TPSBinValueOp; + var + lZero: TPSValueData; + begin + lZero := TPSValueData.Create; + lZero.Pos := aVal.Pos; + lZero.Row := aVal.Row; + lZero.Col := aVal.Col; + lZero.Data := NewVariant(aType); + Result := TPSBinValueOp.Create; + Result.Pos := aVal.Pos; + Result.Row := aVal.Row; + Result.Col := aVal.Col; + Result.Operator := otNotEqual; + Result.aType := at2ut(FDefaultBoolType); + Result.Val1 := aVal; + Result.Val2 := lZero; + end; + function DoBinCalc(BVal: TPSBinValueOp; Output: TPSValue): Boolean; var tmpp, tmpc: TPSValue; + lCurOp: TPSValueData; + lSavedOp: TPSValue; + lCur: Currency; jend, jover: Cardinal; procno: Cardinal; + lWide: TPSType; + lA, lB, lOp: TPSBinValueOp; + lPrepOut, lPrep1, lPrep2: Boolean; begin + { two ByteBool, WordBool or LongBool values are combined and compared by their truth, as in Delphi: as + integers, the WordBools 256 and 1 (both True) gave False for and and for =, and True for xor. A + comparison with a False constant is left to the integer operation, which gives the same answer and keeps + the truth test (`x <> 0`) from coming back here; and, or and xor with one combine the truths, a Boolean } + lWide := _WideBoolType(BVal.FVal1); + if (lWide <> nil) and (BVal.Operator in [otAnd, otOr, otXor, otEqual, otNotEqual]) and + (_WideBoolType(BVal.FVal2) <> nil) and + not ((BVal.Operator in [otEqual, otNotEqual]) and (_IsZeroData(BVal.FVal1) or _IsZeroData(BVal.FVal2))) and + not _IsUnwrappedReplace(BVal.FVal1) and not _IsUnwrappedReplace(BVal.FVal2) then + begin + lA := _BoolTruth(BVal.FVal1, lWide); + lB := _BoolTruth(BVal.FVal2, _WideBoolType(BVal.FVal2)); + lOp := TPSBinValueOp.Create; + lOp.Pos := BVal.Pos; + lOp.Row := BVal.Row; + lOp.Col := BVal.Col; + lOp.Operator := BVal.Operator; + lOp.aType := at2ut(FDefaultBoolType); + lOp.Val1 := lA; + lOp.Val2 := lB; + try + Result := WriteCalculation(lOp, Output); + finally + lA.Val1 := nil; + lB.Val1 := nil; + lOp.Free; + end; + exit; + end; if (BVal.Operator >= otGreaterEqual) or (BVal.Operator = otAs) then begin if BVal.FVal1.ClassType = TPSValueNil then @@ -6074,15 +8292,16 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; begin if not TPSUndefinedClassType(GetTypeNo(BlockInfo, BVal.FVal1)).ExtClass.CompareClass(GetTypeNo(BlockInfo, Bval.FVal2), ProcNo) then begin + MakeError('', ecTypeMismatch, ''); Result := False; exit; end; tmpp := TPSValueProcNo.Create; + TPSValueProcNo(tmpp).ProcNo := ProcNo; with TPSValueProcNo(tmpp) do begin ResultType := at2ut(FDefaultBoolType); Parameters := TPSParameters.Create; - ProcNo := procno; Pos := BVal.Pos; Col := BVal.Col; Row := BVal.Row; @@ -6125,31 +8344,38 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; end; exit; end; - if not (PreWriteOutRec(Output, nil) and PreWriteOutRec(BVal.FVal1, GetTypeNo(BlockInfo, BVal.FVal2)) and PreWriteOutRec(BVal.FVal2, GetTypeNo(BlockInfo, BVal.FVal1))) then - begin - Result := False; - exit; - end; - if BVal.Operator = otAs then - begin - // Both CM_CO ('is') and CM_CA ('as') call Class_IS at runtime, but - // CM_CO writes a Boolean into Output and does not allow further use - // of the object. So 'as' uses CM_A to copy the object, then CM_CA - // to validate the type (raises on mismatch, leaves the object intact). + { each preparation that succeeded is undone, and a nil operand's replacement unwrapped, whatever the + outcome: an exit that skipped them left a computed index's replacement, the operand it replaced or the + nil unfreed } + lPrep1 := False; + lPrep2 := False; + lPrepOut := PreWriteOutRec(Output, nil); + if lPrepOut then + lPrep1 := PreWriteOutRec(BVal.FVal1, GetTypeNo(BlockInfo, BVal.FVal2)); + if lPrep1 then + lPrep2 := PreWriteOutRec(BVal.FVal2, GetTypeNo(BlockInfo, BVal.FVal1)); + Result := lPrep2; + if Result and (BVal.Operator = otAs) then + begin + { the object is copied into a temporary and its class checked there (CM_CA 10 raises on a mismatch and + writes nothing; CM_CO, the check `is` makes, would write a Boolean), and only then copied into + Output: a cast that fails leaves its destination as it was, as in Delphi } + tmpp := AllocStackReg(BVal.aType); BlockWriteByte(BlockInfo, CM_A); - if not (WriteOutRec(Output, False) and writeOutRec(BVal.FVal1, True)) then + Result := WriteOutRec(tmpp, False) and writeOutRec(BVal.FVal1, True); + if Result then begin - Result := False; - exit; + BlockWriteByte(BlockInfo, Cm_CA); + BlockWriteByte(BlockInfo, 10); + Result := WriteOutRec(tmpp, False) and writeOutRec(BVal.FVal2, True); end; - BlockWriteByte(BlockInfo, Cm_CA); - BlockWriteByte(BlockInfo, 10); - if not (WriteOutRec(Output, False) and writeOutRec(BVal.FVal2, True)) then + if Result then begin - Result := False; - exit; + BlockWriteByte(BlockInfo, CM_A); + Result := WriteOutRec(Output, False) and WriteOutRec(tmpp, True); end; - end else + tmpp.Free; + end else if Result then begin BlockWriteByte(BlockInfo, CM_CO); case BVal.Operator of @@ -6163,20 +8389,19 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; otIs: BlockWriteByte(BlockInfo, 7); end; - if not (WriteOutRec(Output, False) and writeOutRec(BVal.FVal1, True) and writeOutRec(BVal.FVal2, True)) then - begin - Result := False; - exit; - end; + Result := WriteOutRec(Output, False) and writeOutRec(BVal.FVal1, True) and writeOutRec(BVal.FVal2, True); end; // Skip AfterWriteOutRec/unwrap when ValuesAllocatedBeforeOutput - see CheckFurther // Instead let the owner (TPSBinValueOp) handle cleanup when it's destroyed. This happens when // vin.Free is called before vout.Free in the caller (e.g., ProcessIf). - if (BVal.Val1.ClassType <> TPSValueReplace) or not TPSValueReplace(BVal.Val1).ValuesAllocatedBeforeOutput then + if lPrep1 and ((BVal.Val1.ClassType <> TPSValueReplace) or + not TPSValueReplace(BVal.Val1).ValuesAllocatedBeforeOutput) then AfterWriteOutRec(BVal.FVal1); - if (BVal.Val2.ClassType <> TPSValueReplace) or not TPSValueReplace(BVal.Val2).ValuesAllocatedBeforeOutput then + if lPrep2 and ((BVal.Val2.ClassType <> TPSValueReplace) or + not TPSValueReplace(BVal.Val2).ValuesAllocatedBeforeOutput) then AfterWriteOutRec(BVal.FVal2); - AfterWriteOutrec(Output); + if lPrepOut then + AfterWriteOutrec(Output); if (BVal.Val1.ClassType = TPSValueReplace) and not TPSValueReplace(BVal.Val1).ValuesAllocatedBeforeOutput then begin tmpp := TPSValueReplace(BVal.Val1).OldValue; @@ -6189,13 +8414,22 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; BVal.Val2.Free; BVal.Val2 := tmpp; end; + if not Result then + exit; end else begin if (BVal.aType <> nil) and (BVal.aType <> GetTypeNo(BlockInfo, Output)) then begin tmpp := AllocStackReg(BVal.aType); - PreWriteOutrec(tmpp, nil); - DoBinCalc(BVal, tmpp); + { an operation that fails to compile stops the expression: its temporary was never written } + if not PreWriteOutrec(tmpp, nil) then + begin + tmpp.Free; + Result := False; + exit; + end; + result := DoBinCalc(BVal, tmpp); afterwriteoutrec(tmpp); - result := WriteCalculation(tmpp, output); + if result then + result := WriteCalculation(tmpp, output); tmpp.Free; exit; end; @@ -6209,6 +8443,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; begin if not WriteCalculation(BVal.FVal1, Output) then begin + AfterWriteOutRec(Output); Result := False; exit; end; @@ -6239,22 +8474,49 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; jover := 0; jend := 0; end; - if not PreWriteOutrec(BVal.FVal2, GetTypeNo(BlockInfo, Output)) then - begin - Result := False; - exit; + { a real literal added to a Currency or taken from one is written as a + Currency when that holds it exactly, as Delphi takes it: added as a + real, a Double on Win64, it lost the ten-thousandths } + lCurOp := nil; + lSavedOp := BVal.FVal2; + if (BVal.Operator in [otAdd, otSub]) and (BVal.aType <> nil) and (BVal.aType.BaseType = btCurrency) and + _ExactCurrencyLiteral(BVal.FVal2, lCur) then + begin + lCurOp := TPSValueData.Create; + lCurOp.Pos := BVal.FVal2.Pos; + lCurOp.Row := BVal.FVal2.Row; + lCurOp.Col := BVal.FVal2.Col; + lCurOp.Data := NewVariant(at2ut(BVal.aType)); + lCurOp.Data.tcurrency := lCur; + BVal.FVal2 := lCurOp; end; - BlockWriteByte(BlockInfo, Cm_CA); - if BVAL.Operator = otIntDiv then - BlockWriteByte(BlockInfo, Ord(otDiv)) - else - BlockWriteByte(BlockInfo, Ord(BVal.Operator)); - if not (WriteOutRec(Output, False) and WriteOutRec(BVal.FVal2, True)) then - begin - Result := False; - exit; + try + if not PreWriteOutrec(BVal.FVal2, GetTypeNo(BlockInfo, Output)) then + begin + AfterWriteOutRec(Output); + Result := False; + exit; + end; + BlockWriteByte(BlockInfo, Cm_CA); + if BVAL.Operator = otIntDiv then + BlockWriteByte(BlockInfo, Ord(otDiv)) + else + BlockWriteByte(BlockInfo, Ord(BVal.Operator)); + if not (WriteOutRec(Output, False) and WriteOutRec(BVal.FVal2, True)) then + begin + AfterWriteOutRec(BVal.FVal2); + AfterWriteOutRec(Output); + Result := False; + exit; + end; + AfterWriteOutRec(BVal.FVal2); + finally + if lCurOp <> nil then + begin + BVal.FVal2 := lSavedOp; + lCurOp.Free; + end; end; - AfterWriteOutRec(BVal.FVal2); if FBooleanShortCircuit and (IsBoolean(BVal.aType)) and (JOver <> JEnd) then begin {$ifdef FPC_REQUIRES_PROPER_ALIGNMENT} @@ -6268,18 +8530,57 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; Result := True; end; - function DoUnCalc(Val: TPSUnValueOp; Output: TPSValue): Boolean; + { DoUnCalc's work, its destination prepared: DoUnCalc (below) releases it } + function _DoUnCalcPrepared(Val: TPSUnValueOp; Output: TPSValue): Boolean; var Tmp: TPSValue; + lWide: TPSType; + lTruth: TPSBinValueOp; begin - if not PreWriteOutRec(Output, nil) then - begin - Result := False; + { a Variant's minus or not is the Variant's own, converted afterwards, as in + Delphi: computed in a destination of another type it converted the + Variant first, and `s := -v` negated the text } + if (Val.Operator in [otMinus, otNot]) and (GetTypeNo(BlockInfo, Val.FVal1) <> nil) and + (GetTypeNo(BlockInfo, Val.FVal1).BaseType = btVariant) and (GetTypeNo(BlockInfo, Output) <> nil) and + (GetTypeNo(BlockInfo, Output).BaseType <> btVariant) then + begin + Tmp := AllocStackReg(GetTypeNo(BlockInfo, Val.FVal1)); + try + Result := WriteCalculation(Val.FVal1, Tmp); + if Result then + begin + if Val.Operator = otMinus then + BlockWriteByte(BlockInfo, cm_vm) + else + BlockWriteByte(BlockInfo, cm_in); + Result := WriteOutRec(Tmp, True) and WriteCalculation(Tmp, Output); + end; + finally + Tmp.Free; + end; exit; end; case Val.Operator of otNot: begin + { an integer not is computed in its operand's type, as in Delphi -- `i := not b` of a Byte 0 is 255: + written into a destination of another type it took that type's width (-1) } + if not IsBoolean(GetTypeNo(BlockInfo, Val)) and (Val.aType <> nil) and IsIntType(Val.aType.BaseType) and + ((GetTypeNo(BlockInfo, Output) = nil) or (GetTypeNo(BlockInfo, Output).BaseType <> Val.aType.BaseType)) then + begin + Tmp := AllocStackReg(Val.aType); + try + Result := WriteCalculation(Val.FVal1, Tmp); + if Result then + begin + BlockWriteByte(BlockInfo, cm_in); + Result := WriteOutRec(Tmp, True) and WriteCalculation(Tmp, Output); + end; + finally + Tmp.Free; + end; + exit; + end; if not SameReg(Val.FVal1, Output) then begin if not WriteCalculation(Val.FVal1, Output) then @@ -6317,8 +8618,34 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; end; otCast: begin - if ((Val.aType.BaseType = btChar) and (GetTypeNo(BlockInfo, Val.FVal1).BaseType <> btU8)) {$IFNDEF PS_NOWIDESTRING}or - ((Val.aType.BaseType = btWideChar) and (GetTypeNo(BlockInfo, Val.FVal1).BaseType <> btU16)){$ENDIF} then + { a ByteBool, WordBool or LongBool value cast to another Boolean type is its truth, as in Delphi: the + assignment below copied it by size, so Boolean(wb) of the WordBool 256 was False } + lWide := _WideBoolType(Val.FVal1); + if (lWide <> nil) and (Val.aType <> nil) and IsBoolean(GetTypeCopyLink(Val.aType)) and + (GetTypeCopyLink(Val.aType) <> lWide) then + begin + Tmp := AllocStackReg(at2ut(FDefaultBoolType)); + lTruth := _BoolTruth(Val.FVal1, lWide); + try + Result := WriteCalculation(lTruth, Tmp) and WriteCalculation(Tmp, Output); + finally + lTruth.Val1 := nil; + lTruth.Free; + Tmp.Free; + end; + exit; + end; + { a character cast always goes through a temporary of its own type: the destination may be + of another type, an AnsiString for one, which the cast's source cannot be assigned to } + if (Val.aType.BaseType = btChar) {$IFNDEF PS_NOWIDESTRING}or + (Val.aType.BaseType = btWideChar){$ENDIF} or + { so does any cast whose destination is of another kind: the cast's own type decides the value, as + in Delphi -- `i := Byte(x)` narrows, `v := Integer(w)` converts } + (GetTypeNo(BlockInfo, Output) = nil) or (GetTypeNo(BlockInfo, Output).BaseType <> Val.aType.BaseType) or + { an enumeration -- every Boolean type is one -- of another type than the destination's: `w := + Boolean(n)` into a WordBool took n whole } + ((Val.aType.BaseType = btEnum) and + (GetTypeCopyLink(GetTypeNo(BlockInfo, Output)) <> GetTypeCopyLink(Val.aType))) then begin Tmp := AllocStackReg(Val.aType); end else @@ -6332,6 +8659,8 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; BlockWriteByte(BlockInfo, CM_A); if not (WriteOutRec(Tmp, False) and WriteOutRec(Val.FVal1, True)) then begin + AfterWriteOutRec(Val.FVal1); + AfterWriteOutRec(Tmp); Result := false; if tmp <> Output then Tmp.Free; exit; @@ -6352,8 +8681,23 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; end; {else donothing} end; - AfterWriteOutRec(Output); - Result := True; + Result := True; + end; + + { Val into Output: the destination is prepared here and released on every way out, the failing ones too -- + an exit that skipped the release left a computed index's replacement unfreed } + function DoUnCalc(Val: TPSUnValueOp; Output: TPSValue): Boolean; + begin + if not PreWriteOutRec(Output, nil) then + begin + Result := False; + exit; + end; + try + Result := _DoUnCalcPrepared(Val, Output); + finally + AfterWriteOutRec(Output); + end; end; @@ -6378,6 +8722,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; tmpp, tmpc: TPSValue; i: Longint; + lElemType: TPSType; function MakeSet(SetType: TPSSetType; arr: TPSValueArray): Boolean; var c, i: Longint; @@ -6390,9 +8735,9 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; for i := 0 to arr.count -1 do begin mType := GetTypeNo(BlockInfo, arr.Item[i]); - if (mType <> SetType.SetType) and + if (mType = nil) or ((mType <> SetType.SetType) and not (IsIntType(mType.FBaseType) and IsIntType(SetType.SetType.BaseType)) and - not (IsCharType(mType.FBaseType) and IsCharType(SetType.SetType.BaseType)) then + not (IsCharType(mType.FBaseType) and IsCharType(SetType.SetType.BaseType))) then begin with MakeError('', ecTypeMismatch, '') do begin @@ -6508,6 +8853,14 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; Result := MakeSet(TPSSetType(FArrType), TPSValueArray(x)); exit; end; + { an array constructor makes a dynamic array, which the run time cannot + copy into a static array: refused, as Delphi refuses it } + if TPSType(FArrType).BaseType = btStaticArray then + begin + MakeError('', ecTypeMismatch, ''); + Result := False; + Exit; + end; if TPSType(FarrType).BaseType = btVariant then FArrType := at2ut(FindAndAddType(self, '!OPENARRAYOFVARIANT', 'array of Variant')); if TPSType(FarrType).BaseType <> btArray then @@ -6523,7 +8876,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; BlockWriteByte(BlockInfo, CM_PV); WriteOutrec(tmpp, False); BlockWriteByte(BlockInfo, CM_C); - BlockWriteLong(BlockInfo, FindProc('SetArrayLength')); + BlockWriteLong(BlockInfo, FindSystemProc('SetArrayLength')); BlockWriteByte(BlockInfo, CM_PO); tmpc.Free; rr := TPSSubNumber.Create; @@ -6533,7 +8886,78 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; begin TPSSubNumber(rr).SubNo := i; tmpc := TPSValueArray(x).Item[i]; - if not PreWriteOutRec(tmpc, GetTypeNo(BlockInfo, tmpc)) then + { an element of an array of a class must be an object of that class, as in Delphi: the array goes to + native code that uses each element as the class, and a number or a Variant would be taken as the + object's address; an element of an array of an interface must be an interface that is that one -- + one interface is copied to another without a query for it -- or an object, which is queried } + if ((TPSArrayType(FArrType).ArrayTypeNo.BaseType = btClass) and ((GetTypeNo(BlockInfo, tmpc) = nil) or + (GetTypeNo(BlockInfo, tmpc).BaseType <> btClass) or + not IsCompatibleType(TPSArrayType(FArrType).ArrayTypeNo, GetTypeNo(BlockInfo, tmpc), False))){$IFNDEF PS_NOINTERFACES} or + ((TPSArrayType(FArrType).ArrayTypeNo.BaseType = btInterface) and ((GetTypeNo(BlockInfo, tmpc) = nil) or + not (GetTypeNo(BlockInfo, tmpc).BaseType in [btInterface, btClass]) or + not IsCompatibleType(TPSArrayType(FArrType).ArrayTypeNo, GetTypeNo(BlockInfo, tmpc), False))){$ENDIF} then + begin + MakeError('', ecTypeMismatch, ''); + tmpp.Free; + Result := false; + exit; + end; + { an element is checked as an assignment to the element is, as in Delphi: `[256]` for an array of + Boolean was copied by size (False), and an enumeration entered an array of Integer. An array of + Variant (an array of const) and an array of Pointer take what they took } + if not (TPSArrayType(FArrType).ArrayTypeNo.BaseType in [btVariant, btPointer]) and + not CheckCompatType(tmpp, tmpc) then + begin + MakeError('', ecTypeMismatch, ''); + tmpp.Free; + Result := false; + exit; + end; + { a ByteBool, WordBool or LongBool element of an array of another Boolean type goes in by its truth, as + an assignment writes it: copied by size, the WordBool 256 became the Boolean 0 } + if (_WideBoolType(tmpc) <> nil) and IsBoolean(GetTypeCopyLink(TPSArrayType(FArrType).ArrayTypeNo)) and + (GetTypeCopyLink(TPSArrayType(FArrType).ArrayTypeNo) <> _WideBoolType(tmpc)) then + begin + if not WriteCalculation(tmpc, tmpp) then + begin + tmpp.Free; + Result := false; + exit; + end; + Continue; + end; + { a constant element of an array of Single, Double or Currency goes in as an assignment writes it: + converted when the script compiles, refused past Currency's range } + if (tmpc.ClassType = TPSValueData) and + (GetTypeCopyLink(TPSArrayType(FArrType).ArrayTypeNo).BaseType in [btSingle, btDouble, btCurrency]) then + begin + if not WriteCalculation(tmpc, tmpp) then + begin + tmpp.Free; + Result := false; + exit; + end; + Continue; + end; + { a set or array constructor takes the element's own type, as in Delphi: + an array of Variant does not convert into a set or an array element. + A static array element refuses it (above) } + if (TPSArrayType(FArrType).ArrayTypeNo.BaseType in [btSet, btArray, btStaticArray]) and + (tmpc is TPSValueArray) then + lElemType := TPSArrayType(FArrType).ArrayTypeNo + else + lElemType := GetTypeNo(BlockInfo, tmpc); + { an element of no type -- a call of a routine with no result, an operator on + one -- has no value to put in, and an array of Variant or of Pointer passed + the checks above whatever the element } + if lElemType = nil then + begin + MakeError('', ecTypeMismatch, ''); + tmpp.Free; + Result := false; + exit; + end; + if not PreWriteOutRec(tmpc, lElemType) then begin tmpp.Free; Result := false; @@ -6637,7 +9061,16 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; BlockWriteLong(BlockInfo, GetAddress(tmpp)); BlockWriteLong(BlockInfo, TPSSubNumber(rr).SubNo); end else begin // if rr.classtype = TPSSubValue then begin - tmpc := AllocStackReg(FindBaseType(btU32)); + { a 64-bit index keeps its width, so that the run time checks the value the script computed: a + Cardinal temporary dropped the high half before the bounds check } + {$IFNDEF PS_NOINT64} + if (GetTypeNo(BlockInfo, TPSSubValue(rr).SubNo) <> nil) and + ((GetTypeNo(BlockInfo, TPSSubValue(rr).SubNo).BaseType = btS64) or + (GetTypeNo(BlockInfo, TPSSubValue(rr).SubNo).BaseType = btU64)) then + tmpc := AllocStackReg(GetTypeNo(BlockInfo, TPSSubValue(rr).SubNo)) + else + {$ENDIF} + tmpc := AllocStackReg(FindBaseType(btU32)); if not WriteCalculation(TPSSubValue(rr).SubNo, tmpc) then begin tmpc.Free; @@ -6866,7 +9299,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; x := nil; exit; end; - if not IsIntType(GetTypeNo(BlockInfo, tmp).BaseType) then + if (GetTypeNo(BlockInfo, tmp) = nil) or not IsIntType(GetTypeNo(BlockInfo, tmp).BaseType) then begin MakeError('', ecTypeMismatch, ''); tmp.Free; @@ -6885,14 +9318,14 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; exit; end; {$IFDEF PS_HAVEVARIANT}if (u.BaseType = btVariant) then - l := FindProc('VarArraySet') else + l := FindSystemProc('VarArraySet') else {$ENDIF} {$IFNDEF PS_NOWIDESTRING} if (u.BaseType = btWideString) or (u.BaseType = btUnicodeString) then - l := FindProc('WStrSet') + l := FindSystemProc('WStrSet') else {$ENDIF} - l := FindProc('StrSet'); + l := FindSystemProc('StrSet'); if l = -1 then begin MakeError('', ecUnknownIdentifier, 'StrSet'); @@ -6936,8 +9369,8 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; end; {$IFDEF PS_HAVEVARIANT}if (u.BaseType <> btVariant) then {$ENDIF} begin - if (GetTypeNo(BlockInfo, Tmp).BaseType <> btChar) - {$IFNDEF PS_NOWIDESTRING} and (GetTypeno(BlockInfo, Tmp).BaseType <> btWideChar) {$ENDIF} then + if (GetTypeNo(BlockInfo, Tmp) = nil) or ((GetTypeNo(BlockInfo, Tmp).BaseType <> btChar) + {$IFNDEF PS_NOWIDESTRING} and (GetTypeno(BlockInfo, Tmp).BaseType <> btWideChar) {$ENDIF}) then begin x.Free; x := nil; @@ -6957,14 +9390,14 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; {$ENDIF} end else begin {$IFDEF PS_HAVEVARIANT}if (u.BaseType = btVariant) then - l := FindProc('VarArrayGet') else + l := FindSystemProc('VarArrayGet') else {$ENDIF} {$IFNDEF PS_NOWIDESTRING} if (u.BaseType = btWideString) or (u.BaseType = btUnicodeString) then - l := FindProc('WStrGet') + l := FindSystemProc('WStrGet') else {$ENDIF} - l := FindProc('StrGet'); + l := FindSystemProc('StrGet'); if l = -1 then begin MakeError('', ecUnknownIdentifier, 'StrGet'); @@ -7020,7 +9453,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; x := nil; exit; end; - if not IsIntType(GetTypeNo(BlockInfo, tmp).BaseType) then + if (GetTypeNo(BlockInfo, tmp) = nil) or not IsIntType(GetTypeNo(BlockInfo, tmp).BaseType) then begin MakeError('', ecTypeMismatch, ''); tmp.Free; @@ -7032,10 +9465,19 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; begin rr := TPSSubNumber.Create; TPSValueVar(x).RecAdd(rr); + { the constant's whole value, less a static array's start: one outside a Cardinal fails the run + time's bounds check, as a 64-bit variable index does } + {$IFNDEF PS_NOINT64} + if (u.BaseType = btStaticArray) then + TPSSubNumber(rr).SubNo := _ConstIndex(GetInt64(TPSValueData(tmp).Data, tmp2) - TPSStaticArrayType(u).StartOffset) + else + TPSSubNumber(rr).SubNo := _ConstIndex(GetInt64(TPSValueData(tmp).Data, tmp2)); + {$ELSE} if (u.BaseType = btStaticArray) then TPSSubNumber(rr).SubNo := Cardinal(GetInt(TPSValueData(tmp).Data, tmp2) - TPSStaticArrayType(u).StartOffset) else TPSSubNumber(rr).SubNo := GetUInt(TPSValueData(tmp).Data, tmp2); + {$ENDIF} tmp.Free; rr.aType := TPSArrayType(u).ArrayTypeNo; u := rr.aType; @@ -7048,10 +9490,24 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; TPSBinValueOp(tmpn).Operator := otSub; TPSBinValueOp(tmpn).Val1 := tmp; tmp := TPSValueData.Create; - TPSValueData(tmp).Data := NewVariant(FindBaseType(btS32)); - TPSValueData(tmp).Data.ts32 := TPSStaticArrayType(u).StartOffset; - TPSBinValueOp(tmpn).Val2 := tmp; - TPSBinValueOp(tmpn).aType := FindBaseType(btS32); + { a 64-bit index keeps its width through the start's subtraction, as the index + expression's temporary does } + {$IFNDEF PS_NOINT64} + if (GetTypeNo(BlockInfo, TPSBinValueOp(tmpn).Val1).BaseType = btS64) or + (GetTypeNo(BlockInfo, TPSBinValueOp(tmpn).Val1).BaseType = btU64) then + begin + TPSValueData(tmp).Data := NewVariant(FindBaseType(btS64)); + TPSValueData(tmp).Data.ts64 := TPSStaticArrayType(u).StartOffset; + TPSBinValueOp(tmpn).Val2 := tmp; + TPSBinValueOp(tmpn).aType := FindBaseType(btS64); + end else + {$ENDIF} + begin + TPSValueData(tmp).Data := NewVariant(FindBaseType(btS32)); + TPSValueData(tmp).Data.ts32 := TPSStaticArrayType(u).StartOffset; + TPSBinValueOp(tmpn).Val2 := tmp; + TPSBinValueOp(tmpn).aType := FindBaseType(btS32); + end; tmp := tmpn; end; rr := TPSSubValue.Create; @@ -7098,7 +9554,15 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; FParser.Next; tmp := AllocStackReg(u); - WriteCalculation(x,tmp); + { a call that fails to compile stops the expression: its error was recorded, the compile went on + and the field of the uncalled result was read } + if not WriteCalculation(x,tmp) then + begin + tmp.Free; + x.Free; + x := nil; + exit; + end; TPSVar(BlockInfo.Proc.FProcVars[TPSValueAllocatedStackVar(tmp).LocalVarNo]).Use; rr := TPSSubNumber.Create; @@ -7283,7 +9747,13 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; if TPSUndefinedClassType(FType).ExtClass.Func_Find(s, Idx) then begin FParser.Next; - TPSUndefinedClassType(FType).ExtClass.Func_Call(Idx, Temp); + if not TPSUndefinedClassType(FType).ExtClass.Func_Call(Idx, Temp) then + begin + MakeError('', ecUnknownIdentifier, s); + p.Free; + P := nil; + Exit; + end; P := ReadProcParameters(Temp, P); if p = nil then begin @@ -7574,7 +10044,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; FParser.Next; Exit; end; - if not IsCompatibleType(FType, FType2, True) then + if (FType2 = nil) or not IsCompatibleType(FType, FType2, True) then begin temp.Free; MakeError('', ecTypeMismatch, ''); @@ -7583,12 +10053,12 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; end; FParser.Next; Result := TPSUnValueOp.Create; + TPSUnValueOp(Result).aType := AT2UT(FType); with TPSUnValueOp(Result) do begin Operator := otCast; Val1 := Temp; SetParserPos(FParser); - aType := AT2UT(FType); end; exit; end; @@ -7611,8 +10081,13 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; MakeError('', ecUnknownIdentifier, FParser.OriginalToken); Exit; end; + if not TPSUndefinedClassType(FType).ExtClass.ClassFunc_Call(Idx, ProcNo) then + begin + Result := nil; + MakeError('', ecUnknownIdentifier, FParser.OriginalToken); + Exit; + end; FParser.Next; - TPSUndefinedClassType(FType).ExtClass.ClassFunc_Call(Idx, ProcNo); Temp := TPSValueData.Create; with TPSValueData(Temp) do begin @@ -7794,45 +10269,53 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; temp2: CArdinal; bi: TPSBlockInfo; lOldRecCount: Integer; + lConstRank: Longint; + lBestRank: Longint; begin s := FParser.GetToken; - if FType <> 1 then + bi := BlockInfo; + while bi <> nil do begin - bi := BlockInfo; - while bi <> nil do + for l := bi.WithList.Count -1 downto 0 do begin - for l := bi.WithList.Count -1 downto 0 do + TWith := TPSValueAllocatedStackVar.Create; + TPSValueAllocatedStackVar(TWith).LocalVarNo := TPSValueAllocatedStackVar(TPSValueReplace(bi.WithList[l]).NewValue).LocalVarNo; + Temp := TWith; + VNo := TPSValueAllocatedStackVar(Temp).LocalVarNo; + lOldRecCount := TPSValueVar(TWith).GetRecCount; + vt := ivtVariable; + if Temp = TWith then CheckFurther(TWith, True); + if Temp = TWith then CheckClass(TWith, vt, vno, True); + if Temp = TWith then CheckExtClass(TWith, vt, vno, True); + if (Temp <> TWith) or (Cardinal(lOldRecCount) <> TPSValueVar(TWith).GetRecCount) then begin - TWith := TPSValueAllocatedStackVar.Create; - TPSValueAllocatedStackVar(TWith).LocalVarNo := TPSValueAllocatedStackVar(TPSValueReplace(bi.WithList[l]).NewValue).LocalVarNo; - Temp := TWith; - VNo := TPSValueAllocatedStackVar(Temp).LocalVarNo; - lOldRecCount := TPSValueVar(TWith).GetRecCount; - vt := ivtVariable; - if Temp = TWith then CheckFurther(TWith, True); - if Temp = TWith then CheckClass(TWith, vt, vno, True); - if Temp = TWith then CheckExtClass(TWith, vt, vno, True); - if (Temp <> TWith) or (Cardinal(lOldRecCount) <> TPSValueVar(TWith).GetRecCount) then + { a for counter (FType 1) is no with subject's member, which the + loop's body would read: Delphi refuses a field as a counter } + if FType = 1 then begin - repeat - Temp := TWith; - if TWith <> nil then CheckFurther(TWith, False); - if TWith <> nil then CheckClass(TWith, vt, vno, False); - if TWith <> nil then CheckExtClass(TWith, vt, vno, False); -{$IFNDEF PS_NOIDISPATCH}if TWith <> nil then CheckIntf(TWith, vt, vno, False);{$ENDIF} - if TWith <> nil then CheckProcCall(TWith); - if TWith <> nil then CheckClassArrayProperty(TWith, vt, vno); - vno := InvalidVal; - until (TWith = nil) or (Temp = TWith); - Result := TWith; + TWith.Free; + Result := nil; + MakeError('', ecVariableExpected, s); Exit; end; - TWith.Free; + repeat + Temp := TWith; + if TWith <> nil then CheckFurther(TWith, False); + if TWith <> nil then CheckClass(TWith, vt, vno, False); + if TWith <> nil then CheckExtClass(TWith, vt, vno, False); +{$IFNDEF PS_NOIDISPATCH}if TWith <> nil then CheckIntf(TWith, vt, vno, False);{$ENDIF} + if TWith <> nil then CheckProcCall(TWith); + if TWith <> nil then CheckClassArrayProperty(TWith, vt, vno); + vno := InvalidVal; + until (TWith = nil) or (Temp = TWith); + Result := TWith; + Exit; end; - bi := bi.FOwner; + TWith.Free; end; + bi := bi.FOwner; end; if s = 'RESULT' then @@ -7938,11 +10421,15 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; end; end; + { a name several modules declare is the nearest scope's, as Delphi's scopes + take it, whatever its kind; within one scope the order below } + lBestRank := _NearestRank(Self, s); for l := 0 to FVars.Count - 1 do begin if (TPSVar(FVars[l]).NameHash = h) and (TPSVar(FVars[l]).Name = s) {$IFDEF PS_USESSUPPORT} and - (IsInLocalUnitList(TPSVar(FVars[l]).FDeclareUnit)){$ENDIF} then + (IsInLocalUnitList(TPSVar(FVars[l]).FDeclareUnit)) and + (_ScopeRank(Self, TPSVar(FVars[l]).FDeclareUnit) >= lBestRank){$ENDIF} then begin TPSVar(FVars[l]).Use; Result := TPSValueGlobalVar.Create; @@ -7971,7 +10458,10 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; exit; end; end; - Temp1 := FindType(FParser.GetToken); + if _TypeRank(Self, s) >= lBestRank then + Temp1 := FindType(FParser.GetToken) + else + Temp1 := nil; if Temp1 <> nil then begin l := FParser.CurrTokenPos; @@ -7998,7 +10488,10 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; exit; end; - Temp2 := FindProc(FParser.GetToken); + if _ProcRank(Self, s) >= lBestRank then + Temp2 := FindProc(FParser.GetToken) + else + Temp2 := InvalidVal; if Temp2 <> InvalidVal then begin if FType = 1 then @@ -8026,40 +10519,41 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; until (Result = nil) or (Temp = Result); exit; end; - for l := 0 to FConstants.Count -1 do + t := _NearestConstant(Self, s, lConstRank); + if t <> nil then begin - t := TPSConstant(FConstants[l]); - if (t.NameHash = h) and (t.Name = s) {$IFDEF PS_USESSUPPORT} and - (IsInLocalUnitList(t.FDeclareUnit)) {$ENDIF} then + if FType <> 0 then begin - if FType <> 0 then - begin - Result := nil; - MakeError('', ecVariableExpected, FParser.OriginalToken); - exit; - end; - fparser.next; - Result := TPSValueData.Create; - with TPSValueData(Result) do - begin - SetParserPos(FParser); - Data := NewVariant(at2ut(t.Value.FType)); - CopyVariantContents(t.Value, Data); - end; - vt := ivtGlobal; - vno := InvalidVal; - repeat - Temp := Result; - if Result <> nil then CheckFurther(Result, False); - if Result <> nil then CheckClass(Result, vt, vno, False); - if Result <> nil then CheckExtClass(Result, vt, vno, False); -{$IFNDEF PS_NOIDISPATCH}if Result <> nil then CheckIntf(Result, vt, vno, False);{$ENDIF} - if Result <> nil then CheckProcCall(Result); - if Result <> nil then CheckClassArrayProperty(Result, vt, vno); - vno := InvalidVal; - until (Result = nil) or (Temp = Result); + Result := nil; + MakeError('', ecVariableExpected, FParser.OriginalToken); exit; end; + fparser.next; + Result := TPSValueData.Create; + with TPSValueData(Result) do + begin + SetParserPos(FParser); + Data := NewVariant(at2ut(t.Value.FType)); + CopyVariantContents(t.Value, Data); + { a type reference is written with the number of the type it names, + which only a used type has } + if Data.FType.BaseType = btType then + Data.ttype := at2ut(Data.ttype); + FRealText := _ConstantRealText(t); + end; + vt := ivtGlobal; + vno := InvalidVal; + repeat + Temp := Result; + if Result <> nil then CheckFurther(Result, False); + if Result <> nil then CheckClass(Result, vt, vno, False); + if Result <> nil then CheckExtClass(Result, vt, vno, False); +{$IFNDEF PS_NOIDISPATCH}if Result <> nil then CheckIntf(Result, vt, vno, False);{$ENDIF} + if Result <> nil then CheckProcCall(Result); + if Result <> nil then CheckClassArrayProperty(Result, vt, vno); + vno := InvalidVal; + until (Result = nil) or (Temp = Result); + exit; end; Result := nil; MakeError('', ecUnknownIdentifier, FParser.OriginalToken); @@ -8213,6 +10707,12 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; NewVar := TPSValueData.Create; NewVar.SetParserPos(FParser); TPSValueData(NewVar).Data := ReadInteger(tbtString('-') + FParser.GetToken); + if TPSValueData(NewVar).Data = nil then + begin + NewVar.Free; + Result := nil; + exit; + end; FParser.Next; end else begin NewVar := ReadTerm; @@ -8224,6 +10724,15 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; NewVarU := TPSUnValueOp.Create; NewVarU.SetParserPos(FParser); NewVarU.aType := GetTypeNo(BlockInfo, NewVar); + { a negated unsigned value is signed, as in Delphi: an Integer for a Byte or Word, an Int64 for a + Cardinal -- as an operand it is computed in a temporary of this type } + if NewVarU.aType <> nil then + case NewVarU.aType.BaseType of + btU8, btU16, btS8, btS16: NewVarU.aType := at2ut(FindBaseType(btS32)); + {$IFNDEF PS_NOINT64} + btU32: NewVarU.aType := at2ut(FindBaseType(btS64)); + {$ENDIF} + end; NewVarU.Operator := otMinus; NewVarU.Val1 := NewVar; NewVar := NewVarU; @@ -8246,7 +10755,11 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; end; NewVar := TPSValueProcPtr.Create; NewVar.SetParserPos(FParser); - TPSValueProcPtr(NewVar).ProcPtr := FindProc(FParser.GetToken); + if not _LocalOrParamNamed(BlockInfo.Proc, FParser.GetToken) and + (_ProcRank(Self, FParser.GetToken) >= _NearestRank(Self, FParser.GetToken)) then + TPSValueProcPtr(NewVar).ProcPtr := FindProc(FParser.GetToken) + else + TPSValueProcPtr(NewVar).ProcPtr := InvalidVal; if TPSValueProcPtr(NewVar).ProcPtr = InvalidVal then begin MakeError('', ecUnknownIdentifier, FParser.OriginalToken); @@ -8300,6 +10813,12 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; NewVar := TPSValueData.Create; NewVar.SetParserPos(FParser); TPSValueData(NewVar).Data := ReadInteger(FParser.GetToken); + if TPSValueData(NewVar).Data = nil then + begin + NewVar.Free; + Result := nil; + exit; + end; FParser.Next; end; CSTI_Real: @@ -8307,6 +10826,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; NewVar := TPSValueData.Create; NewVar.SetParserPos(FParser); TPSValueData(NewVar).Data := ReadReal(FParser.GetToken); + TPSValueData(NewVar).FRealText := FParser.GetToken; FParser.Next; end; CSTII_Ord: @@ -8344,7 +10864,15 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; NewVarU := TPSUnValueOp.Create; NewVarU.SetParserPos(FParser); NewVarU.Operator := otCast; - NewVarU.FType := at2ut(FindBaseType({$IFNDEF PS_NOINT64} btu64 {$ELSE} btu32 {$ENDIF})); + { Ord's value is signed, as in Delphi, unless its operand is a UInt64 } + {$IFNDEF PS_NOINT64} + if GetTypeNo(BlockInfo, NewVar).BaseType = btU64 then + NewVarU.FType := at2ut(FindBaseType(btu64)) + else + NewVarU.FType := at2ut(FindBaseType(bts64)); + {$ELSE} + NewVarU.FType := at2ut(FindBaseType(bts32)); + {$ENDIF} NewVarU.Val1 := NewVar; NewVar := NewVarU; FParser.Next; @@ -8389,7 +10917,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; end; CSTI_Identifier: begin - if FParser.GetToken = 'SUCC' then + if (FParser.GetToken = 'SUCC') and not NameIsDeclared(BlockInfo.Proc, 'SUCC') then begin FParser.Next; if FParser.CurrTokenID <> CSTI_OpenRound then @@ -8423,7 +10951,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; NewVar := CallSucc(NewVar); FParser.Next; end else - if FParser.GetToken = 'PRED' then + if (FParser.GetToken = 'PRED') and not NameIsDeclared(BlockInfo.Proc, 'PRED') then begin FParser.Next; if FParser.CurrTokenID <> CSTI_OpenRound then @@ -8457,7 +10985,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; NewVar := CallPred(NewVar); FParser.Next; end else - if FParser.GetToken = 'ASSIGNED' then + if (FParser.GetToken = 'ASSIGNED') and not NameIsDeclared(BlockInfo.Proc, 'ASSIGNED') then begin FParser.Next; if FParser.CurrTokenID <> CSTI_OpenRound then @@ -8475,6 +11003,8 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; end; if (GetTypeNo(BlockInfo, NewVar) = nil) or ((GetTypeNo(BlockInfo, NewVar).BaseType <> btClass) and + (GetTypeNo(BlockInfo, NewVar).BaseType <> btProcPtr) and + (GetTypeNo(BlockInfo, NewVar).BaseType <> btArray) and (GetTypeNo(BlockInfo, NewVar).BaseType <> btInterface) and (GetTypeNo(BlockInfo, NewVar).BaseType <> btPChar) and (GetTypeNo(BlockInfo, NewVar).BaseType <> btString) @@ -8799,6 +11329,8 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; Result := FDefaultBoolType else if ((t1.BaseType = btVariant) or (t1.BaseType = btNotificationVariant)) or ((t2.BaseType = btVariant) or (t2.BaseType = btNotificationVariant)) then Result := FDefaultBoolType + else if (t1.BaseType = btEnum) and (t1 = t2) then + Result := FDefaultBoolType else Result := nil; end; @@ -8864,7 +11396,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; end; otAs: begin - if t2.BaseType = btType then + if (t2.BaseType = btType) and (p2.ClassType = TPSValueData) then begin Result := at2ut(TPSValueData(p2).Data.ttype); end else @@ -9040,6 +11572,9 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; function TryEvalConst(var P: TPSValue): Boolean; var preplace: TPSValue; + lFits: Boolean; + lCur: Currency; + lCurType: TPSType; begin if p is TPSBinValueOp then begin @@ -9050,6 +11585,17 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; end; if (TPSBinValueOp(p).FVal1.ClassType = TPSValueData) and (TPSBinValueOp(p).FVal2.ClassType = TPSValueData) then begin + { a real literal added to a Currency or taken from one is a Currency + first when that holds it exactly, as Delphi takes it } + if (TPSBinValueOp(p).Operator in [otAdd, otSub]) and + (TPSValueData(TPSBinValueOp(p).Val1).Data.FType.BaseType = btCurrency) and + _ExactCurrencyLiteral(TPSBinValueOp(p).Val2, lCur) then + begin + lCurType := TPSValueData(TPSBinValueOp(p).Val1).Data.FType; + DisposeVariant(TPSValueData(TPSBinValueOp(p).Val2).Data); + TPSValueData(TPSBinValueOp(p).Val2).Data := NewVariant(lCurType); + TPSValueData(TPSBinValueOp(p).Val2).Data.tcurrency := lCur; + end; if not PreCalc(True, 0, TPSValueData(TPSBinValueOp(p).Val1).Data, 0, TPSValueData(TPSBinValueOp(p).Val2).Data, TPSBinValueOp(p).Operator, p.Pos, p.Row, p.Col) then begin Result := False; @@ -9082,7 +11628,8 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; begin if IsBoolean(TPSValueData(TPSUnValueOp(p).FVal1).Data^.FType) then begin - TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu8 := (not TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu8) and 1; + { the whole value is tested, as the run time does (DoBooleanNot): `not ByteBool(2)` is False } + TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu32 := Ord(TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu32 = 0); end else begin MakeError('', ecTypeMismatch, ''); @@ -9115,20 +11662,93 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; otMinus: begin case TPSValueData(TPSUnValueOp(p).FVal1).Data^.FType.BaseType of - btU8: TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu8 := -TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu8; - btU16: TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu16 := -TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu16; + { a negated unsigned constant is signed, as in Delphi and as the run time computes a negated + variable into a wider destination: -Byte(1) is -1, not 255 } + btU8: + begin + TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts32 := -Longint(TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu8); + TPSValueData(TPSUnValueOp(p).FVal1).Data^.FType := at2ut(FindBaseType(bts32)); + end; + btU16: + begin + TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts32 := -Longint(TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu16); + TPSValueData(TPSUnValueOp(p).FVal1).Data^.FType := at2ut(FindBaseType(bts32)); + end; + {$IFNDEF PS_NOINT64} + btU32: + begin + TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts64 := -Int64(TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu32); + TPSValueData(TPSUnValueOp(p).FVal1).Data^.FType := at2ut(FindBaseType(bts64)); + end; + {$ELSE} btU32: TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu32 := -TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu32; - bts8: TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts8 := -TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts8; - bts16: TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts16 := -TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts16; - bts32: TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts32 := -TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts32; + {$ENDIF} + { a negated ShortInt or SmallInt constant is an Integer, as in Delphi: -ShortInt(-128) is 128 } + bts8: + begin + TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts32 := -Longint(TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts8); + TPSValueData(TPSUnValueOp(p).FVal1).Data^.FType := at2ut(FindBaseType(bts32)); + end; + bts16: + begin + TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts32 := -Longint(TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts16); + TPSValueData(TPSUnValueOp(p).FVal1).Data^.FType := at2ut(FindBaseType(bts32)); + end; + { the negation of the least Integer or Int64 is past the range: refused, as Delphi refuses + it -- it wrapped to itself } + bts32: + begin + if TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts32 = Low(Longint) then + begin + MakeError('', ecCustomError, tbtstring(RPS_ConstantOverflow)); + Result := False; + exit; + end; + TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts32 := -TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts32; + end; {$IFNDEF PS_NOINT64} - bts64: TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts64 := -TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts64; - btU64: TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu64 := -TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu64; + bts64: + begin + if TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts64 = Low(Int64) then + begin + MakeError('', ecCustomError, tbtstring(RPS_ConstantOverflow)); + Result := False; + exit; + end; + TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts64 := -TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts64; + end; + { the negation of a UInt64 other than 0 is below the range: refused, as + Delphi refuses it -- it wrapped; the negation of 0 is 0 } + btU64: + begin + if TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu64 <> 0 then + begin + MakeError('', ecCustomError, tbtstring(RPS_ConstantOverflow)); + Result := False; + exit; + end; + end; {$ENDIF} btSingle: TPSValueData(TPSUnValueOp(p).FVal1).Data^.tsingle := -TPSValueData(TPSUnValueOp(p).FVal1).Data^.tsingle; btDouble: TPSValueData(TPSUnValueOp(p).FVal1).Data^.tdouble := -TPSValueData(TPSUnValueOp(p).FVal1).Data^.tdouble; - btExtended: TPSValueData(TPSUnValueOp(p).FVal1).Data^.textended := -TPSValueData(TPSUnValueOp(p).FVal1).Data^.textended; - btCurrency: TPSValueData(TPSUnValueOp(p).FVal1).Data^.tcurrency := -TPSValueData(TPSUnValueOp(p).FVal1).Data^.tcurrency; + btExtended: + begin + TPSValueData(TPSUnValueOp(p).FVal1).Data^.textended := -TPSValueData(TPSUnValueOp(p).FVal1).Data^.textended; + TPSValueData(TPSUnValueOp(p).FVal1).FRealText := + _NegatedRealText(TPSValueData(TPSUnValueOp(p).FVal1).FRealText); + end; + btCurrency: + begin + { the negation of the minimum, which only a host's constant can hold, is past the + range: refused, as a binary operation past the range is } + if PInt64(@TPSValueData(TPSUnValueOp(p).FVal1).Data^.tcurrency)^ = Low(Int64) then + begin + MakeError('', ecCustomError, tbtstring(RPS_ConstantOverflow)); + Result := False; + exit; + end; + TPSValueData(TPSUnValueOp(p).FVal1).Data^.tcurrency := -TPSValueData(TPSUnValueOp(p).FVal1).Data^.tcurrency; + end; else begin MakeError('', ecTypeMismatch, ''); @@ -9423,8 +12043,8 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; btU64: TPSValueData(preplace).Data.tsingle := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu64; {$ENDIF} btSingle: TPSValueData(preplace).Data.tsingle := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tsingle; - btDouble: TPSValueData(preplace).Data.tsingle := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tdouble; - btExtended: TPSValueData(preplace).Data.tsingle := TPSValueData(TPSUnValueOp(p).FVal1).Data^.textended; + btDouble: _NarrowToSingle(TPSValueData(preplace).Data.tsingle, TPSValueData(TPSUnValueOp(p).FVal1).Data^.tdouble); + btExtended: _NarrowToSingle(TPSValueData(preplace).Data.tsingle, TPSValueData(TPSUnValueOp(p).FVal1).Data^.textended); btCurrency: TPSValueData(preplace).Data.tsingle := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tcurrency; else begin @@ -9450,7 +12070,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; {$ENDIF} btSingle: TPSValueData(preplace).Data.tdouble := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tsingle; btDouble: TPSValueData(preplace).Data.tdouble := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tdouble; - btExtended: TPSValueData(preplace).Data.tdouble := TPSValueData(TPSUnValueOp(p).FVal1).Data^.textended; + btExtended: _NarrowToDouble(TPSValueData(preplace).Data.tdouble, TPSValueData(TPSUnValueOp(p).FVal1).Data^.textended); btCurrency: TPSValueData(preplace).Data.tdouble := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tcurrency; else begin @@ -9489,6 +12109,8 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; end; btCurrency: begin + { a value outside the range of Currency is refused, as Delphi refuses it } + lFits := True; case TPSValueData(TPSUnValueOp(p).FVal1).Data.Ftype.basetype of btU8: TPSValueData(preplace).Data.tcurrency := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu8; btS8: TPSValueData(preplace).Data.tcurrency := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tS8; @@ -9497,12 +12119,22 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; btEnum, btU32: TPSValueData(preplace).Data.tcurrency := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tU32; btS32: TPSValueData(preplace).Data.tcurrency := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tS32; {$IFNDEF PS_NOINT64} - btS64: TPSValueData(preplace).Data.tcurrency := TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts64; - btU64: TPSValueData(preplace).Data.tcurrency := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu64; + btS64: + begin + lFits := _IntFitsCurrency(TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts64); + if lFits then + TPSValueData(preplace).Data.tcurrency := TPSValueData(TPSUnValueOp(p).FVal1).Data^.ts64; + end; + btU64: + begin + lFits := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu64 <= 922337203685477; + if lFits then + TPSValueData(preplace).Data.tcurrency := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tu64; + end; {$ENDIF} - btSingle: TPSValueData(preplace).Data.tcurrency := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tsingle; - btDouble: TPSValueData(preplace).Data.tcurrency := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tdouble; - btExtended: TPSValueData(preplace).Data.tcurrency := TPSValueData(TPSUnValueOp(p).FVal1).Data^.textended; + btSingle: lFits := _NarrowToCurrency(TPSValueData(preplace).Data.tcurrency, TPSValueData(TPSUnValueOp(p).FVal1).Data^.tsingle); + btDouble: lFits := _NarrowToCurrency(TPSValueData(preplace).Data.tcurrency, TPSValueData(TPSUnValueOp(p).FVal1).Data^.tdouble); + btExtended: lFits := _NarrowRealToCurrency(TPSValueData(preplace).Data.tcurrency, TPSValueData(TPSUnValueOp(p).FVal1).Data^.textended, TPSValueData(TPSUnValueOp(p).FVal1).FRealText); btCurrency: TPSValueData(preplace).Data.tcurrency := TPSValueData(TPSUnValueOp(p).FVal1).Data^.tcurrency; else begin @@ -9512,6 +12144,13 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; exit; end; end; + if not lFits then + begin + MakeError('', ecCustomError, tbtstring(RPS_ConstantOverflow)); + preplace.Free; + Result := False; + exit; + end; end; else begin @@ -9521,6 +12160,16 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; exit; end; end; + { an enumeration holds only its own size: a cast of a larger value keeps the low bits, as in + Delphi and as the run time stores it -- Ord(TEn(256)) of a one-byte enumeration is 0 } + if (TPSUnValueOp(p).FType.BaseType = btEnum) and + (GetTypeCopyLink(TPSUnValueOp(p).FType) is TPSEnumType) then + begin + if TPSEnumType(GetTypeCopyLink(TPSUnValueOp(p).FType)).HighValue <= 255 then + TPSValueData(preplace).Data.tu32 := TPSValueData(preplace).Data.tu32 and $FF + else if TPSEnumType(GetTypeCopyLink(TPSUnValueOp(p).FType)).HighValue <= 65535 then + TPSValueData(preplace).Data.tu32 := TPSValueData(preplace).Data.tu32 and $FFFF; + end; p.Free; p := preplace; end; @@ -9620,9 +12269,42 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; Result := true; end; + { a call of a routine returning the type of its string argument (Copy, Trim, the case and padding routines, + a procedural type declared so) is of that argument's string type from the start, a character's or a + PChar's a string of its width: typed AnyString, an AnsiString, its result went through an AnsiString + wherever the call is an operand } + procedure SetAnyStringResultType(aCall: TPSValueProc); + var + lParamIdx: Longint; + lType: TPSType; + begin + if aCall.ResultType = FAnyString then + for lParamIdx := aCall.Parameters.Count - 1 downto 0 do + if (aCall.Parameters[lParamIdx].ParamMode <> pmOut) and + (aCall.Parameters[lParamIdx].ExpectedType = FAnyString) and + (aCall.Parameters[lParamIdx].Val <> nil) then + begin + lType := GetTypeNo(BlockInfo, aCall.Parameters[lParamIdx].Val); + if lType <> nil then + begin + if (lType.BaseType = btChar) or (lType.BaseType = btPChar) then + lType := at2ut(FindBaseType(btString)) + {$IFNDEF PS_NOWIDESTRING} + else if lType.BaseType = btWideChar then + lType := at2ut(FindBaseType(btUnicodeString)) + {$ENDIF}; + if lType.BaseType in [btString{$IFNDEF PS_NOWIDESTRING}, btWideString, btUnicodeString{$ENDIF}] then + aCall.ResultType := lType; + end; + Break; + end; + end; + function ReadProcParameters(ProcNo: Cardinal; FSelf: TPSValue): TPSValue; var Decl: TPSParametersDecl; + lType: TPSType; + lSetType: TPSType; begin if TPSProcedure(FProcs[ProcNo]).ClassType = TPSInternalProcedure then Decl := TPSInternalProcedure(FProcs[ProcNo]).Decl @@ -9665,6 +12347,41 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; ExpectedType := GetTypeNo(BlockInfo, FSelf); end; end; + SetAnyStringResultType(TPSValueProc(Result)); + {$IFNDEF PS_NOINT64} + { High and Low of a UInt64 are UInt64s, as in Delphi: typed Int64, High's 18446744073709551615 was -1, + and an expression with Low (Low(u) - u) was computed signed } + if (TObject(FProcs[ProcNo]) is TPSExternalProcedure) and + ((TPSExternalProcedure(FProcs[ProcNo]).RegProc = FHighProc) or + (TPSExternalProcedure(FProcs[ProcNo]).RegProc = FLowProc)) and + (TPSValueProcNo(Result).Parameters.Count = 1) and (TPSValueProcNo(Result).Parameters[0].Val <> nil) then + begin + lType := GetTypeNo(BlockInfo, TPSValueProcNo(Result).Parameters[0].Val); + if (lType <> nil) and (lType.BaseType = btU64) then + TPSValueProcNo(Result).ResultType := at2ut(FindBaseType(btU64)); + end; + {$ENDIF} + { a Char goes into a set of a character type only, as in Delphi: the run time tells the sets apart by + size alone, so Include and Exclude took it into a set of Byte or of an enumeration of 256 members } + if (TObject(FProcs[ProcNo]) is TPSExternalProcedure) and + ((TPSExternalProcedure(FProcs[ProcNo]).RegProc = FIncludeProc) or + (TPSExternalProcedure(FProcs[ProcNo]).RegProc = FExcludeProc)) and + (TPSValueProcNo(Result).Parameters.Count = 2) and (TPSValueProcNo(Result).Parameters[0].Val <> nil) and + (TPSValueProcNo(Result).Parameters[1].Val <> nil) then + begin + lType := GetTypeNo(BlockInfo, TPSValueProcNo(Result).Parameters[1].Val); + lSetType := GetTypeNo(BlockInfo, TPSValueProcNo(Result).Parameters[0].Val); + if lSetType <> nil then + lSetType := GetTypeCopyLink(lSetType); + if (lType <> nil) and (lType.BaseType = btChar) and (lSetType is TPSSetType) and + ((TPSSetType(lSetType).SetType = nil) or (TPSSetType(lSetType).SetType.BaseType <> btChar)) then + begin + MakeError('', ecTypeMismatch, ''); + Result.Free; + Result := nil; + exit; + end; + end; end; {$IFNDEF PS_NOIDISPATCH} @@ -9784,10 +12501,80 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; Result := nil; exit; end; + SetAnyStringResultType(TPSValueProc(Result)); end; function WriteCalculation(InData, OutReg: TPSValue): Boolean; + var + lWide, lOutType: TPSType; + lTruth: TPSBinValueOp; + lBool: TPSValue; + lConst: TPSValueData; + lFits: Boolean; + + { aConst converted to aType when aConst is a real constant, or a 64-bit + integer one, and aType a Single, Double or Currency narrower than it -- as + Delphi converts a constant when it compiles: +Inf or -Inf past the range of + a Single or Double, and aFits False past Currency's; nil when there is + nothing to convert, or the value does not fit } + function NarrowedConstant(aConst: TPSValueData; aType: TPSType; out aFits: Boolean): TPSValueData; + var + lFrom: TPSBaseType; + begin + Result := nil; + aFits := True; + lFrom := aConst.Data.FType.BaseType; + case aType.BaseType of + btSingle: + if (lFrom = btDouble) or (lFrom = btExtended) then + begin + Result := TPSValueData.Create; + Result.Data := NewVariant(aType); + if lFrom = btDouble then + _NarrowToSingle(Result.Data.tsingle, aConst.Data.tdouble) + else + _NarrowToSingle(Result.Data.tsingle, aConst.Data.textended); + end; + btDouble: + if lFrom = btExtended then + begin + Result := TPSValueData.Create; + Result.Data := NewVariant(aType); + _NarrowToDouble(Result.Data.tdouble, aConst.Data.textended); + end; + btCurrency: + if lFrom in [btSingle, btDouble, btExtended{$IFNDEF PS_NOINT64}, btS64, btU64{$ENDIF}] then + begin + Result := TPSValueData.Create; + Result.Data := NewVariant(aType); + case lFrom of + btSingle: aFits := _NarrowToCurrency(Result.Data.tcurrency, aConst.Data.tsingle); + btDouble: aFits := _NarrowToCurrency(Result.Data.tcurrency, aConst.Data.tdouble); + btExtended: aFits := _NarrowRealToCurrency(Result.Data.tcurrency, aConst.Data.textended, aConst.FRealText); + {$IFNDEF PS_NOINT64} + btS64: + begin + aFits := _IntFitsCurrency(aConst.Data.ts64); + if aFits then + Result.Data.tcurrency := aConst.Data.ts64; + end; + btU64: + begin + aFits := aConst.Data.tu64 <= 922337203685477; + if aFits then + Result.Data.tcurrency := aConst.Data.tu64; + end; + {$ENDIF} + end; + if not aFits then + begin + Result.Free; + Result := nil; + end; + end; + end; + end; function CheckOutreg(Where, Outreg: TPSValue; aRoot: Boolean): Boolean; var @@ -9833,6 +12620,65 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; Result := True; exit; end; + { a ByteBool, WordBool or LongBool value goes into another Boolean type -- a condition, an assignment, a + parameter -- as its truth, as in Delphi: the run time assigns by size, so the WordBool 256 became the + Boolean 0 and the LongBool -1 the Boolean 255 } + lWide := _WideBoolType(InData); + lOutType := GetTypeNo(BlockInfo, OutReg); + if lOutType <> nil then + lOutType := GetTypeCopyLink(lOutType); + if (lWide <> nil) and (lOutType <> nil) and (lOutType <> lWide) and IsBoolean(lOutType) and + not ((InData is TPSValueReplace) and not TPSValueReplace(InData).ValuesAllocatedBeforeOutput) then + begin + lTruth := _BoolTruth(InData, lWide); + try + if lOutType = FDefaultBoolType then + Result := WriteCalculation(lTruth, OutReg) + else if PreWriteOutRec(OutReg, nil) then + begin + { the destination first, as an assignment prepares it: an index computed there can change the value } + lBool := AllocStackReg(at2ut(FDefaultBoolType)); + try + Result := WriteCalculation(lTruth, lBool); + if Result then + begin + BlockWriteByte(BlockInfo, CM_A); + Result := WriteOutRec(OutReg, False) and WriteOutRec(lBool, True); + end; + finally + lBool.Free; + end; + AfterWriteOutRec(OutReg); + end else + Result := False; + finally + lTruth.Val1 := nil; + lTruth.Free; + end; + exit; + end; + { a constant goes into a narrower real or Currency converted now, as Delphi + converts it; converted when the script ran, past the range it stopped the + script or stored a wrong Currency } + if (InData.ClassType = TPSValueData) and (lOutType <> nil) then + begin + lConst := NarrowedConstant(TPSValueData(InData), lOutType, lFits); + if not lFits then + begin + MakeError('', ecCustomError, tbtstring(RPS_ConstantOverflow)); + Result := False; + exit; + end; + if lConst <> nil then + begin + try + Result := WriteCalculation(lConst, OutReg); + finally + lConst.Free; + end; + exit; + end; + end; if InData is TPSValueProc then begin Result := _ProcessFunction(TPSValueProc(indata), OutReg) @@ -9872,12 +12718,15 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; end else begin if not PreWriteOutRec(InData, GetTypeNo(BlockInfo, OutReg)) then begin + AfterWriteOutRec(OutReg); Result := False; exit; end; BlockWriteByte(BlockInfo, CM_A); if not (WriteOutRec(OutReg, False) and WriteOutRec(InData, True)) then begin + AfterWriteOutRec(InData); + AfterWriteOutRec(OutReg); Result := False; exit; end; @@ -9893,9 +12742,24 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; var res: TPSType; tmp: TPSParameter; - lTv: TPSValue; resreg: TPSValue; l: Longint; + lOpenTemps: array of TPSValue; + lHigh: TPSValueData; + + { the copies var open array parameters are passed through (below): pushed ahead of the result and the + parameters, so released after them, the last pushed first } + procedure FreeOpenTemps; + var + i: Longint; + begin + for i := 0 to Length(lOpenTemps) - 1 do + if lOpenTemps[i] <> nil then + begin + lOpenTemps[i].Free; + lOpenTemps[i] := nil; + end; + end; function Cleanup: Boolean; var @@ -9921,16 +12785,50 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; begin Result := False; resreg.Free; + FreeOpenTemps; exit; end; end; resreg.Free; end; end; + FreeOpenTemps; Result := True; end; begin + { High of an enumeration is its last member, a constant, as in Delphi: the run time holds an + enumeration as an integer of its size and answered that integer's bound } + if (ProcCall is TPSValueProcNo) and (ProcCall.Parameters.Count = 1) and + (TObject(FProcs[TPSValueProcNo(ProcCall).ProcNo]) is TPSExternalProcedure) and + { the built-in itself -- not a routine of that name a host declares, whatever its parameters } + (TPSExternalProcedure(FProcs[TPSValueProcNo(ProcCall).ProcNo]).RegProc = FHighProc) and + (GetTypeNo(BlockInfo, ProcCall.Parameters[0].Val) <> nil) and + (GetTypeCopyLink(GetTypeNo(BlockInfo, ProcCall.Parameters[0].Val)) is TPSEnumType) and + { ByteBool, WordBool and LongBool are enumerations here whose HighValue only sets their size } + (FastUpperCase(GetTypeCopyLink(GetTypeNo(BlockInfo, ProcCall.Parameters[0].Val)).Name) <> 'BYTEBOOL') and + (FastUpperCase(GetTypeCopyLink(GetTypeNo(BlockInfo, ProcCall.Parameters[0].Val)).Name) <> 'WORDBOOL') and + (FastUpperCase(GetTypeCopyLink(GetTypeNo(BlockInfo, ProcCall.Parameters[0].Val)).Name) <> 'LONGBOOL') then + begin + Result := True; + if ResultRegister <> nil then + begin + lHigh := TPSValueData.Create; + try + lHigh.Data := NewVariant(ProcCall.ResultType); + {$IFNDEF PS_NOINT64}if ProcCall.ResultType.BaseType = btS64 then + lHigh.Data.ts64 := TPSEnumType(GetTypeCopyLink(GetTypeNo(BlockInfo, + ProcCall.Parameters[0].Val))).HighValue + else{$ENDIF} + lHigh.Data.ts32 := Longint(TPSEnumType(GetTypeCopyLink(GetTypeNo(BlockInfo, + ProcCall.Parameters[0].Val))).HighValue); + Result := WriteCalculation(lHigh, ResultRegister); + finally + lHigh.Free; + end; + end; + exit; + end; Res := ProcCall.ResultType; if ProcCall.ResultType = FAnyString then begin @@ -9940,6 +12838,14 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; if (Tmp.ParamMode <> pmOut) and (Tmp.ExpectedType = FAnyString) then begin Res := GetTypeNo(BlockInfo, tmp.Val); + { a character or a PChar argument gives a string of its width, as in Delphi: Copy of a Char is a + string; a property getter typed AnyString is typed only here } + if (Res <> nil) and ((Res.BaseType = btChar) or (Res.BaseType = btPChar)) then + Res := at2ut(FindBaseType(btString)); + {$IFNDEF PS_NOWIDESTRING} + if (Res <> nil) and (Res.BaseType = btWideChar) then + Res := at2ut(FindBaseType(btUnicodeString)); + {$ENDIF} Break; end; end; @@ -9949,8 +12855,29 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; begin MakeError('', ecNoResult, ''); exit; - end - else if (res <> nil) then + end; + { a var open array parameter's argument goes through a copy of the open array's type, which shares its + elements and tells the call layer to pass them with their high bound } + SetLength(lOpenTemps, ProcCall.Parameters.Count); + for l := ProcCall.Parameters.Count - 1 downto 0 do + begin + Tmp := ProcCall.Parameters[l]; + if (Tmp.ParamMode <> pmIn) and (Tmp.ExpectedType <> nil) and + (Copy(Tmp.ExpectedType.Name, 1, 10) = '!OPENARRAY') then + begin + lOpenTemps[l] := AllocStackReg(Tmp.ExpectedType); + if not PreWriteOutRec(Tmp.FValue, nil) then + begin + FreeOpenTemps; + exit; + end; + BlockWriteByte(BlockInfo, CM_A); + WriteOutRec(lOpenTemps[l], False); + WriteOutRec(Tmp.FValue, False); + AfterWriteOutRec(Tmp.FValue); + end; + end; + if (res <> nil) then begin if (ResultRegister = nil) or (Res <> GetTypeNo(BlockInfo, ResultRegister)) then begin @@ -9981,7 +12908,11 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; Tmp := ProcCall.Parameters[l]; if (Tmp.ParamMode <> pmIn) then begin - if IsVarInCompatible(GetTypeNo(BlockInfo, tmp.Val), tmp.ExpectedType) then + if IsVarInCompatible(GetTypeNo(BlockInfo, tmp.Val), tmp.ExpectedType) and not + { a var open array parameter takes a dynamic array of its element type, as ValidateParameters checked } + ((Copy(tmp.ExpectedType.Name, 1, 10) = '!OPENARRAY') and (GetTypeNo(BlockInfo, tmp.Val).BaseType = btArray) and + IsSameScriptType(TPSArrayType(GetTypeNo(BlockInfo, tmp.Val)).ArrayTypeNo, + TPSArrayType(tmp.ExpectedType).ArrayTypeNo)) then begin with MakeError('', ecTypeMismatch, '') do begin @@ -9994,24 +12925,9 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; end; if Copy(tmp.ExpectedType.Name, 1, 10) = '!OPENARRAY' then begin tmp.TempVar := AllocPointer(tmp.ExpectedType); - lTv := AllocStackReg(tmp.ExpectedType); - if not PreWriteOutRec(Tmp.FValue, nil) then - begin - cleanup; - exit; - end; - BlockWriteByte(BlockInfo, CM_A); - WriteOutRec(lTv, False); - WriteOutRec(Tmp.FValue, False); - AfterWriteOutRec(Tmp.FValue); - BlockWriteByte(BlockInfo, cm_sp); WriteOutRec(tmp.TempVar, False); - WriteOutRec(lTv, False); - - lTv.Free; -// BlockWriteByte(BlockInfo, CM_PO); // pop the temp var - + WriteOutRec(lOpenTemps[l], False); end else begin tmp.TempVar := AllocPointer(GetTypeNo(BlockInfo, Tmp.FValue)); if not PreWriteOutRec(Tmp.FValue, nil) then @@ -10031,12 +12947,41 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; Tmp.ExpectedType := GetTypeNo(BlockInfo, tmp.Val) else if Tmp.ExpectedType = FAnyString then begin Tmp.ExpectedType := GetTypeNo(BlockInfo, tmp.Val); - if not IsStringOrCharType(Tmp.ExpectedType.BaseType) and (Tmp.ExpectedType.BaseType <> btVariant) then + if (Tmp.ExpectedType = nil) or + (not IsStringOrCharType(Tmp.ExpectedType.BaseType) and (Tmp.ExpectedType.BaseType <> btVariant) and + (Tmp.ExpectedType.BaseType <> btPChar)) then + begin + MakeError('', ecTypeMismatch, ''); + Cleanup; + exit; + end; + { StringOfChar and Replicate take a character, as in Delphi: a string's first character was + repeated, and an empty one gave #0 } + if (FStringOfCharProc <> nil) and (ProcCall is TPSValueProcNo) and + (TObject(FProcs[TPSValueProcNo(ProcCall).ProcNo]) is TPSExternalProcedure) and + ((TPSExternalProcedure(FProcs[TPSValueProcNo(ProcCall).ProcNo]).RegProc = FStringOfCharProc) or + (TPSExternalProcedure(FProcs[TPSValueProcNo(ProcCall).ProcNo]).RegProc = FReplicateProc)) and + not (Tmp.ExpectedType.BaseType in [btChar{$IFNDEF PS_NOWIDESTRING}, btWideChar{$ENDIF}, btVariant]) then begin MakeError('', ecTypeMismatch, ''); Cleanup; exit; end; + { a character or a PChar goes as a string of its width, as in Delphi: the run time picks the string + routine by the argument's type, and took a WideChar's ANSI one } + if (Tmp.ExpectedType.BaseType = btChar) or (Tmp.ExpectedType.BaseType = btPChar) then + Tmp.ExpectedType := at2ut(FindBaseType(btString)) + {$IFNDEF PS_NOWIDESTRING} + else if Tmp.ExpectedType.BaseType = btWideChar then + Tmp.ExpectedType := at2ut(FindBaseType(btUnicodeString)) + {$ENDIF}; + end; + { an argument of no type (nil) for an untyped parameter: there is nothing to pass } + if Tmp.ExpectedType = nil then + begin + MakeError('', ecTypeMismatch, ''); + Cleanup; + exit; end; if Tmp.ExpectedType.BaseType = btPChar then begin @@ -10160,11 +13105,13 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; FPos, NPos, EPos, EPos2, RPos, RPos2: Longint; OldCO, OldBO: TPSList; I: Longint; - iOldWithCount: Integer; + iOldLoopStackDepth: Integer; iOldTryCount: Integer; iOldExFnlCount: Integer; lType, CounterType: TPSType; ExitCheckEmitted: Boolean; + lFinTemp, lInitTemp, lFinOrig: TPSValue; + lOk: Boolean; function CreateForBoundaryValue: TPSValue; { Returns High(CounterType) for to-loops or Low(CounterType) for @@ -10314,6 +13261,14 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; exit; end; end; + { a call is no variable, as in Delphi: a routine's result taken as the + counter was a temporary, and the routine was called again at every check } + if VariableVar is TPSValueProc then + begin + MakeError('', ecVariableExpected, ''); + VariableVar.Free; + exit; + end; if FParser.CurrTokenId <> CSTI_Assignment then begin MakeError('', ecAssignmentExpected, ''); @@ -10339,19 +13294,35 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; exit; end; FParser.Next; + { a non-constant start is computed before the end is read, as in Delphi: reading a field of a function's + record result in the end calls the function at once } + lInitTemp := nil; + if not (InitVal is TPSValueData) then + begin + lInitTemp := AllocStackReg(CounterType); + if not WriteCalculation(InitVal, lInitTemp) then + begin + lInitTemp.Free; + InitVal.Free; + VariableVar.Free; + exit; + end; + end; finVal := calc(CSTII_do); if finVal = nil then begin - VariableVar.Free; + lInitTemp.Free; InitVal.Free; + VariableVar.Free; exit; end; lType := GetTypeNo(BlockInfo, finVal); if lType = nil then begin MakeError('', ecTypeMismatch, ''); - VariableVar.Free; - InitVal.Free; finVal.Free; + lInitTemp.Free; + InitVal.Free; + VariableVar.Free; exit; end; case lType.BaseType of @@ -10359,39 +13330,75 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; else begin MakeError('', ecTypeMismatch, ''); - VariableVar.Free; - InitVal.Free; finVal.Free; + lInitTemp.Free; + InitVal.Free; + VariableVar.Free; exit; end; end; if FParser.CurrTokenId <> CSTII_do then begin MakeError('', ecDoExpected, ''); - InitVal.Free; finVal.Free; + lInitTemp.Free; + InitVal.Free; VariableVar.Free; exit; end; FParser.Next; - if not WriteCalculation(InitVal, VariableVar) then + { the start and then the end are computed once, before the counter is set, as in Delphi: the loop + compared the counter with the end expression itself, so a variable changed in the body moved the end, + a function was called on every iteration, and the end was computed before the start. The values + reading the bounds left on the stack (a field of a function's record result) stay there, under the + temporaries, to the loop's end, and all are freed last first after it } + lFinTemp := nil; + lFinOrig := nil; + if not (finVal is TPSValueData) then + begin + lFinTemp := AllocStackReg(lType); + if not WriteCalculation(finVal, lFinTemp) then + begin + lFinTemp.Free; + finVal.Free; + lInitTemp.Free; + InitVal.Free; + VariableVar.Free; + exit; + end; + lFinOrig := finVal; + finVal := TPSValueReplace.Create; + finVal.SetParserPos(FParser); + TPSValueReplace(finVal).NewValue := lFinTemp; + TPSValueReplace(finVal).FreeNewValue := False; + end; + if lInitTemp <> nil then + lOk := WriteCalculation(lInitTemp, VariableVar) + else + lOk := WriteCalculation(InitVal, VariableVar); + if not lOk then begin - VariableVar.Free; - InitVal.Free; finVal.Free; + lFinTemp.Free; + lFinOrig.Free; + lInitTemp.Free; + InitVal.Free; + VariableVar.Free; exit; end; - InitVal.Free; TempBool := AllocStackReg(at2ut(FDefaultBoolType)); NPos := Length(BlockInfo.Proc.Data); if not EmitForEntryCheck then { sets EPos/RPos for fixup } begin TempBool.Free; - VariableVar.Free; finVal.Free; + lFinTemp.Free; + lFinOrig.Free; + lInitTemp.Free; + InitVal.Free; + VariableVar.Free; exit; end; - finVal.Free; OldCO := FContinueOffsets; FContinueOffsets := TPSList.Create; OldBO := FBreakOffsets; @@ -10399,8 +13406,8 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; Block := TPSBlockInfo.Create(BlockInfo); Block.SubType := tOneLiner; - iOldWithCount := FWithCount; - FWithCount := 0; + iOldLoopStackDepth := FLoopStackDepth; + FLoopStackDepth := BlockInfo.Proc.ProcVars.Count; iOldTryCount := FTryCount; FTryCount := 0; iOldExFnlCount := FExceptFinallyCount; @@ -10410,13 +13417,18 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; begin Block.Free; TempBool.Free; + finVal.Free; + lFinTemp.Free; + lFinOrig.Free; + lInitTemp.Free; + InitVal.Free; VariableVar.Free; FBreakOffsets.Free; FContinueOffsets.Free; FContinueOffsets := OldCO; FBreakOffsets := OldBo; - FWithCount := iOldWithCount; + FLoopStackDepth := iOldLoopStackDepth; FTryCount := iOldTryCount; FExceptFinallyCount := iOldExFnlCount; @@ -10427,13 +13439,18 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; if not EmitForExitCheck then { sets ExitCheckEmitted/EPos2/RPos2 for fixup } begin TempBool.Free; + finVal.Free; + lFinTemp.Free; + lFinOrig.Free; + lInitTemp.Free; + InitVal.Free; VariableVar.Free; FBreakOffsets.Free; FContinueOffsets.Free; FContinueOffsets := OldCO; FBreakOffsets := OldBo; - FWithCount := iOldWithCount; + FLoopStackDepth := iOldLoopStackDepth; FTryCount := iOldTryCount; FExceptFinallyCount := iOldExFnlCount; @@ -10442,13 +13459,18 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; if not PreWriteOutRec(VariableVar, nil) then begin TempBool.Free; + finVal.Free; + lFinTemp.Free; + lFinOrig.Free; + lInitTemp.Free; + InitVal.Free; VariableVar.Free; FBreakOffsets.Free; FContinueOffsets.Free; FContinueOffsets := OldCO; FBreakOffsets := OldBo; - FWithCount := iOldWithCount; + FLoopStackDepth := iOldLoopStackDepth; FTryCount := iOldTryCount; FExceptFinallyCount := iOldExFnlCount; @@ -10461,13 +13483,18 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; if not WriteOutRec(VariableVar, False) then begin TempBool.Free; + finVal.Free; + lFinTemp.Free; + lFinOrig.Free; + lInitTemp.Free; + InitVal.Free; VariableVar.Free; FBreakOffsets.Free; FContinueOffsets.Free; FContinueOffsets := OldCO; FBreakOffsets := OldBo; - FWithCount := iOldWithCount; + FLoopStackDepth := iOldLoopStackDepth; FTryCount := iOldTryCount; FExceptFinallyCount := iOldExFnlCount; @@ -10512,11 +13539,16 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; FContinueOffsets := OldCO; FBreakOffsets := OldBo; - FWithCount := iOldWithCount; + FLoopStackDepth := iOldLoopStackDepth; FTryCount := iOldTryCount; FExceptFinallyCount := iOldExFnlCount; TempBool.Free; + finVal.Free; + lFinTemp.Free; + lFinOrig.Free; + lInitTemp.Free; + InitVal.Free; VariableVar.Free; if HasInvalidJumps(RPos, Length(BlockInfo.Proc.Data)) then begin @@ -10534,7 +13566,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; I: Longint; Block: TPSBlockInfo; - iOldWithCount: Integer; + iOldLoopStackDepth: Integer; iOldTryCount: Integer; iOldExFnlCount: Integer; @@ -10542,17 +13574,24 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; Result := False; Debug_WriteLine(BlockInfo); FParser.Next; + { the condition's register first, then the condition, inside the loop: a field of a function's record + result is materialized where the condition is parsed, which was before the loop's start, so the + condition read the field once } + vin := AllocStackReg(at2ut(FDefaultBoolType)); + SPos := Length(BlockInfo.Proc.Data); // start position vout := calc(CSTII_do); if vout = nil then + begin + vin.Free; exit; + end; if FParser.CurrTokenId <> CSTII_do then begin vout.Free; + vin.Free; MakeError('', ecDoExpected, ''); exit; end; - vin := AllocStackReg(at2ut(FDefaultBoolType)); - SPos := Length(BlockInfo.Proc.Data); // start position OldCo := FContinueOffsets; FContinueOffsets := TPSList.Create; OldBO := FBreakOffsets; @@ -10567,6 +13606,9 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; FBreakOffsets := OldBo; exit; end; + { the condition's own values go before the jump: the body was compiled without them } + vout.Free; + vout := nil; FParser.Next; // skip DO BlockWriteByte(BlockInfo, Cm_CNG); // only goto if expression is false BlockWriteLong(BlockInfo, $12345678); @@ -10586,8 +13628,8 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; Block := TPSBlockInfo.Create(BlockInfo); Block.SubType := tOneLiner; - iOldWithCount := FWithCount; - FWithCount := 0; + iOldLoopStackDepth := FLoopStackDepth; + FLoopStackDepth := BlockInfo.Proc.ProcVars.Count; iOldTryCount := FTryCount; FTryCount := 0; iOldExFnlCount := FExceptFinallyCount; @@ -10603,7 +13645,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; FContinueOffsets := OldCO; FBreakOffsets := OldBo; - FWithCount := iOldWithCount; + FLoopStackDepth := iOldLoopStackDepth; FTryCount := iOldTryCount; FExceptFinallyCount := iOldExFnlCount; @@ -10641,13 +13683,11 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; FContinueOffsets := OldCO; FBreakOffsets := OldBo; - FWithCount := iOldWithCount; + FLoopStackDepth := iOldLoopStackDepth; FTryCount := iOldTryCount; FExceptFinallyCount := iOldExFnlCount; - // vin must be freed before vout to maintain LIFO order for CM_PO generation vin.Free; - vout.Free; if HasInvalidJumps(RPos, Length(BlockInfo.Proc.Data)) then begin Result := False; @@ -10664,7 +13704,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; OldCo, OldBO: TPSList; Block: TPSBlockInfo; - iOldWithCount: Integer; + iOldLoopStackDepth: Integer; iOldTryCount: Integer; iOldExFnlCount: Integer; @@ -10681,8 +13721,8 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; Block := TPSBlockInfo.Create(BlockInfo); Block.SubType := tRepeat; - iOldWithCount := FWithCount; - FWithCount := 0; + iOldLoopStackDepth := FLoopStackDepth; + FLoopStackDepth := BlockInfo.Proc.ProcVars.Count; iOldTryCount := FTryCount; FTryCount := 0; iOldExFnlCount := FExceptFinallyCount; @@ -10696,7 +13736,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; FContinueOffsets := OldCO; FBreakOffsets := OldBo; - FWithCount := iOldWithCount; + FLoopStackDepth := iOldLoopStackDepth; FTryCount := iOldTryCount; FExceptFinallyCount := iOldExFnlCount; @@ -10705,6 +13745,9 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; end; Block.Free; FParser.Next; //cstii_until + { Continue goes to the condition's own code: a field of a function's record result is materialized where + the condition is parsed, and Continue went past it } + CPos := Length(BlockInfo.Proc.Data); vout := calc(CSTI_Semicolon); if vout = nil then begin @@ -10713,14 +13756,13 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; FContinueOffsets := OldCO; FBreakOffsets := OldBo; - FWithCount := iOldWithCount; + FLoopStackDepth := iOldLoopStackDepth; FTryCount := iOldTryCount; FExceptFinallyCount := iOldExFnlCount; vin.Free; exit; end; - CPos := Length(BlockInfo.Proc.Data); if not WriteCalculation(vout, vin) then begin vin.Free; @@ -10730,12 +13772,15 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; FContinueOffsets := OldCO; FBreakOffsets := OldBo; - FWithCount := iOldWithCount; + FLoopStackDepth := iOldLoopStackDepth; FTryCount := iOldTryCount; FExceptFinallyCount := iOldExFnlCount; exit; end; + { the condition's own values go before the jump back: the body was compiled without them } + vout.Free; + vout := nil; BlockWriteByte(BlockInfo, Cm_CNG); BlockWriteLong(BlockInfo, $12345678); EPos := Length(BlockInfo. Proc.Data); @@ -10749,7 +13794,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; FContinueOffsets := OldCO; FBreakOffsets := OldBo; - FWithCount := iOldWithCount; + FLoopStackDepth := iOldLoopStackDepth; FTryCount := iOldTryCount; FExceptFinallyCount := iOldExFnlCount; @@ -10785,13 +13830,11 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; FContinueOffsets := OldCO; FBreakOffsets := OldBo; - FWithCount := iOldWithCount; + FLoopStackDepth := iOldLoopStackDepth; FTryCount := iOldTryCount; FExceptFinallyCount := iOldExFnlCount; - // vin must be freed before vout to maintain LIFO order for CM_PO generation vin.Free; - vout.Free; if HasInvalidJumps(SPos, Length(BlockInfo. Proc.Data)) then begin Result := False; @@ -10976,6 +14019,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; function ProcessCase: Boolean; var V1, V2, TempRec, Val, CalcItem: TPSValue; + lSelector: TPSValue; p: TPSBinValueOp; SPos, CurrP: Cardinal; I: Longint; @@ -11013,6 +14057,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; begin Debug_WriteLine(BlockInfo); FParser.Next; + lSelector := nil; Val := calc(CSTII_of); if Val = nil then begin @@ -11038,11 +14083,14 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; if not WriteCalculation(Val, TempRec) then begin TempRec.Free; + lSelector.Free; val.Free; ProcessCase := False; exit; end; {if} - val.Free; + { the selector's own values (a field of a function's record result) lie under TempRec, so the selector + is freed after it: freed here, it popped TempRec } + lSelector := Val; EndReloc := TPSList.Create; CalcItem := AllocStackReg(at2ut(FDefaultBoolType)); SPos := Length(BlockInfo.Proc.Data); @@ -11051,11 +14099,18 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; while true do begin Val := calc(CSTI_Colon); + if (Val <> nil) and (GetTypeNo(BlockInfo, Val) = nil) and (Val.ClassType <> TPSValueNil) then + begin + MakeError('', ecTypeMismatch, ''); + Val.Free; + Val := nil; + end; if (Val = nil) then begin V1.Free; CalcItem.Free; TempRec.Free; + lSelector.Free; EndReloc.Free; ProcessCase := False; exit; @@ -11063,10 +14118,17 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; if fParser.CurrTokenID = CSTI_TwoDots then begin FParser.Next; V2 := Calc(CSTI_colon); + if (V2 <> nil) and (GetTypeNo(BlockInfo, V2) = nil) and (V2.ClassType <> TPSValueNil) then + begin + MakeError('', ecTypeMismatch, ''); + V2.Free; + V2 := nil; + end; if V2 = nil then begin V1.Free; CalcItem.Free; TempRec.Free; + lSelector.Free; EndReloc.Free; ProcessCase := False; Val.Free; @@ -11102,6 +14164,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; V1.Free; CalcItem.Free; TempRec.Free; + lSelector.Free; EndReloc.Free; ProcessCase := False; exit; @@ -11114,6 +14177,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; CalcItem.Free; v1.Free; TempRec.Free; + lSelector.Free; EndReloc.Free; ProcessCase := False; exit; @@ -11130,6 +14194,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; Block.Free; CalcItem.Free; TempRec.Free; + lSelector.Free; EndReloc.Free; ProcessCase := False; exit; @@ -11154,6 +14219,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; Block.Free; CalcItem.Free; TempRec.Free; + lSelector.Free; EndReloc.Free; ProcessCase := False; exit; @@ -11165,6 +14231,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; MakeError('', ecEndExpected, ''); CalcItem.Free; TempRec.Free; + lSelector.Free; EndReloc.Free; ProcessCase := False; exit; @@ -11182,35 +14249,10 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; end; CalcItem.Free; TempRec.Free; + lSelector.Free; EndReloc.Free; - if FContinueOffsets <> nil then - begin - for i := 0 to FContinueOffsets.Count -1 do - begin - if Cardinal(FContinueOffsets[i]) >= SPos then - begin - {$ifdef FPC_REQUIRES_PROPER_ALIGNMENT} - unaligned(Byte((@BlockInfo.Proc.Data[Longint(FContinueOffsets[i]) - 4])^)) := Cm_P2G; - {$else} - Byte((@BlockInfo.Proc.Data[Longint(FContinueOffsets[i]) - 4])^) := Cm_P2G; - {$endif} - end; - end; - end; - if FBreakOffsets <> nil then - begin - for i := 0 to FBreakOffsets.Count -1 do - begin - if Cardinal(FBreakOffsets[i]) >= SPos then - begin - {$ifdef FPC_REQUIRES_PROPER_ALIGNMENT} - unaligned(Byte((@BlockInfo.Proc.Data[Longint(FBreakOffsets[i]) - 4])^)) := Cm_P2G; - {$else} - Byte((@BlockInfo.Proc.Data[Longint(FBreakOffsets[i]) - 4])^) := Cm_P2G; - {$endif} - end; - end; - end; + { a Break or Continue in an arm pops the selector and condition itself, with every other value pushed + since its loop's body began } if HasInvalidJumps(SPos, Length(BlockInfo.Proc.Data)) then begin Result := False; @@ -11257,6 +14299,22 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; iStartOffset: Integer; tmp: TPSValue; + lPrepared: array of TPSValue; + + { releases every subject's preparation, last first. Each is kept until the statement's end -- a function + result's preparation holds the result the body reads -- and released there or on a failing exit } + procedure ReleasePrepared; + var + lIdx: Longint; + lPrep: TPSValue; + begin + for lIdx := High(lPrepared) downto 0 do + begin + lPrep := lPrepared[lIdx]; + AfterWriteOutRec(lPrep); + end; + end; + begin Debug_WriteLine(BlockInfo); Block := TPSBlockInfo.Create(BlockInfo); @@ -11267,6 +14325,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; aVar := GetIdentifier(0); if aVar = nil then begin + ReleasePrepared; block.Free; Result := False; exit; @@ -11275,6 +14334,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; if (AType = nil) or ((aType.BaseType <> btRecord) and (aType.BaseType <> btClass)) then begin MakeError('', ecClassTypeExpected, ''); + ReleasePrepared; aVar.Free; Block.Free; Result := False; @@ -11290,11 +14350,31 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; //if aVar.InheritsFrom(TPSVar) then TPSVar(aVar).Use; tmp := AllocPointer(GetTypeNo(BlockInfo, aVar)); TPSProcVar(BlockInfo.Proc.ProcVars[TPSValueAllocatedStackVar(tmp).LocalVarNo]).Use; - PreWriteOutRec(tmp,GetTypeNo(BlockInfo, tmp)); - PreWriteOutRec(aVar,GetTypeNo(BlockInfo, aVar)); + { a subject that fails to compile stops the statement: its error was recorded, the compile went on and + emitted an instruction without its operand } + if not (PreWriteOutRec(tmp, GetTypeNo(BlockInfo, tmp)) and PreWriteOutRec(aVar, GetTypeNo(BlockInfo, aVar))) then + begin + ReleasePrepared; + tmp.Free; + aReplace.Free; + Block.Free; + Result := False; + exit; + end; + SetLength(lPrepared, Length(lPrepared) + 1); + lPrepared[High(lPrepared)] := aVar; BlockWriteByte(BlockInfo, cm_sp); - WriteOutRec(tmp, false); - WriteOutRec(aVar, false); + if not (WriteOutRec(tmp, false) and WriteOutRec(aVar, false)) then + begin + { a constant -- a host's of a record or class type -- has no address } + MakeError('', ecVariableExpected, ''); + ReleasePrepared; + tmp.Free; + aReplace.Free; + Block.Free; + Result := False; + exit; + end; TPSValueReplace(aReplace).NewValue := tmp; @@ -11309,6 +14389,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; if FParser.CurrTokenId <> CSTI_Comma then begin MakeError('', ecDoExpected, ''); + ReleasePrepared; Block.Free; Result := False; exit; @@ -11317,20 +14398,17 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; until False; - inc(FWithCount); - iStartOffset := Length(Block.Proc.Data); if not (ProcessSub(Block) and (not HasInvalidJumps(iStartOffset,Length(BlockInfo.Proc.Data) + 1)) ) then begin - dec(FWithCount); + ReleasePrepared; Block.Free; Result := False; exit; end; - dec(FWithCount); - AfterWriteOutRec(aVar); + ReleasePrepared; AfterWriteOutRec(tmp); Block.Free; Result := True; @@ -11341,6 +14419,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; FStartOffset: Cardinal; iBlockStartOffset: Integer; Block: TPSBlockInfo; + lOldLoopTryDepth: Longint; begin FParser.Next; BlockWriteByte(BlockInfo, cm_puexh); @@ -11351,6 +14430,9 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; BlockWriteLong(BlockInfo, InvalidVal); Block := TPSBlockInfo.Create(BlockInfo); Block.SubType := tTry; + lOldLoopTryDepth := FLoopTryDepth; + if (FTryCount = 0) and (FExceptFinallyCount = 0) then + FLoopTryDepth := BlockInfo.Proc.ProcVars.Count; inc(FTryCount); if ProcessSub(Block) and (not HasInvalidJumps(FStartOffset,Length(BlockInfo.Proc.Data) + 1)) then begin @@ -11479,6 +14561,7 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; exit; end; Cardinal((@BlockInfo.Proc.Data[FStartOffset + 12])^) := Cardinal(Length(BlockInfo.Proc.Data)) - FStartOffset - 15; + FLoopTryDepth := lOldLoopTryDepth; Result := True; end; {ProcessTry} @@ -11603,6 +14686,12 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; Debug_WriteLine2(BlockInfo, BlockInfo.SubType = tProcBegin); BlockWriteByte(BlockInfo, Cm_R); FParser.Next; + { Exit takes no value: `Exit(F())` compiled as Exit and a call after it that never ran } + if FParser.CurrTokenId = CSTI_OpenRound then + begin + MakeError('', ecSemicolonExpected, ''); + exit; + end; if (BlockInfo.SubType = tifOneliner) or (BlockInfo.SubType = TOneLiner) then break; end; @@ -11628,58 +14717,60 @@ function TPSPascalCompiler.ProcessSub(BlockInfo: TPSBlockInfo): Boolean; 1: ; else begin - if FParser.GetToken = 'BREAK' then + if (FParser.GetToken = 'BREAK') and not NameIsDeclared(BlockInfo.Proc, 'BREAK') then begin if FBreakOffsets = nil then begin MakeError('', ecNotInLoop, ''); exit; end; - for i := 0 to FExceptFinallyCount - 1 do + { leave every exception frame the jump crosses, innermost first: each runs its pending finally + and comes back here, as Exit does -- 0 and 1 went on at the end of the try statement } + for i := 0 to FExceptFinallyCount + FTryCount - 1 do begin BlockWriteByte(BlockInfo, cm_poexh); - BlockWriteByte(BlockInfo, 1); + BlockWriteByte(BlockInfo, 4); end; - for i := 0 to FTryCount - 1 do - begin - BlockWriteByte(BlockInfo, cm_poexh); - BlockWriteByte(BlockInfo, 0); - BlockWriteByte(BlockInfo, cm_poexh); - BlockWriteByte(BlockInfo, 1); - end; - - for i := 0 to FWithCount - 1 do - BlockWriteByte(BlockInfo,cm_po); + { every value pushed since the loop's body began -- a with's pointers and temporaries, a case's + selector and condition -- which the jump out of them passes over; the frames left above + removed those inside their try statements } + if FExceptFinallyCount + FTryCount > 0 then + for i := FLoopStackDepth to FLoopTryDepth - 1 do + BlockWriteByte(BlockInfo, cm_po) + else + for i := FLoopStackDepth to Longint(BlockInfo.Proc.ProcVars.Count) - 1 do + BlockWriteByte(BlockInfo, cm_po); BlockWriteByte(BlockInfo, Cm_G); BlockWriteLong(BlockInfo, $12345678); FBreakOffsets.Add(Pointer(Length(BlockInfo.Proc.Data))); FParser.Next; if (BlockInfo.SubType= tifOneliner) or (BlockInfo.SubType = TOneLiner) then break; - end else if FParser.GetToken = 'CONTINUE' then + end else if (FParser.GetToken = 'CONTINUE') and not NameIsDeclared(BlockInfo.Proc, 'CONTINUE') then begin if FBreakOffsets = nil then begin MakeError('', ecNotInLoop, ''); exit; end; - for i := 0 to FExceptFinallyCount - 1 do - begin - BlockWriteByte(BlockInfo, cm_poexh); - BlockWriteByte(BlockInfo, 1); - end; - - for i := 0 to FTryCount - 1 do + { leave every exception frame the jump crosses, innermost first: each runs its pending finally + and comes back here, as Exit does -- 0 and 1 went on at the end of the try statement } + for i := 0 to FExceptFinallyCount + FTryCount - 1 do begin BlockWriteByte(BlockInfo, cm_poexh); - BlockWriteByte(BlockInfo, 0); - BlockWriteByte(BlockInfo, cm_poexh); - BlockWriteByte(BlockInfo, 1); + BlockWriteByte(BlockInfo, 4); end; - for i := 0 to FWithCount - 1 do - BlockWriteByte(BlockInfo,cm_po); + { every value pushed since the loop's body began -- a with's pointers and temporaries, a case's + selector and condition -- which the jump out of them passes over; the frames left above + removed those inside their try statements } + if FExceptFinallyCount + FTryCount > 0 then + for i := FLoopStackDepth to FLoopTryDepth - 1 do + BlockWriteByte(BlockInfo, cm_po) + else + for i := FLoopStackDepth to Longint(BlockInfo.Proc.ProcVars.Count) - 1 do + BlockWriteByte(BlockInfo, cm_po); BlockWriteByte(BlockInfo, Cm_G); BlockWriteLong(BlockInfo, $12345678); FContinueOffsets.Add(Pointer(Length(BlockInfo.Proc.Data))); @@ -11855,9 +14946,40 @@ function TPSPascalCompiler.ProcessLabelForwards(Proc: TPSInternalProcedure): Boo TCompilerState = (csStart, csProgram, csUnit, csUses, csInterface, csInterfaceUses, csImplementation); function TPSPascalCompiler.Compile(const s: tbtString): Boolean; +var + lOuter : Boolean; + {$IFDEF PS_USESSUPPORT} + lModule : tbtString; + {$ENDIF} +begin + lOuter := fInCompile = 0; + {$IFDEF PS_USESSUPPORT} + lModule := fModule; + {$ENDIF} + try + Result := CompileText(s); + except + { an exception ends the compilation the host started: what it made is + released, so that the next one is not taken for a unit of it; a unit's + own compilation leaves that to the uses clause that named it } + if lOuter then + begin + {$IFDEF PS_USESSUPPORT} + fModule := lModule; + {$ENDIF} + fInCompile := 0; + if FGlobalBlock <> nil then + ReleaseCompileState; + end; + raise; + end; +end; + +function TPSPascalCompiler.CompileText(const s: tbtString): Boolean; var Position: TCompilerState; i: Longint; + lRaised: Boolean; {$IFDEF PS_USESSUPPORT} OldFileName: tbtString; OldParser : TPSPascalParser; @@ -11866,9 +14988,6 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; {$ENDIF} procedure Cleanup; - var - I: Longint; - PT: TPSType; begin {$IFDEF PS_USESSUPPORT} if fInCompile>1 then @@ -11877,81 +14996,18 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; exit; end; {$ENDIF} - - if @FOnBeforeCleanup <> nil then - FOnBeforeCleanup(Self); // no reason it actually read the result of this call - FGlobalBlock.Free; - FGlobalBlock := nil; - - for I := 0 to FRegProcs.Count - 1 do - TObject(FRegProcs[I]).Free; - FRegProcs.Free; - for i := 0 to FConstants.Count -1 do - begin - TPSConstant(FConstants[I]).Free; - end; - Fconstants.Free; - for I := 0 to FVars.Count - 1 do - begin - TPSVar(FVars[I]).Free; - end; - FVars.Free; - FVars := nil; - for I := 0 to FProcs.Count - 1 do - TPSProcedure(FProcs[I]).Free; - FProcs.Free; - FProcs := nil; - //reverse free types: a custom type's attribute value type may point to a base type - for I := FTypes.Count - 1 downto 0 do - begin - PT := FTypes[I]; - pt.Free; - end; - FTypes.Free; - -{$IFNDEF PS_NOINTERFACES} - for i := FInterfaces.Count -1 downto 0 do - TPSInterface(FInterfaces[i]).Free; - FInterfaces.Free; -{$ENDIF} - - for i := FClasses.Count -1 downto 0 do - begin - TPSCompileTimeClass(FClasses[I]).Free; - end; - FClasses.Free; - for i := FAttributeTypes.Count -1 downto 0 do - begin - TPSAttributeType(FAttributeTypes[i]).Free; - end; - FAttributeTypes.Free; - FAttributeTypes := nil; - - {$IFDEF PS_USESSUPPORT} - for I := 0 to FUnitInits.Count - 1 do //nvds - begin //nvds - TPSBlockInfo(FUnitInits[I]).free; //nvds - end; //nvds - FUnitInits.Free; //nvds - FUnitInits := nil; // - for I := 0 to FUnitFinits.Count - 1 do //nvds - begin //nvds - TPSBlockInfo(FUnitFinits[I]).free; //nvds - end; //nvds - FUnitFinits.Free; // - FUnitFinits := nil; // - - FreeAndNil(fUnits); - FreeAndNil(FUses); - fInCompile:=0; - {$ENDIF} + ReleaseCompileState; end; function MakeOutput: Boolean; procedure WriteByte(b: Byte); begin + {$IFDEF FPC} + _PSAppendByte(FOutput, b); + {$ELSE} FOutput := FOutput + tbtChar(b); + {$ENDIF} end; procedure WriteData(const Data; Len: Longint); @@ -12010,7 +15066,7 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; if FExecIs64Bit then begin {$IFNDEF CPU64} { On 64-bit Exec, Extended is an alias for Double, so write a Double instead } - TempDouble := tbtDouble(p^.textended); + TempDouble := p^.textended; WriteData(TempDouble, sizeof(tbtDouble)); {$ELSE} WriteData(p^.textended, sizeof(tbtExtended)); @@ -12315,7 +15371,11 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; var l: Longint; begin + {$IFDEF FPC} + _PSAppendByte(ProcData, cm_c); + {$ELSE} ProcData := ProcData + Chr(cm_c); + {$ENDIF} l := Length(ProcData); SetLength(ProcData, l + 4); Move(aData, ProcData[l + 1], 4); @@ -12341,7 +15401,12 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; begin Proc := NewProc('Master proc', '!MASTERPROC'); Result := FindProc('!MASTERPROC'); + {$IFDEF FPC} + _PSAppendByte(ProcData, cm_R); + Proc.data := ProcData; + {$ELSE} Proc.data := Procdata + Chr(cm_R); + {$ENDIF} end; end; {$ELSE} @@ -12469,7 +15534,10 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; TokenRow := FParser.Row; TokenCol := FParser.Col; COrgName := FParser.OriginalToken; - if IsDuplicate(FastUpperCase(COrgName), [dcVars, dcProcs, dcConsts]) then + { another module's type is hidden by it, its own module's is the name + declared twice } + if IsDuplicate(FastUpperCase(COrgName), [dcVars, dcProcs, dcConsts]) + {$IFDEF PS_USESSUPPORT} or _TypeDeclaredInModule(Self, FastUpperCase(COrgName), fModule){$ENDIF} then begin MakeError('', ecDuplicateIdentifier, COrgName); Result := False; @@ -12509,6 +15577,10 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; InitializeVariant(CTemp, CValue.FType); CopyVariantContents(cvalue, CTemp); cp.Value := CTemp; + cp.FRealText := FConstRealText; + { a literal's text comes with an Extended value (RealTextOf) } + if FConstRealText <> '' then + cp.FRealTextValue := CTemp.textended; FConstants.Add(cp); DisposeVariant(CValue); FParser.Next; @@ -12527,12 +15599,19 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; Parse: Boolean; ParseUnit: tbtString; ParserPos: TPSPascalParser; + ParserIsUnit: Boolean; + ParserUnit: TPSUnit; + ParserInCompile: Integer; + lUsesModule: tbtString; + lUsesParser: TPSPascalParser; {$ENDIF} + lRaised: Boolean; begin FParser.Next; {$IFNDEF PS_USESSUPPORT} FUses := TIfStringList.Create; - FUses.Add('System'); + { in the form the parser gives a unit's name, so that `uses System` finds it } + FUses.Add('SYSTEM'); {$ENDIF} repeat if FParser.CurrTokenID <> CSTI_Identifier then @@ -12578,20 +15657,47 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; FUses.Add(s); if @FOnUses <> nil then begin + {$IFDEF PS_USESSUPPORT} + { what a unit's compilation changes, to give back when it fails or raises: + an exception out of it leaves its nesting counted, which would send + the next compilation into the nested branch } + OldFileName:=fModule; + ParserPos:=FParser; + ParserIsUnit:=FIsUnit; + ParserUnit:=fUnit; + ParserInCompile:=fInCompile; + {$ENDIF} + {$IFDEF PS_USESSUPPORT} + { what the host does with this parser current -- its finder, its + own work after the unit compiled -- is this module's; the unit's + uses clause asks in its turn, so the pair before is given back + on every way out } + lUsesModule := fUsesModule; + lUsesParser := fUsesParser; + fUsesModule := OldFileName; + fUsesParser := ParserPos; + {$ENDIF} + lRaised := False; try {$IFDEF PS_USESSUPPORT} - OldFileName:=fModule; fModule:=FParser.OriginalToken; ParseUnit:=FParser.OriginalToken; - ParserPos:=FParser; {$ENDIF} if not OnUses(Self, FParser.GetToken) then begin {$IFNDEF PS_USESSUPPORT} FUses.Free; {$ELSE} + { a unit that did not compile leaves its own parser behind } + if FParser <> ParserPos then + FParser.Free; FParser:=ParserPos; + FIsUnit:=ParserIsUnit; + fUnit:=ParserUnit; + fInCompile:=ParserInCompile; fModule:=OldFileName; + fUsesModule := lUsesModule; + fUsesParser := lUsesParser; MakeError(OldFileName, ecUnitNotFoundOrContainsErrors, ParseUnit); {$ENDIF} Result := False; @@ -12599,18 +15705,41 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; end; {$IFDEF PS_USESSUPPORT} fModule:=OldFileName; + fUsesModule := lUsesModule; + fUsesParser := lUsesParser; {$ENDIF} except on e: Exception do begin + {$IFDEF PS_USESSUPPORT} + fUsesModule := lUsesModule; + fUsesParser := lUsesParser; + { raised before the unit's own text was read: the place is the + caller's uses clause } + if FParser = ParserPos then + fModule:=OldFileName; + {$ENDIF} MakeError('', ecCustomError, tbtstring(e.Message)); {$IFNDEF PS_USESSUPPORT} FUses.Free; + {$ELSE} + if FParser <> ParserPos then + FParser.Free; + FParser:=ParserPos; + FIsUnit:=ParserIsUnit; + fUnit:=ParserUnit; + fInCompile:=ParserInCompile; + fModule:=OldFileName; {$ENDIF} - Result := False; - exit; + lRaised := True; end; end; + { left after the handler: Delphi XE3 to XE5 for Win64 keep the exception object of a handler left by a jump } + if lRaised then + begin + Result := False; + exit; + end; end; {$IFDEF PS_USESSUPPORT} end; @@ -12642,7 +15771,7 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; {$ENDIF} begin Result := False; - FWithCount := -1; + FLoopStackDepth := -1; {$IFDEF PS_USESSUPPORT} if fInCompile=0 then @@ -12680,7 +15809,8 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; {$IFDEF PS_USESSUPPORT} OldFileName:=fModule; fModule:='System'; - FUses.Add('System'); + { in the form the parser gives a unit's name, so that `uses System` finds it } + FUses.Add('SYSTEM'); {$ENDIF} {$IFNDEF PS_NOSTANDARDTYPES} DefineStandardTypes; @@ -12688,9 +15818,13 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; {$ENDIF} if @FOnUses <> nil then begin + lRaised := False; try if not OnUses(Self, 'SYSTEM') then begin + {$IFDEF PS_USESSUPPORT} + fModule:=OldFileName; + {$ENDIF} Cleanup; exit; end; @@ -12698,10 +15832,18 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; on e: Exception do begin MakeError('', ecCustomError, tbtstring(e.Message)); + { the module is the main script's again, for this and every later + compilation } + {$IFDEF PS_USESSUPPORT} + fModule:=OldFileName; + {$ENDIF} Cleanup; - exit; + lRaised := True; end; end; + { left after the handler: Delphi XE3 to XE5 for Win64 keep the exception object of a handler left by a jump } + if lRaised then + exit; end; {$IFDEF PS_USESSUPPORT} fModule:=OldFileName; @@ -12713,8 +15855,13 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; begin OldParser:=FParser; OldIsUnit:=FIsUnit; + { the text a uses clause names is a unit's, with or without its unit header: + a headerless text would take the kind of the file that uses it, and from + the program its block would join the program's own, which then never runs } + FIsUnit:=True; OldUnit:=fUnit; FParser:=TPSPascalParser.Create; + FParser.OnParserError := ParserError; FParser.SetText(s); end; @@ -12979,7 +16126,8 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; Proc := FProcs[I]; if (Proc.ClassType = TPSInternalProcedure) and (TPSInternalProcedure(Proc).Forwarded) then begin - with MakeError('', ecUnsatisfiedForward, TPSInternalProcedure(Proc).Name) do + with MakeError({$IFDEF PS_USESSUPPORT}TPSInternalProcedure(Proc).DeclareUnit{$ELSE}''{$ENDIF}, + ecUnsatisfiedForward, TPSInternalProcedure(Proc).Name) do begin FPosition := TPSInternalProcedure(Proc).DeclarePos; FRow := TPSInternalProcedure(Proc).DeclareRow; @@ -13022,6 +16170,98 @@ function TPSPascalCompiler.Compile(const s: tbtString): Boolean; {$ENDIF} end; +procedure TPSPascalCompiler.ReleaseCompileState; +var + I: Longint; + PT: TPSType; +begin + { released once: a second Cleanup finds nothing } + if FGlobalBlock = nil then + Exit; + { the release completes even when the host's event raises: the exception + then goes on, with nothing of the compilation left for the next one } + try + if @FOnBeforeCleanup <> nil then + FOnBeforeCleanup(Self); // no reason it actually read the result of this call + finally + FGlobalBlock.Free; + FGlobalBlock := nil; + + for I := 0 to FRegProcs.Count - 1 do + TObject(FRegProcs[I]).Free; + FRegProcs.Free; + FRegProcs := nil; + for i := 0 to FConstants.Count -1 do + begin + TPSConstant(FConstants[I]).Free; + end; + Fconstants.Free; + for I := 0 to FVars.Count - 1 do + begin + TPSVar(FVars[I]).Free; + end; + FVars.Free; + FVars := nil; + for I := 0 to FProcs.Count - 1 do + TPSProcedure(FProcs[I]).Free; + FProcs.Free; + FProcs := nil; + //reverse free types: a custom type's attribute value type may point to a base type + for I := FTypes.Count - 1 downto 0 do + begin + PT := FTypes[I]; + pt.Free; + end; + FTypes.Free; + +{$IFNDEF PS_NOINTERFACES} + for i := FInterfaces.Count -1 downto 0 do + TPSInterface(FInterfaces[i]).Free; + FInterfaces.Free; +{$ENDIF} + + for i := FClasses.Count -1 downto 0 do + begin + TPSCompileTimeClass(FClasses[I]).Free; + end; + FClasses.Free; + for i := FAttributeTypes.Count -1 downto 0 do + begin + TPSAttributeType(FAttributeTypes[i]).Free; + end; + FAttributeTypes.Free; + FAttributeTypes := nil; + + {$IFDEF PS_USESSUPPORT} + for I := 0 to FUnitInits.Count - 1 do //nvds + begin //nvds + TPSBlockInfo(FUnitInits[I]).free; //nvds + end; //nvds + FUnitInits.Free; //nvds + FUnitInits := nil; // + for I := 0 to FUnitFinits.Count - 1 do //nvds + begin //nvds + TPSBlockInfo(FUnitFinits[I]).free; //nvds + end; //nvds + FUnitFinits.Free; // + FUnitFinits := nil; // + + FreeAndNil(fUnits); + FreeAndNil(FUses); + fInCompile:=0; + {$ENDIF} + + { the lists of a loop an exception left while it compiled: a Break or + Continue of the next compilation must find no loop } + FBreakOffsets.Free; + FBreakOffsets := nil; + FContinueOffsets.Free; + FContinueOffsets := nil; + FTryCount := 0; + FExceptFinallyCount := 0; + end; +end; + constructor TPSPascalCompiler.Create; begin inherited Create; @@ -13273,6 +16513,11 @@ function TPSPascalCompiler.ReadAttributes(Dest: TPSAttributes): Boolean; Result := False; exit; end; + { the value is written with its type's number, which only a used type + has, and a type reference with the number of the type it names } + varp.FType := at2ut(varp.FType); + if varp.FType.BaseType = btType then + varp.ttype := at2ut(varp.ttype); at.AddValue(varp); if not IsCompatibleType(varp.FType, Att.Fields[i].FieldType, False) then begin @@ -13356,6 +16601,8 @@ TBinConstOperation = class(TConstOperation) TConstData = class(TConstOperation) private FData: PIfRVariant; + { a real literal's text, as for TPSValueData } + FRealText: tbtString; public property Data: PIfRVariant read FData write FData; destructor Destroy; override; @@ -13381,26 +16628,21 @@ function TPSPascalCompiler.ReadConstant(FParser: TPSPascalParser; StopOn: TPSPas NewVarU: TUnConstOperation; function GetConstantIdentifier: PIfRVariant; var - s: tbtString; - sh: Longint; - i: Longint; p: TPSConstant; + lRank: Longint; begin - s := FParser.GetToken; - sh := MakeHash(s); - for i := FConstants.Count -1 downto 0 do + p := _NearestConstant(Self, FParser.GetToken, lRank); + if (p <> nil) and (lRank >= _NearestRank(Self, FParser.GetToken)) and + not _LocalOrParamNamed(FDeclaringProc, FParser.GetToken) then begin - p := FConstants[I]; - if (p.NameHash = sh) and (p.Name = s) then - begin - New(Result); - InitializeVariant(Result, p.Value.FType); - CopyVariantContents(P.Value, Result); - FParser.Next; - exit; - end; + New(Result); + InitializeVariant(Result, p.Value.FType); + CopyVariantContents(P.Value, Result); + TConstData(NewVar).FRealText := _ConstantRealText(p); + FParser.Next; + exit; end; - MakeError('', ecUnknownIdentifier, ''); + MakeError('', ecUnknownIdentifier, FParser.OriginalToken); Result := nil; end; begin @@ -13428,6 +16670,12 @@ function TPSPascalCompiler.ReadConstant(FParser: TPSPascalParser; StopOn: TPSPas NewVar := TConstData.Create; NewVar.SetPos(FParser); TConstData(NewVar).Data := ReadInteger(tbtString('-') + FParser.GetToken); + if TConstData(NewVar).Data = nil then + begin + NewVar.Free; + Result := nil; + exit; + end; FParser.Next; end else begin NewVar := ReadTerm; @@ -13465,6 +16713,12 @@ function TPSPascalCompiler.ReadConstant(FParser: TPSPascalParser; StopOn: TPSPas NewVar := TConstData.Create; NewVar.SetPos(FParser); TConstData(NewVar).Data := ReadString; + if TConstData(NewVar).Data = nil then + begin + NewVar.Free; + Result := nil; + exit; + end; end; CSTI_HexInt, CSTI_Integer: begin @@ -13472,6 +16726,12 @@ function TPSPascalCompiler.ReadConstant(FParser: TPSPascalParser; StopOn: TPSPas NewVar := TConstData.Create; NewVar.SetPos(FParser); TConstData(NewVar).Data := ReadInteger(FParser.GetToken); + if TConstData(NewVar).Data = nil then + begin + NewVar.Free; + Result := nil; + exit; + end; FParser.Next; end; CSTI_Real: @@ -13479,6 +16739,7 @@ function TPSPascalCompiler.ReadConstant(FParser: TPSPascalParser; StopOn: TPSPas NewVar := TConstData.Create; NewVar.SetPos(FParser); TConstData(NewVar).Data := ReadReal(FParser.GetToken); + TConstData(NewVar).FRealText := FParser.GetToken; FParser.Next; end; CSTI_Identifier: @@ -13666,7 +16927,8 @@ function TPSPascalCompiler.ReadConstant(FParser: TPSPascalParser; StopOn: TPSPas begin if IsBoolean(p1.FType) then begin - p1.tu8 := (not p1.tu8) and 1; + { the whole value, as in the previous entry } + p1.tu32 := Ord(p1.tu32 = 0); end else begin MakeError('', ecTypeMismatch, ''); @@ -13695,19 +16957,88 @@ function TPSPascalCompiler.ReadConstant(FParser: TPSPascalParser; StopOn: TPSPas end; otMinus: case p1.FType.BaseType of - btU8: p1.tu8 := -p1.tu8; - btU16: p1.tu16 := -p1.tu16; + { a negated unsigned constant is signed, as in the previous entry } + btU8: + begin + p1.ts32 := -Longint(p1.tu8); + p1.FType := FindBaseType(bts32); + end; + btU16: + begin + p1.ts32 := -Longint(p1.tu16); + p1.FType := FindBaseType(bts32); + end; + {$IFNDEF PS_NOINT64} + btU32: + begin + p1.ts64 := -Int64(p1.tu32); + p1.FType := FindBaseType(bts64); + end; + {$ELSE} btU32: p1.tu32 := -p1.tu32; - bts8: p1.ts8 := -p1.ts8; - bts16: p1.ts16 := -p1.ts16; - bts32: p1.ts32 := -p1.ts32; + {$ENDIF} + { a negated ShortInt or SmallInt constant is an Integer, as in the previous entry } + bts8: + begin + p1.ts32 := -Longint(p1.ts8); + p1.FType := FindBaseType(bts32); + end; + bts16: + begin + p1.ts32 := -Longint(p1.ts16); + p1.FType := FindBaseType(bts32); + end; + { the negation of the least Integer or Int64 is refused, as in the previous entry } + bts32: + begin + if p1.ts32 = Low(Longint) then + begin + MakeError('', ecCustomError, tbtstring(RPS_ConstantOverflow)); + DisposeVariant(p1); + Result := nil; + exit; + end; + p1.ts32 := -p1.ts32; + end; {$IFNDEF PS_NOINT64} - bts64: p1.ts64 := -p1.ts64; - btU64: p1.tu64 := -p1.tu64; + bts64: + begin + if p1.ts64 = Low(Int64) then + begin + MakeError('', ecCustomError, tbtstring(RPS_ConstantOverflow)); + DisposeVariant(p1); + Result := nil; + exit; + end; + p1.ts64 := -p1.ts64; + end; + { the negation of a UInt64 other than 0 is refused, as in the previous entry } + btU64: + begin + if p1.tu64 <> 0 then + begin + MakeError('', ecCustomError, tbtstring(RPS_ConstantOverflow)); + DisposeVariant(p1); + Result := nil; + exit; + end; + end; {$ENDIF} btDouble: p1.tdouble := - p1.tDouble; btSingle: p1.tsingle := - p1.tsingle; - btCurrency: p1.tcurrency := - p1.tcurrency; + btCurrency: + begin + { the negation of the minimum, which only a host's constant can hold, is refused, as in + the previous entry } + if PInt64(@p1.tcurrency)^ = Low(Int64) then + begin + MakeError('', ecCustomError, tbtstring(RPS_ConstantOverflow)); + DisposeVariant(p1); + Result := nil; + exit; + end; + p1.tcurrency := - p1.tcurrency; + end; btExtended: p1.textended := - p1.textended; else begin @@ -13746,7 +17077,21 @@ function TPSPascalCompiler.ReadConstant(FParser: TPSPascalParser; StopOn: TPSPas var Val: TConstOperation; + + { the text of the real literal aOp is, negated as often as aOp negates it; + '' for any other expression } + function RealTextOf(aOp: TConstOperation): tbtString; + begin + if aOp is TConstData then + Result := TConstData(aOp).FRealText + else if (aOp is TUnConstOperation) and (TUnConstOperation(aOp).OpType = otMinus) then + Result := _NegatedRealText(RealTextOf(TUnConstOperation(aOp).Val1)) + else + Result := ''; + end; + begin + FConstRealText := ''; Val := ReadExpression; if val = nil then begin @@ -13754,12 +17099,18 @@ function TPSPascalCompiler.ReadConstant(FParser: TPSPascalParser; StopOn: TPSPas exit; end; Result := EvalConst(Val); + if Result <> nil then + FConstRealText := RealTextOf(Val); Val.Free; end; procedure TPSPascalCompiler.WriteDebugData(const s: tbtString); begin + {$IFDEF FPC} + _PSAppendBytes(FDebugOutput, s); + {$ELSE} FDebugOutput := FDebugOutput + s; + {$ENDIF} end; function TPSPascalCompiler.GetDebugOutput(var s: tbtString): Boolean; @@ -13785,7 +17136,81 @@ function TPSPascalCompiler.AddUsedFunction(var Proc: TPSInternalProcedure): Card const IUnknown_Guid: TGuid = (D1: 0; d2: 0; d3: 0; d4: ($c0,00,00,00,00,00,00,$46)); IDispatch_Guid: Tguid = (D1: $20400; D2: $0; D3: $0; D4:($C0, $0, $0, $0, $0, $0, $0, $46)); + +{ True for an interface type that is IUnknown in all but name: of the IUnknown GUID, with no method besides + IUnknown's three -- IUnknown, IInterface, and an interface declared as either without methods + (a library's own base interface, for one). In Delphi each of them is IUnknown. } +function IsUnknownInterfaceType(p: TPSType): Boolean; +var + Intf: TPSInterface; + Count: Longint; +begin + Result := False; + if (p = nil) or (p.ClassType <> TPSInterfaceType) then + exit; + Intf := TPSInterfaceType(p).FIntf; + if (Intf = nil) or not IsEqualGUID(Intf.FGuid, IUnknown_Guid) then + exit; + Count := 0; + while Intf <> nil do + begin + Inc(Count, Intf.FItems.Count); + Intf := Intf.FInheritedFrom; + end; + Result := Count = 3; +end; +{$ENDIF} + +{ The group of names the engine declares one Delphi type under (DefineStandardTypes): 1 the string types, + 2 the signed and 3 the unsigned native-size integers; 0 for any other type. } +function ScriptAliasGroup(t: TPSType): Integer; +begin + if (t.Name = 'STRING') or (t.Name = 'NATIVESTRING') or (t.Name = 'ANSISTRING') or (t.Name = 'TBTSTRING') or + (t.Name = 'UNICODESTRING') or (t.Name = 'WIDESTRING') then + Result := 1 + else if (t.Name = 'NATIVEINT') or (t.Name = 'LONGINT') or (t.Name = 'INT64') then + Result := 2 + else if (t.Name = 'NATIVEUINT') or (t.Name = 'LONGWORD') or (t.Name = 'UINT64') then + Result := 3 + else + Result := 0; +end; + +{ True when t1 and t2 are one type to Delphi, as a var or out parameter and a procedural type's parameters + and result require: one script type or aliases of it; two interface types that are each IUnknown in all + but name; two names the engine declares one Delphi type under -- string and NativeString with + UnicodeString (Delphi 2009 on) or AnsiString and tbtString (before), AnsiString and tbtString, WideString + and UnicodeString where tbtWideString and tbtUnicodeString are one type (WIDESTRING_EQUAL_UNICODESTRING: + Delphi before 2009, and Free Pascal where its WideString is its UnicodeString), NativeInt and NativeUInt + with the integer types of their size; or + two dynamic arrays whose element types are one type. An open array parameter's type ('!' names) and + AnyString stay types of their own: a call passes them otherwise. } +function IsSameScriptType(t1, t2: TPSType): Boolean; +begin + if (t1 <> nil) and (t1.BaseType = btTypeCopy) then + t1 := TPSTypeLink(t1).LinkTypeNo; + if (t2 <> nil) and (t2.BaseType = btTypeCopy) then + t2 := TPSTypeLink(t2).LinkTypeNo; + Result := t1 = t2; + if Result or (t1 = nil) or (t2 = nil) then + exit; +{$IFNDEF PS_NOINTERFACES} + if IsUnknownInterfaceType(t1) and IsUnknownInterfaceType(t2) then + begin + Result := True; + exit; + end; {$ENDIF} + if (t1.ClassType = TPSType) and (t2.ClassType = TPSType) then + begin + if (ScriptAliasGroup(t1) <> 0) and (ScriptAliasGroup(t1) = ScriptAliasGroup(t2)) then + Result := (t1.BaseType = t2.BaseType){$IFDEF WIDESTRING_EQUAL_UNICODESTRING}{$IFNDEF PS_NOWIDESTRING} or + ((t1.BaseType in [btWideString, btUnicodeString]) and (t2.BaseType in [btWideString, btUnicodeString])){$ENDIF}{$ENDIF}; + end + else if (t1.ClassType = TPSArrayType) and (t2.ClassType = TPSArrayType) and (Copy(t1.Name, 1, 1) <> '!') and + (Copy(t2.Name, 1, 1) <> '!') and (TPSArrayType(t1).ArrayTypeNo <> nil) and (TPSArrayType(t2).ArrayTypeNo <> nil) then + Result := IsSameScriptType(TPSArrayType(t1).ArrayTypeNo, TPSArrayType(t2).ArrayTypeNo); +end; procedure TPSPascalCompiler.DefineStandardProcedures; var @@ -13850,11 +17275,15 @@ procedure TPSPascalCompiler.DefineStandardProcedures; end; end; {$IFNDEF PS_NOINT64} - AddFunction('function Low: Int64;').Decl.AddParam.OrgName := 'X'; - AddFunction('function High: Int64;').Decl.AddParam.OrgName := 'X'; + FLowProc := AddFunction('function Low: Int64;'); + FLowProc.Decl.AddParam.OrgName := 'X'; + FHighProc := AddFunction('function High: Int64;'); + FHighProc.Decl.AddParam.OrgName := 'X'; {$ELSE} - AddFunction('function Low: Integer;').Decl.AddParam.OrgName := 'X'; - AddFunction('function High: Integer;').Decl.AddParam.OrgName := 'X'; + FLowProc := AddFunction('function Low: Integer;'); + FLowProc.Decl.AddParam.OrgName := 'X'; + FHighProc := AddFunction('function High: Integer;'); + FHighProc.Decl.AddParam.OrgName := 'X'; {$ENDIF} with AddFunction('procedure Dec;').Decl do begin with AddParam do @@ -13870,7 +17299,8 @@ procedure TPSPascalCompiler.DefineStandardProcedures; Mode:=pmInOut; end; end; - with AddFunction('procedure Include;').Decl do begin + FIncludeProc := AddFunction('procedure Include;'); + with FIncludeProc.Decl do begin with AddParam do begin OrgName:='s'; @@ -13882,7 +17312,8 @@ procedure TPSPascalCompiler.DefineStandardProcedures; Mode:=pmIn; end; end; - with AddFunction('procedure Exclude;').Decl do begin + FExcludeProc := AddFunction('procedure Exclude;'); + with FExcludeProc.Decl do begin with AddParam do begin OrgName:='s'; @@ -13897,8 +17328,14 @@ procedure TPSPascalCompiler.DefineStandardProcedures; AddFunction('function Sin(E: Extended): Extended;'); AddFunction('function Cos(E: Extended): Extended;'); AddFunction('function Sqrt(E: Extended): Extended;'); + {$IFNDEF PS_NOINT64} + { an Int64, as Delphi's Round and Trunc return: a LongInt lost the high half of a value past 2^31 } + AddFunction('function Round(E: Extended): Int64;'); + AddFunction('function Trunc(E: Extended): Int64;'); + {$ELSE} AddFunction('function Round(E: Extended): LongInt;'); AddFunction('function Trunc(E: Extended): LongInt;'); + {$ENDIF} AddFunction('function Int(E: Extended): Extended;'); AddFunction('function Pi: Extended;'); AddFunction('function Abs(E: Extended): Extended;'); @@ -13907,8 +17344,16 @@ procedure TPSPascalCompiler.DefineStandardProcedures; AddFunction('function PadL(S: AnyString; I: LongInt): AnyString;'); AddFunction('function PadR(S: AnyString; I: LongInt): AnyString;'); AddFunction('function PadZ(S: AnyString; I: LongInt): AnyString;'); + {$IFNDEF PS_NOWIDESTRING} + { the character as an AnyString: a WideChar arrives as a wide string and keeps its character, as with + Delphi's WideChar overload, and a Char as an AnsiString, converted through the code page as with the ANSI + overload -- a Char parameter narrowed a WideChar, and a WideChar parameter took a Char by its ordinal } + FReplicateProc := AddFunction('function Replicate(C: AnyString; I: LongInt): string;'); + FStringOfCharProc := AddFunction('function StringOfChar(C: AnyString; I: LongInt): string;'); + {$ELSE} AddFunction('function Replicate(C: Char; I: LongInt): string;'); AddFunction('function StringOfChar(C: Char; I: LongInt): string;'); + {$ENDIF} AddTypeS('TVarType', 'Word'); AddConstantN('varEmpty', 'Word').Value.tu16 := varempty; AddConstantN('varNull', 'Word').Value.tu16 := varnull; @@ -13931,6 +17376,9 @@ procedure TPSPascalCompiler.DefineStandardProcedures; AddConstantN('varLongWord', 'Word').Value.tu16 := varlongword; AddConstantN('varInt64', 'Word').Value.tu16 := varint64; {$ENDIF} +{$IFDEF DELPHI2009UP} + AddConstantN('varUInt64', 'Word').Value.tu16 := varUInt64; +{$ENDIF} {$IFDEF DELPHI5UP} AddConstantN('varStrArg', 'Word').Value.tu16 := varstrarg; AddConstantN('varAny', 'Word').Value.tu16 := varany; @@ -14195,24 +17643,26 @@ function TPSPascalCompiler.AddTypeS(const Name, Decl: tbtString): TPSType; Parser: TPSPascalParser; begin if FProcs = nil then raise EPSCompilerException.Create(RPS_OnUseEventOnly); - Parser := TPSPascalParser.Create; - Parser.SetText(Decl); - if not(AllowDuplicateRegister) and (FindType(Name)<>nil) then Raise EPSCompilerException.CreateFmt(RPS_DuplicateIdent, [Name]); - Result := ReadType(Name, Parser); - if Result<>nil then - begin - Result.ExportName := True; - Result.DeclarePos:=InvalidVal; - {$IFDEF PS_USESSUPPORT} - Result.DeclareUnit:=fModule; - {$ENDIF} - Result.DeclareRow:=0; - Result.DeclareCol:=0; + Parser := TPSPascalParser.Create; + try + Parser.SetText(Decl); + Result := ReadType(Name, Parser); + if Result<>nil then + begin + Result.ExportName := True; + Result.DeclarePos:=InvalidVal; + {$IFDEF PS_USESSUPPORT} + Result.DeclareUnit:=fModule; + {$ENDIF} + Result.DeclareRow:=0; + Result.DeclareCol:=0; + end; + finally + Parser.Free; end; - Parser.Free; if result = nil then Raise EPSCompilerException.CreateFmt(RPS_UnableToRegisterType, [name]); end; @@ -14238,14 +17688,14 @@ function TPSPascalCompiler.CheckCompatProc(P: TPSType; ProcNo: Cardinal): Boolea s2 := TPSInternalProcedure(FProcs[ProcNo]).Decl else s2 := TPSExternalProcedure(FProcs[ProcNo]).RegProc.Decl; - if (s1.Result <> s2.Result) or (s1.ParamCount <> s2.ParamCount) then + if not IsSameScriptType(s1.Result, s2.Result) or (s1.ParamCount <> s2.ParamCount) then begin Result := False; Exit; end; for i := 0 to s1.ParamCount -1 do begin - if (s1.Params[i].Mode <> s2.Params[i].Mode) or (s1.Params[i].aType <> s2.Params[i].aType) then + if (s1.Params[i].Mode <> s2.Params[i].Mode) or not IsSameScriptType(s1.Params[i].aType, s2.Params[i].aType) then begin Result := False; Exit; @@ -14307,6 +17757,8 @@ function TPSPascalCompiler.AddDelphiFunction(const Decl: tbtString): TPSRegProc; i: Longint; begin + if FProcs = nil then + raise EPSCompilerException.Create(RPS_OnUseEventOnly); pDecl := TPSParametersDecl.Create; {$IFNDEF DELPHI_TOKYO_UP} p := nil; @@ -14315,13 +17767,16 @@ function TPSPascalCompiler.AddDelphiFunction(const Decl: tbtString): TPSRegProc; if not ParseMethod(Self, '', Decl, DOrgName, pDecl, FT) then Raise EPSCompilerException.CreateFmt(RPS_UnableToRegisterFunction, [Decl]); - if (FindProc(DOrgName)<>InvalidVal) and not(FAllowDuplicateRegister) then + if not(FAllowDuplicateRegister) and (FindProc(DOrgName)<>InvalidVal) then Raise EPSCompilerException.CreateFmt(RPS_DuplicateIdent, [Decl]); p := TPSRegProc.Create; P.Name := FastUppercase(DOrgName); p.OrgName := DOrgName; p.ExportName := True; + {$IFDEF PS_USESSUPPORT} + p.DeclareUnit := fModule; + {$ENDIF} p.Decl.Assign(pDecl); FRegProcs.Add(p); @@ -14390,12 +17845,14 @@ function TPSPascalCompiler.AddClass(InheritsFrom: TPSCompileTimeClass; aClass: T begin if FProcs = nil then raise EPSCompilerException.Create(RPS_OnUseEventOnly); Result := FindClass(tbtstring(aClass.ClassName)); - if (Result<>nil) and not(FAllowDuplicateRegister) then + if (Result<>nil) and ((Result.FInheritsFrom<>nil) or (Result.FClass<>nil)) and not(FAllowDuplicateRegister) then Raise EPSCompilerException.CreateFmt(RPS_DuplicateIdent, [aClass.ClassName]); if Result <> nil then begin if InheritsFrom <> nil then Result.FInheritsFrom := InheritsFrom; + if Result.FClass = nil then + Result.FClass := aClass; exit; end; f := AddType(tbtstring(aClass.ClassName), btClass); @@ -14412,7 +17869,7 @@ function TPSPascalCompiler.AddClassN(InheritsFrom: TPSCompileTimeClass; const aC begin if FProcs = nil then raise EPSCompilerException.Create(RPS_OnUseEventOnly); Result := FindClass(aClass); - if (Result<>nil) and (Result.FInheritsFrom<>nil) and not(FAllowDuplicateRegister) then + if (Result<>nil) and ((Result.FInheritsFrom<>nil) or (Result.FClass<>nil)) and not(FAllowDuplicateRegister) then Raise EPSCompilerException.CreateFmt(RPS_DuplicateIdent, [aClass]); if Result <> nil then begin @@ -14775,6 +18232,7 @@ procedure TPSConstant.SetSet(const val); begin if length(tbtstring(FValue.tstring)) <> TPSSetType(FValue.FType).ByteSize then SetLength(tbtstring(FValue.tstring), TPSSetType(FValue.FType).ByteSize); + UniqueString(tbtstring(FValue.tstring)); Move(Val, FValue.tstring^, TPSSetType(FValue.FType).ByteSize); end; else @@ -14881,7 +18339,21 @@ function TPSPascalCompilerError.ErrorType: tbtString; end; function TPSPascalCompilerError.ShortMessageToString: tbtString; +{$IFDEF FPC} +var + lOrd: Integer; +{$ENDIF} begin + {$IFDEF FPC} + { Free Pascal, optimising, jumps through an unbounded table for a case that + names every value: a value past the enumeration is answered here, as the + else below answers it on Delphi } + lOrd := Ord(Error); + if (lOrd < Ord(Low(TPSPascalCompilerErrorType))) or (lOrd > Ord(High(TPSPascalCompilerErrorType))) then begin + Result := tbtString(RPS_UnknownError); + Exit; + end; + {$ENDIF} case Error of ecUnknownIdentifier: Result := tbtstring(Format (RPS_UnknownIdentifier, [Param])); ecIdentifierExpected: Result := tbtstring(RPS_IdentifierExpected); @@ -14945,7 +18417,21 @@ function TPSPascalCompilerHint.ErrorType: tbtString; end; function TPSPascalCompilerHint.ShortMessageToString: tbtString; +{$IFDEF FPC} +var + lOrd: Integer; +{$ENDIF} begin + {$IFDEF FPC} + { Free Pascal, optimising, jumps through an unbounded table for a case that + names every value: a value past the enumeration is answered here, as the + else below answers it on Delphi } + lOrd := Ord(Hint); + if (lOrd < Ord(Low(TPSPascalCompilerHintType))) or (lOrd > Ord(High(TPSPascalCompilerHintType))) then begin + Result := tbtString(RPS_UnknownHint); + Exit; + end; + {$ENDIF} case Hint of ehVariableNotUsed: Result := tbtstring(Format (RPS_VariableNotUsed, [Param])); ehFunctionNotUsed: Result := tbtstring(Format (RPS_FunctionNotUsed, [Param])); @@ -14963,7 +18449,21 @@ function TPSPascalCompilerWarning.ErrorType: tbtString; end; function TPSPascalCompilerWarning.ShortMessageToString: tbtString; +{$IFDEF FPC} +var + lOrd: Integer; +{$ENDIF} begin + {$IFDEF FPC} + { Free Pascal, optimising, jumps through an unbounded table for a case that + names every value: a value past the enumeration is answered here, as the + else below answers it on Delphi } + lOrd := Ord(Warning); + if (lOrd < Ord(Low(TPSPascalCompilerWarningType))) or (lOrd > Ord(High(TPSPascalCompilerWarningType))) then begin + Result := tbtString(RPS_UnknownWarning); + Exit; + end; + {$ENDIF} case Warning of ewCustomWarning: Result := Param; ewCalculationAlwaysEvaluatesTo: Result := tbtstring(Format (RPS_CalculationAlwaysEvaluatesTo, [Param])); @@ -15262,7 +18762,11 @@ destructor TPSValueAllocatedStackVar.Destroy; pv := Proc.ProcVars[Proc.ProcVars.Count -1]; Proc.ProcVars.Delete(Proc.ProcVars.Count -1); pv.Free; + {$IFDEF FPC} + _PSAppendByte(Proc.FData, CM_PO); + {$ELSE} Proc.Data := Proc.Data + tbtChar(CM_PO); + {$ENDIF} end; inherited Destroy; end; @@ -16062,13 +19566,15 @@ function TPSAttributes.FindAttribute( const Name: tbtString): TPSAttribute; var h, i: Longint; + n: tbtString; begin - h := MakeHash(name); + n := FastUpperCase(Name); + h := MakeHash(n); for i := FItems.Count -1 downto 0 do begin Result := FItems[i]; - if (Result.FAttribType.NameHash = h) and (Result.FAttribType.Name = Name) then + if (Result.FAttribType.NameHash = h) and (Result.FAttribType.Name = n) then exit; end; result := nil; @@ -16301,6 +19807,14 @@ function TPSInterface.Func_Call(Index: TPSInterfaceMethod; P.RegProc.Name := ''; FOwner.UseProc(C.Decl); P.RegProc.Decl.Assign(c.Decl); + {$IFDEF FPC} + s := tbtstring('intf:.'); + _PSAppendBytes(s, PS_mi2s(c.AbsoluteProcOffset)); + _PSAppendByte(s, ord(c.CC)); + _PSAppendByte(s, Ord(c.Decl.Result <> nil)); + for i := 0 to C.Decl.ParamCount -1 do + _PSAppendByte(s, Ord(c.Decl.Params[i].Mode <> pmIn)); + {$ELSE} s := tbtstring('intf:.') + PS_mi2s(c.AbsoluteProcOffset) + tbtchar(ord(c.CC)); if c.Decl.Result = nil then s := s + #0 @@ -16313,6 +19827,7 @@ function TPSInterface.Func_Call(Index: TPSInterfaceMethod; else s := s + #0; end; + {$ENDIF} P.RegProc.ImportDecl := s; C.FScriptProcNo := ProcNo; Result := True; @@ -16359,6 +19874,13 @@ function TPSInterface.IsCompatibleWith(aType: TPSType): Boolean; Result := False; exit; end; + { every interface is an IUnknown, as in Delphi: IUnknown and IInterface are two script interfaces of + the one GUID, and another interface descends from one of them or from neither } + if IsUnknownInterfaceType(FType) then + begin + Result := True; + exit; + end; temp := TPSInterfaceType(atype).FIntf; while Temp <> nil do begin @@ -16477,7 +19999,7 @@ function TPSVariantType.GetDynInvokeParamType(Owner: TPSPascalCompiler) : TPSTyp function TPSVariantType.GetDynInvokeProcNo(Owner: TPSPascalCompiler; const Name: tbtString; Params: TPSParameters): Cardinal; begin - Result := Owner.FindProc('IdispatchInvoke'); + Result := Owner.FindSystemProc('IdispatchInvoke'); end; function TPSVariantType.GetDynIvokeResulType( diff --git a/Source/uPSR_controls.pas b/Source/uPSR_controls.pas index a1b808ec..203567ac 100644 --- a/Source/uPSR_controls.pas +++ b/Source/uPSR_controls.pas @@ -17,6 +17,12 @@ procedure RIRegisterTSizeConstraints(cl: TPSRuntimeClassImporter); procedure RIRegister_Controls(Cl: TPSRuntimeClassImporter); +{$IFDEF UNICODE}{$IFNDEF FPC} +{ Binds OnKeyPress of aClass, a windowed control class registered at run time, through + helpers that hand a script's handler the key as an ANSI character (a script's Char). } +procedure RIRegisterKeyPressHelper(aClass: TPSRuntimeClass); +{$ENDIF}{$ENDIF} + implementation {$IFNDEF FPC} uses @@ -26,6 +32,110 @@ implementation Classes, Controls, Graphics; {$ENDIF} +{ Members that are dynamic methods, bound through routines that call them: a descendant's + override then runs, where bound by address a script ran this class's own code. } +function TControlHasParent_P(Self: TControl): Boolean; +begin + Result := Self.HasParent; +end; + +function TWinControlCanFocus_P(Self: TWinControl): Boolean; +begin + Result := Self.CanFocus; +end; + +function TWinControlFocused_P(Self: TWinControl): Boolean; +begin + Result := Self.Focused; +end; + +{$IFDEF UNICODE}{$IFNDEF FPC} +{ A script's Char is an ANSI character and Delphi's a 16-bit one. A script's OnKeyPress handler is + installed as a method whose code is _ScriptKeyPress and whose object pointer is the script method's + own, as for any script handler: it hands the handler the key converted to the ANSI code page + (PSWideCharToAnsiChar) and, when the handler changed it, hands Delphi the new key converted back; a + key the handler leaves alone stays what it was. It holds no state of its own, so the event can be + copied to another control as any handler can. Any other handler a script assigns -- nil, or a + Delphi handler it read back -- is assigned as it is. } +type + TPSAnsiKeyPressEvent = procedure(Sender: TObject; var Key: AnsiChar) of object; + + TPSWinControlAccess = class(TWinControl); + +{ Called as a TKeyPressEvent method: aScriptMethod is the method's object pointer. } +procedure _ScriptKeyPress( aScriptMethod : Pointer; + Sender : TObject; + var Key : Char); +var + lHandler : TPSAnsiKeyPressEvent; + lWas : AnsiChar; + lKey : AnsiChar; +begin + TMethod(lHandler).Code := @MyAllMethodsHandler; + TMethod(lHandler).Data := aScriptMethod; + lWas := PSWideCharToAnsiChar(Key); + lKey := lWas; + lHandler(Sender, lKey); + if lKey <> lWas then + Key := PSAnsiCharToWideChar(lKey); +end; + +procedure _WinControlOnKeyPressR(Self: TWinControl; var T: TKeyPressEvent); +begin + T := TPSWinControlAccess(Self).OnKeyPress; + if TMethod(T).Code = @_ScriptKeyPress then + TMethod(T).Code := @MyAllMethodsHandler; +end; + +procedure _WinControlOnKeyPressW(Self: TWinControl; const T: TKeyPressEvent); +var + lEvent : TKeyPressEvent; +begin + lEvent := T; + if TMethod(lEvent).Code = @MyAllMethodsHandler then + TMethod(lEvent).Code := @_ScriptKeyPress; + TPSWinControlAccess(Self).OnKeyPress := lEvent; +end; + +procedure RIRegisterKeyPressHelper(aClass: TPSRuntimeClass); +begin + if Assigned(aClass) then + aClass.RegisterEventPropertyHelper(@_WinControlOnKeyPressR, @_WinControlOnKeyPressW, 'OnKeyPress'); +end; +{$ENDIF}{$ENDIF} + +{$IFNDEF PS_MINIVCL} +{ A script PChar is a PAnsiChar on every compiler, Delphi's PChar a PWideChar from Delphi 2009: the + text members that take one are bound through routines that go through a string, and copy at most + BufSize - 1 bytes and a #0 into the script's buffer. } +{$IFNDEF CLX}{$IFNDEF FPC} +function TControlGetTextBuf_P(Self: TControl; Buffer: PAnsiChar; BufSize: Integer): Integer; +var + lText : string; +begin + Result := 0; + if BufSize <= 0 then + Exit; + SetLength(lText, BufSize); + SetLength(lText, Self.GetTextBuf(PChar(lText), BufSize)); + Result := PSTextToAnsiBuffer(lText, Buffer, BufSize); +end; + +procedure TControlSetTextBuf_P(Self: TControl; Buffer: PAnsiChar); +begin + Self.SetTextBuf(PChar(string(AnsiString(Buffer)))); +end; +{$ENDIF}{$ENDIF} + +{$IFNDEF FPC} +{ BeginDrag is bound through a routine, so that Threshold takes its Delphi default. } +procedure TControlBeginDrag_P(Self: TControl; Immediate: Boolean); +begin + Self.BeginDrag(Immediate); +end; +{$ENDIF} +{$ENDIF} + {$IFDEF DELPHI10UP}{$REGION 'TControl'}{$ENDIF} {$IFDEF class_helper_present} type @@ -49,7 +159,7 @@ TControl_PSHelper = class helper for TControl procedure StyleElementsR( var T: TStyleElements); procedure StyleElementsW( T: TStyleElements); {$ENDIF} - {$IFDEF DELPHI26UP} + {$IFDEF DELPHI27UP} procedure StyleNameR( var T: string); procedure StyleNameW( T: string); {$ENDIF} @@ -81,7 +191,7 @@ procedure TControl_PSHelper.StyleElementsR( var T: TStyleElements); begin T := S procedure TControl_PSHelper.StyleElementsW( T: TStyleElements); begin Self.StyleElements:= T; end; {$ENDIF} -{$IFDEF DELPHI26UP} +{$IFDEF DELPHI27UP} procedure TControl_PSHelper.StyleNameR( var T: string); begin T := Self.StyleName; end; procedure TControl_PSHelper.StyleNameW( T: string); begin Self.StyleName:= T; end; {$ENDIF} @@ -111,7 +221,7 @@ procedure RIRegisterTControl(Cl: TPSRuntimeClassImporter); {$IFDEF DELPHI23UP} RegisterPropertyHelper(@TControl.StyleElementsR, @TControl.StyleElementsW, 'StyleElements'); {$ENDIF} - {$IFDEF DELPHI26UP} + {$IFDEF DELPHI27UP} RegisterPropertyHelper(@TControl.StyleNameR, @TControl.StyleNameW, 'StyleName'); {$ENDIF} @@ -119,17 +229,17 @@ procedure RIRegisterTControl(Cl: TPSRuntimeClassImporter); {$IFNDEF PS_MINIVCL} RegisterMethod(@TControl.Dragging, 'Dragging'); - RegisterMethod(@TControl.HasParent, 'HasParent'); + RegisterMethod(@TControlHasParent_P, 'HasParent'); RegisterMethod(@TCONTROL.CLIENTTOSCREEN, 'ClientToScreen'); {$IFNDEF FPC} - RegisterMethod(@TCONTROL.BEGINDRAG, 'BeginDrag'); + RegisterMethod(@TControlBeginDrag_P, 'BeginDrag'); RegisterMethod(@TCONTROL.ENDDRAG, 'EndDrag'); {$ENDIF} {$IFNDEF CLX} - RegisterMethod(@TCONTROL.GETTEXTBUF, 'GetTextBuf'); + {$IFDEF FPC}RegisterMethod(@TCONTROL.GETTEXTBUF, 'GetTextBuf');{$ELSE}RegisterMethod(@TControlGetTextBuf_P, 'GetTextBuf');{$ENDIF} RegisterMethod(@TCONTROL.GETTEXTLEN, 'GetTextLen'); RegisterMethod(@TCONTROL.PERFORM, 'Perform'); - RegisterMethod(@TCONTROL.SETTEXTBUF, 'SetTextBuf'); + {$IFDEF FPC}RegisterMethod(@TCONTROL.SETTEXTBUF, 'SetTextBuf');{$ELSE}RegisterMethod(@TControlSetTextBuf_P, 'SetTextBuf');{$ENDIF} {$ENDIF} RegisterMethod(@TCONTROL.SCREENTOCLIENT, 'ScreenToClient'); {$ENDIF} @@ -163,7 +273,7 @@ procedure TControlStyleElementsR(Self: TControl; var T: TStyleElements); begin T procedure TControlStyleElementsW(Self: TControl; T: TStyleElements); begin Self.StyleElements:= T; end; {$ENDIF} -{$IFDEF DELPHI26UP} +{$IFDEF DELPHI27UP} procedure TControlStyleNameR(Self: TControl; var T: string); begin T := Self.StyleName; end; procedure TControlStyleNameW(Self: TControl; T: string); begin Self.StyleName:= T; end; {$ENDIF} @@ -193,7 +303,7 @@ procedure RIRegisterTControl(Cl: TPSRuntimeClassImporter); {$IFDEF DELPHI23UP} RegisterPropertyHelper(@TControlStyleElementsR, @TControlStyleElementsW, 'StyleElements'); {$ENDIF} - {$IFDEF DELPHI26UP} + {$IFDEF DELPHI27UP} RegisterPropertyHelper(@TControlStyleNameR, @TControlStyleNameW, 'StyleName'); {$ENDIF} @@ -201,17 +311,17 @@ procedure RIRegisterTControl(Cl: TPSRuntimeClassImporter); {$IFNDEF PS_MINIVCL} RegisterMethod(@TControl.Dragging, 'Dragging'); - RegisterMethod(@TControl.HasParent, 'HasParent'); + RegisterMethod(@TControlHasParent_P, 'HasParent'); RegisterMethod(@TCONTROL.CLIENTTOSCREEN, 'ClientToScreen'); {$IFNDEF FPC} - RegisterMethod(@TCONTROL.BEGINDRAG, 'BeginDrag'); + RegisterMethod(@TControlBeginDrag_P, 'BeginDrag'); RegisterMethod(@TCONTROL.ENDDRAG, 'EndDrag'); {$ENDIF} {$IFNDEF CLX} - RegisterMethod(@TCONTROL.GETTEXTBUF, 'GetTextBuf'); + {$IFDEF FPC}RegisterMethod(@TCONTROL.GETTEXTBUF, 'GetTextBuf');{$ELSE}RegisterMethod(@TControlGetTextBuf_P, 'GetTextBuf');{$ENDIF} RegisterMethod(@TCONTROL.GETTEXTLEN, 'GetTextLen'); RegisterMethod(@TCONTROL.PERFORM, 'Perform'); - RegisterMethod(@TCONTROL.SETTEXTBUF, 'SetTextBuf'); + {$IFDEF FPC}RegisterMethod(@TCONTROL.SETTEXTBUF, 'SetTextBuf');{$ELSE}RegisterMethod(@TControlSetTextBuf_P, 'SetTextBuf');{$ENDIF} {$ENDIF} RegisterMethod(@TCONTROL.SCREENTOCLIENT, 'ScreenToClient'); {$ENDIF} @@ -264,8 +374,8 @@ procedure RIRegisterTWinControl(Cl: TPSRuntimeClassImporter); // requires TContr RegisterPropertyHelper(@TWinControl.ShowingR, nil, 'Showing'); RegisterPropertyHelper(@TWinControl.TabOrderR, @TWinControl.TabOrderW, 'TabOrder'); RegisterPropertyHelper(@TWinControl.TabStopR, @TWinControl.TabStopW, 'TabStop'); - RegisterMethod(@TWinControl.CANFOCUS, 'CanFocus'); - RegisterMethod(@TWinControl.FOCUSED, 'Focused'); + RegisterMethod(@TWinControlCanFocus_P, 'CanFocus'); + RegisterMethod(@TWinControlFocused_P, 'Focused'); RegisterPropertyHelper(@TWinControl.CONTROLS_R, nil, 'Controls'); RegisterPropertyHelper(@TWinControl.CONTROLCOUNT_R, nil, 'ControlCount'); {$IFNDEF PS_MINIVCL} @@ -317,8 +427,8 @@ procedure RIRegisterTWinControl(Cl: TPSRuntimeClassImporter); // requires TContr RegisterPropertyHelper(@TWinControlShowingR, nil, 'Showing'); RegisterPropertyHelper(@TWinControlTabOrderR, @TWinControlTabOrderW, 'TabOrder'); RegisterPropertyHelper(@TWinControlTabStopR, @TWinControlTabStopW, 'TabStop'); - RegisterMethod(@TWINCONTROL.CANFOCUS, 'CanFocus'); - RegisterMethod(@TWINCONTROL.FOCUSED, 'Focused'); + RegisterMethod(@TWinControlCanFocus_P, 'CanFocus'); + RegisterMethod(@TWinControlFocused_P, 'Focused'); RegisterPropertyHelper(@TWINCONTROLCONTROLS_R, nil, 'Controls'); RegisterPropertyHelper(@TWINCONTROLCONTROLCOUNT_R, nil, 'ControlCount'); {$IFNDEF PS_MINIVCL} @@ -522,7 +632,12 @@ procedure RIRegister_TDragObject(CL: TPSRuntimeClassImporter); {$IFDEF DELPHI10UP}{$REGION 'TSizeConstraints'}{$ENDIF} procedure RIRegisterTSizeConstraints(cl: TPSRuntimeClassImporter); begin - Cl.Add(TSizeConstraints); + with Cl.Add(TSizeConstraints) do + begin + {$IFNDEF FPC} + RegisterVirtualConstructor(@TSizeConstraints.Create, 'Create'); + {$ENDIF} + end; end; {$IFDEF DELPHI10UP}{$ENDREGION}{$ENDIF} {$ENDIF} diff --git a/Source/uPSR_extctrls.pas b/Source/uPSR_extctrls.pas index 4b7e5176..fe46883c 100644 --- a/Source/uPSR_extctrls.pas +++ b/Source/uPSR_extctrls.pas @@ -34,7 +34,7 @@ implementation {$IFDEF CLX} QExtCtrls, QGraphics; {$ELSE} - ExtCtrls, Graphics; + SysUtils, ExtCtrls, Graphics; {$ENDIF} {$IFDEF DELPHI10UP}{$REGION 'TShape'}{$ENDIF} @@ -210,8 +210,13 @@ procedure RIRegisterTRADIOGROUP(Cl: TPSRuntimeClassImporter); {$IFDEF DELPHI14UP} procedure TCUSTOMLINKLABELALIGNMENT_R(Self: TCUSTOMLINKLABEL; var T: TCustomLinkLabel.TLinkAlignment); begin T := Self.ALIGNMENT; end; -procedure TCUSTOMLINKLABELALIGNMENT_W(Self: TCUSTOMLINKLABEL; T: TCustomLinkLabel.TLinkAlignment); begin -Self.ALIGNMENT := T; +procedure TCUSTOMLINKLABELALIGNMENT_W(Self: TCUSTOMLINKLABEL; T: TCustomLinkLabel.TLinkAlignment); +var + lRaw : Byte absolute T; +begin + if lRaw > Ord(High(TCustomLinkLabel.TLinkAlignment)) then + raise ERangeError.Create('Out Of Range'); + Self.ALIGNMENT := T; end; procedure TCUSTOMLINKLABELAUTOSIZE_R(Self: TCUSTOMLINKLABEL; var T: Boolean); begin T := Self.AUTOSIZE; end; procedure TCUSTOMLINKLABELAUTOSIZE_W(Self: TCUSTOMLINKLABEL; T: Boolean); begin Self.AUTOSIZE := T; end; @@ -227,7 +232,7 @@ procedure RIRegisterTCUSTOMLINKLABEL(Cl: TPSRuntimeClassImporter); RegisterPropertyHelper(@TCUSTOMLINKLABELALIGNMENT_R, @TCUSTOMLINKLABELALIGNMENT_W, 'Alignment'); RegisterPropertyHelper(@TCUSTOMLINKLABELAUTOSIZE_R, @TCUSTOMLINKLABELAUTOSIZE_W, 'AutoSize'); RegisterPropertyHelper(@TCUSTOMLINKLABELUSEVISUALSTYLE_R, @TCUSTOMLINKLABELUSEVISUALSTYLE_W, 'UseVisualStyle'); - RegisterPropertyHelper(@TCUSTOMLINKLABELONLINKCLICK_R, @TCUSTOMLINKLABELONLINKCLICK_W, 'OnLinkClick'); + RegisterEventPropertyHelper(@TCUSTOMLINKLABELONLINKCLICK_R, @TCUSTOMLINKLABELONLINKCLICK_W, 'OnLinkClick'); end; end; diff --git a/Source/uPSR_forms.pas b/Source/uPSR_forms.pas index 2a36c2a7..9f611a6e 100644 --- a/Source/uPSR_forms.pas +++ b/Source/uPSR_forms.pas @@ -4,7 +4,7 @@ {$I PascalScript.inc} interface uses - uPSRuntime, uPSUtils; + uPSRuntime, uPSUtils, uPSR_controls; procedure RIRegisterTCONTROLSCROLLBAR(Cl: TPSRuntimeClassImporter); {$IFNDEF FPC} procedure RIRegisterTSCROLLINGWINCONTROL(Cl: TPSRuntimeClassImporter);{$ENDIF} @@ -74,6 +74,39 @@ procedure RIRegisterTSCROLLBOX(Cl: TPSRuntimeClassImporter); end; {$IFDEF DELPHI10UP}{$ENDREGION}{$ENDIF} +{ Members that are virtual in some or all Delphi versions, bound through routines that call them + by name: the compiler then calls through the object's virtual method table wherever the member is + virtual, so a descendant's override runs. Bound by address, a script ran this class's own code + whatever the object's class. } +function TFormShowModal_P(Self: TForm): Integer; +begin + Result := Self.ShowModal; +end; + +function TFormCloseQuery_P(Self: TForm): Boolean; +begin + Result := Self.CloseQuery; +end; + +function TFormSetFocusedControl_P(Self: TForm; Control: TWinControl): Boolean; +begin + Result := Self.SetFocusedControl(Control); +end; + +{$IFDEF DELPHI28UP} +{ From Delphi 11 Alexandria PixelsPerInch is no longer published (TForm inherits + TWinControl's public one): read and written through helpers. } +procedure TFormPixelsPerInch_R(Self: TForm; var T: Integer); +begin + T := Self.PixelsPerInch; +end; + +procedure TFormPixelsPerInch_W(Self: TForm; T: Integer); +begin + Self.PixelsPerInch := T; +end; +{$ENDIF} + {$IFDEF DELPHI10UP}{$REGION 'TForm'}{$ENDIF} {$IFDEF class_helper_present} type @@ -140,7 +173,7 @@ procedure RIRegisterTFORM(Cl: TPSRuntimeClassImporter); RegisterMethod(@TForm.CLOSE, 'Close'); RegisterMethod(@TForm.HIDE, 'Hide'); RegisterMethod(@TForm.SHOW, 'Show'); - RegisterMethod(@TForm.SHOWMODAL, 'ShowModal'); + RegisterMethod(@TFormShowModal_P, 'ShowModal'); RegisterMethod(@TForm.RELEASE, 'Release'); RegisterPropertyHelper(@TForm.ACTIVE_R, nil, 'Active'); @@ -163,14 +196,20 @@ procedure RIRegisterTFORM(Cl: TPSRuntimeClassImporter); RegisterPropertyHelper(@TForm.MDICHILDCOUNT_R, nil, 'MDIChildCount'); RegisterPropertyHelper(@TForm.MDICHILDREN_R, nil, 'MDIChildren'); {$ENDIF}{FPC} - RegisterMethod(@TForm.CLOSEQUERY, 'CloseQuery'); + RegisterMethod(@TFormCloseQuery_P, 'CloseQuery'); RegisterMethod(@TForm.DEFOCUSCONTROL, 'DefocusControl'); RegisterMethod(@TForm.FOCUSCONTROL, 'FocusControl'); - RegisterMethod(@TForm.SETFOCUSEDCONTROL, 'SetFocusedControl'); + RegisterMethod(@TFormSetFocusedControl_P, 'SetFocusedControl'); RegisterPropertyHelper(@TForm.CANVAS_R, nil, 'Canvas'); RegisterPropertyHelper(@TForm.MODALRESULT_R, @TForm.MODALRESULT_W, 'ModalResult'); + {$IFDEF DELPHI28UP} + RegisterPropertyHelper(@TFormPixelsPerInch_R, @TFormPixelsPerInch_W, 'PixelsPerInch'); + {$ENDIF} {$ENDIF}{PS_MINIVCL} end; + {$IFDEF UNICODE}{$IFNDEF FPC} + RIRegisterKeyPressHelper(Cl.FindClass('TForm')); + {$ENDIF}{$ENDIF} end; {$ELSE} @@ -212,11 +251,7 @@ procedure RIRegisterTFORM(Cl: TPSRuntimeClassImporter); RegisterMethod(@TFORM.CLOSE, 'Close'); RegisterMethod(@TFORM.HIDE, 'Hide'); RegisterMethod(@TFORM.SHOW, 'Show'); - {$IFDEF DELPHI_SEATTLE_UP} - RegisterVirtualMethod(@TFORM.SHOWMODAL, 'ShowModal'); - {$ELSE} - RegisterMethod(@TFORM.SHOWMODAL, 'ShowModal'); - {$ENDIF} + RegisterMethod(@TFormShowModal_P, 'ShowModal'); RegisterMethod(@TFORM.RELEASE, 'Release'); RegisterPropertyHelper(@TFORMACTIVE_R, nil, 'Active'); @@ -239,10 +274,10 @@ procedure RIRegisterTFORM(Cl: TPSRuntimeClassImporter); RegisterPropertyHelper(@TFORMMDICHILDCOUNT_R, nil, 'MDIChildCount'); RegisterPropertyHelper(@TFORMMDICHILDREN_R, nil, 'MDIChildren'); {$ENDIF}{FPC} - RegisterMethod(@TFORM.CLOSEQUERY, 'CloseQuery'); + RegisterMethod(@TFormCloseQuery_P, 'CloseQuery'); RegisterMethod(@TFORM.DEFOCUSCONTROL, 'DefocusControl'); RegisterMethod(@TFORM.FOCUSCONTROL, 'FocusControl'); - RegisterMethod(@TFORM.SETFOCUSEDCONTROL, 'SetFocusedControl'); + RegisterMethod(@TFormSetFocusedControl_P, 'SetFocusedControl'); RegisterPropertyHelper(@TFORMCANVAS_R, nil, 'Canvas'); RegisterPropertyHelper(@TFORMMODALRESULT_R, @TFORMMODALRESULT_W, 'ModalResult'); {$ENDIF}{PS_MINIVCL} @@ -283,6 +318,10 @@ TApplication_PSHelper = class helper for TApplication procedure HINTSHORTPAUSE_W(T: INTEGER); procedure HINTHIDEPAUSE_R(var T: INTEGER); procedure HINTHIDEPAUSE_W(T: INTEGER); + {$IFNDEF FPC} + procedure ICON_R(var T: TICON); + procedure ICON_W(T: TICON); + {$ENDIF} procedure MAINFORM_R(var T: {$IFDEF DELPHI3UP}TCustomForm{$ELSE}TFORM{$ENDIF}); procedure SHOWHINT_R(var T: BOOLEAN); procedure SHOWHINT_W(T: BOOLEAN); @@ -341,6 +380,10 @@ procedure TApplication_PSHelper.HINTSHORTPAUSE_R(var T: INTEGER); begin T := Sel procedure TApplication_PSHelper.HINTSHORTPAUSE_W(T: INTEGER); begin Self.HINTSHORTPAUSE := T; end; procedure TApplication_PSHelper.HINTHIDEPAUSE_R(var T: INTEGER); begin T := Self.HINTHIDEPAUSE; end; procedure TApplication_PSHelper.HINTHIDEPAUSE_W(T: INTEGER); begin Self.HINTHIDEPAUSE := T; end; +{$IFNDEF FPC} +procedure TApplication_PSHelper.ICON_R(var T: TICON); begin T := Self.ICON; end; +procedure TApplication_PSHelper.ICON_W(T: TICON); begin Self.ICON := T; end; +{$ENDIF} procedure TApplication_PSHelper.MAINFORM_R(var T: {$IFDEF DELPHI3UP}TCustomForm{$ELSE}TFORM{$ENDIF}); begin T := Self.MAINFORM; end; procedure TApplication_PSHelper.SHOWHINT_R(var T: BOOLEAN); begin T := Self.SHOWHINT; end; procedure TApplication_PSHelper.SHOWHINT_W(T: BOOLEAN); begin Self.SHOWHINT := T; end; @@ -380,10 +423,10 @@ procedure RIRegisterTAPPLICATION(Cl: TPSRuntimeClassImporter); RegisterMethod(@TApplication.MINIMIZE, 'Minimize'); RegisterMethod(@TApplication.RESTORE, 'Restore'); RegisterPropertyHelper(@TApplication.ACTIVE_R, nil, 'Active'); - RegisterPropertyHelper(@TApplication.ONACTIVATE_R, @TApplication.ONACTIVATE_W, 'OnActivate'); - RegisterPropertyHelper(@TApplication.ONDEACTIVATE_R, @TApplication.ONDEACTIVATE_W, 'OnDeactivate'); - RegisterPropertyHelper(@TApplication.ONMINIMIZE_R, @TApplication.ONMINIMIZE_W, 'OnMinimize'); - RegisterPropertyHelper(@TApplication.ONRESTORE_R, @TApplication.ONRESTORE_W, 'OnRestore'); + RegisterEventPropertyHelper(@TApplication.ONACTIVATE_R, @TApplication.ONACTIVATE_W, 'OnActivate'); + RegisterEventPropertyHelper(@TApplication.ONDEACTIVATE_R, @TApplication.ONDEACTIVATE_W, 'OnDeactivate'); + RegisterEventPropertyHelper(@TApplication.ONMINIMIZE_R, @TApplication.ONMINIMIZE_W, 'OnMinimize'); + RegisterEventPropertyHelper(@TApplication.ONRESTORE_R, @TApplication.ONRESTORE_W, 'OnRestore'); RegisterMethod(@TApplication.NORMALIZETOPMOSTS, 'NormalizeTopMosts'); RegisterMethod(@TApplication.RESTORETOPMOSTS, 'RestoreTopMosts'); {$IFNDEF CLX} @@ -404,8 +447,8 @@ procedure RIRegisterTAPPLICATION(Cl: TPSRuntimeClassImporter); RegisterPropertyHelper(@TApplication.SHOWMAINFORM_R, @TApplication.SHOWMAINFORM_W, 'ShowMainForm'); RegisterPropertyHelper(@TApplication.TERMINATED_R, nil, 'Terminated'); RegisterPropertyHelper(@TApplication.TITLE_R, @TApplication.TITLE_W, 'Title'); - RegisterPropertyHelper(@TApplication.ONIDLE_R, @TApplication.ONIDLE_W, 'OnIdle'); - RegisterPropertyHelper(@TApplication.ONHINT_R, @TApplication.ONHINT_W, 'OnHint'); + RegisterEventPropertyHelper(@TApplication.ONIDLE_R, @TApplication.ONIDLE_W, 'OnIdle'); + RegisterEventPropertyHelper(@TApplication.ONHINT_R, @TApplication.ONHINT_W, 'OnHint'); {$IFNDEF PS_MINIVCL} RegisterMethod(@TApplication.CONTROLDESTROYED, 'ControlDestroyed'); RegisterMethod(@TApplication.CANCELHINT, 'CancelHint'); @@ -427,7 +470,10 @@ procedure RIRegisterTAPPLICATION(Cl: TPSRuntimeClassImporter); RegisterPropertyHelper(@TApplication.HINTPAUSE_R, @TApplication.HINTPAUSE_W, 'HintPause'); RegisterPropertyHelper(@TApplication.HINTSHORTPAUSE_R, @TApplication.HINTSHORTPAUSE_W, 'HintShortPause'); RegisterPropertyHelper(@TApplication.HINTHIDEPAUSE_R, @TApplication.HINTHIDEPAUSE_W, 'HintHidePause'); - RegisterPropertyHelper(@TApplication.ONHELP_R, @TApplication.ONHELP_W, 'OnHelp'); + {$IFNDEF FPC} + RegisterPropertyHelper(@TApplication.ICON_R, @TApplication.ICON_W, 'Icon'); + {$ENDIF} + RegisterEventPropertyHelper(@TApplication.ONHELP_R, @TApplication.ONHELP_W, 'OnHelp'); {$ENDIF} end; end; @@ -459,6 +505,10 @@ procedure TAPPLICATIONHINTSHORTPAUSE_R(Self: TAPPLICATION; var T: INTEGER); begi procedure TAPPLICATIONHINTSHORTPAUSE_W(Self: TAPPLICATION; T: INTEGER); begin Self.HINTSHORTPAUSE := T; end; procedure TAPPLICATIONHINTHIDEPAUSE_R(Self: TAPPLICATION; var T: INTEGER); begin T := Self.HINTHIDEPAUSE; end; procedure TAPPLICATIONHINTHIDEPAUSE_W(Self: TAPPLICATION; T: INTEGER); begin Self.HINTHIDEPAUSE := T; end; +{$IFNDEF FPC} +procedure TAPPLICATIONICON_R(Self: TAPPLICATION; var T: TICON); begin T := Self.ICON; end; +procedure TAPPLICATIONICON_W(Self: TAPPLICATION; T: TICON); begin Self.ICON := T; end; +{$ENDIF} procedure TAPPLICATIONMAINFORM_R(Self: TAPPLICATION; var T: {$IFDEF DELPHI3UP}TCustomForm{$ELSE}TFORM{$ENDIF}); begin T := Self.MAINFORM; end; procedure TAPPLICATIONSHOWHINT_R(Self: TAPPLICATION; var T: BOOLEAN); begin T := Self.SHOWHINT; end; procedure TAPPLICATIONSHOWHINT_W(Self: TAPPLICATION; T: BOOLEAN); begin Self.SHOWHINT := T; end; @@ -498,10 +548,10 @@ procedure RIRegisterTAPPLICATION(Cl: TPSRuntimeClassImporter); RegisterMethod(@TAPPLICATION.MINIMIZE, 'Minimize'); RegisterMethod(@TAPPLICATION.RESTORE, 'Restore'); RegisterPropertyHelper(@TAPPLICATIONACTIVE_R, nil, 'Active'); - RegisterPropertyHelper(@TAPPLICATIONONACTIVATE_R, @TAPPLICATIONONACTIVATE_W, 'OnActivate'); - RegisterPropertyHelper(@TAPPLICATIONONDEACTIVATE_R, @TAPPLICATIONONDEACTIVATE_W, 'OnDeactivate'); - RegisterPropertyHelper(@TAPPLICATIONONMINIMIZE_R, @TAPPLICATIONONMINIMIZE_W, 'OnMinimize'); - RegisterPropertyHelper(@TAPPLICATIONONRESTORE_R, @TAPPLICATIONONRESTORE_W, 'OnRestore'); + RegisterEventPropertyHelper(@TAPPLICATIONONACTIVATE_R, @TAPPLICATIONONACTIVATE_W, 'OnActivate'); + RegisterEventPropertyHelper(@TAPPLICATIONONDEACTIVATE_R, @TAPPLICATIONONDEACTIVATE_W, 'OnDeactivate'); + RegisterEventPropertyHelper(@TAPPLICATIONONMINIMIZE_R, @TAPPLICATIONONMINIMIZE_W, 'OnMinimize'); + RegisterEventPropertyHelper(@TAPPLICATIONONRESTORE_R, @TAPPLICATIONONRESTORE_W, 'OnRestore'); RegisterMethod(@TAPPLICATION.NORMALIZETOPMOSTS, 'NormalizeTopMosts'); RegisterMethod(@TAPPLICATION.RESTORETOPMOSTS, 'RestoreTopMosts'); {$IFNDEF CLX} @@ -522,8 +572,8 @@ procedure RIRegisterTAPPLICATION(Cl: TPSRuntimeClassImporter); RegisterPropertyHelper(@TAPPLICATIONSHOWMAINFORM_R, @TAPPLICATIONSHOWMAINFORM_W, 'ShowMainForm'); RegisterPropertyHelper(@TAPPLICATIONTERMINATED_R, nil, 'Terminated'); RegisterPropertyHelper(@TAPPLICATIONTITLE_R, @TAPPLICATIONTITLE_W, 'Title'); - RegisterPropertyHelper(@TAPPLICATIONONIDLE_R, @TAPPLICATIONONIDLE_W, 'OnIdle'); - RegisterPropertyHelper(@TAPPLICATIONONHINT_R, @TAPPLICATIONONHINT_W, 'OnHint'); + RegisterEventPropertyHelper(@TAPPLICATIONONIDLE_R, @TAPPLICATIONONIDLE_W, 'OnIdle'); + RegisterEventPropertyHelper(@TAPPLICATIONONHINT_R, @TAPPLICATIONONHINT_W, 'OnHint'); {$IFNDEF PS_MINIVCL} RegisterMethod(@TAPPLICATION.CONTROLDESTROYED, 'ControlDestroyed'); RegisterMethod(@TAPPLICATION.CANCELHINT, 'CancelHint'); @@ -545,7 +595,10 @@ procedure RIRegisterTAPPLICATION(Cl: TPSRuntimeClassImporter); RegisterPropertyHelper(@TAPPLICATIONHINTPAUSE_R, @TAPPLICATIONHINTPAUSE_W, 'HintPause'); RegisterPropertyHelper(@TAPPLICATIONHINTSHORTPAUSE_R, @TAPPLICATIONHINTSHORTPAUSE_W, 'HintShortPause'); RegisterPropertyHelper(@TAPPLICATIONHINTHIDEPAUSE_R, @TAPPLICATIONHINTHIDEPAUSE_W, 'HintHidePause'); - RegisterPropertyHelper(@TAPPLICATIONONHELP_R, @TAPPLICATIONONHELP_W, 'OnHelp'); + {$IFNDEF FPC} + RegisterPropertyHelper(@TAPPLICATIONICON_R, @TAPPLICATIONICON_W, 'Icon'); + {$ENDIF} + RegisterEventPropertyHelper(@TAPPLICATIONONHELP_R, @TAPPLICATIONONHELP_W, 'OnHelp'); {$ENDIF} end; end; diff --git a/Source/uPSR_graphics.pas b/Source/uPSR_graphics.pas index abf489c3..e7d5462d 100644 --- a/Source/uPSR_graphics.pas +++ b/Source/uPSR_graphics.pas @@ -21,10 +21,10 @@ procedure RIRegister_Graphics(Cl: TPSRuntimeClassImporter; Streams: Boolean); implementation {$IFNDEF FPC} uses - Classes{$IFDEF CLX}, QGraphics{$ELSE}, Windows, Graphics{$ENDIF} {$IFDEF DELPHI_TOKYO_UP}, UITypes {$ENDIF}; + SysUtils, Classes{$IFDEF CLX}, QGraphics{$ELSE}, Windows, Graphics{$ENDIF} {$IFDEF DELPHI_TOKYO_UP}, UITypes {$ENDIF}; {$ELSE} uses - Classes, Graphics,LCLType; + SysUtils, Classes, Graphics,LCLType; {$ENDIF} {$IFDEF DELPHI10UP}{$REGION 'TFont'}{$ENDIF} @@ -87,6 +87,81 @@ procedure RIRegisterTFont(Cl: TPSRuntimeClassImporter); {$ENDIF class_helper_present} {$IFDEF DELPHI10UP}{$ENDREGION}{$ENDIF} +{ Members that are virtual in some or all Delphi versions, bound through routines that call them + by name: the compiler then calls through the object's virtual method table wherever the member is + virtual, so a descendant's override runs. Bound by address, a script ran this class's own code + whatever the object's class. } +procedure TCanvasArc_P(Self: TCanvas; X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); +begin + Self.Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4); +end; + +procedure TCanvasChord_P(Self: TCanvas; X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); +begin + Self.Chord(X1, Y1, X2, Y2, X3, Y3, X4, Y4); +end; + +procedure TCanvasDraw_P(Self: TCanvas; X, Y: Integer; Graphic: TGraphic); +begin + Self.Draw(X, Y, Graphic); +end; + +procedure TCanvasEllipse_P(Self: TCanvas; X1, Y1, X2, Y2: Integer); +begin + Self.Ellipse(X1, Y1, X2, Y2); +end; + +procedure TCanvasFillRect_P(Self: TCanvas; const Rect: TRect); +begin + Self.FillRect(Rect); +end; + +{$IFNDEF CLX} +{ FillStyle is a byte in scripts and TFillStyle has two members, which index a two-entry table: a value + outside them is refused } +procedure TCanvasFloodFill_P(Self: TCanvas; X, Y: Integer; Color: TColor; FillStyle: Byte); +begin + if FillStyle > Ord(High(TFillStyle)) then + raise ERangeError.Create('Out Of Range'); + Self.FloodFill(X, Y, Color, TFillStyle(FillStyle)); +end; +{$ENDIF} + +procedure TCanvasLineTo_P(Self: TCanvas; X, Y: Integer); +begin + Self.LineTo(X, Y); +end; + +procedure TCanvasMoveTo_P(Self: TCanvas; X, Y: Integer); +begin + Self.MoveTo(X, Y); +end; + +procedure TCanvasPie_P(Self: TCanvas; X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); +begin + Self.Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4); +end; + +procedure TCanvasRectangle_P(Self: TCanvas; X1, Y1, X2, Y2: Integer); +begin + Self.Rectangle(X1, Y1, X2, Y2); +end; + +procedure TCanvasRefresh_P(Self: TCanvas); +begin + Self.Refresh; +end; + +procedure TCanvasRoundRect_P(Self: TCanvas; X1, Y1, X2, Y2, X3, Y3: Integer); +begin + Self.RoundRect(X1, Y1, X2, Y2, X3, Y3); +end; + +procedure TCanvasTextOut_P(Self: TCanvas; X, Y: Integer; Text: string); +begin + Self.TextOut(X, Y, Text); +end; + {$IFDEF DELPHI10UP}{$REGION 'TCanvas'}{$ENDIF} {$IFDEF class_helper_present} type @@ -134,27 +209,30 @@ procedure RIRegisterTCanvas(cl: TPSRuntimeClassImporter); // requires TPersisten begin with Cl.Add(TCanvas) do begin - RegisterMethod(@TCanvas.Arc, 'Arc'); - RegisterMethod(@TCanvas.Chord, 'Chord'); - RegisterMethod(@TCanvas.Rectangle, 'Rectangle'); - RegisterMethod(@TCanvas.RoundRect, 'RoundRect'); - RegisterMethod(@TCanvas.Ellipse, 'Ellipse'); - RegisterMethod(@TCanvas.FillRect, 'FillRect'); + {$IFNDEF FPC} + RegisterConstructor(@TCanvas.Create, 'Create'); + {$ENDIF} + RegisterMethod(@TCanvasArc_P, 'Arc'); + RegisterMethod(@TCanvasChord_P, 'Chord'); + RegisterMethod(@TCanvasRectangle_P, 'Rectangle'); + RegisterMethod(@TCanvasRoundRect_P, 'RoundRect'); + RegisterMethod(@TCanvasEllipse_P, 'Ellipse'); + RegisterMethod(@TCanvasFillRect_P, 'FillRect'); {$IFDEF FPC} - RegisterMethod(@TCanvas.FloodFill, 'FloodFill'); + RegisterMethod(@TCanvasFloodFill_P, 'FloodFill'); {$ELSE} {$IFNDEF CLX} - RegisterMethod(@TCanvas.FloodFill, 'FloodFill'); + RegisterMethod(@TCanvasFloodFill_P, 'FloodFill'); {$ENDIF} {$ENDIF} - RegisterMethod(@TCanvas.Draw, 'Draw'); + RegisterMethod(@TCanvasDraw_P, 'Draw'); - RegisterMethod(@TCanvas.Lineto, 'LineTo'); - RegisterMethod(@TCanvas.Moveto, 'MoveTo'); - RegisterMethod(@TCanvas.Pie, 'Pie'); - RegisterMethod(@TCanvas.Refresh, 'Refresh'); + RegisterMethod(@TCanvasLineTo_P, 'LineTo'); + RegisterMethod(@TCanvasMoveTo_P, 'MoveTo'); + RegisterMethod(@TCanvasPie_P, 'Pie'); + RegisterMethod(@TCanvasRefresh_P, 'Refresh'); RegisterMethod(@TCanvas.TextHeight, 'TextHeight'); - RegisterMethod(@TCanvas.TextOut, 'TextOut'); + RegisterMethod(@TCanvasTextOut_P, 'TextOut'); RegisterMethod(@TCanvas.TextWidth, 'TextWidth'); {$IFNDEF CLX} RegisterPropertyHelper(@TCanvas.HandleR, @TCanvas.HandleW, 'Handle'); @@ -187,6 +265,9 @@ procedure RIRegisterTCanvas(cl: TPSRuntimeClassImporter); // requires TPersisten begin with Cl.Add(TCanvas) do begin + {$IFNDEF FPC} + RegisterConstructor(@TCanvas.Create, 'Create'); + {$ENDIF} {$IFDEF FPC} RegisterMethod(@TCanvasArc, 'Arc'); RegisterMethod(@TCanvasChord, 'Chord'); @@ -196,24 +277,24 @@ procedure RIRegisterTCanvas(cl: TPSRuntimeClassImporter); // requires TPersisten RegisterMethod(@TCanvasFillRect, 'FillRect'); RegisterMethod(@TCanvasFloodFill, 'FloodFill'); {$ELSE} - RegisterMethod(@TCanvas{$IFNDEF FPC}.{$ENDIF}Arc, 'Arc'); - RegisterMethod(@TCanvas{$IFNDEF FPC}.{$ENDIF}Chord, 'Chord'); - RegisterMethod(@TCanvas{$IFNDEF FPC}.{$ENDIF}Rectangle, 'Rectangle'); - RegisterMethod(@TCanvas{$IFNDEF FPC}.{$ENDIF}RoundRect, 'RoundRect'); - RegisterMethod(@TCanvas{$IFNDEF FPC}.{$ENDIF}Ellipse, 'Ellipse'); - RegisterMethod(@TCanvas{$IFNDEF FPC}.{$ENDIF}FillRect, 'FillRect'); + RegisterMethod(@TCanvasArc_P, 'Arc'); + RegisterMethod(@TCanvasChord_P, 'Chord'); + RegisterMethod(@TCanvasRectangle_P, 'Rectangle'); + RegisterMethod(@TCanvasRoundRect_P, 'RoundRect'); + RegisterMethod(@TCanvasEllipse_P, 'Ellipse'); + RegisterMethod(@TCanvasFillRect_P, 'FillRect'); {$IFNDEF CLX} - RegisterMethod(@TCanvas{$IFNDEF FPC}.{$ENDIF}FloodFill, 'FloodFill'); + RegisterMethod(@TCanvasFloodFill_P, 'FloodFill'); {$ENDIF} {$ENDIF} - RegisterMethod(@TCanvas.Draw, 'Draw'); + RegisterMethod(@TCanvasDraw_P, 'Draw'); - RegisterMethod(@TCanvas.Lineto, 'LineTo'); - RegisterMethod(@TCanvas.Moveto, 'MoveTo'); - RegisterMethod(@TCanvas.Pie, 'Pie'); - RegisterMethod(@TCanvas.Refresh, 'Refresh'); + RegisterMethod(@TCanvasLineTo_P, 'LineTo'); + RegisterMethod(@TCanvasMoveTo_P, 'MoveTo'); + RegisterMethod(@TCanvasPie_P, 'Pie'); + RegisterMethod(@TCanvasRefresh_P, 'Refresh'); RegisterMethod(@TCanvas.TextHeight, 'TextHeight'); - RegisterMethod(@TCanvas.TextOut, 'TextOut'); + RegisterMethod(@TCanvasTextOut_P, 'TextOut'); RegisterMethod(@TCanvas.TextWidth, 'TextWidth'); {$IFNDEF CLX} RegisterPropertyHelper(@TCanvasHandleR, @TCanvasHandleW, 'Handle'); @@ -243,7 +324,7 @@ procedure RIRegisterTGRAPHICSOBJECT(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TGraphicsObject) do begin - RegisterPropertyHelper(@TGraphicsObject.ONCHANGE_R, @TGraphicsObject.ONCHANGE_W, 'OnChange'); + RegisterEventPropertyHelper(@TGraphicsObject.ONCHANGE_R, @TGraphicsObject.ONCHANGE_W, 'OnChange'); end; end; {$ELSE} @@ -254,7 +335,7 @@ procedure RIRegisterTGRAPHICSOBJECT(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TGRAPHICSOBJECT) do begin - RegisterPropertyHelper(@TGRAPHICSOBJECTONCHANGE_R, @TGRAPHICSOBJECTONCHANGE_W, 'OnChange'); + RegisterEventPropertyHelper(@TGRAPHICSOBJECTONCHANGE_R, @TGRAPHICSOBJECTONCHANGE_W, 'OnChange'); end; end; {$ENDIF class_helper_present} @@ -316,7 +397,7 @@ procedure RIRegisterTGraphic(CL: TPSRuntimeClassImporter); RegisterPropertyHelper(@TGraphic.Empty_R,nil,'Empty'); RegisterPropertyHelper(@TGraphic.Height_R,@TGraphic.Height_W,'Height'); RegisterPropertyHelper(@TGraphic.Width_R,@TGraphic.Width_W,'Width'); - RegisterPropertyHelper(@TGraphic.OnChange_R,@TGraphic.OnChange_W,'OnChange'); + RegisterEventPropertyHelper(@TGraphic.OnChange_R,@TGraphic.OnChange_W,'OnChange'); {$IFNDEF PS_MINIVCL} RegisterPropertyHelper(@TGraphic.Modified_R,@TGraphic.Modified_W,'Modified'); @@ -345,7 +426,7 @@ procedure RIRegisterTGraphic(CL: TPSRuntimeClassImporter); RegisterPropertyHelper(@TGraphicEmpty_R,nil,'Empty'); RegisterPropertyHelper(@TGraphicHeight_R,@TGraphicHeight_W,'Height'); RegisterPropertyHelper(@TGraphicWidth_R,@TGraphicWidth_W,'Width'); - RegisterPropertyHelper(@TGraphicOnChange_R,@TGraphicOnChange_W,'OnChange'); + RegisterEventPropertyHelper(@TGraphicOnChange_R,@TGraphicOnChange_W,'OnChange'); {$IFNDEF PS_MINIVCL} RegisterPropertyHelper(@TGraphicModified_R,@TGraphicModified_W,'Modified'); @@ -356,6 +437,33 @@ procedure RIRegisterTGraphic(CL: TPSRuntimeClassImporter); {$ENDIF class_helper_present} {$IFDEF DELPHI10UP}{$ENDREGION}{$ENDIF} +{ Members that are virtual in some or all Delphi versions, bound through routines that call them + by name: the compiler then calls through the object's virtual method table wherever the member is + virtual, so a descendant's override runs. Bound by address, a script ran this class's own code + whatever the object's class. } +procedure TBitmapLoadFromStream_P(Self: TBitmap; Stream: TStream); +begin + Self.LoadFromStream(Stream); +end; + +procedure TBitmapSaveToStream_P(Self: TBitmap; Stream: TStream); +begin + Self.SaveToStream(Stream); +end; + +{$IFNDEF CLX}{$IFNDEF FPC} +procedure TBitmapLoadFromClipboardFormat_P(Self: TBitmap; AFormat: Word; AData: THandle; APalette: HPALETTE); +begin + Self.LoadFromClipboardFormat(AFormat, AData, APalette); +end; + +procedure TBitmapSaveToClipboardFormat_P(Self: TBitmap; var Format: Word; var Data: THandle; + var APalette: HPALETTE); +begin + Self.SaveToClipboardFormat(Format, Data, APalette); +end; +{$ENDIF}{$ENDIF} + {$IFDEF DELPHI10UP}{$REGION 'TBitmap'}{$ENDIF} {$IFDEF class_helper_present} type @@ -401,8 +509,8 @@ procedure RIRegisterTBitmap(CL: TPSRuntimeClassImporter; Streams: Boolean); with CL.Add(TBitmap) do begin if Streams then begin - RegisterMethod(@TBitmap.LoadFromStream, 'LoadFromStream'); - RegisterMethod(@TBitmap.SaveToStream, 'SaveToStream'); + RegisterMethod(@TBitmapLoadFromStream_P, 'LoadFromStream'); + RegisterMethod(@TBitmapSaveToStream_P, 'SaveToStream'); end; RegisterPropertyHelper(@TBitmap.Canvas_R,nil,'Canvas'); {$IFNDEF CLX} @@ -415,14 +523,14 @@ procedure RIRegisterTBitmap(CL: TPSRuntimeClassImporter; Streams: Boolean); {$ENDIF} RegisterMethod(@TBitmap.FreeImage, 'FreeImage'); {$IFNDEF CLX} - RegisterMethod(@TBitmap.LoadFromClipboardFormat, 'LoadFromClipboardFormat'); + {$IFDEF FPC}RegisterMethod(@TBitmap.LoadFromClipboardFormat, 'LoadFromClipboardFormat');{$ELSE}RegisterMethod(@TBitmapLoadFromClipboardFormat_P, 'LoadFromClipboardFormat');{$ENDIF} {$ENDIF} RegisterMethod(@TBitmap.LoadFromResourceName, 'LoadFromResourceName'); RegisterMethod(@TBitmap.LoadFromResourceID, 'LoadFromResourceID'); {$IFNDEF CLX} RegisterMethod(@TBitmap.ReleaseHandle, 'ReleaseHandle'); RegisterMethod(@TBitmap.ReleasePalette, 'ReleasePalette'); - RegisterMethod(@TBitmap.SaveToClipboardFormat, 'SaveToClipboardFormat'); + {$IFDEF FPC}RegisterMethod(@TBitmap.SaveToClipboardFormat, 'SaveToClipboardFormat');{$ELSE}RegisterMethod(@TBitmapSaveToClipboardFormat_P, 'SaveToClipboardFormat');{$ENDIF} RegisterPropertyHelper(@TBitmap.Monochrome_R,@TBitmap.Monochrome_W,'Monochrome'); RegisterPropertyHelper(@TBitmap.Palette_R,@TBitmap.Palette_W,'Palette'); {$IFNDEF FPC} @@ -457,8 +565,8 @@ procedure RIRegisterTBitmap(CL: TPSRuntimeClassImporter; Streams: Boolean); with CL.Add(TBitmap) do begin if Streams then begin - RegisterMethod(@TBitmap.LoadFromStream, 'LoadFromStream'); - RegisterMethod(@TBitmap.SaveToStream, 'SaveToStream'); + RegisterMethod(@TBitmapLoadFromStream_P, 'LoadFromStream'); + RegisterMethod(@TBitmapSaveToStream_P, 'SaveToStream'); end; RegisterPropertyHelper(@TBitmapCanvas_R,nil,'Canvas'); {$IFNDEF CLX} @@ -471,14 +579,14 @@ procedure RIRegisterTBitmap(CL: TPSRuntimeClassImporter; Streams: Boolean); {$ENDIF} RegisterMethod(@TBitmap.FreeImage, 'FreeImage'); {$IFNDEF CLX} - RegisterMethod(@TBitmap.LoadFromClipboardFormat, 'LoadFromClipboardFormat'); + {$IFDEF FPC}RegisterMethod(@TBitmap.LoadFromClipboardFormat, 'LoadFromClipboardFormat');{$ELSE}RegisterMethod(@TBitmapLoadFromClipboardFormat_P, 'LoadFromClipboardFormat');{$ENDIF} {$ENDIF} RegisterMethod(@TBitmap.LoadFromResourceName, 'LoadFromResourceName'); RegisterMethod(@TBitmap.LoadFromResourceID, 'LoadFromResourceID'); {$IFNDEF CLX} RegisterMethod(@TBitmap.ReleaseHandle, 'ReleaseHandle'); RegisterMethod(@TBitmap.ReleasePalette, 'ReleasePalette'); - RegisterMethod(@TBitmap.SaveToClipboardFormat, 'SaveToClipboardFormat'); + {$IFDEF FPC}RegisterMethod(@TBitmap.SaveToClipboardFormat, 'SaveToClipboardFormat');{$ELSE}RegisterMethod(@TBitmapSaveToClipboardFormat_P, 'SaveToClipboardFormat');{$ENDIF} RegisterPropertyHelper(@TBitmapMonochrome_R,@TBitmapMonochrome_W,'Monochrome'); RegisterPropertyHelper(@TBitmapPalette_R,@TBitmapPalette_W,'Palette'); {$IFNDEF FPC} diff --git a/Source/uPSR_menus.pas b/Source/uPSR_menus.pas index 823c1873..a3b97790 100644 --- a/Source/uPSR_menus.pas +++ b/Source/uPSR_menus.pas @@ -144,7 +144,7 @@ procedure RIRegisterTPOPUPMENU(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TPopupMenu) do begin - RegisterConstructor(@TPopupMenu.CREATE, 'Create'); + RegisterVirtualConstructor(@TPopupMenu.CREATE, 'Create'); RegisterVirtualMethod(@TPopupMenu.POPUP, 'Popup'); RegisterPropertyHelper(@TPopupMenu.POPUPCOMPONENT_R,@TPopupMenu.POPUPCOMPONENT_W,'PopupComponent'); RegisterEventPropertyHelper(@TPopupMenu.ONPOPUP_R,@TPopupMenu.ONPOPUP_W,'OnPopup'); @@ -209,7 +209,7 @@ procedure RIRegisterTPOPUPMENU(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TPOPUPMENU) do begin - RegisterConstructor(@TPOPUPMENU.CREATE, 'Create'); + RegisterVirtualConstructor(@TPOPUPMENU.CREATE, 'Create'); RegisterVirtualMethod(@TPOPUPMENU.POPUP, 'Popup'); RegisterPropertyHelper(@TPOPUPMENUPOPUPCOMPONENT_R,@TPOPUPMENUPOPUPCOMPONENT_W,'PopupComponent'); RegisterEventPropertyHelper(@TPOPUPMENUONPOPUP_R,@TPOPUPMENUONPOPUP_W,'OnPopup'); @@ -285,6 +285,27 @@ procedure RIRegisterTMAINMENU(Cl: TPSRuntimeClassImporter); {$ENDIF class_helper_present} {$IFDEF DELPHI10UP}{$ENDREGION}{$ENDIF} +{ Members that are dynamic methods, bound through routines that call them: a descendant's + override then runs, where bound by address a script ran this class's own code. } +function TMenuItemGetParentComponent_P(Self: TMenuItem): TComponent; +begin + Result := Self.GetParentComponent; +end; + +function TMenuItemHasParent_P(Self: TMenuItem): Boolean; +begin + Result := Self.HasParent; +end; + +{$IFNDEF FPC} +{ ParentBiDiModeChanged is overloaded; bound through a routine, the script's call reaches the overload + that takes the control. } +procedure TMenuParentBiDiModeChanged_P(Self: TMenu; AControl: TObject); +begin + Self.ParentBiDiModeChanged(AControl); +end; +{$ENDIF} + {$IFDEF DELPHI10UP}{$REGION 'TMenu'}{$ENDIF} {$IFDEF class_helper_present} type @@ -339,13 +360,25 @@ procedure TMenu_PSHelper.BIDIMODE_R(var T: TBIDIMODE); begin T := Self.BIDIMODE; end; procedure TMenu_PSHelper.AUTOLINEREDUCTION_W(const T: TMENUAUTOFLAG); -begin Self.AUTOLINEREDUCTION := T; end; +var + lRaw : Byte absolute T; +begin + if lRaw > Ord(High(TMenuAutoFlag)) then + raise ERangeError.Create('Out Of Range'); + Self.AUTOLINEREDUCTION := T; +end; procedure TMenu_PSHelper.AUTOLINEREDUCTION_R(var T: TMENUAUTOFLAG); begin T := Self.AUTOLINEREDUCTION; end; procedure TMenu_PSHelper.AUTOHOTKEYS_W(const T: TMENUAUTOFLAG); -begin Self.AUTOHOTKEYS := T; end; +var + lRaw : Byte absolute T; +begin + if lRaw > Ord(High(TMenuAutoFlag)) then + raise ERangeError.Create('Out Of Range'); + Self.AUTOHOTKEYS := T; +end; procedure TMenu_PSHelper.AUTOHOTKEYS_R(var T: TMENUAUTOFLAG); begin T := Self.AUTOHOTKEYS; end; @@ -364,7 +397,7 @@ procedure RIRegisterTMENU(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TMENU) do begin - RegisterConstructor(@TMENU.CREATE, 'Create'); + RegisterVirtualConstructor(@TMENU.CREATE, 'Create'); RegisterMethod(@TMENU.DISPATCHCOMMAND, 'DispatchCommand'); RegisterMethod(@TMENU.FINDITEM, 'FindItem'); RegisterPropertyHelper(@TMENU.IMAGES_R,@TMENU.IMAGES_W,'Images'); @@ -373,7 +406,7 @@ procedure RIRegisterTMENU(Cl: TPSRuntimeClassImporter); RegisterPropertyHelper(@TMENU.ITEMS_R,nil,'Items'); {$IFNDEF FPC} RegisterMethod(@TMENU.DISPATCHPOPUP, 'DispatchPopup'); - RegisterMethod(@TMENU.PARENTBIDIMODECHANGED, 'ParentBiDiModeChanged'); + RegisterMethod(@TMenuParentBiDiModeChanged_P, 'ParentBiDiModeChanged'); RegisterMethod(@TMENU.PROCESSMENUCHAR, 'ProcessMenuChar'); RegisterPropertyHelper(@TMENU.AUTOHOTKEYS_R,@TMENU.AUTOHOTKEYS_W,'AutoHotkeys'); RegisterPropertyHelper(@TMENU.AUTOLINEREDUCTION_R,@TMENU.AUTOLINEREDUCTION_W,'AutoLineReduction'); @@ -415,13 +448,25 @@ procedure TMENUBIDIMODE_R(Self: TMENU; var T: TBIDIMODE); begin T := Self.BIDIMODE; end; procedure TMENUAUTOLINEREDUCTION_W(Self: TMENU; const T: TMENUAUTOFLAG); -begin Self.AUTOLINEREDUCTION := T; end; +var + lRaw : Byte absolute T; +begin + if lRaw > Ord(High(TMenuAutoFlag)) then + raise ERangeError.Create('Out Of Range'); + Self.AUTOLINEREDUCTION := T; +end; procedure TMENUAUTOLINEREDUCTION_R(Self: TMENU; var T: TMENUAUTOFLAG); begin T := Self.AUTOLINEREDUCTION; end; procedure TMENUAUTOHOTKEYS_W(Self: TMENU; const T: TMENUAUTOFLAG); -begin Self.AUTOHOTKEYS := T; end; +var + lRaw : Byte absolute T; +begin + if lRaw > Ord(High(TMenuAutoFlag)) then + raise ERangeError.Create('Out Of Range'); + Self.AUTOHOTKEYS := T; +end; procedure TMENUAUTOHOTKEYS_R(Self: TMENU; var T: TMENUAUTOFLAG); begin T := Self.AUTOHOTKEYS; end; @@ -445,7 +490,7 @@ procedure RIRegisterTMENU(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TMENU) do begin - RegisterConstructor(@TMENU.CREATE, 'Create'); + RegisterVirtualConstructor(@TMENU.CREATE, 'Create'); RegisterMethod(@TMENU.DISPATCHCOMMAND, 'DispatchCommand'); RegisterMethod(@TMENU.FINDITEM, 'FindItem'); RegisterPropertyHelper(@TMENUIMAGES_R,@TMENUIMAGES_W,'Images'); @@ -454,7 +499,7 @@ procedure RIRegisterTMENU(Cl: TPSRuntimeClassImporter); RegisterPropertyHelper(@TMENUITEMS_R,nil,'Items'); {$IFNDEF FPC} RegisterMethod(@TMENU.DISPATCHPOPUP, 'DispatchPopup'); - RegisterMethod(@TMENU.PARENTBIDIMODECHANGED, 'ParentBiDiModeChanged'); + RegisterMethod(@TMenuParentBiDiModeChanged_P, 'ParentBiDiModeChanged'); RegisterMethod(@TMENU.PROCESSMENUCHAR, 'ProcessMenuChar'); RegisterPropertyHelper(@TMENUAUTOHOTKEYS_R,@TMENUAUTOHOTKEYS_W,'AutoHotkeys'); RegisterPropertyHelper(@TMENUAUTOLINEREDUCTION_R,@TMENUAUTOLINEREDUCTION_W,'AutoLineReduction'); @@ -676,7 +721,7 @@ procedure RIRegisterTMENUITEM(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TMenuItem) do begin - RegisterConstructor(@TMenuItem.CREATE, 'Create'); + RegisterVirtualConstructor(@TMenuItem.CREATE, 'Create'); RegisterVirtualMethod(@TMenuItem.INITIATEACTION, 'InitiateAction'); RegisterMethod(@TMenuItem.INSERT, 'Insert'); RegisterMethod(@TMenuItem.DELETE, 'Delete'); @@ -694,9 +739,9 @@ procedure RIRegisterTMENUITEM(Cl: TPSRuntimeClassImporter); {$ENDIF} RegisterMethod(@TMenuItem.INDEXOF, 'IndexOf'); RegisterMethod(@TMenuItem.GETIMAGELIST, 'GetImageList'); - RegisterMethod(@TMenuItem.GETPARENTCOMPONENT, 'GetParentComponent'); + RegisterMethod(@TMenuItemGetParentComponent_P, 'GetParentComponent'); RegisterMethod(@TMenuItem.GETPARENTMENU, 'GetParentMenu'); - RegisterMethod(@TMenuItem.HASPARENT, 'HasParent'); + RegisterMethod(@TMenuItemHasParent_P, 'HasParent'); RegisterMethod(@TMenuItem.ADD, 'Add'); RegisterMethod(@TMenuItem.REMOVE, 'Remove'); {$IFNDEF FPC} @@ -881,7 +926,7 @@ procedure RIRegisterTMENUITEM(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TMENUITEM) do begin - RegisterConstructor(@TMENUITEM.CREATE, 'Create'); + RegisterVirtualConstructor(@TMENUITEM.CREATE, 'Create'); RegisterVirtualMethod(@TMENUITEM.INITIATEACTION, 'InitiateAction'); RegisterMethod(@TMENUITEM.INSERT, 'Insert'); RegisterMethod(@TMENUITEM.DELETE, 'Delete'); @@ -899,9 +944,9 @@ procedure RIRegisterTMENUITEM(Cl: TPSRuntimeClassImporter); {$ENDIF} RegisterMethod(@TMENUITEM.INDEXOF, 'IndexOf'); RegisterMethod(@TMENUITEM.GETIMAGELIST, 'GetImageList'); - RegisterMethod(@TMENUITEM.GETPARENTCOMPONENT, 'GetParentComponent'); + RegisterMethod(@TMenuItemGetParentComponent_P, 'GetParentComponent'); RegisterMethod(@TMENUITEM.GETPARENTMENU, 'GetParentMenu'); - RegisterMethod(@TMENUITEM.HASPARENT, 'HasParent'); + RegisterMethod(@TMenuItemHasParent_P, 'HasParent'); RegisterMethod(@TMENUITEM.ADD, 'Add'); RegisterMethod(@TMENUITEM.REMOVE, 'Remove'); {$IFNDEF FPC} @@ -975,6 +1020,9 @@ procedure RIRegister_Menus(CL: TPSRuntimeClassImporter); {$IFNDEF FPC} RIRegisterTPOPUPLIST(Cl); RIRegisterTMENUITEMSTACK(Cl); + { declared to scripts under ancestors a host can supply } + Cl.Add(EMenuError); + Cl.Add(TMenuActionLink); {$ENDIF} end; diff --git a/Source/uPSR_stdctrls.pas b/Source/uPSR_stdctrls.pas index 0a89d5be..39e434db 100644 --- a/Source/uPSR_stdctrls.pas +++ b/Source/uPSR_stdctrls.pas @@ -4,7 +4,7 @@ {$I PascalScript.inc} interface uses - uPSRuntime, uPSUtils; + uPSRuntime, uPSUtils, uPSR_controls; procedure RIRegisterTCUSTOMGROUPBOX(Cl: TPSRuntimeClassImporter); @@ -97,6 +97,52 @@ procedure RIRegisterTLABEL(Cl: TPSRuntimeClassImporter); end; {$IFDEF DELPHI10UP}{$ENDREGION}{$ENDIF} +{ Members that are virtual in some or all Delphi versions, bound through routines that call them + by name: the compiler then calls through the object's virtual method table wherever the member is + virtual, so a descendant's override runs. Bound by address, a script ran this class's own code + whatever the object's class. } +procedure TCustomEditClear_P(Self: TCustomEdit); +begin + Self.Clear; +end; + +procedure TCustomComboBoxClear_P(Self: TCustomComboBox); +begin + Self.Clear; +end; + +procedure TCustomComboBoxSelectAll_P(Self: TCustomComboBox); +begin + Self.SelectAll; +end; + +procedure TCustomListBoxClear_P(Self: TCustomListBox); +begin + Self.Clear; +end; + +{$IFNDEF PS_MINIVCL}{$IFNDEF FPC} +{ A script PChar is a PAnsiChar on every compiler, Delphi's PChar a PWideChar from Delphi 2009: the + text members that take one are bound through routines that go through a string, and copy at most + BufSize - 1 bytes and a #0 into the script's buffer. } +function TCustomEditGetSelTextBuf_P(Self: TCustomEdit; Buffer: PAnsiChar; BufSize: Integer): Integer; +var + lText : string; +begin + Result := 0; + if BufSize <= 0 then + Exit; + SetLength(lText, BufSize); + SetLength(lText, Self.GetSelTextBuf(PChar(lText), BufSize)); + Result := PSTextToAnsiBuffer(lText, Buffer, BufSize); +end; + +procedure TCustomEditSetSelTextBuf_P(Self: TCustomEdit; Buffer: PAnsiChar); +begin + Self.SetSelTextBuf(PChar(string(AnsiString(Buffer)))); +end; +{$ENDIF}{$ENDIF} + {$IFDEF DELPHI10UP}{$REGION 'TCustomEdit'}{$ENDIF} {$IFDEF class_helper_present} type @@ -130,7 +176,7 @@ procedure RIRegisterTCUSTOMEDIT(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TCustomEdit) do begin - RegisterMethod(@TCustomEdit.CLEAR, 'Clear'); + RegisterMethod(@TCustomEditClear_P, 'Clear'); RegisterMethod(@TCustomEdit.CLEARSELECTION, 'ClearSelection'); RegisterMethod(@TCustomEdit.SELECTALL, 'SelectAll'); RegisterPropertyHelper(@TCustomEdit.MODIFIED_R, @TCustomEdit.MODIFIED_W, 'Modified'); @@ -144,8 +190,8 @@ procedure RIRegisterTCUSTOMEDIT(Cl: TPSRuntimeClassImporter); RegisterMethod(@TCustomEdit.CUTTOCLIPBOARD, 'CutToClipboard'); RegisterMethod(@TCustomEdit.PASTEFROMCLIPBOARD, 'PasteFromClipboard'); {$IFNDEF FPC} - RegisterMethod(@TCustomEdit.GETSELTEXTBUF, 'GetSelTextBuf'); - RegisterMethod(@TCustomEdit.SETSELTEXTBUF, 'SetSelTextBuf'); + RegisterMethod(@TCustomEditGetSelTextBuf_P, 'GetSelTextBuf'); + RegisterMethod(@TCustomEditSetSelTextBuf_P, 'SetSelTextBuf'); {$ENDIF}{FPC} {$ENDIF} end; @@ -168,7 +214,7 @@ procedure RIRegisterTCUSTOMEDIT(Cl: TPSRuntimeClassImporter); begin with Cl.Add(TCUSTOMEDIT) do begin - RegisterMethod(@TCUSTOMEDIT.CLEAR, 'Clear'); + RegisterMethod(@TCustomEditClear_P, 'Clear'); RegisterMethod(@TCUSTOMEDIT.CLEARSELECTION, 'ClearSelection'); RegisterMethod(@TCUSTOMEDIT.SELECTALL, 'SelectAll'); RegisterPropertyHelper(@TCUSTOMEDITMODIFIED_R, @TCUSTOMEDITMODIFIED_W, 'Modified'); @@ -182,8 +228,8 @@ procedure RIRegisterTCUSTOMEDIT(Cl: TPSRuntimeClassImporter); RegisterMethod(@TCUSTOMEDIT.CUTTOCLIPBOARD, 'CutToClipboard'); RegisterMethod(@TCUSTOMEDIT.PASTEFROMCLIPBOARD, 'PasteFromClipboard'); {$IFNDEF FPC} - RegisterMethod(@TCUSTOMEDIT.GETSELTEXTBUF, 'GetSelTextBuf'); - RegisterMethod(@TCUSTOMEDIT.SETSELTEXTBUF, 'SetSelTextBuf'); + RegisterMethod(@TCustomEditGetSelTextBuf_P, 'GetSelTextBuf'); + RegisterMethod(@TCustomEditSetSelTextBuf_P, 'SetSelTextBuf'); {$ENDIF}{FPC} {$ENDIF} end; @@ -196,6 +242,9 @@ procedure RIRegisterTCUSTOMEDIT(Cl: TPSRuntimeClassImporter); procedure RIRegisterTEDIT(Cl: TPSRuntimeClassImporter); begin Cl.Add(TEdit); + {$IFDEF UNICODE}{$IFNDEF FPC} + RIRegisterKeyPressHelper(Cl.FindClass('TEdit')); + {$ENDIF}{$ENDIF} end; {$IFDEF DELPHI10UP}{$ENDREGION}{$ENDIF} @@ -222,6 +271,9 @@ procedure RIRegisterTCUSTOMMEMO(Cl: TPSRuntimeClassImporter); procedure RIRegisterTMEMO(Cl: TPSRuntimeClassImporter); begin Cl.Add(TMEMO); + {$IFDEF UNICODE}{$IFNDEF FPC} + RIRegisterKeyPressHelper(Cl.FindClass('TMemo')); + {$ENDIF}{$ENDIF} end; {$ELSE} @@ -295,8 +347,8 @@ procedure RIRegisterTCUSTOMCOMBOBOX(Cl: TPSRuntimeClassImporter); RegisterPropertyHelper(@TCustomComboBox.ITEMINDEX_R, @TCustomComboBox.ITEMINDEX_W, 'ItemIndex'); {$IFNDEF PS_MINIVCL} - RegisterMethod(@TCustomComboBox.CLEAR, 'Clear'); - RegisterMethod(@TCustomComboBox.SELECTALL, 'SelectAll'); + RegisterMethod(@TCustomComboBoxClear_P, 'Clear'); + RegisterMethod(@TCustomComboBoxSelectAll_P, 'SelectAll'); RegisterPropertyHelper(@TCustomComboBox.CANVAS_R, nil, 'Canvas'); RegisterPropertyHelper(@TCustomComboBox.SELLENGTH_R, @TCustomComboBox.SELLENGTH_W, 'SelLength'); RegisterPropertyHelper(@TCustomComboBox.SELSTART_R, @TCustomComboBox.SELSTART_W, 'SelStart'); @@ -330,8 +382,8 @@ procedure RIRegisterTCUSTOMCOMBOBOX(Cl: TPSRuntimeClassImporter); RegisterPropertyHelper(@TCUSTOMCOMBOBOXITEMINDEX_R, @TCUSTOMCOMBOBOXITEMINDEX_W, 'ItemIndex'); {$IFNDEF PS_MINIVCL} - RegisterMethod(@TCUSTOMCOMBOBOX.CLEAR, 'Clear'); - RegisterMethod(@TCUSTOMCOMBOBOX.SELECTALL, 'SelectAll'); + RegisterMethod(@TCustomComboBoxClear_P, 'Clear'); + RegisterMethod(@TCustomComboBoxSelectAll_P, 'SelectAll'); RegisterPropertyHelper(@TCUSTOMCOMBOBOXCANVAS_R, nil, 'Canvas'); RegisterPropertyHelper(@TCUSTOMCOMBOBOXSELLENGTH_R, @TCUSTOMCOMBOBOXSELLENGTH_W, 'SelLength'); RegisterPropertyHelper(@TCUSTOMCOMBOBOXSELSTART_R, @TCUSTOMCOMBOBOXSELSTART_W, 'SelStart'); @@ -346,6 +398,9 @@ procedure RIRegisterTCUSTOMCOMBOBOX(Cl: TPSRuntimeClassImporter); procedure RIRegisterTCOMBOBOX(Cl: TPSRuntimeClassImporter); begin Cl.Add(TComboBox); + {$IFDEF UNICODE}{$IFNDEF FPC} + RIRegisterKeyPressHelper(Cl.FindClass('TComboBox')); + {$ENDIF}{$ENDIF} end; {$IFDEF DELPHI10UP}{$ENDREGION}{$ENDIF} @@ -360,6 +415,9 @@ procedure RIRegisterTBUTTONCONTROL(Cl: TPSRuntimeClassImporter); procedure RIRegisterTBUTTON(Cl: TPSRuntimeClassImporter); begin Cl.Add(TButton); + {$IFDEF UNICODE}{$IFNDEF FPC} + RIRegisterKeyPressHelper(Cl.FindClass('TButton')); + {$ENDIF}{$ENDIF} end; {$IFDEF DELPHI10UP}{$ENDREGION}{$ENDIF} @@ -374,6 +432,9 @@ procedure RIRegisterTCUSTOMCHECKBOX(Cl: TPSRuntimeClassImporter); procedure RIRegisterTCHECKBOX(Cl: TPSRuntimeClassImporter); begin Cl.Add(TCheckBox); + {$IFDEF UNICODE}{$IFNDEF FPC} + RIRegisterKeyPressHelper(Cl.FindClass('TCheckBox')); + {$ENDIF}{$ENDIF} end; {$IFDEF DELPHI10UP}{$ENDREGION}{$ENDIF} @@ -381,6 +442,9 @@ procedure RIRegisterTCHECKBOX(Cl: TPSRuntimeClassImporter); procedure RIRegisterTRADIOBUTTON(Cl: TPSRuntimeClassImporter); begin Cl.Add(TRadioButton); + {$IFDEF UNICODE}{$IFNDEF FPC} + RIRegisterKeyPressHelper(Cl.FindClass('TRadioButton')); + {$ENDIF}{$ENDIF} end; {$IFDEF DELPHI10UP}{$ENDREGION}{$ENDIF} @@ -423,7 +487,7 @@ procedure RIRegisterTCUSTOMLISTBOX(Cl: TPSRuntimeClassImporter); RegisterPropertyHelper(@TCustomListBox.SELECTED_R, @TCustomListBox.SELECTED_W, 'Selected'); {$IFNDEF PS_MINIVCL} - RegisterMethod(@TCustomListBox.CLEAR, 'Clear'); + RegisterMethod(@TCustomListBoxClear_P, 'Clear'); RegisterMethod(@TCustomListBox.ITEMATPOS, 'ItemAtPos'); RegisterMethod(@TCustomListBox.ITEMRECT, 'ItemRect'); RegisterPropertyHelper(@TCustomListBox.CANVAS_R, nil, 'Canvas'); @@ -455,7 +519,7 @@ procedure RIRegisterTCUSTOMLISTBOX(Cl: TPSRuntimeClassImporter); RegisterPropertyHelper(@TCUSTOMLISTBOXSELECTED_R, @TCUSTOMLISTBOXSELECTED_W, 'Selected'); {$IFNDEF PS_MINIVCL} - RegisterMethod(@TCUSTOMLISTBOX.CLEAR, 'Clear'); + RegisterMethod(@TCustomListBoxClear_P, 'Clear'); RegisterMethod(@TCUSTOMLISTBOX.ITEMATPOS, 'ItemAtPos'); RegisterMethod(@TCUSTOMLISTBOX.ITEMRECT, 'ItemRect'); RegisterPropertyHelper(@TCUSTOMLISTBOXCANVAS_R, nil, 'Canvas'); @@ -470,6 +534,9 @@ procedure RIRegisterTCUSTOMLISTBOX(Cl: TPSRuntimeClassImporter); procedure RIRegisterTLISTBOX(Cl: TPSRuntimeClassImporter); begin Cl.Add(TListBox); + {$IFDEF UNICODE}{$IFNDEF FPC} + RIRegisterKeyPressHelper(Cl.FindClass('TListBox')); + {$ENDIF}{$ENDIF} end; {$IFDEF DELPHI10UP}{$ENDREGION}{$ENDIF} @@ -480,6 +547,9 @@ procedure RIRegisterTSCROLLBAR(Cl: TPSRuntimeClassImporter); begin RegisterMethod(@TSCROLLBAR.SETPARAMS, 'SetParams'); end; + {$IFDEF UNICODE}{$IFNDEF FPC} + RIRegisterKeyPressHelper(Cl.FindClass('TScrollBar')); + {$ENDIF}{$ENDIF} end; {$IFDEF DELPHI10UP}{$ENDREGION}{$ENDIF} diff --git a/Source/uPSRuntime.pas b/Source/uPSRuntime.pas index 95dd7803..c7354007 100644 --- a/Source/uPSRuntime.pas +++ b/Source/uPSRuntime.pas @@ -9,7 +9,7 @@ interface uses - {$IFNDEF FPC} {$IFDEF DELPHI2010UP} System.Rtti,{$ENDIF} {$ENDIF} + {$IFNDEF FPC} {$IFDEF DELPHIXE2UP} System.Rtti,{$ELSE}{$IFDEF DELPHI2010UP} Rtti,{$ENDIF}{$ENDIF} {$ENDIF} {$IFDEF FPC}{$IFDEF USEINVOKECALL}Rtti,{$ENDIF}{$ENDIF} SysUtils, uPSUtils{$IFDEF DELPHI6UP}, variants{$ENDIF} {$IFNDEF PS_NOIDISPATCH}{$IFDEF DELPHI3UP}, ActiveX, Windows{$ELSE}, Ole2{$ENDIF}{$ENDIF}; @@ -37,14 +37,8 @@ TPSRuntimeAttribute = class; PDWordArray = ^TDWordArray; TDWordArray = array[0..1023] of Cardinal; -{@link(TPSProcRec) - PIFProcRec is a pointer to a TIProcRec record} TPSProcRec = class; - TIFProcRec = TPSProcRec; TPSExternalProcRec = class; - TIFPSExternalProcRec = TPSExternalProcRec; - TIFExternalProcRec = TPSExternalProcRec; - PIFProcRec = TPSProcRec; PProcRec = ^TProcRec; TPSProcPtr = function(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStack): Boolean; @@ -64,6 +58,13 @@ TPSProcRec = class property Attributes: TPSRuntimeAttributes read FAttributes; end; + { The aliases follow the class bodies: XE3 and XE4 emit an alias declared before its class body into the C++ + header without its closing semicolon. } + TIFProcRec = TPSProcRec; +{@link(TPSProcRec) + PIFProcRec is a pointer to a TIProcRec record} + PIFProcRec = TPSProcRec; + TPSExternalProcRec = class(TPSProcRec) private FExt1: Pointer; @@ -84,6 +85,9 @@ TPSExternalProcRec = class(TPSProcRec) property ProcPtr: TPSProcPtr read FProcPtr write FProcPtr; end; + TIFPSExternalProcRec = TPSExternalProcRec; + TIFExternalProcRec = TPSExternalProcRec; + TPSInternalProcRec = class(TPSProcRec) private FData: PByteArray; @@ -607,6 +611,9 @@ TPSExec = class(TObject) FId: Pointer; FJumpFlag: Boolean; FCallCleanup: Boolean; + { the runs RunProc began, still going: a Stop in one of them leaves the + stack below it to whatever began the run } + FNestedRuns: Longint; FOnException: TPSOnException; function ReadData(var Data; Len: Cardinal): Boolean; function ReadLong(var b: Cardinal): Boolean; @@ -630,6 +637,10 @@ TPSExec = class(TObject) FExceptionStack: TPSList; + { the exceptions ExceptionProc has raised, wrapping: compared across a + call, it tells whether the callee raised one } + FRaisedCount: Cardinal; + FResources: TPSList; FExportedVars: TPSList; @@ -661,6 +672,7 @@ TPSExec = class(TObject) FOnRunLine: TPSOnLineEvent; FSpecialProcList: TPSList; + FOwnedImporters: TPSList; FRegProcs: TPSList; @@ -676,6 +688,7 @@ TPSExec = class(TObject) function InvokeExternalMethod(At: TPSTypeRec_ProcPtr; Slf, Ptr: Pointer): Boolean; + function PlatformInnerfuseCall(_Self, Address: Pointer; CallingConv: TPSCallingConvention; Params: TPSList; res: PPSVariantIFC): Boolean; function InnerfuseCall(_Self, Address: Pointer; CallingConv: TPSCallingConvention; Params: TPSList; res: PPSVariantIFC): Boolean; procedure RunLine; virtual; @@ -683,6 +696,9 @@ TPSExec = class(TObject) function ImportProc(const Name: ShortString; proc: TPSExternalProcRec): Boolean; Virtual; procedure ExceptionProc(proc, Position: Cardinal; Ex: TPSError; const s: tbtstring; NewObject: TObject); Virtual; + { the exception the top exception frame holds goes on unwinding, without + that frame } + procedure ResumeUnwinding; function FindSpecialProcImport(P: TPSOnSpecialProcImport): pointer; Public @@ -808,9 +824,26 @@ TPSStack = class(TPSList) FDataPtr: Pointer; FCapacity, FLength: Longint; + { after UseChunks the stack keeps its values in chunks (TPSStackChunk + records) that never move -- FChunkCount of them, FChunkIdx the one in + use; without it the data is one block, moved when it grows. The lists + are made long enough before anything changes, so that storing, moving + and freeing a chunk never allocates } + FChunked: Boolean; + FChunks: array of Pointer; + FChunkCount, + FChunkIdx: Longint; + { the native calls in progress, and the chunks a Clear released meanwhile: + kept until the last of those calls ends } + FNativeCalls: Longint; + FRetired: array of Pointer; + FRetiredCount: Longint; function GetItem(I: Longint): PPSVariant; procedure SetCapacity(const Value: Longint); procedure AdjustLength; + procedure NextChunk(aSize: Longint); + procedure NativeCallStarts; + procedure NativeCallEnds; public property DataPtr: Pointer read FDataPtr; @@ -826,6 +859,10 @@ TPSStack = class(TPSList) procedure Clear; {$IFDEF DELPHI5UP} reintroduce;{$ELSE} override; {$ENDIF} + { from now on the stack grows by adding a chunk, so its values never move: an + address into it stays valid until its value is popped } + procedure UseChunks; + function Push(TotalSize: Longint): PPSVariant; function PushType(aType: TPSTypeRec): PPSVariant; @@ -889,7 +926,22 @@ procedure FreePSVariantList(l: TPSList); function PIFVariantToVariant(Src: PIFVariant; var Dest: Variant): Boolean; function VariantToPIFVariant(Exec: TPSExec; const Src: Variant; Dest: PIFVariant): Boolean; function ParamAsVariable(const Modifier: tbtchar; aType: TPSTypeRec): Boolean; + +{ empty_methods_handler: the platforms where no native stub carries a call into a script + method, so MyAllMethodsHandler is empty and ResultAsRegister, which only the stubs use, + is not compiled. Defined here so that this interface can test it. } +{$ifdef fpc} + {$if defined(cpupowerpc) or defined(cpuarm) or defined(cpu64)} + {$define empty_methods_handler} + {$ifend} +{$else} + {$if defined(cpuarm) or defined(cpuarm64)} + {$define empty_methods_handler} + {$ifend} +{$endif} +{$ifndef empty_methods_handler} function ResultAsRegister(b: TPSTypeRec): Boolean; +{$endif} function PSGetRecField(const avar: TPSVariantIFC; Fieldno: Longint): TPSVariantIFC; function PSGetArrayField(const avar: TPSVariantIFC; Fieldno: Longint): TPSVariantIFC; @@ -1055,6 +1107,7 @@ TPSRuntimeClassImporter = class constructor Create; + { AutoFree: Exec owns the importer, which goes when Exec does } constructor CreateAndRegister(Exec: TPSExec; AutoFree: Boolean); destructor Destroy; override; @@ -1175,12 +1228,17 @@ procedure ODS_stack(stack: TPSStack);forward; RPS_OutOfMemory = 'Out Of Memory'; RPS_InterfaceNotSupported = 'Interface not supported'; RPS_UnknownError = 'Unknown error'; + RPS_HostRoutineAsMethod = 'A host routine cannot be called as a native event'; + RPS_EndedScriptMethod = 'A script routine cannot be called after its script has ended'; RPS_InvalidVariable = 'Invalid variable'; RPS_InvalidArray = 'Invalid array'; RPS_OLEError = 'OLE error %.8x'; RPS_UnknownProcedure = 'Unknown procedure'; +{$IFDEF FPC}{$IFDEF empty_methods_handler} + RPS_NoNativeMethodsHandler = 'A script method cannot be bound to a native event on this platform'; +{$ENDIF}{$ENDIF} RPS_NotEnoughParameters = 'Not enough parameters'; RPS_InvalidParameter = 'Invalid parameter'; RPS_TooManyParameters = 'Too many parameters'; @@ -1216,6 +1274,13 @@ TPSExceptionHandler = class ExceptionData: TPSError; ExceptionObject: TObject; ExceptionParam: tbtString; + { True while the frame's finally runs for the exception it holds in the + fields above, from the finally's start to its end, where the exception + goes on } + Unwinding: Boolean; + { where the exception the frame holds or handles was raised } + ExceptionProcNo, ExceptionPos: Cardinal; + procedure DropException; destructor Destroy; override; end; TPSHeader = packed record @@ -1259,6 +1324,30 @@ destructor TPSExceptionHandler.Destroy; inherited; end; +procedure TPSExceptionHandler.DropException; +begin + ExceptionObject.Free; + ExceptionObject := nil; + ExceptionData := ENoError; + ExceptionParam := ''; + Unwinding := False; +end; + +{ The frame whose except handler runs, nearest the top of aStack; nil when + none does. Frames of statements nested in the handler are above it. } +function _HandlerFrame(aStack: TPSList): TPSExceptionHandler; +var + lFrameIdx : Longint; +begin + for lFrameIdx := aStack.Count - 1 downto 0 do + begin + Result := aStack[lFrameIdx]; + if Result.ExceptOffset = Cardinal(InvalidVal -1) then + Exit; + end; + Result := nil; +end; + procedure P_CM_A; begin end; procedure P_CM_CA; begin end; procedure P_CM_P; begin end; @@ -1348,11 +1437,6 @@ procedure Set_membership(Item: Longint; Src: PByteArray; var Val: Boolean); end; -procedure RCIFreeProc(Sender: TPSExec; P: TPSRuntimeClassImporter); -begin - p.Free; -end; - function Trim(const s: tbtstring): tbtstring; begin Result := s; @@ -1424,41 +1508,46 @@ function uPadr(s: tbtunicodestring; i: longInt): tbtunicodestring; function MakeWString(const s: tbtunicodestring): tbtString; var i: Longint; - e: tbtString; + e: tbtunicodestring; b: boolean; + w: tbtunicodestring; begin - Result := tbtString(s); + { the text is built on the wide string and narrowed last: a character past + #255 is written by its number, and so is one from #128 that the host's + ANSI code page cannot hold -- a narrowing first could lose either } + w := s; i := 1; b := false; - while i <= length(result) do + while i <= length(w) do begin - if Result[i] = '''' then + if w[i] = '''' then begin if not b then begin b := true; - Insert('''', Result, i); + Insert('''', w, i); inc(i); end; - Insert('''', Result, i); + Insert('''', w, i); inc(i, 2); - end else if (Result[i] < #32) or (Result[i] > #255) then + end else if (w[i] < #32) or (w[i] > #255) or + ((w[i] > #127) and (tbtunicodestring(tbtString(w[i])) <> w[i])) then begin - e := '#'+inttostr(ord(Result[i])); - Delete(Result, i, 1); + e := tbtunicodestring('#'+inttostr(ord(w[i]))); + Delete(w, i, 1); if b then begin b := false; - Insert('''', Result, i); + Insert('''', w, i); inc(i); end; - Insert(e, Result, i); + Insert(e, w, i); inc(i, length(e)); end else begin if not b then begin b := true; - Insert('''', Result, i); + Insert('''', w, i); inc(i, 2); end else inc(i); @@ -1466,10 +1555,11 @@ function MakeWString(const s: tbtunicodestring): tbtString; end; if b then begin - Result := Result + ''''; + w := w + ''''; end; - if Result = '' then - Result := ''''''; + if w = '' then + w := ''''''; + Result := tbtString(w); end; {$ENDIF} function MakeString(const s: tbtString): tbtString; @@ -1539,6 +1629,10 @@ function SafeStr(const s: tbtString): tbtString; end; +{$IFNDEF DELPHI2009UP} +function UIntToStr(const Value: tbtu64): string; forward; +{$ENDIF} + function PropertyToString(Instance: TObject; PName: tbtString): tbtString; var s: tbtString; @@ -1563,26 +1657,59 @@ function PropertyToString(Instance: TObject; PName: tbtString): tbtString; end; pp := GetPropInfo(PTypeInfo(Instance.ClassInfo), string(s)); if pp = nil then begin Result := tbtstring(RPS_UnknownIdentifier); exit; end; + { a name after one that is no object names nothing } + if (PName <> '') and (pp^.PropType^.Kind <> tkClass) then + begin + Result := tbtstring(RPS_UnknownIdentifier); + exit; + end; case pp^.PropType^.Kind of - tkInteger: begin Result := IntToStr(GetOrdProp(Instance, pp)); exit; end; + tkInteger: + begin + { a Cardinal is read as the unsigned number it is } + if GetTypeData(pp^.PropType{$IFNDEF FPC}{$IFDEF DELPHI3UP}^{$ENDIF}{$ENDIF})^.OrdType = otULong then + Result := tbtString(SysUtils.IntToStr(Int64(Cardinal(GetOrdProp(Instance, pp))))) + else + Result := IntToStr(GetOrdProp(Instance, pp)); + exit; + end; tkChar, tkWChar: begin Result := '#'+IntToStr(GetOrdProp(Instance, pp)); exit; end; tkEnumeration: begin Result := tbtstring(GetEnumName(pp^.PropType{$IFNDEF FPC}{$IFDEF DELPHI3UP}^{$ENDIF}{$ENDIF}, GetOrdProp(Instance, pp))); exit; end; + {$IFDEF FPC} + { Free Pascal gives Boolean a kind of its own; written as Delphi writes it, by name } + tkBool: begin Result := tbtstring(GetEnumName(TypeInfo(Boolean), Ord(GetOrdProp(Instance, pp) <> 0))); exit; end; + {$ENDIF} {$IFNDEF PS_NOINT64} - tkInt64: begin Result := tbtString(SysUtils.IntToStr(GetInt64Prop(Instance, pp))); exit; end; + tkInt64: + begin + { a UInt64 -- its type's least value past its greatest, as the RTL's own + GetPropValue tells it -- is read as the unsigned number it is } + if GetTypeData(pp^.PropType{$IFNDEF FPC}{$IFDEF DELPHI3UP}^{$ENDIF}{$ENDIF})^.MinInt64Value > + GetTypeData(pp^.PropType{$IFNDEF FPC}{$IFDEF DELPHI3UP}^{$ENDIF}{$ENDIF})^.MaxInt64Value then + Result := tbtString(UIntToStr(tbtu64(GetInt64Prop(Instance, pp)))) + else + Result := tbtString(SysUtils.IntToStr(GetInt64Prop(Instance, pp))); + exit; + end; + {$IFDEF FPC} + { Free Pascal gives UInt64 a kind of its own: read as the unsigned number it is } + tkQWord: begin Result := tbtString(UIntToStr(tbtu64(GetInt64Prop(Instance, pp)))); exit; end; + {$ENDIF} {$ENDIF} tkFloat: begin Result := FloatToStr(GetFloatProp(Instance, PP)); exit; end; - tkString, tkLString: begin Result := ''''+tbtString(GetStrProp(Instance, PP))+''''; exit; end; + { a string as a string variable's is written } + tkString, tkLString{$IFDEF FPC}, tkAString{$ENDIF}: begin Result := MakeString(tbtString(GetStrProp(Instance, PP))); exit; end; tkSet: begin Result := '[Set]'; exit; end; tkClass: begin Instance := TObject(GetOrdProp(Instance, pp)); end; tkMethod: begin Result := '[Method]'; exit; end; tkVariant: begin Result := '[Variant]'; exit; end; {$IFDEF DELPHI6UP} {$IFNDEF PS_NOWIDESTRING} - tkWString: begin Result := ''''+tbtString(GetWideStrProp(Instance, pp))+''''; exit; end; + tkWString: begin Result := MakeWString(GetWideStrProp(Instance, pp)); exit; end; {$IFDEF DELPHI2009UP} - tkUString: begin Result := ''''+tbtString({$IFDEF DELPHI_TOKYO_UP}GetStrProp{$ELSE}GetUnicodeStrProp{$ENDIF}(Instance, pp))+''''; exit; end; + tkUString: begin Result := MakeWString({$IFDEF DELPHI_TOKYO_UP}GetStrProp{$ELSE}GetUnicodeStrProp{$ENDIF}(Instance, pp)); exit; end; {$ENDIF} {$ENDIF} {$ENDIF} @@ -1606,6 +1733,102 @@ function ClassVariantInfo(const pvar: TPSVariantIFC; const PropertyName: tbtStri else Result := tbtstring(RPS_InvalidType); end; +{$IFNDEF DELPHI2009UP} +{ The RTL has UIntToStr for a 64-bit value from Delphi 2009 on. The value is divided by ten in two + 32-bit halves because unsigned 64-bit arithmetic is not dependable on the oldest compilers. } +function UIntToStr(const Value: tbtu64): string; +var + Hi, Lo: Cardinal; + Temp: Int64; +begin + Hi := Int64Rec(Value).Hi; + Lo := Int64Rec(Value).Lo; + Result := ''; + repeat + Temp := (Int64(Hi mod 10) shl 32) or Int64(Lo); + Hi := Hi div 10; + Lo := Cardinal(Temp div 10); + Result := Chr(Ord('0') + Integer(Temp mod 10)) + Result; + until (Hi = 0) and (Lo = 0); +end; +{$ENDIF} + +{$IFNDEF DELPHI25UP} +{ The RTL has StrToUInt64 and StrToUInt64Def from Delphi XE6 on, and through 10.1 Berlin its + StrToUInt64Def answers 0 for a number past the 64-bit range instead of the default. So every + compiler before 10.2 Tokyo gets these. They read what Val reads for an unsigned value: leading + blanks, an optional plus sign -- or a minus sign before a value of zero --, decimal digits, or + hexadecimal digits after $, x or 0x. The value is built in two 32-bit halves because unsigned + 64-bit arithmetic is not dependable on the oldest compilers. } +function PSTryStrToUInt64(const S: string; var Value: tbtu64): Boolean; +var + Idx, Len, Digit, Base: Integer; + Hi, Lo: Cardinal; + Temp: Int64; + Any, Minus: Boolean; +begin + Result := False; + Len := Length(S); + Idx := 1; + while (Idx <= Len) and (S[Idx] = ' ') do + Inc(Idx); + Minus := (Idx <= Len) and (S[Idx] = '-'); + if (Idx <= Len) and ((S[Idx] = '+') or Minus) then + Inc(Idx); + Base := 10; + if (Idx <= Len) and ((S[Idx] = '$') or (S[Idx] = 'x') or (S[Idx] = 'X')) then + begin + Base := 16; + Inc(Idx); + end + else if (Idx < Len) and (S[Idx] = '0') and ((S[Idx + 1] = 'x') or (S[Idx + 1] = 'X')) then + begin + Base := 16; + Inc(Idx, 2); + end; + Hi := 0; + Lo := 0; + Any := False; + while Idx <= Len do + begin + case S[Idx] of + '0'..'9': Digit := Ord(S[Idx]) - Ord('0'); + 'a'..'f': Digit := Ord(S[Idx]) - Ord('a') + 10; + 'A'..'F': Digit := Ord(S[Idx]) - Ord('A') + 10; + else + Exit; + end; + if Digit >= Base then + Exit; + Temp := Int64(Lo) * Base + Digit; + Lo := Cardinal(Temp and $FFFFFFFF); + Temp := Int64(Hi) * Base + (Temp shr 32); + if (Temp shr 32) <> 0 then + Exit; + Hi := Cardinal(Temp and $FFFFFFFF); + Any := True; + Inc(Idx); + end; + if not Any or (Minus and ((Hi <> 0) or (Lo <> 0))) then + Exit; + Int64Rec(Value).Hi := Hi; + Int64Rec(Value).Lo := Lo; + Result := True; +end; + +function StrToUInt64(const S: string): tbtu64; +begin + if not PSTryStrToUInt64(S, Result) then + raise EConvertError.CreateFmt('''%s'' is not a valid integer value', [S]); +end; + +function StrToUInt64Def(const S: string; const Default: tbtu64): tbtu64; +begin + if not PSTryStrToUInt64(S, Result) then + Result := Default; +end; +{$ENDIF} + function PSVariantToString(const p: TPSVariantIFC; const ClassProperties: tbtString): tbtString; var i, n: Longint; @@ -1667,7 +1890,7 @@ function PSVariantToString(const p: TPSVariantIFC; const ClassProperties: tbtStr {$ENDIF} {$IFNDEF PS_NOINT64} btS64: str(tbts64(p.dta^), Result); - btU64: str(tbtu64(p.dta^), Result); + btU64: Result := tbtString(UIntToStr(tbtu64(p.dta^))); {$ENDIF} btStaticArray, btArray: begin @@ -1692,7 +1915,8 @@ function PSVariantToString(const p: TPSVariantIFC; const ClassProperties: tbtStr if b then begin if Result <> '' then Result := Result + ', '; - Result := Result + IntToStr(i+1); + { a member by its ordinal, as the in operator and Include number it } + Result := Result + IntToStr(i); end; end; Result := '[' + Result + ']'; @@ -1726,7 +1950,21 @@ function TIFErrorToString(x: TPSError; const Param: tbtString): tbtString; end; function PSErrorToString(x: TPSError; const Param: tbtString): tbtString; +{$IFDEF FPC} +var + lOrd: Integer; +{$ENDIF} begin + {$IFDEF FPC} + { Free Pascal, optimising, jumps through an unbounded table for a case that + names every value: a value past the enumeration is answered here, as the + else below answers it on Delphi } + lOrd := Ord(x); + if (lOrd < Ord(Low(TPSError))) or (lOrd > Ord(High(TPSError))) then begin + Result := tbtString(RPS_UnknownError); + Exit; + end; + {$ENDIF} case x of ErNoError: Result := tbtString(RPS_NoError); erCannotImport: Result := tbtString(Format (RPS_CannotImport, [Safestr(Param)])); @@ -1936,12 +2174,32 @@ function IsManagedType(aType: TPSTypeRec): Boolean; end; end; +{$IFNDEF PS_NOINTERFACES} +{ stores an interface reference in Delphi's order (_IntfCopy, _IntfClear): + the variable holds the new value before the old one is released, so what + the release runs (a native destructor running a script event) does not + find the old value there, nor copy it out when it moves the container. + Free Pascal's own interface assignment releases first. } +procedure SetInterfaceVar(var Dest: Pointer; Source: Pointer); +var + lOld: Pointer; +begin + if Source <> nil then + IUnknown(Source)._AddRef; + lOld := Dest; + Dest := Source; + if lOld <> nil then + IUnknown(lOld)._Release; +end; +{$ENDIF} + procedure FinalizeVariant(p: Pointer; aType: TPSTypeRec); var t: TPSTypeRec; elsize: Cardinal; i, l: Longint; darr: PDynArrayRec; + lBlock: Pointer; begin case aType.BaseType of btString: tbtString(p^) := ''; @@ -1955,7 +2213,7 @@ procedure FinalizeVariant(p: Pointer; aType: TPSTypeRec); if IUnknown(p^) <> nil then IUnknown(p^).Release; {$ENDIF} - IUnknown(p^) := nil; + SetInterfaceVar(Pointer(p^), nil); end; {$ENDIF} btVariant: begin @@ -1967,16 +2225,27 @@ procedure FinalizeVariant(p: Pointer; aType: TPSTypeRec); btPointer: if Pointer(Pointer(IPointer(p)+PointerSize2)^) <> nil then begin - DestroyHeapVariant2(Pointer(p^), Pointer(Pointer(IPointer(p)+PointerSize)^)); + { taken out of the slot before it is destroyed, as an interface + variable is cleared before its release: what the destruction runs + (a native destructor running a script event) does not reach the + value through the slot } + lBlock := Pointer(p^); Pointer(p^) := nil; + DestroyHeapVariant2(lBlock, Pointer(Pointer(IPointer(p)+PointerSize)^)); end; btArray: begin if IPointer(P^) = 0 then exit; darr := PDynArrayRec(IPointer(p^) - sizeof(TDynArrayRecHeader)); + { emptied first, whoever else shares the block, as Delphi's + _DynArrayClear empties the variable before it releases the block: + what a finalization runs (a native destructor running a script + event) does not reach the block through this variable } + Pointer(P^) := nil; if darr^.header.refCnt < 0 then exit;// refcount < 0 means don't free Dec(darr^.header.refCnt); if darr^.header.refCnt <> 0 then exit; + lBlock := darr; t := TPSTypeRec_Array(aType).ArrayType; elsize := t.RealSize; {$IFDEF FPC} @@ -1997,8 +2266,7 @@ procedure FinalizeVariant(p: Pointer; aType: TPSTypeRec); end; end; end; - FreeMem(Pointer(IPointer(p^) - SizeOf(TDynArrayRecHeader)), IPointer(Cardinal(l) * elsize) + SizeOf(TDynArrayRecHeader)); - Pointer(P^) := nil; + FreeMem(lBlock, IPointer(Cardinal(l) * elsize) + SizeOf(TDynArrayRecHeader)); end; btRecord: begin @@ -2048,6 +2316,12 @@ function CreateHeapVariant(aType: TPSTypeRec): PPSVariant; var aSize: Longint; begin + { a type the loaded script lacks gives no value, which the helpers refuse } + if aType = nil then + begin + Result := nil; + exit; + end; aSize := aType.RealSize + RTTISize; GetMem(Result, aSize); Result.FType := aType; @@ -2134,28 +2408,44 @@ procedure TPSExec.Clear; pp := FExceptionStack.Data^[i]; pp.Free; end; - for i := Longint(FResources.Count) -1 downto 0 do + FExceptionStack.Clear; + { the script's values are released while the script can still run: what a + release runs (a native destructor running a script event) needs the + method records among the resources, the procs and the types -- and the + locals an unhandled error left on the stack go before the globals, which + their events may use } + FStack.Clear; + FTempVars.Clear; + FGlobalVars.Clear; + { each resource is taken out of the list before its release runs: a host + looking a resource up from a release sees only those not yet released, + and one it adds is released here too } + while FResources.Count > 0 do begin - Temp := FResources.Data^[i]; - Proc := Temp^.Proc; - Proc(Self, Temp^.P); - Dispose(Temp); + Temp := FResources.Data^[Pred(Longint(FResources.Count))]; + FResources.DeleteLast; + try + Proc := Temp^.Proc; + Proc(Self, Temp^.P); + finally + Dispose(Temp); + end; end; for i := Longint(FExportedVars.Count) -1 downto 0 do Dispose(PPSExportedVar(FExportedVars.Data^[I])); for I := Longint(FProcs.Count) - 1downto 0 do TPSProcRec(FProcs.Data^[i]).Destroy; FProcs.Clear; - FGlobalVars.Clear; - FStack.Clear; - FTempVars.Clear; for I := Longint(FTypes.Count) - 1downto 0 do TPSTypeRec(FTypes.Data^[i]).Free; FTypes.Clear; + { nothing refers to the destroyed procs } + FCurrProc := nil; + FData := nil; + FDataLength := 0; FStatus := isNotLoaded; FResources.Clear; FExportedVars.Clear; - FExceptionStack.Clear; FCurrStackBase := InvalidVal; end; @@ -2175,6 +2465,7 @@ constructor TPSExec.Create; FRegProcs := TPSList.Create; FExportedVars := TPSList.create; FSpecialProcList := TPSList.Create; + FOwnedImporters := TPSList.Create; RegisterStandardProcs; FReturnAddressType := TPSTypeRec.Create(self); FReturnAddressType.BaseType := btReturnAddress; @@ -2187,6 +2478,7 @@ constructor TPSExec.Create; FVariantArrayType.CalcSize; TPSTypeRec_Array(FVariantArrayType).ArrayType := FVariantType; FStack := TPSStack.Create; + FStack.UseChunks; end; destructor TPSExec.Destroy; @@ -2206,6 +2498,9 @@ destructor TPSExec.Destroy; P := FSpecialProcList.Data^[I]; Dispose(p); end; + for I := Pred(FOwnedImporters.Count) downto 0 do + TObject(FOwnedImporters.Data^[I]).Free; + FOwnedImporters.Free; FResources.Free; FExportedVars.Free; FTempVars.Free; @@ -2234,6 +2529,22 @@ procedure TPSExec.ExceptionProc(proc, Position: Cardinal; Ex: TPSError; const s: var d, l: Longint; pp: TPSExceptionHandler; + + { aFrame's finally runs for the exception: the frame holds it until the + finally ends, so that what the finally does cannot take it } + procedure HoldIn(aFrame: TPSExceptionHandler); + begin + aFrame.DropException; + aFrame.Unwinding := True; + aFrame.ExceptionProcNo := ExProc; + aFrame.ExceptionPos := ExPos; + aFrame.ExceptionData := ExEx; + aFrame.ExceptionParam := ExParam; + aFrame.ExceptionObject := ExObject; + ExObject := nil; + ExEx := ENoError; + end; + begin ExProc := proc; ExPos := Position; @@ -2243,9 +2554,16 @@ procedure TPSExec.ExceptionProc(proc, Position: Cardinal; Ex: TPSError; const s: ExObject.Free; ExObject := NewObject; if Ex = eNoError then Exit; + if FRaisedCount = High(Cardinal) then + FRaisedCount := 0 + else + Inc(FRaisedCount); for d := FExceptionStack.Count -1 downto 0 do begin pp := FExceptionStack[d]; + { an exception escaping a finally replaces the one the finally ran for } + if pp.Unwinding then + pp.DropException; if Cardinal(FStack.Count) > pp.StackSize then begin for l := Longint(FStack.count) -1 downto Longint(pp.StackSize) do @@ -2257,7 +2575,9 @@ procedure TPSExec.ExceptionProc(proc, Position: Cardinal; Ex: TPSError; const s: FExceptionStack.DeleteLast; FCurrStackBase := InvalidVal; - FStatus := isPaused; + { a Stop made before the exception stands } + if FStatus = isRunning then + FStatus := isPaused; exit; end; FCurrProc := pp.CurrProc; @@ -2269,11 +2589,16 @@ procedure TPSExec.ExceptionProc(proc, Position: Cardinal; Ex: TPSError; const s: begin FCurrentPosition := pp.FinallyOffset; pp.FinallyOffset := InvalidVal; + HoldIn(pp); Exit; end else if (pp.ExceptOffset <> InvalidVal) and (pp.ExceptOffset <> Cardinal(InvalidVal -1)) then begin FCurrentPosition := pp.ExceptOffset; pp.ExceptOffset := Cardinal(InvalidVal -1); + { the exception cancels the jump whose finally raised it } + pp.ExitPoint := InvalidVal; + pp.ExceptionProcNo := ExProc; + pp.ExceptionPos := ExPos; pp.ExceptionObject := ExObject; pp.ExceptionData := ExEx; pp.ExceptionParam := ExParam; @@ -2284,15 +2609,40 @@ procedure TPSExec.ExceptionProc(proc, Position: Cardinal; Ex: TPSError; const s: begin FCurrentPosition := pp.Finally2Offset; pp.Finally2Offset := InvalidVal; + { the except before the second finally is over } + pp.ExceptOffset := InvalidVal; + HoldIn(pp); Exit; end; pp.Free; FExceptionStack.DeleteLast; end; - if FStatus <> isNotLoaded then + { a Stop made before the exception stands } + if FStatus = isRunning then FStatus := isPaused; end; +procedure TPSExec.ResumeUnwinding; +var + pp : TPSExceptionHandler; + lProcNo : Cardinal; + lPos : Cardinal; + lData : TPSError; + lParam : tbtString; + lObject : TObject; +begin + pp := FExceptionStack[FExceptionStack.Count -1]; + lProcNo := pp.ExceptionProcNo; + lPos := pp.ExceptionPos; + lData := pp.ExceptionData; + lParam := pp.ExceptionParam; + lObject := pp.ExceptionObject; + pp.ExceptionObject := nil; + pp.Free; + FExceptionStack.DeleteLast; + ExceptionProc(lProcNo, lPos, lData, lParam, lObject); +end; + function LookupProc(List: TPSList; const Name: ShortString): PProcRec; var h, l: Longint; @@ -2596,6 +2946,16 @@ function TPSExec.LoadData(const s: tbtString): Boolean; l2, l: Longint; d: Cardinal; + { the sum of a record's field sizes, which the Longint offsets below wrap } + function RecordSize(Dta: TPSTypeRec_Record): Int64; + var + l: Longint; + begin + Result := 0; + for l := 0 to Dta.FieldTypes.Count -1 do + Result := Result + TPSTypeRec(Dta.FieldTypes[l]).RealSize; + end; + function resolve(Dta: TPSTypeRec_Record): Boolean; var offs, l: Longint; @@ -2843,6 +3203,16 @@ function TPSExec.LoadData(const s: tbtString): Boolean; Curr.ExportNameHash := MakeHash(Curr.ExportName); end; curr.CalcSize; + { a static array whose size a Longint cannot hold got a wrapped size, which every allocation then trusted } + if ((curr is TPSTypeRec_StaticArray) and (Int64(TPSTypeRec_StaticArray(curr).ArrayType.RealSize) * + TPSTypeRec_StaticArray(curr).Size > High(Longint))) or + { so did a record whose fields' sizes sum past it } + ((curr is TPSTypeRec_Record) and (RecordSize(TPSTypeRec_Record(curr)) > High(Longint))) then + begin + cmd_err(erInvalidType); + LoadTypes := False; + exit; + end; if HDR.PSBuildNo >= 21 then // since build 21 we support attributes begin if not ReadAttributes(Curr.Attributes) then @@ -3037,8 +3407,10 @@ function TPSExec.LoadData(const s: tbtString): Boolean; dispose(e); cmd_err(erInvalidType); LoadVars := False; - exit; end; + { left after the handler: Delphi XE3 to XE5 for Win64 keep the exception object of a handler left by a jump } + if not Result then + exit; end; end; end; @@ -3090,7 +3462,9 @@ function TPSExec.LoadData(const s: tbtString): Boolean; procedure TPSExec.Pause; begin - if FStatus = isRunning then + { a run RunProc began cannot be left part way to be resumed: its caller + gets control back when it ends, so it runs on } + if (FStatus = isRunning) and (FNestedRuns = 0) then FStatus := isPaused; end; @@ -3451,23 +3825,8 @@ function PSGetUInt(Src: Pointer; aType: TPSTypeRec): Cardinal; {$ENDIF} btChar: Result := Ord(tbtchar(Src^)); {$IFNDEF PS_NOWIDESTRING} btWideChar: Result := Ord(tbtwidechar(Src^));{$ENDIF} - btVariant: - case VarType(Variant(Src^)) of - varString: - if Length(VarToStr(Variant(Src^))) = 1 then - Result := Ord(VarToStr(Variant(Src^))[1]) - else - raise Exception.Create(RPS_TypeMismatch); -{$IFNDEF PS_NOWIDESTRING} - varOleStr: - if Length(VarToWideStr(Variant(Src^))) = 1 then - Result := Ord(VarToWideStr(Variant(Src^))[1]) - else - raise Exception.Create(RPS_TypeMismatch); -{$ENDIF} - else - Result := Variant(src^); - end; + { a Variant converts as Delphi converts it, as PSGetInt does: text holding a number gives the number } + btVariant: Result := Variant(src^); else raise Exception.Create(RPS_TypeMismatch); end; end; @@ -3530,6 +3889,17 @@ function PSGetInt64(Src: Pointer; aType: TPSTypeRec): Int64; end; end; +{ the base type of a value, followed through a pointer: a division by a 64-bit divisor keeps its 64 bits } +function _DivisorBaseType(Src: Pointer; aType: TPSTypeRec): TPSBaseType; +begin + if aType.BaseType = btPointer then + aType := PIFTypeRec(Pointer(IPointer(Src)+PointerSize)^); + if aType = nil then + Result := btPointer + else + Result := aType.BaseType; +end; + function PSGetUInt64(Src: Pointer; aType: TPSTypeRec): UInt64; begin if aType.BaseType = btPointer then @@ -3647,7 +4017,7 @@ function PSGetAnsiChar(Src: Pointer; aType: TPSTypeRec): tbtchar; begin Res := PSGetAnsiString(Src,aType); if Length(Res) > 0 then - Result := Res[{$IFDEF DELPHI2009UP}Low(Res){$ELSE}1{$ENDIF}] + Result := Res[{$IFDEF DELPHI17UP}Low(Res){$ELSE}1{$ENDIF}] else Result := #0; end; @@ -4056,6 +4426,77 @@ procedure PSSetString(Src: Pointer; aType: TPSTypeRec; var Ok: Boolean; const Va function CopyArrayContents(dest, src: Pointer; Len: Longint; aType: TPSTypeRec): Boolean; forward; +function IsZeroBlock(p: Pointer; Size: Cardinal): Boolean; +var + lIdx: Cardinal; +begin + Result := False; + lIdx := 0; + while lIdx < Size do + begin + if PAnsiChar(IPointer(p) + lIdx)^ <> #0 then + exit; + Inc(lIdx); + end; + Result := True; +end; + +{ whether releasing a value of the type can run code: an interface, or what + may hold one (a string's release runs none) } +function ReleaseCanRunCode(aType: TPSTypeRec): Boolean; +var + lIdx: Longint; +begin + case aType.BaseType of + btArray, btVariant, btPointer{$IFNDEF PS_NOINTERFACES}, btInterface{$ENDIF}: + Result := True; + btStaticArray: + Result := ReleaseCanRunCode(TPSTypeRec_Array(aType).ArrayType); + btRecord: + begin + Result := True; + for lIdx := 0 to TPSTypeRec_Record(aType).FieldTypes.Count -1 do + if ReleaseCanRunCode(TPSTypeRec_Record(aType).FieldTypes[lIdx]) then + exit; + Result := False; + end; + else + Result := False; + end; +end; + +{ copies into a destination that holds a value: its old contents are moved + out first and released only after the copy, as Delphi's _IntfCopy orders + an interface, so what the release runs (a native destructor running a + script event) finds the destination assigned, and may change or free + the container it lies in } +function ReplaceArrayContents(dest, src: Pointer; Len: Longint; aType: TPSTypeRec): Boolean; +var + lSize: Cardinal; + lOld: Pointer; + lBuf: array[0..255] of Byte; + lIdx: Longint; +begin + lSize := Cardinal(Len) * aType.RealSize; + if lSize <= SizeOf(lBuf) then + lOld := @lBuf + else + GetMem(lOld, lSize); + try + Move(dest^, lOld^, lSize); + FillChar(dest^, lSize, 0); + Result := CopyArrayContents(dest, src, Len, aType); + finally + try + for lIdx := 0 to Len - 1 do + FinalizeVariant(Pointer(IPointer(lOld) + Cardinal(lIdx) * aType.RealSize), aType); + finally + if lOld <> @lBuf then + FreeMem(lOld); + end; + end; +end; + function CopyRecordContents(dest, src: Pointer; aType: TPSTypeRec_Record): Boolean; var o, i: Longint; @@ -4068,23 +4509,38 @@ function CopyRecordContents(dest, src: Pointer; aType: TPSTypeRec_Record): Boole Result := true; end; +{ src by value: converting an element can run host code (a custom variant + type's cast, copy or clear) that runs a script event, which can free or + replace the script variable the caller's Variant lives in -- the copy is + what the conversion reads } function CreateArrayFromVariant(Exec: TPSExec; dest: Pointer; src: Variant; DestType: TPSTypeRec): Boolean; var i: Integer; r: Pointer; lVarType: TPSTypeRec; v: variant; + lElType: TPSTypeRec; + lNewArr: Pointer; begin lVarType := Exec.FindType2(btVariant); - if lVarType = nil then begin result := false; exit; end; - PSDynArraySetLength(Pointer(dest^), desttype, VarArrayHighBound(src, 1) - VarArrayLowBound(src, 1) + 1); - r := Pointer(Dest^); - DestType := TPSTypeRec_Array(DestType).ArrayType; - for i := 0 to VarArrayHighBound(src, 1) - VarArrayLowBound(src, 1) do begin - v := src[i + VarArrayLowBound(src, 1)]; - if not Exec.SetVariantValue(r, @v, desttype, lVarType) then begin result := false; exit; end; - //r := Pointer(IPointer(r) + Longint(DestType.RealSize)); - r := Pointer(IPointer(r) + DestType.RealSize); + if lVarType = nil then begin Exec.CMD_Err(ErTypeMismatch); result := false; exit; end; + { built apart and then assigned: releasing the destination's old + elements (a native destructor running a script event) comes after the + destination holds the new array, and a failed conversion leaves it as + it was } + lNewArr := nil; + PSDynArraySetLength(lNewArr, desttype, VarArrayHighBound(src, 1) - VarArrayLowBound(src, 1) + 1); + try + r := lNewArr; + lElType := TPSTypeRec_Array(DestType).ArrayType; + for i := 0 to VarArrayHighBound(src, 1) - VarArrayLowBound(src, 1) do begin + v := src[i + VarArrayLowBound(src, 1)]; + if not Exec.SetVariantValue(r, @v, lElType, lVarType) then begin result := false; exit; end; + r := Pointer(IPointer(r) + lElType.RealSize); + end; + CopyArrayContents(dest, @lNewArr, 1, DestType); + finally + FinalizeVariant(@lNewArr, DestType); end; Result := true; end; @@ -4093,7 +4549,26 @@ function CopyArrayContents(dest, src: Pointer; Len: Longint; aType: TPSTypeRec): var elsize: Cardinal; i: Longint; + lSrcArr: Pointer; begin + { a copy onto itself changes nothing, as in Delphi: releasing the destination first would release the + source } + if dest = src then + begin + Result := True; + exit; + end; + { a destination whose release can run code (an interface, and what may + hold one) is replaced: see ReplaceArrayContents. A source overlapping + the destination is copied in place. } + if (Len > 0) and ReleaseCanRunCode(aType) and + not IsZeroBlock(dest, Cardinal(Len) * aType.RealSize) and + ((IPointer(src) >= IPointer(dest) + Cardinal(Len) * aType.RealSize) or + (IPointer(dest) >= IPointer(src) + Cardinal(Len) * aType.RealSize)) then + begin + Result := ReplaceArrayContents(dest, src, Len, aType); + exit; + end; try case aType.BaseType of btU8, btS8, btChar: @@ -4221,15 +4696,15 @@ function CopyArrayContents(dest, src: Pointer; Len: Longint; aType: TPSTypeRec): begin for i := 0 to Len -1 do begin + { the source is taken, with its reference, before the destination is + released, as Delphi's _DynArrayAsg takes it: what the release runs + (a native destructor running a script event) can empty the source } + lSrcArr := Pointer(Src^); + if lSrcArr <> nil then + Inc(PDynArrayRec(PAnsiChar(lSrcArr) - SizeOf(TDynArrayRecHeader))^.header.refCnt); if Pointer(Dest^) <> nil then - begin PSDynArraySetLength(Pointer(Dest^), aType, 0); - end; - Pointer(Dest^) := Pointer(Src^); - if Pointer(Dest^) <> nil then - begin - Inc(PDynArrayRec(PAnsiChar(Dest^) - SizeOf(TDynArrayRecHeader))^.header.refCnt); - end; + Pointer(Dest^) := lSrcArr; Dest := Pointer(IPointer(Dest) + PointerSize); Src := Pointer(IPointer(Src) + PointerSize); end; @@ -4270,7 +4745,7 @@ function CopyArrayContents(dest, src: Pointer; Len: Longint; aType: TPSTypeRec): IUnknown(Dest^) := nil; end; {$ENDIF} - IUnknown(Dest^) := IUnknown(Src^); + SetInterfaceVar(Pointer(Dest^), Pointer(Src^)); {$IFNDEF DELPHI3UP} if IUnknown(Dest^) <> nil then IUnknown(Dest^).AddRef; @@ -4282,7 +4757,9 @@ function CopyArrayContents(dest, src: Pointer; Len: Longint; aType: TPSTypeRec): {$ENDIF} btPointer: begin - if (Pointer(Pointer(IPointer(Dest)+PointerSize2)^) = nil) and (Pointer(Pointer(IPointer(Src)+PointerSize2)^) = nil) then + { the borrowed copy for one element: of several, a later one may own + its value, which the loop below copies } + if (Len = 1) and (Pointer(Pointer(IPointer(Dest)+PointerSize2)^) = nil) and (Pointer(Pointer(IPointer(Src)+PointerSize2)^) = nil) then begin for i := 0 to Len -1 do begin @@ -4336,11 +4813,11 @@ function CopyArrayContents(dest, src: Pointer; Len: Longint; aType: TPSTypeRec): Result := False; exit; end; + Result := true; except + { left after the handler: Delphi XE3 to XE5 for Win64 keep the exception object of a handler left by a jump } Result := False; - exit; end; - Result := true; end; function GetPSArrayLength(Arr: PIFVariant): Longint; @@ -4364,38 +4841,71 @@ procedure PSDynArraySetLength(var arr: Pointer; aType: TPSTypeRec; NewLength: Lo var elSize, i, OldLen: Longint; darr : PDynArrayRec; + lRemoved: Pointer; begin if aType.BaseType <> btArray then raise Exception.Create(RPS_InvalidArray); OldLen := PSDynArrayGetLength(arr, aType); elSize := TPSTypeRec_Array(aType).ArrayType.RealSize; if NewLength<0 then NewLength:=0; + { the size below is a Longint: a length whose size it cannot hold allocated a few bytes and initialised + the whole length past them } + if (NewLength > 0) and (TPSTypeRec_Array(aType).ArrayType.RealSize > 0) and + (NewLength > (High(Longint) - SizeOf(TDynArrayRecHeader)) div Longint(TPSTypeRec_Array(aType).ArrayType.RealSize)) then + raise Exception.Create(RPS_OutOfRange); if (OldLen = 0) and (NewLength = 0) then exit; // already are both 0 - if (OldLen = NewLength) then exit; // already same size, noop + { at its length already: nothing to do unless another variable shares the array -- Delphi's SetLength + makes it unique } + if (OldLen = NewLength) and (PDynArrayRec(PAnsiChar(Arr) - SizeOf(TDynArrayRecHeader))^.header.refCnt = 1) then + exit; darr := PDynArrayRec(PAnsiChar(Arr) - SizeOf(TDynArrayRecHeader)); if (OldLen <> 0) and (darr^.header.refCnt = 1) then // unique copy of this dynamic array begin - for i := NewLength to OldLen -1 do - begin - if TPSTypeRec_Array(aType).ArrayType.BaseType in NeedFinalization then - FinalizeVariant(Pointer(IPointer(arr) + Cardinal(elsize * i)), TPSTypeRec_Array(aType).ArrayType); - end; if NewLength <= 0 then begin - FreeMem(darr); + { emptied before its elements are finalized, as Delphi's _DynArrayClear + empties the variable first: what a finalization runs (a native + destructor running a script event) does not reach the block freed here } arr := nil; + if TPSTypeRec_Array(aType).ArrayType.BaseType in NeedFinalization then + for i := 0 to OldLen -1 do + FinalizeVariant(Pointer(IPointer(@darr^.datas) + Cardinal(elsize * i)), TPSTypeRec_Array(aType).ArrayType); + FreeMem(darr); exit; end; - ReallocMem(darr, Longint(NewLength * elSize) + SizeOf(TDynArrayRecHeader)); - {$IFDEF FPC} - darr^.header.high := NewLength -1; - {$ELSE} - darr^.header.length := NewLength; - {$ENDIF} - arr := @darr^.datas; - for i := OldLen to NewLength -1 do + { the elements a shrink removes are moved out and the array shortened + before they are finalized, as an assignment stores its new value + before it releases the old one: what a finalization runs (a native + destructor running a script event) finds the array at its new length, + and what it does to the array stands. When the smaller block cannot + be had, the array keeps its length, the removed elements emptied. } + lRemoved := nil; + if (NewLength < OldLen) and (TPSTypeRec_Array(aType).ArrayType.BaseType in NeedFinalization) then begin - InitializeVariant(Pointer(IPointer(arr) + Cardinal(elsize * i)), TPSTypeRec_Array(aType).ArrayType); + GetMem(lRemoved, (OldLen - NewLength) * elSize); + Move(Pointer(IPointer(arr) + Cardinal(elsize * NewLength))^, lRemoved^, (OldLen - NewLength) * elSize); + FillChar(Pointer(IPointer(arr) + Cardinal(elsize * NewLength))^, (OldLen - NewLength) * elSize, 0); + end; + try + ReallocMem(darr, Longint(NewLength * elSize) + SizeOf(TDynArrayRecHeader)); + {$IFDEF FPC} + darr^.header.high := NewLength -1; + {$ELSE} + darr^.header.length := NewLength; + {$ENDIF} + arr := @darr^.datas; + for i := OldLen to NewLength -1 do + begin + InitializeVariant(Pointer(IPointer(arr) + Cardinal(elsize * i)), TPSTypeRec_Array(aType).ArrayType); + end; + finally + if lRemoved <> nil then + try + for i := 0 to OldLen - NewLength - 1 do + FinalizeVariant(Pointer(IPointer(lRemoved) + Cardinal(elsize * i)), TPSTypeRec_Array(aType).ArrayType); + finally + FreeMem(lRemoved); + end; end; end else begin @@ -4517,18 +5027,84 @@ procedure AssignIDispatchFromVariant(var Dest: IDispatch; const Src: Variant); end; {$ENDIF} -function TPSExec.SetVariantValue(dest, Src: Pointer; desttype, srctype: TPSTypeRec): Boolean; +{ moves aNew into the Variant at dest, leaving aNew empty, and only then + releases the value dest held: Delphi's own Variant assignment releases + first, and what a release runs (a native destructor running a script + event) can move or free the container dest lies in } +procedure MoveIntoVariant(dest: Pointer; var aNew: Variant); var - Tmp: TObject; + lOld: Variant; +begin + { the old value moves out and the new one in; lOld is released when + this routine ends } + Move(dest^, lOld, SizeOf(TVarData)); + Move(aNew, dest^, SizeOf(TVarData)); + FillChar(aNew, SizeOf(TVarData), 0); +end; + +{ stores a copy of aNew into the Variant at dest by MoveIntoVariant } +procedure StoreVariant(dest: Pointer; const aNew: Variant); +var + lNew: Variant; +begin + lNew := aNew; + MoveIntoVariant(dest, lNew); +end; + +{ SetVariantValue's Variant destination: the new value is made apart and + then moved in by MoveIntoVariant } +function SetVariantFromValue(Exec: TPSExec; dest, src: Pointer; srctype: TPSTypeRec): Boolean; +var + lNew: Variant; tt: TPSVariantPointer; begin Result := True; - try - case desttype.BaseType of - btSet: - begin - if desttype = srctype then - Move(Src^, Dest^, TPSTypeRec_Set(desttype).aByteSize) +{$IFNDEF PS_NOINTERFACES} + if srctype.ExportName = 'IDISPATCH' then + begin + {$IFDEF DELPHI3UP} + lNew := IDispatch(src^); + {$ELSE} + AssignVariantFromIDispatch(lNew, IDispatch(src^)); + {$ENDIF} + end else +{$ENDIF} + if srctype.BaseType = btVariant then + begin + { a Variant assigned to itself changes nothing, as in Delphi } + if src = dest then + exit; + lNew := Variant(src^); + end else + begin + tt.VI.FType := Exec.FindType2(btPointer); + if tt.VI.FType = nil then + begin + Result := False; + exit; + end; + tt.DestType := srctype; + tt.DataDest := src; + tt.FreeIt := False; + Result := PIFVariantToVariant(@tt, lNew); + if not Result then + exit; + end; + MoveIntoVariant(dest, lNew); +end; + +function TPSExec.SetVariantValue(dest, Src: Pointer; desttype, srctype: TPSTypeRec): Boolean; +var + Tmp: TObject; + lNewArr: Pointer; +begin + Result := True; + try + case desttype.BaseType of + btSet: + begin + if desttype = srctype then + Move(Src^, Dest^, TPSTypeRec_Set(desttype).aByteSize) else Result := False; end; @@ -4758,7 +5334,20 @@ function TPSExec.SetVariantValue(dest, Src: Pointer; desttype, srctype: TPSTypeR end; end; btCurrency: tbtcurrency(Dest^) := PSGetCurrency(Src, srctype); - btPChar: pansichar(dest^) := pansichar(PSGetAnsiString(Src, srctype)); + btPChar: + begin + if srctype.BaseType = btPointer then + begin + srctype := PIFTypeRec(Pointer(IPointer(Src)+PointerSize)^); + Src := Pointer(Src^); + if (src = nil) or (srctype = nil) then raise Exception.Create(RPS_TypeMismatch); + end; + { a PChar takes the other's pointer, as in Delphi: a string made of its text would be freed here } + if srctype.BaseType = btPChar then + pansichar(dest^) := pansichar(src^) + else + pansichar(dest^) := pansichar(PSGetAnsiString(Src, srctype)); + end; btString: tbtstring(dest^) := PSGetAnsiString(Src, srctype); btChar: tbtchar(dest^) := PSGetAnsiChar(Src, srctype); @@ -4769,22 +5358,47 @@ function TPSExec.SetVariantValue(dest, Src: Pointer; desttype, srctype: TPSTypeR {$ENDIF} btStaticArray: begin + { here, for a static array assigned to a dynamic one, and for a record: + CopyArrayContents takes a failed copy's exception and answers False, and + the assignment is refused, as Delphi raises, rather than going on with + the destination partly copied } if desttype <> srctype then Result := False - else - CopyArrayContents(dest, Src, TPSTypeRec_StaticArray(desttype).Size, TPSTypeRec_StaticArray(desttype).ArrayType); + else if not CopyArrayContents(dest, Src, TPSTypeRec_StaticArray(desttype).Size, TPSTypeRec_StaticArray(desttype).ArrayType) then + Result := False; end; btArray: begin if (srctype.BaseType = btStaticArray) and (TPSTypeRec_Array(desttype).ArrayType = TPSTypeRec_Array(srctype).ArrayType) then begin - PSDynArraySetLength(Pointer(Dest^), desttype, TPSTypeRec_StaticArray(srctype).Size); - CopyArrayContents(Pointer(dest^), Src, TPSTypeRec_StaticArray(srctype).Size, TPSTypeRec_StaticArray(srctype).ArrayType); + { built apart and then assigned: releasing the destination's old + elements (a native destructor running a script event) comes + after the destination holds the new array } + lNewArr := nil; + PSDynArraySetLength(lNewArr, desttype, TPSTypeRec_StaticArray(srctype).Size); + try + if CopyArrayContents(lNewArr, Src, TPSTypeRec_StaticArray(srctype).Size, TPSTypeRec_StaticArray(srctype).ArrayType) then + CopyArrayContents(Dest, @lNewArr, 1, desttype) + else + Result := False; + finally + FinalizeVariant(@lNewArr, desttype); + end; end else if (srctype.BaseType = btvariant) and VarIsArray(Variant(src^)) then - Result := CreateArrayFromVariant(Self, dest, Variant(src^), desttype) - else if (desttype <> srctype) and not ((desttype.BaseType = btarray) and (srctype.BaseType = btArray) - and ((TPSTypeRec_Array(desttype).ArrayType.BaseType = TPSTypeRec_Array(srctype).ArrayType.BaseType) and - not (TPSTypeRec_Array(desttype).ArrayType.BaseType in [btRecord, btSet, btStaticArray, btArray]))) then + begin + { CreateArrayFromVariant has reported its failure: a second report would find the handler of the + try that took the first used up, and go on to an outer handler or stop the script } + if not CreateArrayFromVariant(Self, dest, Variant(src^), desttype) then + begin + Result := False; + exit; + end; + end else if (desttype <> srctype) and not ((desttype.BaseType = btarray) and (srctype.BaseType = btArray) + and (((TPSTypeRec_Array(desttype).ArrayType.BaseType = TPSTypeRec_Array(srctype).ArrayType.BaseType){$IFDEF WIDESTRING_EQUAL_UNICODESTRING}{$IFNDEF PS_NOWIDESTRING} or + ((TPSTypeRec_Array(desttype).ArrayType.BaseType in [btWideString, btUnicodeString]) and + (TPSTypeRec_Array(srctype).ArrayType.BaseType in [btWideString, btUnicodeString])){$ENDIF}{$ENDIF}) and + (not (TPSTypeRec_Array(desttype).ArrayType.BaseType in [btRecord, btSet, btStaticArray, btArray]) or + (TPSTypeRec_Array(desttype).ArrayType = TPSTypeRec_Array(srctype).ArrayType)))) then { ^ Comparing BaseType is needed because the compiler doesn't merge open array types and regular array types in ReadType (see the '!' check). Still it considers them compatible in IsCompatibleType, so we should check ArrayType.BaseType instead of @@ -4797,39 +5411,18 @@ function TPSExec.SetVariantValue(dest, Src: Pointer; desttype, srctype: TPSTypeR begin if desttype <> srctype then Result := False - else - CopyArrayContents(dest, Src, 1, desttype); + else if not CopyArrayContents(dest, Src, 1, desttype) then + Result := False; end; btVariant: - begin -{$IFNDEF PS_NOINTERFACES} - if srctype.ExportName = 'IDISPATCH' then - begin - {$IFDEF DELPHI3UP} - Variant(Dest^) := IDispatch(Src^); - {$ELSE} - AssignVariantFromIDispatch(Variant(Dest^), IDispatch(Src^)); - {$ENDIF} - end else -{$ENDIF} - if srctype.BaseType = btVariant then - variant(Dest^) := variant(src^) - else - begin - tt.VI.FType := FindType2(btPointer); - tt.DestType := srctype; - tt.DataDest := src; - tt.FreeIt := False; - Result := PIFVariantToVariant(@tt, variant(dest^)); - end; - end; + Result := SetVariantFromValue(Self, Dest, Src, srctype); btClass: begin if srctype.BaseType = btClass then TObject(Dest^) := TObject(Src^) else if srctype.BaseType = btVariant then - TbtU32(Dest^) := Variant(Src^) + {$IFDEF CPU64} TbtU64(Dest^) := Variant(Src^) {$ELSE} TbtU32(Dest^) := Variant(Src^) {$ENDIF} else // nx change start if (srctype.BaseType in {$IFDEF CPU64} [btU64, btS64] {$ELSE} [btU32, btS32] {$ENDIF}) then @@ -4856,7 +5449,10 @@ function TPSExec.SetVariantValue(dest, Src: Pointer; desttype, srctype: TPSTypeR end else if srctype.BaseType = btClass then begin - if (TObject(Src^) = nil) or not TObject(Src^).GetInterface(TPSTypeRec_Interface(desttype).Guid, IUnknown(Dest^)) then + { a nil object is a nil interface, as in Delphi } + if TObject(Src^) = nil then + SetInterfaceVar(Pointer(Dest^), nil) + else if not TObject(Src^).GetInterface(TPSTypeRec_Interface(desttype).Guid, IUnknown(Dest^)) then begin Result := false; Cmd_Err(erInterfaceNotSupported); @@ -4872,7 +5468,7 @@ function TPSExec.SetVariantValue(dest, Src: Pointer; desttype, srctype: TPSTypeR IUnknown(Dest^) := nil; end; {$ENDIF} - IUnknown(Dest^) := IUnknown(Src^); + SetInterfaceVar(Pointer(Dest^), Pointer(Src^)); {$IFNDEF Delphi3UP} if IUnknown(Dest^) <> nil then IUnknown(Dest^).AddRef; @@ -4990,6 +5586,167 @@ function TPSExec.DoBooleanCalc(var1, Var2, into: Pointer; var1Type, var2type, in b: Boolean; Tmp: TObject; tvar: Variant; + lRight: Pointer; + lRightType: TPSTypeRec; + + { an integer compared with an integer compares by value, with a Currency exactly and with a real as a real, + and a Currency with a Single, Double or Extended as a real, as in Delphi: the cases below read the right + operand in the left one's width and sign, or a real as a Currency } + function NumericCompare(out aResult: Boolean): Boolean; + const + cInts = [btU8, btS8, btU16, btS16, btU32, btS32{$IFNDEF PS_NOINT64}, btS64, btU64{$ENDIF}]; + { the largest integer a Currency holds } + cCurrencyIntMax = 922337203685477; + var + lP2: Pointer; + lT2: TPSTypeRec; + lI1, lI2: Int64; + lHuge1, lHuge2: Boolean; + lR1, lR2: Extended; + lC: Integer; + + { the value, and whether it is a UInt64 past High(Int64) } + function OrdOf(aP: Pointer; aT: TPSTypeRec; out aHuge: Boolean): Int64; + begin + aHuge := False; + case aT.BaseType of + btU8: Result := tbtu8(aP^); + btS8: Result := tbts8(aP^); + btU16: Result := tbtu16(aP^); + btS16: Result := tbts16(aP^); + btU32: Result := tbtu32(aP^); + btS32: Result := tbts32(aP^); + {$IFNDEF PS_NOINT64} + btS64: Result := PInt64(aP)^; + btU64: + begin + Result := PInt64(aP)^; + aHuge := Result < 0; + end; + {$ENDIF} + else + Result := 0; + end; + end; + + { the order of an integer against a Currency's raw value, -1, 0 or 1: an integer past the range of + Currency is greater or less than every Currency } + function IntegerCurrencyOrder(aP: Pointer; aT: TPSTypeRec; aCurrency: Int64): Integer; + var + lValue: Int64; + lHuge: Boolean; + begin + lValue := OrdOf(aP, aT, lHuge); + if lHuge or (lValue > cCurrencyIntMax) then + Result := 1 + else if lValue < -cCurrencyIntMax then + Result := -1 + else + begin + lValue := lValue * 10000; + if lValue < aCurrency then + Result := -1 + else if lValue > aCurrency then + Result := 1 + else + Result := 0; + end; + end; + + begin + Result := False; + if (Cmd > 5) or not ((var1Type.BaseType in cInts) or (var1Type.BaseType = btCurrency)) then + exit; + lP2 := lRight; + lT2 := lRightType; + if (var1Type.BaseType in cInts) and (lT2.BaseType in cInts) then + begin + lI1 := OrdOf(var1, var1Type, lHuge1); + lI2 := OrdOf(lP2, lT2, lHuge2); + if lHuge1 <> lHuge2 then + begin + if lHuge1 then + lC := 1 + else + lC := -1; + end else if lI1 < lI2 then + lC := -1 + else if lI1 > lI2 then + lC := 1 + else + lC := 0; + case Cmd of + 0: aResult := lC >= 0; + 1: aResult := lC <= 0; + 2: aResult := lC > 0; + 3: aResult := lC < 0; + 4: aResult := lC <> 0; + else + aResult := lC = 0; + end; + end else if ((var1Type.BaseType in cInts) and (lT2.BaseType = btCurrency)) or + ((var1Type.BaseType = btCurrency) and (lT2.BaseType in cInts)) then + begin + { an integer compared with a Currency compares exactly, whichever is on the left: a real here would be a + Double on Win64, which cannot hold every Currency, and converting the integer to a Currency wraps or + raises past the range of Currency } + if var1Type.BaseType = btCurrency then + lC := -IntegerCurrencyOrder(lP2, lT2, PInt64(var1)^) + else + lC := IntegerCurrencyOrder(var1, var1Type, PInt64(lP2)^); + case Cmd of + 0: aResult := lC >= 0; + 1: aResult := lC <= 0; + 2: aResult := lC > 0; + 3: aResult := lC < 0; + 4: aResult := lC <> 0; + else + aResult := lC = 0; + end; + end else if ((var1Type.BaseType in cInts) and (lT2.BaseType in [btSingle, btDouble, btExtended])) or + ((var1Type.BaseType = btCurrency) and (lT2.BaseType in [btSingle, btDouble, btExtended])) then + begin + lR1 := PSGetReal(var1, var1Type); + lR2 := PSGetReal(lP2, lT2); + case Cmd of + 0: aResult := lR1 >= lR2; + 1: aResult := lR1 <= lR2; + 2: aResult := lR1 > lR2; + 3: aResult := lR1 < lR2; + 4: aResult := lR1 <> lR2; + else + aResult := lR1 = lR2; + end; + end else + exit; + Result := True; + end; +{$IFNDEF PS_NOWIDESTRING} + + { an AnsiString, a PChar or a Char compared with a wide string or character compares as a UnicodeString, + as in Delphi: the cases below read the wide operand through the ANSI code page } + function WideCompare(out aResult: Boolean): Boolean; + var + lU1, lU2: tbtunicodestring; + begin + Result := False; + if (Cmd > 5) or not (var1Type.BaseType in [btString, btPChar, btChar]) or + not (lRightType.BaseType in [btWideChar, btWideString, btUnicodeString]) then + exit; + lU1 := PSGetUnicodeString(var1, var1Type); + lU2 := PSGetUnicodeString(var2, var2type); + case Cmd of + 0: aResult := lU1 >= lU2; + 1: aResult := lU1 <= lU2; + 2: aResult := lU1 > lU2; + 3: aResult := lU1 < lU2; + 4: aResult := lU1 <> lU2; + else + aResult := lU1 = lU2; + end; + Result := True; + end; +{$ENDIF} procedure SetBoolean(b: Boolean; var Ok: Boolean); @@ -5006,7 +5763,7 @@ function TPSExec.DoBooleanCalc(var1, Var2, into: Pointer; var1Type, var2type, in btS64: tbts64(Into^) := Longint(b); btU64: tbtu64(Into^) := Cardinal(b); {$ENDIF} - btVariant: Variant(Into^) := b; + btVariant: StoreVariant(Into, b); else begin CMD_Err(ErTypeMismatch); Ok := False; @@ -5016,6 +5773,43 @@ function TPSExec.DoBooleanCalc(var1, Var2, into: Pointer; var1Type, var2type, in begin Result := true; try + { a host's pointer to a pointer (TPSScript.SetPointerToData) reaches here as + the pointer: the rules below read the value where it points, as the typed + arms do; a cell of no value or no type is left to the arms } + lRight := var2; + lRightType := var2type; + if (var2type.BaseType = btPointer) and (Pointer(var2^) <> nil) and + (PIFTypeRec(Pointer(IPointer(var2)+PointerSize)^) <> nil) then + begin + lRight := Pointer(var2^); + lRightType := PIFTypeRec(Pointer(IPointer(var2)+PointerSize)^); + end; + if NumericCompare(b){$IFNDEF PS_NOWIDESTRING} or WideCompare(b){$ENDIF} then + begin + SetBoolean(b, Result); + exit; + end; + { a value compared with a Variant compares as two Variants, as in Delphi: the + cases below read the Variant in the other operand's type, which rounds a + fraction away, reads a Boolean as a number and refuses a Null } + if (Cmd <= 5) and (lRightType.BaseType = btVariant) and + (var1Type.BaseType in [btU8, btS8, btU16, btS16, btU32, btS32{$IFNDEF PS_NOINT64}, btS64, btU64{$ENDIF}, + btSingle, btDouble, btExtended, btCurrency, btChar, btString{$IFNDEF PS_NOWIDESTRING}, btWideChar, + btWideString, btUnicodeString{$ENDIF}]) and + IntPIFVariantToVariant(var1, var1Type, tvar) then + begin + case Cmd of + 0: b := tvar >= Variant(lRight^); + 1: b := tvar <= Variant(lRight^); + 2: b := tvar > Variant(lRight^); + 3: b := tvar < Variant(lRight^); + 4: b := tvar <> Variant(lRight^); + else + b := tvar = Variant(lRight^); + end; + SetBoolean(b, Result); + exit; + end; case Cmd of 0: begin { >= } case var1Type.BaseType of @@ -5660,6 +6454,17 @@ function VarIsFloat(const V: Variant): Boolean; Result := VarType(V) in [varSingle, varDouble, varCurrency]; end; +{$IFDEF FPC_CURRENCY_IS_INT64} +{ Free Pascal makes Currency op real (+ - *) a Currency operation, and where + Currency is an Int64 (x86_64) that rounds the real operand alone first: + 1 + 0.00005 would give 1. Taken into a real first, the operation is the + real one, as Delphi computes it. } +function _CurrAsReal(const c: Currency): Extended; +begin + Result := c; +end; +{$ENDIF} + function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; CalcType: Cardinal): Boolean; { var1=dest, var2=src } var @@ -5752,7 +6557,7 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal btSingle: tbtsingle(var1^) := tbtsingle(var1^) + tbtsingle(var2^); btDouble: tbtsingle(var1^) := tbtsingle(var1^) + tbtdouble(var2^); btExtended: tbtsingle(var1^) := tbtsingle(var1^) + tbtextended(var2^); - btCurrency: tbtsingle(var1^) := tbtsingle(var1^) + tbtcurrency(var2^); + btCurrency: tbtsingle(var1^) := tbtsingle(var1^) + {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var2^)){$ELSE}tbtcurrency(var2^){$ENDIF}; btVariant: tbtsingle(var1^) := tbtsingle(var1^) + Variant(var2^); else raise Exception.Create(RPS_TypeMismatch); end; @@ -5779,7 +6584,7 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal btSingle: tbtdouble(var1^) := tbtdouble(var1^) + tbtsingle(var2^); btDouble: tbtdouble(var1^) := tbtdouble(var1^) + tbtdouble(var2^); btExtended: tbtdouble(var1^) := tbtdouble(var1^) + tbtextended(var2^); - btCurrency: tbtdouble(var1^) := tbtdouble(var1^) + tbtcurrency(var2^); + btCurrency: tbtdouble(var1^) := tbtdouble(var1^) + {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var2^)){$ELSE}tbtcurrency(var2^){$ENDIF}; btVariant: tbtdouble(var1^) := tbtdouble(var1^) + Variant(var2^); else raise Exception.Create(RPS_TypeMismatch); end; @@ -5803,9 +6608,9 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal btS64: tbtcurrency(var1^) := tbtcurrency(var1^) + tbts64(var2^); btU64: tbtcurrency(var1^) := tbtcurrency(var1^) + tbtu64(var2^); {$ENDIF} - btSingle: tbtcurrency(var1^) := tbtcurrency(var1^) + tbtsingle(var2^); - btDouble: tbtcurrency(var1^) := tbtcurrency(var1^) + tbtdouble(var2^); - btExtended: tbtcurrency(var1^) := tbtcurrency(var1^) + tbtextended(var2^); + btSingle: tbtcurrency(var1^) := {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var1^)){$ELSE}tbtcurrency(var1^){$ENDIF} + tbtsingle(var2^); + btDouble: tbtcurrency(var1^) := {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var1^)){$ELSE}tbtcurrency(var1^){$ENDIF} + tbtdouble(var2^); + btExtended: tbtcurrency(var1^) := {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var1^)){$ELSE}tbtcurrency(var1^){$ENDIF} + tbtextended(var2^); btCurrency: tbtcurrency(var1^) := tbtcurrency(var1^) + tbtcurrency(var2^); btVariant: tbtcurrency(var1^) := tbtcurrency(var1^) + Variant(var2^); else raise Exception.Create(RPS_TypeMismatch); @@ -5833,7 +6638,7 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal btSingle: tbtextended(var1^) := tbtextended(var1^) + tbtsingle(var2^); btDouble: tbtextended(var1^) := tbtextended(var1^) + tbtdouble(var2^); btExtended: tbtextended(var1^) := tbtextended(var1^) + tbtextended(var2^); - btCurrency: tbtextended(var1^) := tbtextended(var1^) + tbtcurrency(var2^); + btCurrency: tbtextended(var1^) := tbtextended(var1^) + {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var2^)){$ELSE}tbtcurrency(var2^){$ENDIF}; btVariant: tbtextended(var1^) := tbtextended(var1^) + Variant(var2^); else raise Exception.Create(RPS_TypeMismatch); end; @@ -5956,7 +6761,7 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal btSingle: tbtsingle(var1^) := tbtsingle(var1^) - tbtsingle(var2^); btDouble: tbtsingle(var1^) := tbtsingle(var1^) - tbtdouble(var2^); btExtended: tbtsingle(var1^) := tbtsingle(var1^) - tbtextended(var2^); - btCurrency: tbtsingle(var1^) := tbtsingle(var1^) - tbtcurrency(var2^); + btCurrency: tbtsingle(var1^) := tbtsingle(var1^) - {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var2^)){$ELSE}tbtcurrency(var2^){$ENDIF}; btVariant: tbtsingle(var1^) := tbtsingle(var1^) - Variant(var2^); else raise Exception.Create(RPS_TypeMismatch); end; @@ -5980,9 +6785,9 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal btS64: tbtcurrency(var1^) := tbtcurrency(var1^) - tbts64(var2^); btU64: tbtcurrency(var1^) := tbtcurrency(var1^) - tbtu64(var2^); {$ENDIF} - btSingle: tbtcurrency(var1^) := tbtcurrency(var1^) - tbtsingle(var2^); - btDouble: tbtcurrency(var1^) := tbtcurrency(var1^) - tbtdouble(var2^); - btExtended: tbtcurrency(var1^) := tbtcurrency(var1^) - tbtextended(var2^); + btSingle: tbtcurrency(var1^) := {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var1^)){$ELSE}tbtcurrency(var1^){$ENDIF} - tbtsingle(var2^); + btDouble: tbtcurrency(var1^) := {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var1^)){$ELSE}tbtcurrency(var1^){$ENDIF} - tbtdouble(var2^); + btExtended: tbtcurrency(var1^) := {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var1^)){$ELSE}tbtcurrency(var1^){$ENDIF} - tbtextended(var2^); btCurrency: tbtcurrency(var1^) := tbtcurrency(var1^) - tbtcurrency(var2^); btVariant: tbtcurrency(var1^) := tbtcurrency(var1^) - Variant(var2^); else raise Exception.Create(RPS_TypeMismatch); @@ -6010,7 +6815,7 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal btSingle: tbtdouble(var1^) := tbtdouble(var1^) - tbtsingle(var2^); btDouble: tbtdouble(var1^) := tbtdouble(var1^) - tbtdouble(var2^); btExtended: tbtdouble(var1^) := tbtdouble(var1^) - tbtextended(var2^); - btCurrency: tbtdouble(var1^) := tbtdouble(var1^) - tbtcurrency(var2^); + btCurrency: tbtdouble(var1^) := tbtdouble(var1^) - {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var2^)){$ELSE}tbtcurrency(var2^){$ENDIF}; btVariant: tbtdouble(var1^) := tbtdouble(var1^) - Variant(var2^); else raise Exception.Create(RPS_TypeMismatch); end; @@ -6037,7 +6842,7 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal btSingle: tbtextended(var1^) := tbtextended(var1^) - tbtsingle(var2^); btDouble: tbtextended(var1^) := tbtextended(var1^) - tbtdouble(var2^); btExtended: tbtextended(var1^) := tbtextended(var1^) - tbtextended(var2^); - btCurrency: tbtextended(var1^) := tbtextended(var1^) - tbtcurrency(var2^); + btCurrency: tbtextended(var1^) := tbtextended(var1^) - {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var2^)){$ELSE}tbtcurrency(var2^){$ENDIF}; btVariant: tbtextended(var1^) := tbtextended(var1^) - Variant(var2^); else raise Exception.Create(RPS_TypeMismatch); end; @@ -6152,9 +6957,9 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal btS64: tbtcurrency(var1^) := tbtcurrency(var1^) * tbts64(var2^); btU64: tbtcurrency(var1^) := tbtcurrency(var1^) * tbtu64(var2^); {$ENDIF} - btSingle: tbtcurrency(var1^) := tbtcurrency(var1^) * tbtsingle(var2^); - btDouble: tbtcurrency(var1^) := tbtcurrency(var1^) * tbtdouble(var2^); - btExtended: tbtcurrency(var1^) := tbtcurrency(var1^) * tbtextended(var2^); + btSingle: tbtcurrency(var1^) := {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var1^)){$ELSE}tbtcurrency(var1^){$ENDIF} * tbtsingle(var2^); + btDouble: tbtcurrency(var1^) := {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var1^)){$ELSE}tbtcurrency(var1^){$ENDIF} * tbtdouble(var2^); + btExtended: tbtcurrency(var1^) := {$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var1^)){$ELSE}tbtcurrency(var1^){$ENDIF} * tbtextended(var2^); btCurrency: tbtcurrency(var1^) := tbtcurrency(var1^) * tbtcurrency(var2^); btVariant: tbtcurrency(var1^) := tbtcurrency(var1^) * Variant(var2^); else raise Exception.Create(RPS_TypeMismatch); @@ -6182,7 +6987,7 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal btSingle: tbtsingle(var1^) := tbtsingle(var1^) *tbtsingle(var2^); btDouble: tbtsingle(var1^) := tbtsingle(var1^) *tbtdouble(var2^); btExtended: tbtsingle(var1^) := tbtsingle(var1^) *tbtextended(var2^); - btCurrency: tbtsingle(var1^) := tbtsingle(var1^) *tbtcurrency(var2^); + btCurrency: tbtsingle(var1^) := tbtsingle(var1^) *{$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var2^)){$ELSE}tbtcurrency(var2^){$ENDIF}; btVariant: tbtsingle(var1^) := tbtsingle(var1^) * Variant(var2^); else raise Exception.Create(RPS_TypeMismatch); end; @@ -6209,7 +7014,7 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal btSingle: tbtdouble(var1^) := tbtdouble(var1^) *tbtsingle(var2^); btDouble: tbtdouble(var1^) := tbtdouble(var1^) *tbtdouble(var2^); btExtended: tbtdouble(var1^) := tbtdouble(var1^) *tbtextended(var2^); - btCurrency: tbtdouble(var1^) := tbtdouble(var1^) *tbtcurrency(var2^); + btCurrency: tbtdouble(var1^) := tbtdouble(var1^) *{$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var2^)){$ELSE}tbtcurrency(var2^){$ENDIF}; btVariant: tbtdouble(var1^) := tbtdouble(var1^) * Variant(var2^); else raise Exception.Create(RPS_TypeMismatch); end; @@ -6236,7 +7041,7 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal btSingle: tbtextended(var1^) := tbtextended(var1^) *tbtsingle(var2^); btDouble: tbtextended(var1^) := tbtextended(var1^) *tbtdouble(var2^); btExtended: tbtextended(var1^) := tbtextended(var1^) *tbtextended(var2^); - btCurrency: tbtextended(var1^) := tbtextended(var1^) *tbtcurrency(var2^); + btCurrency: tbtextended(var1^) := tbtextended(var1^) *{$IFDEF FPC_CURRENCY_IS_INT64}_CurrAsReal(tbtcurrency(var2^)){$ELSE}tbtcurrency(var2^){$ENDIF}; btVariant: tbtextended(var1^) := tbtextended(var1^) * Variant(var2^); else raise Exception.Create(RPS_TypeMismatch); end; @@ -6270,10 +7075,55 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal {$IFDEF DELPHI10UP}{$REGION '/'}{$ENDIF} 3: begin { / } case var1Type.BaseType of - btU8: tbtU8(var1^) := tbtU8(var1^) div PSGetUInt(Var2, var2type); - btS8: tbts8(var1^) := tbts8(var1^) div PSGetInt(Var2, var2type); - btU16: tbtU16(var1^) := tbtU16(var1^) div PSGetUInt(Var2, var2type); - btS16: tbts16(var1^) := tbts16(var1^) div PSGetInt(Var2, var2type); + { a 64-bit divisor is not narrowed, as for a 32-bit dividend } + btU8: + {$IFNDEF PS_NOINT64} + if _DivisorBaseType(Var2, var2type) = btS64 then + tbtU8(var1^) := tbtU8(var1^) div PSGetInt64(Var2, var2type) + else if _DivisorBaseType(Var2, var2type) = btU64 then + tbtU8(var1^) := tbtU8(var1^) div PSGetUInt64(Var2, var2type) + { a signed divisor makes the division signed, as in Delphi } + else if _DivisorBaseType(Var2, var2type) in [btS8, btS16, btS32] then + tbtU8(var1^) := Int64(tbtU8(var1^)) div PSGetInt(Var2, var2type) + else + {$ENDIF} + tbtU8(var1^) := tbtU8(var1^) div PSGetUInt(Var2, var2type); + btS8: + {$IFNDEF PS_NOINT64} + if _DivisorBaseType(Var2, var2type) = btS64 then + tbts8(var1^) := tbts8(var1^) div PSGetInt64(Var2, var2type) + else if _DivisorBaseType(Var2, var2type) = btU64 then + tbts8(var1^) := tbts8(var1^) div PSGetUInt64(Var2, var2type) + { a Cardinal divisor makes the division 64-bit, as in Delphi } + else if _DivisorBaseType(Var2, var2type) = btU32 then + tbts8(var1^) := Int64(tbts8(var1^)) div PSGetUInt(Var2, var2type) + else + {$ENDIF} + tbts8(var1^) := tbts8(var1^) div PSGetInt(Var2, var2type); + btU16: + {$IFNDEF PS_NOINT64} + if _DivisorBaseType(Var2, var2type) = btS64 then + tbtU16(var1^) := tbtU16(var1^) div PSGetInt64(Var2, var2type) + else if _DivisorBaseType(Var2, var2type) = btU64 then + tbtU16(var1^) := tbtU16(var1^) div PSGetUInt64(Var2, var2type) + { a signed divisor makes the division signed, as in Delphi } + else if _DivisorBaseType(Var2, var2type) in [btS8, btS16, btS32] then + tbtU16(var1^) := Int64(tbtU16(var1^)) div PSGetInt(Var2, var2type) + else + {$ENDIF} + tbtU16(var1^) := tbtU16(var1^) div PSGetUInt(Var2, var2type); + btS16: + {$IFNDEF PS_NOINT64} + if _DivisorBaseType(Var2, var2type) = btS64 then + tbts16(var1^) := tbts16(var1^) div PSGetInt64(Var2, var2type) + else if _DivisorBaseType(Var2, var2type) = btU64 then + tbts16(var1^) := tbts16(var1^) div PSGetUInt64(Var2, var2type) + { a Cardinal divisor makes the division 64-bit, as in Delphi } + else if _DivisorBaseType(Var2, var2type) = btU32 then + tbts16(var1^) := Int64(tbts16(var1^)) div PSGetUInt(Var2, var2type) + else + {$ENDIF} + tbts16(var1^) := tbts16(var1^) div PSGetInt(Var2, var2type); btU32: begin if var2type.BaseType = btPointer then @@ -6284,11 +7134,11 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal end; case var2type.BaseType of btU8: tbtU32(var1^) := tbtU32(var1^) div tbtu8(var2^); - btS8: tbtU32(var1^) := tbtU32(var1^) div cardinal(longint(tbts8(var2^))); + btS8: tbtU32(var1^) := Int64(tbtU32(var1^)) div tbts8(var2^); btU16: tbtU32(var1^) := tbtU32(var1^) div tbtu16(var2^); - btS16: tbtU32(var1^) := tbtU32(var1^) div cardinal(longint(tbts16(var2^))); + btS16: tbtU32(var1^) := Int64(tbtU32(var1^)) div tbts16(var2^); btU32: tbtU32(var1^) := tbtU32(var1^) div tbtu32(var2^); - btS32: tbtU32(var1^) := tbtU32(var1^) div cardinal(tbts32(var2^)); + btS32: tbtU32(var1^) := Int64(tbtU32(var1^)) div tbts32(var2^); {$IFNDEF PS_NOINT64} btS64: tbtU32(var1^) := tbtU32(var1^) div tbts64(var2^); btU64: tbtU32(var1^) := tbtU32(var1^) div tbtu64(var2^); @@ -6312,7 +7162,7 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal btS8: tbts32(var1^) := tbts32(var1^) div tbts8(var2^); btU16: tbts32(var1^) := tbts32(var1^) div tbtu16(var2^); btS16: tbts32(var1^) := tbts32(var1^) div tbts16(var2^); - btU32: tbts32(var1^) := tbts32(var1^) div Longint(tbtu32(var2^)); + btU32: tbts32(var1^) := Int64(tbts32(var1^)) div tbtu32(var2^); btS32: tbts32(var1^) := tbts32(var1^) div tbts32(var2^); {$IFNDEF PS_NOINT64} btS64: tbts32(var1^) := tbts32(var1^) div tbts64(var2^); @@ -6463,10 +7313,55 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal {$IFDEF DELPHI10UP}{$REGION 'MOD'}{$ENDIF} 4: begin { MOD } case var1Type.BaseType of - btU8: tbtU8(var1^) := tbtU8(var1^) mod PSGetUInt(Var2, var2type); - btS8: tbts8(var1^) := tbts8(var1^) mod PSGetInt(Var2, var2type); - btU16: tbtU16(var1^) := tbtU16(var1^) mod PSGetUInt(Var2, var2type); - btS16: tbts16(var1^) := tbts16(var1^) mod PSGetInt(Var2, var2type); + { a 64-bit divisor is not narrowed, as for a 32-bit dividend } + btU8: + {$IFNDEF PS_NOINT64} + if _DivisorBaseType(Var2, var2type) = btS64 then + tbtU8(var1^) := tbtU8(var1^) mod PSGetInt64(Var2, var2type) + else if _DivisorBaseType(Var2, var2type) = btU64 then + tbtU8(var1^) := tbtU8(var1^) mod PSGetUInt64(Var2, var2type) + { a signed divisor makes the division signed, as in Delphi } + else if _DivisorBaseType(Var2, var2type) in [btS8, btS16, btS32] then + tbtU8(var1^) := Int64(tbtU8(var1^)) mod PSGetInt(Var2, var2type) + else + {$ENDIF} + tbtU8(var1^) := tbtU8(var1^) mod PSGetUInt(Var2, var2type); + btS8: + {$IFNDEF PS_NOINT64} + if _DivisorBaseType(Var2, var2type) = btS64 then + tbts8(var1^) := tbts8(var1^) mod PSGetInt64(Var2, var2type) + else if _DivisorBaseType(Var2, var2type) = btU64 then + tbts8(var1^) := tbts8(var1^) mod PSGetUInt64(Var2, var2type) + { a Cardinal divisor makes the division 64-bit, as in Delphi } + else if _DivisorBaseType(Var2, var2type) = btU32 then + tbts8(var1^) := Int64(tbts8(var1^)) mod PSGetUInt(Var2, var2type) + else + {$ENDIF} + tbts8(var1^) := tbts8(var1^) mod PSGetInt(Var2, var2type); + btU16: + {$IFNDEF PS_NOINT64} + if _DivisorBaseType(Var2, var2type) = btS64 then + tbtU16(var1^) := tbtU16(var1^) mod PSGetInt64(Var2, var2type) + else if _DivisorBaseType(Var2, var2type) = btU64 then + tbtU16(var1^) := tbtU16(var1^) mod PSGetUInt64(Var2, var2type) + { a signed divisor makes the division signed, as in Delphi } + else if _DivisorBaseType(Var2, var2type) in [btS8, btS16, btS32] then + tbtU16(var1^) := Int64(tbtU16(var1^)) mod PSGetInt(Var2, var2type) + else + {$ENDIF} + tbtU16(var1^) := tbtU16(var1^) mod PSGetUInt(Var2, var2type); + btS16: + {$IFNDEF PS_NOINT64} + if _DivisorBaseType(Var2, var2type) = btS64 then + tbts16(var1^) := tbts16(var1^) mod PSGetInt64(Var2, var2type) + else if _DivisorBaseType(Var2, var2type) = btU64 then + tbts16(var1^) := tbts16(var1^) mod PSGetUInt64(Var2, var2type) + { a Cardinal divisor makes the division 64-bit, as in Delphi } + else if _DivisorBaseType(Var2, var2type) = btU32 then + tbts16(var1^) := Int64(tbts16(var1^)) mod PSGetUInt(Var2, var2type) + else + {$ENDIF} + tbts16(var1^) := tbts16(var1^) mod PSGetInt(Var2, var2type); btU32: begin if var2type.BaseType = btPointer then @@ -6477,11 +7372,11 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal end; case var2type.BaseType of btU8: tbtU32(var1^) := tbtU32(var1^) mod tbtu8(var2^); - btS8: tbtU32(var1^) := tbtU32(var1^) mod cardinal(longint(tbts8(var2^))); + btS8: tbtU32(var1^) := Int64(tbtU32(var1^)) mod tbts8(var2^); btU16: tbtU32(var1^) := tbtU32(var1^) mod tbtu16(var2^); - btS16: tbtU32(var1^) := tbtU32(var1^) mod cardinal(longint(tbts16(var2^))); + btS16: tbtU32(var1^) := Int64(tbtU32(var1^)) mod tbts16(var2^); btU32: tbtU32(var1^) := tbtU32(var1^) mod tbtu32(var2^); - btS32: tbtU32(var1^) := tbtU32(var1^) mod cardinal(tbts32(var2^)); + btS32: tbtU32(var1^) := Int64(tbtU32(var1^)) mod tbts32(var2^); {$IFNDEF PS_NOINT64} btS64: tbtU32(var1^) := tbtU32(var1^) mod tbts64(var2^); btU64: tbtU32(var1^) := tbtU32(var1^) mod tbtu64(var2^); @@ -6505,7 +7400,7 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal btS8: tbts32(var1^) := tbts32(var1^) mod tbts8(var2^); btU16: tbts32(var1^) := tbts32(var1^) mod tbtu16(var2^); btS16: tbts32(var1^) := tbts32(var1^) mod tbts16(var2^); - btU32: tbts32(var1^) := tbts32(var1^) mod Longint(tbtu32(var2^)); + btU32: tbts32(var1^) := Int64(tbts32(var1^)) mod tbtu32(var2^); btS32: tbts32(var1^) := tbts32(var1^) mod tbts32(var2^); {$IFNDEF PS_NOINT64} btS64: tbts32(var1^) := tbts32(var1^) mod tbts64(var2^); @@ -6773,12 +7668,31 @@ function TPSExec.DoCalc(var1, Var2: Pointer; var1Type, var2type: TPSTypeRec; Cal end; function TPSExec.ReadVariable(var Dest: TPSResultData; UsePointer: Boolean): Boolean; +const + { the types the constant case below reads: a constant of any other type is + refused before its place is made, since a static array or a record can be + larger than the temporaries can hold } + ConstantTypes = [btSet, bts8, btchar, btU8, bts16{$IFNDEF PS_NOWIDESTRING}, btwidechar{$ENDIF}, btU16, bts32, btU32, + btProcPtr{$IFNDEF PS_NOINT64}, bts64, btU64{$ENDIF}, btSingle, btDouble, btExtended, btCurrency, btPchar, btString + {$IFNDEF PS_NOWIDESTRING}, btWidestring, btUnicodeString{$ENDIF}]; var VarType: Cardinal; Param: Cardinal; Tmp: PIfVariant; at: TPSTypeRec; +{$IFNDEF PS_NOINT64} + { a 64-bit index as the Cardinal the bounds checks below compare: one outside a Cardinal becomes + High(Cardinal), which fails every check, as a negative 32-bit index does } + function Index64(const aValue: Int64): Cardinal; + begin + if (aValue < 0) or (aValue > High(Cardinal)) then + Result := High(Cardinal) + else + Result := Cardinal(aValue); + end; +{$ENDIF} + begin if FCurrentPosition + 4 >= FDataLength then begin @@ -6843,28 +7757,29 @@ function TPSExec.ReadVariable(var Dest: TPSResultData; UsePointer: Boolean): Boo exit; end; at := FTypes.Data^[Param]; + if not (at.BaseType in ConstantTypes) then + begin + CMD_Err(erInvalidType); + Result := False; + exit; + end; Param := FTempVars.FLength; FTempVars.FLength := Cardinal(Longint(Param) + Longint(at.RealSize) + Longint(RTTISize + 3)) and not 3; if FTempVars.FLength > FTempVars.FCapacity then FtempVars.AdjustLength; Tmp := Pointer(IPointer(FtempVars.FDataPtr) + IPointer(Param)); - if Cardinal(FTempVars.FCount) >= Cardinal(FTempVars.FCapacity) then - begin - Inc(FTempVars.FCapacity, FCapacityInc);// := FCount + 1; - ReAllocMem(FTempVars.FData, FTempVars.FCapacity shl 2); - end; - FTempVars.FData[FTempVars.FCount] := Tmp; // Instead of SetItem - Inc(FTempVars.FCount); - {$IFNDEF PS_NOSMARTLIST} - Inc(FTempVars.FCheckCount); - if FTempVars.FCheckCount > FMaxCheckCount then FTempVars.Recreate; - {$ENDIF} + { TPSList.Add: TPSStack's own FCapacity is the size of its data in bytes, not of its item list } + FTempVars.Add(Tmp); Tmp.FType := at; Dest.P := @PPSVariantData(Tmp).Data; Dest.aType := tmp.FType; dest.FreeType := vtTempVar; + { a value refused below is popped, which finalizes one of a managed + type: its place holds nothing until its value is read } + if at.BaseType in NeedFinalization then + FillChar(Dest.P^, at.RealSize, 0); case Dest.aType.BaseType of btSet: begin @@ -7306,6 +8221,10 @@ function TPSExec.ReadVariable(var Dest: TPSResultData; UsePointer: Boolean): Boo bts16: Param := PPSVariants16(Tmp).Data; btu32: Param := PPSVariantU32(Tmp).Data; bts32: Param := PPSVariants32(Tmp).Data; + {$IFNDEF PS_NOINT64} + bts64: Param := Index64(PPSVariantS64(Tmp).Data); + btu64: Param := Index64(PInt64(@PPSVariantU64(Tmp).Data)^); + {$ENDIF} btPointer: begin if PPSVariantPointer(tmp).DestType <> nil then @@ -7317,6 +8236,9 @@ function TPSExec.ReadVariable(var Dest: TPSResultData; UsePointer: Boolean): Boo bts16: Param := tbts16(PPSVariantPointer(tmp).DataDest^); btu32, btProcPtr: Param := tbtu32(PPSVariantPointer(tmp).DataDest^); bts32: Param := tbts32(PPSVariantPointer(tmp).DataDest^); + {$IFNDEF PS_NOINT64} + bts64, btu64: Param := Index64(PInt64(PPSVariantPointer(tmp).DataDest)^); + {$ENDIF} else begin CMD_Err(ErTypeMismatch); @@ -7393,6 +8315,7 @@ function TPSExec.ReadVariable(var Dest: TPSResultData; UsePointer: Boolean): Boo end; else begin + CMD_Err(erInvalidOpcodeParameter); Result := False; exit; end; @@ -7419,13 +8342,15 @@ function TPSExec.DoMinus(Dta: Pointer; aType: TPSTypeRec): Boolean; btCurrency: tbtcurrency(dta^) := -tbtcurrency(dta^); btVariant: begin + Result := True; try Variant(dta^) := - Variant(dta^); except CMD_Err(erTypeMismatch); Result := False; - exit; end; + { left after the handler: Delphi XE3 to XE5 for Win64 keep the exception object of a handler left by a jump } + exit; end; else begin @@ -7452,13 +8377,15 @@ function TPSExec.DoBooleanNot(Dta: Pointer; aType: TPSTypeRec): Boolean; {$ENDIF} btVariant: begin + Result := True; try Variant(dta^) := Variant(dta^) = 0; except CMD_Err(erTypeMismatch); Result := False; - exit; end; + { left after the handler: Delphi XE3 to XE5 for Win64 keep the exception object of a handler left by a jump } + exit; end; else begin @@ -7498,6 +8425,64 @@ function TPSExec.ReadLong(var b: Cardinal): Boolean; Result := False; end; +{ Runs aProcNo for native code -- RunProcP and RunProcPVar, a host's call into + the script -- as the method handlers run a script method: behind a frame of + its own, so that the routine's exception ends the call there and never + reaches a try statement of a script that is running. If a script was + running when the call began, the exception goes to the native code that made + the call -- also when the routine stopped that script -- which may handle it + and go on: the script holds it no longer, and counts it again only if the + native code lets it come back. With no script running the executor keeps + it, for RaiseCurrentException and the host to read. } +procedure _RunProcForNative(aExec: TPSExec; aParams: TPSList; aProcNo: Cardinal); +var + lFrame : TPSExceptionHandler; + lIdx : Integer; + lPosition : Cardinal; + lStackBase : Cardinal; + lRaised : Cardinal; + lObject : TObject; + lRunning : Boolean; +begin + lFrame := TPSExceptionHandler.Create; + lFrame.FinallyOffset := InvalidVal; + lFrame.ExceptOffset := InvalidVal; + lFrame.Finally2Offset := InvalidVal; + lFrame.EndOfBlock := InvalidVal; + lFrame.CurrProc := nil; + lFrame.BasePtr := aExec.FCurrStackBase; + lFrame.StackSize := aExec.FStack.Count; + lIdx := aExec.FExceptionStack.Add(lFrame); + { where the interpreter stands while the native code runs the routine } + lPosition := aExec.FCurrentPosition; + lStackBase := aExec.FCurrStackBase; + lRaised := aExec.FRaisedCount; + lRunning := aExec.FStatus = isRunning; + aExec.RunProc(aParams, aProcNo); + if aExec.FExceptionStack[lIdx] = lFrame then + begin + aExec.FExceptionStack.Remove(lFrame); + lFrame.Free; + end else + begin + { the routine's exception ended the call at this frame, below the return + address: the interpreter is back where the native code called it } + aExec.FCurrentPosition := lPosition; + aExec.FCurrStackBase := lStackBase; + end; + if (aExec.ExEx <> erNoError) and lRunning then + begin + lObject := aExec.ExObject; + aExec.ExObject := nil; + if lObject = nil then + lObject := EPSException.Create(PSErrorToString(aExec.ExceptionCode, aExec.ExceptionString), aExec, + aExec.ExProc, aExec.ExPos); + aExec.ExceptionProc(InvalidVal, InvalidVal, erNoError, '', nil); + aExec.FRaisedCount := lRaised; + raise lObject; + end; +end; + function TPSExec.RunProcP(const Params: array of Variant; const Procno: Cardinal): Variant; var ParamList: TPSList; @@ -7529,18 +8514,23 @@ function TPSExec.RunProcP(const Params: array of Variant; const Procno: Cardinal if I > -1 then raise Exception.Create(RPS_TooManyParameters); if res <> '-1' then begin - pvar := CreateHeapVariant(FTypes[StrToInt(res)]); + ct := FTypes[StrToInt(res)]; + if ct = nil then raise Exception.Create(RPS_InvalidParameter); + pvar := CreateHeapVariant(ct); ParamList.Add(pvar); end else pvar := nil; - RunProc(ParamList, ProcNo); + _RunProcForNative(Self, ParamList, ProcNo); RaiseCurrentException; if pvar <> nil then begin - PIFVariantToVariant(PVar, Result); + { what no Variant can hold answers no value: Result can arrive holding a + value of the caller's } + if not PIFVariantToVariant(PVar, Result) then + Result := Null; end else Result := Null; finally @@ -7578,12 +8568,14 @@ function TPSExec.RunProcPVar(var Params: array of Variant; const Procno: Cardina if I > -1 then raise Exception.Create(RPS_TooManyParameters); if res <> '-1' then begin - pvar := CreateHeapVariant(FTypes[StrToInt(res)]); + ct := FTypes[StrToInt(res)]; + if ct = nil then raise Exception.Create(RPS_InvalidParameter); + pvar := CreateHeapVariant(ct); ParamList.Add(pvar); end else pvar := nil; - RunProc(ParamList, ProcNo); + _RunProcForNative(Self, ParamList, ProcNo); RaiseCurrentException; @@ -7593,7 +8585,10 @@ function TPSExec.RunProcPVar(var Params: array of Variant; const Procno: Cardina if pvar <> nil then begin - PIFVariantToVariant(PVar, Result); + { what no Variant can hold answers no value: Result can arrive holding a + value of the caller's } + if not PIFVariantToVariant(PVar, Result) then + Result := Null; end else Result := Null; finally @@ -7619,7 +8614,11 @@ function TPSExec.RunProc(Params: TPSList; ProcNo: Cardinal): Boolean; Cp: TPSInternalProcRec; oldStatus: TPSStatus; tmp: TObject; + lBase: Longint; + lRaised: Cardinal; + lReported: Boolean; begin + lBase := FStack.Count; {$IFDEF LOG} ODS_stack(FStack); __Log(string('==== RunProc, paramcnt='+IntToStr(Params.Count)+', procNo='+IntToStr(ProcNo))); @@ -7637,6 +8636,8 @@ function TPSExec.RunProc(Params: TPSList; ProcNo: Cardinal): Boolean; vd := Params[I]; if vd = nil then begin + while Longint(FStack.Count) > lBase do + FStack.Pop; Result := False; exit; end; @@ -7654,6 +8655,7 @@ function TPSExec.RunProc(Params: TPSList; ProcNo: Cardinal): Boolean; I := FStack.Count; Cp := FCurrProc; oldStatus := FStatus; + lReported := False; {$IFDEF LOG} ODS_stack(FStack); {$ENDIF} @@ -7669,16 +8671,32 @@ function TPSExec.RunProc(Params: TPSList; ProcNo: Cardinal): Boolean; FDataLength := FCurrProc.Length; FCurrentPosition := 0; FStatus := isPaused; - Result := RunScript; + lRaised := FRaisedCount; + Inc(FNestedRuns); + try + Result := RunScript; + finally + Dec(FNestedRuns); + end; + { what the routine raised and handled itself never reached the native + routine that ran it: that routine's call is judged as if nothing was } + if ExEx = erNoError then + FRaisedCount := lRaised; end else begin try + lRaised := FRaisedCount; Result := TPSExternalProcRec(FProcs.Data^[ProcNo]).ProcPtr(Self, TPSExternalProcRec(FProcs.Data^[ProcNo]), FGlobalVars, FStack); if not Result then begin - if ExEx = erNoError then + { False with nothing raised: the call failed without saying why } + if FRaisedCount = lRaised then CMD_Err(erCouldNotCallProc); end; + { a routine that reported an error failed, whatever it answered } + lReported := FRaisedCount <> lRaised; + if lReported then + Result := False; except {$IFDEF DELPHI6UP} Tmp := AcquireExceptionObject; @@ -7690,6 +8708,10 @@ function TPSExec.RunProc(Params: TPSList; ProcNo: Cardinal): Boolean; end else Tmp := nil; {$ENDIF} + { the arms below leave RunProc at once: the values pushed for the call + go first } + while Longint(FStack.Count) > lBase do + FStack.Pop; if Tmp <> nil then begin if Tmp is EPSException then @@ -7737,18 +8759,21 @@ function TPSExec.RunProc(Params: TPSList; ProcNo: Cardinal): Boolean; FStack.Pop; end; end; - if Params <> nil then + { down to where the stack stood: an exception the routine raised has already unwound it to there, and + popping the parameters again removed the caller's values } + while Longint(FStack.Count) > lBase do + FStack.Pop; + { an imported routine's report moved the run -- to the handler that took + it, or paused it where no handler was left -- as it does when the script + calls the routine itself: the status and the routine are the report's } + if not lReported then begin - for I := Params.Count - 1 downto 0 do - begin - if FStack.Count = 0 then - Break - else - FStack.Pop; - end; + { a Stop in a run begun while the script was running stops the script: + the run it interrupted ends when control comes back to it } + if (FStatus <> isLoaded) or (oldStatus <> isRunning) then + FStatus := oldStatus; + FCurrProc := Cp; end; - FStatus := oldStatus; - FCurrProc := Cp; if FCurrProc <> nil then begin FData := FCurrProc.Data; @@ -7795,7 +8820,11 @@ function TPSExec.GetProc(const Name: tbtString): Cardinal; I: Longint; n: PIFProcRec; s: tbtString; + lExternal: Cardinal; begin + { a script's routine comes before an external one of its name, which the + compiler's own code may have added } + lExternal := InvalidVal; s := FastUpperCase(name); MM := MakeHash(s); for I := FProcs.Count - 1 downto 0 do begin @@ -7803,13 +8832,10 @@ function TPSExec.GetProc(const Name: tbtString): Cardinal; if (n.ClassType = TPSInternalProcRec) and (TPSInternalProcRec(n).ExportNameHash = MM) and (TPSInternalProcRec(n).ExportName = s) then begin Result := I; exit; - end else if (n.ClassType = TPSExternalProcRec) and (TPSExternalProcRec(n).Name = s) then - begin - Result := I; - exit; - end; + end else if (n.ClassType = TPSExternalProcRec) and (TPSExternalProcRec(n).Name = s) and (lExternal = InvalidVal) then + lExternal := I; end; - Result := InvalidVal; + Result := lExternal; end; function TPSExec.GetType(const Name: tbtString): Cardinal; @@ -7882,8 +8908,8 @@ function TPSExec.IsValidResource(Proc, P: Pointer): Boolean; for i := 0 to Longint(FResources.Count) -1 do begin temp := FResources[i]; - if temp^.p = p then begin - result := temp^.Proc = Proc; + if (temp^.p = p) and (temp^.Proc = Proc) then begin + result := True; exit; end; end; @@ -7922,6 +8948,7 @@ procedure TPSExec.CMD_Err3(EC: TPSError; const Param: tbtString; ExObject: TObje var l: Longint; C: Cardinal; + lOnException: TPSOnException; begin C := InvalidVal; for l := FProcs.Count - 1 downto 0 do begin @@ -7930,8 +8957,11 @@ procedure TPSExec.CMD_Err3(EC: TPSError; const Param: tbtString; ExObject: TObje break; end; end; - if @FOnException <> nil then - FOnException(Self, Ec, Param, ExObject, C, FCurrentPosition); + { the handler is called from a local: for the field, Delphi 10 Seattle's Win64 + compiler reads Self from a stack slot it never writes } + lOnException := FOnException; + if @lOnException <> nil then + lOnException(Self, Ec, Param, ExObject, C, FCurrentPosition); ExceptionProc(C, FCurrentPosition, EC, Param, ExObject); end; @@ -7999,13 +9029,15 @@ function TPSExec.DoIntegerNot(Dta: Pointer; aType: TPSTypeRec): Boolean; {$ENDIF} btVariant: begin + Result := True; try Variant(dta^) := not Variant(dta^); except CMD_Err(erTypeMismatch); Result := False; - exit; end; + { left after the handler: Delphi XE3 to XE5 for Win64 keep the exception object of a handler left by a jump } + exit; end; else begin @@ -8105,6 +9137,9 @@ function TPSExec.RunScript: Boolean; Tmp: TObject; btemp: Boolean; CallRunline: TMyRunLine; + lRaised: Cardinal; + lFrames: Longint; + lCalled: Boolean; begin {$IFDEF LOG} ODS_stack(Fstack); @@ -8118,6 +9153,7 @@ function TPSExec.RunScript: Boolean; end; FExceptionStack.Clear; end; + lFrames := FExceptionStack.Count; ExceptionProc(InvalidVal, InvalidVal, erNoError, '', nil); RunScript := True; FOldStatus := FStatus; @@ -8133,6 +9169,7 @@ function TPSExec.RunScript: Boolean; if FCurrProc.ClassType = TPSExternalProcRec then begin CMD_Err(erNoMainProc); FStatus := isLoaded; + RunScript := False; exit; end; FData := FCurrProc.Data; @@ -8141,6 +9178,9 @@ function TPSExec.RunScript: Boolean; FCurrentPosition := 0; end; isPaused: begin + { a run resumed at the top ends as one begun from the start does } + if FNestedRuns = 0 then + FOldStatus := isLoaded; FStatus := isRunning; end; else begin @@ -8155,6 +9195,10 @@ function TPSExec.RunScript: Boolean; while FStatus = isRunning do begin if @CallRunLine <> nil then CallRunLine(Self); + { a line hook that stopped or paused the script: the next instruction + does not run } + if FStatus <> isRunning then + break; if FCurrentPosition >= FDataLength then begin CMD_Err(erOutOfRange); // Error @@ -8452,9 +9496,11 @@ function TPSExec.RunScript: Boolean; {$IFDEF LOG} ODS_TPSExternalProcRec('proc', TPSExternalProcRec(u)); {$ENDIF} + lRaised := FRaisedCount; try if not TPSExternalProcRec(u).ProcPtr(Self, TPSExternalProcRec(u), FGlobalVars, FStack) then begin - if ExEx = erNoError then + { False with nothing raised: the call failed without saying why } + if FRaisedCount = lRaised then CMD_Err(erCouldNotCallProc); Break; end; @@ -8528,12 +9574,19 @@ function TPSExec.RunScript: Boolean; NewPosition: Longint; //relative to end of this instruction
} begin - FStack.Pop; if FCurrentPosition + 3 >= FDataLength then begin Cmd_Err(erOutOfRange); Break; end; + { as CM_PO: a value to pop, and not a routine's return address } + if (FStack.Count = 0) + or (PIFVariant(FStack.Data^[FStack.Count -1]).FType.BaseType = btReturnAddress) then + begin + CMD_Err(erOutOfStackRange); + break; + end; + FStack.Pop; {$ifdef FPC_REQUIRES_PROPER_ALIGNMENT} p := unaligned(Cardinal((@FData^[FCurrentPosition])^)); {$else} @@ -8548,13 +9601,21 @@ function TPSExec.RunScript: Boolean; NewPosition: Longint; //relative to end of this instruction
} begin - FStack.Pop; - FStack.Pop; if FCurrentPosition + 3 >= FDataLength then begin Cmd_Err(erOutOfRange); Break; end; + { as CM_PO, for each of the two values } + if (FStack.Count < 2) + or (PIFVariant(FStack.Data^[FStack.Count -1]).FType.BaseType = btReturnAddress) + or (PIFVariant(FStack.Data^[FStack.Count -2]).FType.BaseType = btReturnAddress) then + begin + CMD_Err(erOutOfStackRange); + break; + end; + FStack.Pop; + FStack.Pop; {$ifdef FPC_REQUIRES_PROPER_ALIGNMENT} p := unaligned(Cardinal((@FData^[FCurrentPosition])^)); {$else} @@ -8603,13 +9664,14 @@ function TPSExec.RunScript: Boolean; btemp := true; if not ReadVariable(vs, btemp) then Break; - { The compiler only emits Cm_CG for boolean types via - short-circuit 'or' evaluation in DoBinCalc (guarded by - IsBoolean) and for the boundary check in for-loops - (ProcessFor). Enum serialization in WriteTypes maps these - to btU8 (Boolean/ByteBool), btU16 (WordBool), or btU32 - (LongBool) only, so btS8/btS16/btS32 never fire and - btS64/btU64 are correctly absent. } + { The compiler writes Cm_CG for the boundary check of a for + loop (ProcessFor), on a Boolean register, and for the + short-circuit 'or' in DoBinCalc, on its result: a Boolean + (btU8) -- two ByteBool, WordBool or LongBool operands are + combined by their truth into one first -- except that a + Variant right operand keeps the left one's type, a ByteBool + (btU8), WordBool (btU16) or LongBool (btU32). The signed + arms are for compiled code this compiler did not write. } case Vs.aType.BaseType of btU8: btemp := tbtu8(vs.p^) <> 0; btS8: btemp := tbts8(vs.p^) <> 0; @@ -8650,9 +9712,10 @@ function TPSExec.RunScript: Boolean; btemp := true; if not ReadVariable(vs, BTemp) then Break; - { See Cm_CG comment: only btU8/btU16/btU32 are reachable - via short-circuit 'and' in DoBinCalc and for-loop entry - checks in ProcessFor. } + { As at Cm_CG: the compiler writes Cm_CNG for the + short-circuit 'and' in DoBinCalc, on the types of the 'or' + there, and for the conditions of while, repeat, for and + case statements, each a Boolean (btU8). } case Vs.aType.BaseType of btU8: btemp := tbtu8(vs.p^) = 0; btS8: btemp := tbts8(vs.p^) = 0; @@ -8685,6 +9748,9 @@ function TPSExec.RunScript: Boolean; pp := FExceptionStack.Data[FExceptionStack.Count -1]; while (pp.BasePtr = FCurrStackBase) or ((pp.BasePtr > FCurrStackBase) and (pp.BasePtr <> InvalidVal)) do begin + { an Exit out of a finally an exception runs ends that exception } + if pp.Unwinding then + pp.DropException; if pp.StackSize < Cardinal(FStack.Count) then begin for p := Longint(FStack.count) -1 downto Longint(pp.StackSize) do @@ -8703,6 +9769,8 @@ function TPSExec.RunScript: Boolean; pp.ExitPoint := FCurrentPosition -1; FCurrentPosition := pp.Finally2Offset; pp.Finally2Offset := InvalidVal; + pp.ExceptOffset := InvalidVal; + pp.DropException; p2 := 1; break; end else @@ -8734,7 +9802,11 @@ function TPSExec.RunScript: Boolean; FCurrStackBase := PPSVariantReturnAddress(vtemp).Addr.StackBase; FStack.Pop; if FCurrProc = nil then begin - FStatus := FOldStatus; + { the end of a run RunProc began: a Stop that the release of the + routine's locals above made (a destructor running a script + event) stands } + if FStatus = isRunning then + FStatus := FOldStatus; break; end; FData := FCurrProc.Data; @@ -8792,7 +9864,7 @@ function TPSExec.RunScript: Boolean; cm_in: { Script internal command: Integer NOT
Command: TPSCommand;
- Where: Cardinal;
+ Var: TPSVariable;
} begin if not ReadVariable(vd, True) then @@ -8876,14 +9948,12 @@ function TPSExec.RunScript: Boolean; FCurrentPosition := FCurrentPosition + p; end; cm_puexh: - { Script internal command: Pop Exception Handler
+ { Script internal command: Push Exception Handler
Command:TPSCommand;
- Position: Byte;
- 0 = end of try/finally/exception block;
- 1 = end of first finally
- 2 = end of except
- 3 = end of second finally
-

+ FinallyOffset,
+ ExceptionOffset, // FinallyOffset or ExceptionOffset need to be set.
+ Finally2Offset,
+ EndOfBlock: Cardinal;
} begin pp := TPSExceptionHandler.Create; @@ -8938,6 +10008,7 @@ function TPSExec.RunScript: Boolean; 1 = end of first finally
2 = end of except
3 = end of second finally
+ 4 = a jump leaving the frame (Break, Continue)

} begin @@ -8962,6 +10033,8 @@ function TPSExec.RunScript: Boolean; Break; end; pp.ExceptOffset := InvalidVal; + { the handler is over, and so is its exception } + pp.DropException; if pp.Finally2Offset <> InvalidVal then begin FCurrentPosition := pp.Finally2Offset; @@ -8996,6 +10069,8 @@ function TPSExec.RunScript: Boolean; begin FCurrentPosition := pp.Finally2Offset; pp.Finally2Offset := InvalidVal; + { the except before it, not entered, is over } + pp.ExceptOffset := InvalidVal; end else begin if pp.ExitPoint <> InvalidVal then p := pp.ExitPoint @@ -9024,6 +10099,22 @@ function TPSExec.RunScript: Boolean; cmd_err(ErOutOfRange); Break; end; + if pp.Unwinding then + begin + { the end of a finally an exception ran: the except of the same + statement takes it, a second finally runs for it, or it goes on } + if (pp.ExceptOffset <> InvalidVal) and (pp.ExceptOffset <> Cardinal(InvalidVal -1)) then + begin + pp.Unwinding := False; + FCurrentPosition := pp.ExceptOffset; + pp.ExceptOffset := Cardinal(InvalidVal -1); + end else if pp.Finally2Offset <> InvalidVal then + begin + FCurrentPosition := pp.Finally2Offset; + pp.Finally2Offset := InvalidVal; + end else + ResumeUnwinding; + end else if (ExEx <> ENoError) and (pp.ExceptOffset <> InvalidVal) and (pp.ExceptOffset <> InvalidVal -1) then begin FCurrentPosition := pp.ExceptOffset; @@ -9037,6 +10128,7 @@ function TPSExec.RunScript: Boolean; begin FCurrentPosition := pp.Finally2Offset; pp.Finally2Offset := InvalidVal; + pp.ExceptOffset := InvalidVal; end else begin if pp.ExitPoint <> InvalidVal then p := pp.ExitPoint @@ -9065,38 +10157,90 @@ function TPSExec.RunScript: Boolean; cmd_err(ErOutOfRange); Break; end; - if pp.ExitPoint <> InvalidVal then - p := pp.ExitPoint + if pp.Unwinding then + { the end of a second finally an exception ran: it goes on } + ResumeUnwinding else - p := pp.EndOfBlock; - pp.Free; - FExceptionStack.DeleteLast; - if ExEx <> eNoError then begin - Tmp := ExObject; - ExObject := nil; - ExceptionProc(ExProc, ExPos, ExEx, ExParam, Tmp); - end else - FCurrentPosition := p; + if pp.ExitPoint <> InvalidVal then + p := pp.ExitPoint + else + p := pp.EndOfBlock; + pp.Free; + FExceptionStack.DeleteLast; + if ExEx <> eNoError then + begin + Tmp := ExObject; + ExObject := nil; + ExceptionProc(ExProc, ExPos, ExEx, ExParam, Tmp); + end else + FCurrentPosition := p; + end; end; - end; - end; - cm_spc: - {Script internal command: Set Stack Pointer To Copy
- Command: TPSCommand;
- Where: Cardinal;
- } - begin - if not ReadVariable(vd, False) then - Break; - if vd.FreeType <> vtNone then - begin - FTempVars.Pop; - CMD_Err(erInvalidOpcodeParameter); - break; - end; - if (Vd.aType.BaseType <> btPointer) then - begin + 4: + { leave the frame for a jump (Break, Continue): run its pending finally, which comes back to + the next command, or remove the frame and go on } + begin + if (FExceptionStack.Count = 0) then + begin + cmd_err(ErOutOfRange); + Break; + end; + pp := FExceptionStack.Data^[FExceptionStack.Count -1]; + if pp = nil then begin + cmd_err(ErOutOfRange); + Break; + end; + { a jump out of a finally an exception runs ends that exception } + if pp.Unwinding then + pp.DropException; + { the values pushed inside the frame's statement go first, as for Exit and an exception: + its finally was compiled without them } + if pp.StackSize < Cardinal(FStack.Count) then + for p := Longint(FStack.Count) -1 downto Longint(pp.StackSize) do + FStack.Pop; + if pp.FinallyOffset <> InvalidVal then + begin + pp.ExitPoint := FCurrentPosition; + FCurrentPosition := pp.FinallyOffset; + pp.FinallyOffset := InvalidVal; + end else if pp.Finally2Offset <> InvalidVal then + begin + pp.ExitPoint := FCurrentPosition; + FCurrentPosition := pp.Finally2Offset; + pp.Finally2Offset := InvalidVal; + pp.ExceptOffset := InvalidVal; + pp.DropException; + end else + begin + pp.Free; + FExceptionStack.DeleteLast; + if ExEx <> eNoError then + begin + Tmp := ExObject; + ExObject := nil; + ExceptionProc(ExProc, ExPos, ExEx, ExParam, Tmp); + end; + end; + end; + end; + end; + cm_spc: + {Script internal command: Set Stack Pointer To Copy
+ Command: TPSCommand;
+ VarDest, VarSrc: TPSVariable;
+ } + begin + if not ReadVariable(vd, False) then + Break; + if vd.FreeType <> vtNone then + begin + FTempVars.Pop; + CMD_Err(erInvalidOpcodeParameter); + break; + end; + if (Vd.aType.BaseType <> btPointer) then + begin CMD_Err(erInvalidOpcodeParameter); break; end; @@ -9167,7 +10311,7 @@ function TPSExec.RunScript: Boolean; bts64: dec(tbts64(vd.P^)); btU64: dec(tbtu64(vd.P^)); {$ENDIF} - btVariant: dec(Variant(vd.P^)); + btVariant: {$IFDEF FPC}Variant(vd.P^) := Variant(vd.P^) - 1{$ELSE}dec(Variant(vd.P^)){$ENDIF}; else begin CMD_Err(ErTypeMismatch); @@ -9200,7 +10344,7 @@ function TPSExec.RunScript: Boolean; bts64: Inc(tbts64(vd.P^)); btU64: Inc(tbtu64(vd.P^)); {$ENDIF} - btVariant: Inc(Variant(vd.P^)); + btVariant: {$IFDEF FPC}Variant(vd.P^) := Variant(vd.P^) + 1{$ELSE}Inc(Variant(vd.P^)){$ENDIF}; else begin CMD_Err(ErTypeMismatch); @@ -9267,75 +10411,88 @@ function TPSExec.RunScript: Boolean; VdPtr := Pointer(Pointer(IPointer(vd.p)+PointerSize2)^); if vd.FreeType <> vtNone then FTempVars.Pop; { This makes vd invalid } + { a native method: routine 0 with the method beside it, called as a + host's routine is, so that its exception and a refused call are + the script's error } if (p = 0) and (VdPtr <> nil) then - begin - if not InvokeExternalMethod(TPSTypeRec_ProcPtr(vd.aType), VdSlf, VdPtr) then - Break; - end else begin + u := nil + else begin + { a nil procedural value: proc 0 with no method -- proc 0 is the + script's main block, which no script can name } + if p = 0 then begin + CMD_Err(erNullPointerException); + break; + end; if (p >= FProcs.Count) or (p = FMainProc) then begin CMD_Err(erOutOfProcRange); break; end; u := FProcs.Data^[p]; - if u.ClassType = TPSExternalProcRec then begin - try - if not TPSExternalProcRec(u).ProcPtr(Self, TPSExternalProcRec(u), FGlobalVars, FStack) then begin - if ExEx = erNoError then - CMD_Err(erCouldNotCallProc); - Break; - end; - except - {$IFDEF DELPHI6UP} - Tmp := AcquireExceptionObject; - {$ELSE} - if RaiseList <> nil then + end; + if (u = nil) or (u.ClassType = TPSExternalProcRec) then begin + lRaised := FRaisedCount; + try + if u = nil then + lCalled := InvokeExternalMethod(TPSTypeRec_ProcPtr(vd.aType), VdSlf, VdPtr) + else + lCalled := TPSExternalProcRec(u).ProcPtr(Self, TPSExternalProcRec(u), FGlobalVars, FStack); + if not lCalled then begin + { False with nothing raised: the call failed without saying why } + if FRaisedCount = lRaised then + CMD_Err(erCouldNotCallProc); + Break; + end; + except + {$IFDEF DELPHI6UP} + Tmp := AcquireExceptionObject; + {$ELSE} + if RaiseList <> nil then + begin + Tmp := Exception(PRaiseFrame(RaiseList)^.ExceptObject); + PRaiseFrame(RaiseList)^.ExceptObject := nil; + end else + Tmp := nil; + {$ENDIF} + if Tmp <> nil then + begin + if Tmp is EPSException then begin - Tmp := Exception(PRaiseFrame(RaiseList)^.ExceptObject); - PRaiseFrame(RaiseList)^.ExceptObject := nil; + ExceptionProc(EPSException(tmp).ProcNo, EPSException(tmp).ProcPos, erCustomError, tbtString(EPSException(tmp).Message), nil); + Tmp.Free; + break; end else - Tmp := nil; - {$ENDIF} - if Tmp <> nil then + if Tmp is EDivByZero then begin - if Tmp is EPSException then - begin - ExceptionProc(EPSException(tmp).ProcNo, EPSException(tmp).ProcPos, erCustomError, tbtString(EPSException(tmp).Message), nil); - Tmp.Free; - break; - end else - if Tmp is EDivByZero then - begin - CMD_Err3(erDivideByZero, tbtString(Exception(Tmp).Message), Tmp); - break; - end; - if Tmp is EZeroDivide then - begin - CMD_Err3(erDivideByZero, tbtString(Exception(Tmp).Message), Tmp); - break; - end; - if Tmp is EMathError then - begin - CMD_Err3(erMathError, tbtString(Exception(Tmp).Message), Tmp); - break; - end; + CMD_Err3(erDivideByZero, tbtString(Exception(Tmp).Message), Tmp); + break; + end; + if Tmp is EZeroDivide then + begin + CMD_Err3(erDivideByZero, tbtString(Exception(Tmp).Message), Tmp); + break; + end; + if Tmp is EMathError then + begin + CMD_Err3(erMathError, tbtString(Exception(Tmp).Message), Tmp); + break; end; - if (Tmp <> nil) and (Tmp is Exception) then - CMD_Err3(erException, tbtString(Exception(Tmp).Message), Tmp) else - CMD_Err3(erException, '', Tmp); - Break; end; - end - else begin - vtemp := FStack.PushType(FReturnAddressType); - PPSVariantReturnAddress(vtemp).Addr.ProcNo := FCurrProc; - PPSVariantReturnAddress(vtemp).Addr.Position := FCurrentPosition; - PPSVariantReturnAddress(vtemp).Addr.StackBase := FCurrStackBase; - FCurrStackBase := FStack.Count - 1; - FCurrProc := TPSInternalProcRec(u); - FData := FCurrProc.Data; - FDataLength := FCurrProc.Length; - FCurrentPosition := 0; + if (Tmp <> nil) and (Tmp is Exception) then + CMD_Err3(erException, tbtString(Exception(Tmp).Message), Tmp) else + CMD_Err3(erException, '', Tmp); + Break; end; + end + else begin + vtemp := FStack.PushType(FReturnAddressType); + PPSVariantReturnAddress(vtemp).Addr.ProcNo := FCurrProc; + PPSVariantReturnAddress(vtemp).Addr.Position := FCurrentPosition; + PPSVariantReturnAddress(vtemp).Addr.StackBase := FCurrStackBase; + FCurrStackBase := FStack.Count - 1; + FCurrProc := TPSInternalProcRec(u); + FData := FCurrProc.Data; + FDataLength := FCurrProc.Length; + FCurrentPosition := 0; end; end; CM_CO: @@ -9431,7 +10588,32 @@ function TPSExec.RunScript: Boolean; // if cmd <> invalidval then ProfilerExitProc(Cmd+1); // if ExEx <> erNoError then FStatus := FOldStatus; until (FExceptionStack.Count = 0) or (Fstatus <> IsRunning); - if FStatus = isLoaded then begin + { a Stop skips the code that retires the frames of the try statements it + leaves: they go with this run, before another run can meet them } + if FStatus = isLoaded then + while Longint(FExceptionStack.Count) > lFrames do + begin + pp := FExceptionStack.Data[FExceptionStack.Count - 1]; + FExceptionStack.DeleteLast; + { the exception a finally of the run was running for, which the run + did not handle, ends the run with it } + if pp.Unwinding and (ExEx = erNoError) then + begin + ExProc := pp.ExceptionProcNo; + ExPos := pp.ExceptionPos; + ExEx := pp.ExceptionData; + ExParam := pp.ExceptionParam; + if ExObject <> nil then + ExObject.Free; + ExObject := pp.ExceptionObject; + pp.ExceptionObject := nil; + end; + pp.Free; + end; + { a run RunProc began leaves the stack below it to whatever began it -- a + running script, a host, or a release while the stack is being popped or + cleared: RunProc pops this run's own values } + if (FStatus = isLoaded) and (FNestedRuns = 0) then begin for I := Longint(FStack.Count) - 1 downto 0 do FStack.Pop; FStack.Clear; @@ -9474,6 +10656,26 @@ function DefProc(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStack S: string; pex: TPSExceptionHandler; Tmp: TObject; + lStrIdx: {$IFNDEF PS_NOINT64}Int64{$ELSE}Longint{$ENDIF}; +{$IFNDEF PS_NOWIDESTRING} + + { WStrSet's character: a WideChar or Char, or the first character of a string, which is how a character + argument of its AnyString parameter arrives } + function WStrSetChar: WideChar; + var + lText: tbtunicodestring; + begin + if Stack.GetItem(Stack.Count - 1)^.FType.BaseType in [btString, btWideString, btUnicodeString] then + begin + lText := Stack.GetUnicodeString(-1); + if lText = '' then + raise Exception.Create(RPS_TypeMismatch); + Result := lText[1]; + end else + Result := WideChar(Stack.GetInt(-1)); + end; +{$ENDIF} + begin { The following needs to be in synch in these 3 functions: -UPSCompiler.TPSPascalCompiler.DefineStandardProcedures @@ -9486,10 +10688,14 @@ function DefProc(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStack 2: Stack.SetInt(-1, StrToIntDef(Stack.GetAnsiString(-2), Stack.GetInt(-3))); // strtointdef 3: {$IFNDEF PS_NOWIDESTRING} - if Stack.GetItem(Stack.Count -2)^.FType.BaseType = btUnicodeString then + { a wide string on either side makes the search wide, as in Delphi: by the substring's type alone, a Char + or AnsiString substring read a wide S through the ANSI code page } + if (Stack.GetItem(Stack.Count -2)^.FType.BaseType = btUnicodeString) or + (Stack.GetItem(Stack.Count -3)^.FType.BaseType = btUnicodeString) then Stack.SetInt(-1, Pos(Stack.GetUnicodeString(-2), Stack.GetUnicodeString(-3)))// pos else - if Stack.GetItem(Stack.Count -2)^.FType.BaseType = btWideString then + if (Stack.GetItem(Stack.Count -2)^.FType.BaseType = btWideString) or + (Stack.GetItem(Stack.Count -3)^.FType.BaseType = btWideString) then Stack.SetInt(-1, Pos(Stack.GetWideString(-2), Stack.GetWideString(-3)))// pos else{$ENDIF} Stack.SetInt(-1, Pos(Stack.GetAnsiString(-2), Stack.GetAnsiString(-3)));// pos @@ -9548,24 +10754,28 @@ function DefProc(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStack case temp.aType.BaseType of btString: begin - I := Stack.GetInt(-3); - if (i<1) or (i>length(tbtstring(temp.Dta^))) then + { the whole index: narrowed to 32 bits first, 4294967297 selected the first character } + lStrIdx := Stack.{$IFNDEF PS_NOINT64}GetInt64{$ELSE}GetInt{$ENDIF}(-3); + if (lStrIdx<1) or (lStrIdx>length(tbtstring(temp.Dta^))) then begin Caller.CMD_Err2(erCustomError, tbtString(RPS_OutOfStringRange)); Result := True; exit; end; + I := lStrIdx; Stack.SetInt(-1,Ord(tbtstring(temp.Dta^)[i])); end; btUnicodeString: begin - I := Stack.GetInt(-3); - if (i<1) or (i>length(tbtUnicodeString(temp.Dta^))) then + { the whole index: narrowed to 32 bits first, 4294967297 selected the first character } + lStrIdx := Stack.{$IFNDEF PS_NOINT64}GetInt64{$ELSE}GetInt{$ENDIF}(-3); + if (lStrIdx<1) or (lStrIdx>length(tbtUnicodeString(temp.Dta^))) then begin Caller.CMD_Err2(erCustomError, tbtString(RPS_OutOfStringRange)); Result := True; exit; end; + I := lStrIdx; Stack.SetInt(-1,Ord(tbtUnicodeString(temp.Dta^)[i])); end; @@ -9587,24 +10797,28 @@ function DefProc(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStack case temp.aType.BaseType of btString: begin - I := Stack.GetInt(-2); - if (i<1) or (i>length(tbtstring(temp.Dta^))) then + { the whole index: narrowed to 32 bits first, 4294967297 selected the first character } + lStrIdx := Stack.{$IFNDEF PS_NOINT64}GetInt64{$ELSE}GetInt{$ENDIF}(-2); + if (lStrIdx<1) or (lStrIdx>length(tbtstring(temp.Dta^))) then begin Caller.CMD_Err2(erCustomError, tbtString(RPS_OutOfStringRange)); Result := True; exit; end; + I := lStrIdx; tbtstring(temp.Dta^)[i] := tbtchar(Stack.GetInt(-1)); end; btUnicodeString: begin - I := Stack.GetInt(-2); - if (i<1) or (i>length(tbtUnicodeString(temp.Dta^))) then + { the whole index: narrowed to 32 bits first, 4294967297 selected the first character } + lStrIdx := Stack.{$IFNDEF PS_NOINT64}GetInt64{$ELSE}GetInt{$ENDIF}(-2); + if (lStrIdx<1) or (lStrIdx>length(tbtUnicodeString(temp.Dta^))) then begin Caller.CMD_Err2(erCustomError, tbtString(RPS_OutOfStringRange)); Result := True; exit; end; + I := lStrIdx; tbtUnicodeString(temp.Dta^)[i] := WideChar(Stack.GetInt(-1)); end; @@ -9664,8 +10878,15 @@ function DefProc(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStack 15: Stack.SetReal(-1, Sin(Stack.GetReal(-2))); // Sin 16: Stack.SetReal(-1, Cos(Stack.GetReal(-2))); // Cos 17: Stack.SetReal(-1, SQRT(Stack.GetReal(-2))); // Sqrt + {$IFNDEF PS_NOINT64} + { the whole Int64, which the compiler now declares; a script compiled with the LongInt declaration gets + the low half, as before } + 18: Stack.SetInt64(-1, Round(Stack.GetReal(-2))); // Round + 19: Stack.SetInt64(-1, Trunc(Stack.GetReal(-2))); // Trunc + {$ELSE} 18: Stack.SetInt(-1, Round(Stack.GetReal(-2))); // Round 19: Stack.SetInt(-1, Trunc(Stack.GetReal(-2))); // Trunc + {$ENDIF} 20: Stack.SetReal(-1, Int(Stack.GetReal(-2))); // Int 21: Stack.SetReal(-1, Pi); // Pi 22: Stack.SetReal(-1, Abs(Stack.GetReal(-2))); // Abs @@ -9702,7 +10923,19 @@ function DefProc(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStack begin S := Stack.GetString(-2); if S <> '' then +{$IF Defined(FPC_FULLVERSION) and (FPC_FULLVERSION < 30204)} + begin + { Free Pascal before 3.2.4 declares StringOfChar for an AnsiChar alone, which would narrow a + wide character through the code page: the string is built from the character here } + I := Stack.GetInt(-3); + S := Copy(S, 1, 1); + while (I > 0) and (Length(S) < I) do + S := S + S; + Stack.SetString(-1, Copy(S, 1, I)); + end +{$ELSE} Stack.SetString(-1, StringOfChar(S[1], Stack.GetInt(-3))) +{$IFEND} else Stack.SetString(-1, StringOfChar(#0, Stack.GetInt(-3))); end; @@ -9724,6 +10957,8 @@ function DefProc(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStack btUnicodeString: b := tbtUnicodeString(temp.dta^)<> ''; {$ENDIF} btArray, btClass{$IFNDEF PS_NOINTERFACES}, btInterface{$ENDIF}: b := Pointer(temp.dta^) <> nil; + { a script routine has a routine number, a Delphi method a code address } + btProcPtr: b := (tbtu32(temp.dta^) <> 0) or (Pointer(Pointer(IPointer(temp.dta)+PointerSize2)^) <> nil); else Result := False; Exit; @@ -9735,13 +10970,13 @@ function DefProc(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStack end; 30: begin {RaiseLastException} - if (Caller.FExceptionStack.Count > 0) then begin - pex := Caller.FExceptionStack.Data[Caller.fExceptionStack.Count -1]; - if pex.ExceptOffset = Cardinal(InvalidVal -1) then begin - Tmp := pex.ExceptionObject; - pex.ExceptionObject := nil; - Caller.ExceptionProc(Caller.ExProc, pex.ExceptOffset, pex.ExceptionData, pex.ExceptionParam, tmp); - end; + { the exception of the nearest except handler running, raised again + where it was raised first } + pex := _HandlerFrame(Caller.FExceptionStack); + if pex <> nil then begin + Tmp := pex.ExceptionObject; + pex.ExceptionObject := nil; + Caller.ExceptionProc(pex.ExceptionProcNo, pex.ExceptionPos, pex.ExceptionData, pex.ExceptionParam, tmp); end; end; 31: Caller.CMD_Err2(TPSError(Stack.GetInt(-1)), Stack.GetAnsiString(-2)); {RaiseExeption} @@ -9757,10 +10992,10 @@ function DefProc(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStack 40: Stack.SetAnsiString(-1, tbtstring(SysUtils.IntToStr(Stack.GetInt64(-2))));// Int64ToStr 41: Stack.SetInt64(-1, StrToInt64Def(string(Stack.GetAnsiString(-2)), Stack.GetInt64(-3))); // StrToInt64Def 45: Stack.SetUInt64(-1, StrToUInt64(string(Stack.GetAnsiString(-2)))); // StrToUInt64 - 46: Stack.SetAnsiString(-1, tbtstring(SysUtils.UIntToStr(Stack.GetUInt64(-2))));// UInt64ToStr + 46: Stack.SetAnsiString(-1, tbtstring(UIntToStr(Stack.GetUInt64(-2))));// UInt64ToStr 47: Stack.SetUInt64(-1, StrToUInt64Def(string(Stack.GetAnsiString(-2)), Stack.GetUInt64(-3))); // StrToUInt64Def {$ENDIF} - 48: Stack.SetAnsiString(-1, tbtstring(SysUtils.UIntToStr({$IFNDEF PS_NOINT64}Stack.GetUInt64(-2){$ELSE}Stack.GetUInt(-2){$ENDIF}))); // UIntToStr + 48: Stack.SetAnsiString(-1, tbtstring(UIntToStr({$IFNDEF PS_NOINT64}Stack.GetUInt64(-2){$ELSE}Stack.GetUInt(-2){$ENDIF}))); // UIntToStr 42: // sizeof begin temp := NewTPSVariantIFC(Stack[Stack.Count -2], False); @@ -9780,24 +11015,28 @@ function DefProc(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStack case temp.aType.BaseType of btWideString: begin - I := Stack.GetInt(-3); - if (i<1) or (i>length(tbtwidestring(temp.Dta^))) then + { the whole index: narrowed to 32 bits first, 4294967297 selected the first character } + lStrIdx := Stack.{$IFNDEF PS_NOINT64}GetInt64{$ELSE}GetInt{$ENDIF}(-3); + if (lStrIdx<1) or (lStrIdx>length(tbtwidestring(temp.Dta^))) then begin Caller.CMD_Err2(erCustomError, tbtString(RPS_OutOfStringRange)); Result := True; exit; end; + I := lStrIdx; Stack.SetInt(-1,Ord(tbtwidestring(temp.Dta^)[i])); end; btUnicodeString: begin - I := Stack.GetInt(-3); - if (i<1) or (i>length(tbtUnicodeString(temp.Dta^))) then + { the whole index: narrowed to 32 bits first, 4294967297 selected the first character } + lStrIdx := Stack.{$IFNDEF PS_NOINT64}GetInt64{$ELSE}GetInt{$ENDIF}(-3); + if (lStrIdx<1) or (lStrIdx>length(tbtUnicodeString(temp.Dta^))) then begin Caller.CMD_Err2(erCustomError, tbtString(RPS_OutOfStringRange)); Result := True; exit; end; + I := lStrIdx; Stack.SetInt(-1,Ord(tbtUnicodeString(temp.Dta^)[i])); end; @@ -9819,26 +11058,30 @@ function DefProc(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStack case temp.aType.BaseType of btWideString: begin - I := Stack.GetInt(-2); - if (i<1) or (i>length(tbtWidestring(temp.Dta^))) then + { the whole index: narrowed to 32 bits first, 4294967297 selected the first character } + lStrIdx := Stack.{$IFNDEF PS_NOINT64}GetInt64{$ELSE}GetInt{$ENDIF}(-2); + if (lStrIdx<1) or (lStrIdx>length(tbtWidestring(temp.Dta^))) then begin Caller.CMD_Err2(erCustomError, tbtString(RPS_OutOfStringRange)); Result := True; exit; end; - tbtWidestring(temp.Dta^)[i] := WideChar(Stack.GetInt(-1)); + I := lStrIdx; + tbtWidestring(temp.Dta^)[i] := WStrSetChar; end; btUnicodeString: begin - I := Stack.GetInt(-2); - if (i<1) or (i>length(tbtunicodestring(temp.Dta^))) then + { the whole index: narrowed to 32 bits first, 4294967297 selected the first character } + lStrIdx := Stack.{$IFNDEF PS_NOINT64}GetInt64{$ELSE}GetInt{$ENDIF}(-2); + if (lStrIdx<1) or (lStrIdx>length(tbtunicodestring(temp.Dta^))) then begin Caller.CMD_Err2(erCustomError, tbtString(RPS_OutOfStringRange)); Result := True; exit; end; - tbtunicodestring(temp.Dta^)[i] := WideChar(Stack.GetInt(-1)); + I := lStrIdx; + tbtunicodestring(temp.Dta^)[i] := WStrSetChar; end; else begin @@ -9967,6 +11210,9 @@ function SetLength_(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSSt arr:=NewTPSVariantIFC(Stack[Stack.Count-1],true); if arr.aType.BaseType=btArray then begin + { a negative length is an error for an array, as in Delphi (a string takes it as 0) } + if Stack.GetInt(-2) < 0 then + raise Exception.Create(RPS_OutOfRange); PSDynArraySetLength(Pointer(arr.Dta^),arr.aType,Stack.GetInt(-2)); Result:=true; end else @@ -10103,10 +11349,17 @@ function Include_(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStac begin TheSet:=NewTPSVariantIFC(Stack[Stack.Count-1],true); NewMember:=NewTPSVariantIFC(Stack[Stack.Count-2],false); - Result := (TheSet.aType.BaseType = btSet) and (NewMember.aType.BaseType = btU8); + { a Char is one byte, as the set's members are -- of a set of 256 members, a set of Char: a Char into an + enumeration's set is refused, as before } + Result := (TheSet.aType.BaseType = btSet) and + ((NewMember.aType.BaseType = btU8) or + ((NewMember.aType.BaseType = btChar) and (TPSTypeRec_Set(TheSet.aType).aBitSize = 256))); if not Result then Exit; SetData := TheSet.Dta; Val := Tbtu8(NewMember.dta^); + { a member past the set's size would change the memory after the set } + if Val >= TPSTypeRec_Set(TheSet.aType).aBitSize then + raise Exception.Create(RPS_OutOfRange); SetData^[Val shr 3] := SetData^[Val shr 3] or (1 shl (Val and 7)); end; @@ -10118,10 +11371,17 @@ function Exclude_(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStac begin TheSet:=NewTPSVariantIFC(Stack[Stack.Count-1],true); NewMember:=NewTPSVariantIFC(Stack[Stack.Count-2],false); - Result := (TheSet.aType.BaseType = btSet) and (NewMember.aType.BaseType = btU8); + { a Char is one byte, as the set's members are -- of a set of 256 members, a set of Char: a Char into an + enumeration's set is refused, as before } + Result := (TheSet.aType.BaseType = btSet) and + ((NewMember.aType.BaseType = btU8) or + ((NewMember.aType.BaseType = btChar) and (TPSTypeRec_Set(TheSet.aType).aBitSize = 256))); if not Result then Exit; SetData := TheSet.Dta; Val := Tbtu8(NewMember.dta^); + { a member past the set's size would change the memory after the set } + if Val >= TPSTypeRec_Set(TheSet.aType).aBitSize then + raise Exception.Create(RPS_OutOfRange); SetData^[Val shr 3] := SetData^[Val shr 3] and not (1 shl (Val and 7)); end; @@ -10158,6 +11418,7 @@ procedure TPSExec.RegisterStandardProcs; RegisterFunctionName('Insert', DefProc, Pointer(6), nil); RegisterFunctionName('StrGet', DefProc, Pointer(7), nil); + RegisterFunctionName('StrGet2', DefProc, Pointer(7), nil); RegisterFunctionName('StrSet', DefProc, Pointer(8), nil); RegisterFunctionName('UpperCase', DefProc, Pointer(10), nil); RegisterFunctionName('LowerCase', DefProc, Pointer(11), nil); @@ -10275,6 +11536,12 @@ function IntPIFVariantToVariant(Src: pointer; aType: TPSTypeRec; var Dest: Varia begin aType := TPSTypeRec(Pointer(IPointer(src)+PointerSize)^); Src := Pointer(Pointer(Src)^); + if (aType = nil) or (Src = nil) then + begin + Dest := null; + Result := True; + exit; + end; end; case aType.BaseType of @@ -10354,13 +11621,26 @@ TOpenArray = record ItemCount: Longint; Data: Pointer; VarParam: Boolean; + { the script array's elements: an argument naming the same array shares + the earlier one's Data } + Source: Pointer; end; -function CreateOpenArray(VarParam: Boolean; Sender: TPSExec; val: PPSVariantIFC): POpenArray; + +{ An open array argument of a native call. An array of const goes as a buffer + of TVarRec made from the script's elements, written back by DestroyOpenArray + for a var argument. An argument naming the same script array as an earlier + one of the call (in aCallData) shares that one's buffer, as two arguments of + one array share its elements in Delphi -- a const one sees what a var one + writes, a value one the routine copies on entry -- and a var one makes the + shared buffer written back, once } +function CreateOpenArray(VarParam: Boolean; Sender: TPSExec; val: PPSVariantIFC; aCallData: TPSList): POpenArray; var datap, p: Pointer; ctype: TPSTypeRec; cp: Pointer; i: Longint; + lIdx: Longint; + lEarlier: POpenArray; begin if (Val.aType.BaseType <> btArray) and (val.aType.BaseType <> btStaticArray) then begin @@ -10381,6 +11661,7 @@ function CreateOpenArray(VarParam: Boolean; Sender: TPSExec; val: PPSVariantIFC) Result^.ItemCount := PSDynArrayGetLength(Pointer(Val.Dta^), val.aType); datap := Pointer(Val.Dta^); end; + Result.Source := datap; if TPSTypeRec_Array(Val.aType).ArrayType.BaseType <> btPointer then begin Result.FreeIt := False; @@ -10391,6 +11672,20 @@ function CreateOpenArray(VarParam: Boolean; Sender: TPSExec; val: PPSVariantIFC) { BaseType is btPointer, which means array of const } + if aCallData <> nil then + for lIdx := 0 to aCallData.Count - 1 do + begin + lEarlier := aCallData[lIdx]; + if (lEarlier^.AType = 0) and (lEarlier^.Source = datap) then + begin + Result.FreeIt := False; + Result.Data := lEarlier^.Data; + if VarParam then + lEarlier^.VarParam := True; + exit; + end; + end; + Result.FreeIt := True; Result.ElementSize := sizeof(TVarRec); GetMem(Result.Data, Result.ItemCount * Result.ElementSize); @@ -10443,7 +11738,7 @@ function CreateOpenArray(VarParam: Boolean; Sender: TPSExec; val: PPSVariantIFC) tvarrec(p^).VType := vtWideChar; tvarrec(p^).VWideChar := tbtwidechar(cp^); end; - {$IFDEF DELPHI2009UP} + {$IFNDEF WIDESTRING_EQUAL_UNICODESTRING} btUnicodeString: begin tvarrec(p^).VType := vtUnicodeString; tbtunicodestring(TVarRec(p^).VUnicodeString) := tbtunicodestring(cp^); @@ -10541,6 +11836,8 @@ procedure DestroyOpenArray(Sender: TPSExec; V: POpenArray); begin ctype := Pointer(Pointer(IPointer(datap)+PointerSize)^); cp := Pointer(Datap^); + { an element without data went as a nil pointer (CreateOpenArray): nothing to free or write back } + if cp <> nil then case ctype.BaseType of btU8: begin @@ -10608,7 +11905,7 @@ procedure DestroyOpenArray(Sender: TPSExec; V: POpenArray); if v^.varParam then tbtwidechar(cp^) := tvarrec(p^).VWideChar; end; - {$IFDEF DELPHI2009UP} + {$IFNDEF WIDESTRING_EQUAL_UNICODESTRING} btUnicodeString: begin if v^.VarParam then @@ -10630,6 +11927,10 @@ procedure DestroyOpenArray(Sender: TPSExec; V: POpenArray); tbtstring(cp^) := tbtstring(TVarRec(p^).VString); finalize(tbtString(TVarRec(p^).VAnsiString)); end; + btPChar: begin + if v^.VarParam then + Pointer(cp^) := TVarRec(p^).VPChar; + end; btClass: begin if v^.VarParam then Pointer(cp^) := TVarRec(p^).VObject; @@ -10638,7 +11939,7 @@ procedure DestroyOpenArray(Sender: TPSExec; V: POpenArray); {$IFDEF Delphi3UP} btInterface: begin if v^.VarParam then - IUnknown(cp^) := IUnknown(TVarRec(p^).VInterface); + SetInterfaceVar(Pointer(cp^), TVarRec(p^).VInterface); IUnknown(TVarRec(p^).VInterface) := nil; end; {$ENDIF} @@ -10653,6 +11954,19 @@ procedure DestroyOpenArray(Sender: TPSExec; V: POpenArray); end; +{ The method a procedure-pointer value stands for: the script procedure whose number it holds, + otherwise the method stored beside the number -- a handler the script read from an event + Delphi had assigned -- and nil when there is none. } +function ProcPtrToMethod(Se: TPSExec; ProcPtr: Pointer): TMethod; +begin + if tbtu32(ProcPtr^) <> 0 then + Result := MkMethod(Se, tbtu32(ProcPtr^)) + else begin + Result.Data := Pointer(Pointer(IPointer(ProcPtr)+PointerSize)^); + Result.Code := Pointer(Pointer(IPointer(ProcPtr)+PointerSize2)^); + end; +end; + {$IFNDEF FPC} {$UNDEF _INVOKECALL_INC_} {$UNDEF USEINVOKECALL} @@ -10705,9 +12019,24 @@ procedure DestroyOpenArray(Sender: TPSExec; V: POpenArray); {$ENDIF} {$ENDIF} +{ A native routine can call a script routine back, which can grow the script's + stack -- its data does not move (UseChunks) -- or clear it, while the + native routine holds addresses into it: chunks a Clear releases meanwhile are + kept until the call ends } +function TPSExec.InnerfuseCall(_Self, Address: Pointer; CallingConv: TPSCallingConvention; Params: TPSList; res: PPSVariantIFC): Boolean; +begin + FStack.NativeCallStarts; + try + Result := PlatformInnerfuseCall(_Self, Address, CallingConv, Params, res); + finally + FStack.NativeCallEnds; + end; +end; + type PScriptMethodInfo = ^TScriptMethodInfo; TScriptMethodInfo = record + { nil once the script has ended } Se: TPSExec; ProcNo: Cardinal; end; @@ -10720,6 +12049,9 @@ function MkMethod(FSE: TPSExec; No: Cardinal): TMethod; Result.Code := nil; Result.Data := nil; end else begin + {$IFDEF FPC}{$IFDEF empty_methods_handler} + raise Exception.Create(RPS_NoNativeMethodsHandler); + {$ENDIF}{$ENDIF} Result.Code := @MyAllMethodsHandler; Result.Data := GetMethodInfoRec(FSE, No); end; @@ -10728,7 +12060,15 @@ function MkMethod(FSE: TPSExec; No: Cardinal): TMethod; procedure PFree(Sender: TPSExec; P: PScriptMethodInfo); begin - Dispose(p); + { the script has ended, but native code can still hold a method made from + this record -- an event of an object that outlives the script -- so the + record is never freed: a call through it finds no executor and is + refused. Where the RTL has the entry, the memory manager is asked to + leave it out of a leak report at exit; whether it does is the manager's } + P^.Se := nil; + {$IF Defined(DELPHI2006UP) and not Defined(FPC)} + System.RegisterExpectedMemoryLeak(P); + {$IFEND} end; function GetMethodInfoRec(SE: TPSExec; ProcNo: Cardinal): Pointer; @@ -10744,7 +12084,8 @@ function GetMethodInfoRec(SE: TPSExec; ProcNo: Cardinal): Pointer; I := 2147483647; repeat pp := Se.FindProcResource2(@PFree, I); - if (i <> -1) and (pp^.ProcNo = ProcNo) then + { a record at the list's first place too: the search leaves i at -1 there } + if (pp <> nil) and (pp^.ProcNo = ProcNo) then begin Result := Pp; exit; @@ -10809,7 +12150,7 @@ procedure CheckPackagePtr(var P: PByteArr); {$ifdef Win64} if (word((@p[0])^) = $25FF) {and (word((@p[6])^)=$C08B)}then begin - p := PPointer(NativeUInt(@P[0]) + Cardinal((@p[2])^) + 6{Instruction Size})^ + p := PPointer(NativeInt(@P[0]) + Integer((@p[2])^) + 6{Instruction Size})^ end; {$endif} end; @@ -10953,7 +12294,10 @@ function PSGetArrayField(const avar: TPSVariantIFC; Fieldno: Longint): TPSVarian if TPSTypeRec_Array(Result.aType).ArrayType.BaseType = btPointer then begin { See CreateOpenArray } - Result := PPSVariantIFC(IPointer(Result.Dta^) + IPointer(Fieldno) * 3 * SizeOf(Pointer))^; + if Result.aType.BaseType = btStaticArray then + Result := PPSVariantIFC(IPointer(Result.Dta) + IPointer(Fieldno) * 3 * SizeOf(Pointer))^ + else + Result := PPSVariantIFC(IPointer(Result.Dta^) + IPointer(Fieldno) * 3 * SizeOf(Pointer))^; exit; end; @@ -11032,6 +12376,13 @@ function ClassCallProcMethod(Caller: TPSExec; p: TPSExternalProcRec; Global, Sta n := Stack[Stack.Count -1] else n := Stack[Stack.Count -2]; + { Free on nil does nothing, as Delphi's TObject.Free does; any other method on nil is refused below } + if (n <> nil) and (n^.FType.BaseType = btClass) and (PPSVariantClass(n).Data = nil) and (p.Ext2 = nil) and + (p.Ext1 = @TObject.Free) then + begin + Result := True; + exit; + end; if (n = nil) or (n^.FType.BaseType <> btClass)or (PPSVariantClass(n).Data = nil) then begin Caller.CMD_Err(erNullPointerException); @@ -11128,9 +12479,10 @@ function ClassCallProcConstructor(Caller: TPSExec; p: TPSExternalProcRec; Global exit; end; {$IFDEF FPC} - // under FPC a constructor it's called with self=0 (EAX) and - // the VMT class pointer in EDX so they are effectively swaped - // using register calling convention + // Free Pascal 3 calls a constructor as Delphi does, with the class in the + // first register and 1 in the second. Here the class travels as the first + // parameter and Self is 1; the stubs' constructor arm (x86.inc, x64.inc) + // loads the first parameter first, so the two arrive in that order. {$IFDEF CPU64} PPSVariantS64(IntVal).Data := Int64(FSelf); {$ELSE} @@ -11287,8 +12639,9 @@ function CastProc(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStac if IUnknown(resvar.Dta^) <> nil then IUnknown(resvar.Dta^).Release; {$ENDIF} - IUnknown(resvar.Dta^) := nil; - if (IUnknown(invar.Dta^) = nil) or (IUnknown(invar.Dta^).QueryInterface(TPSTypeRec_Interface(ResVar.aType).Guid, IUnknown(resvar.Dta^)) <> 0) then + SetInterfaceVar(Pointer(resvar.Dta^), nil); + { a nil interface casts to nil, as in Delphi } + if (IUnknown(invar.Dta^) <> nil) and (IUnknown(invar.Dta^).QueryInterface(TPSTypeRec_Interface(ResVar.aType).Guid, IUnknown(resvar.Dta^)) <> 0) then begin Caller.CMD_Err2(erCustomError, tbtString(RPS_CannotCastInterface)); Result := False; @@ -11301,8 +12654,9 @@ function CastProc(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStac if IUnknown(resvar.Dta^) <> nil then IUnknown(resvar.Dta^).Release; {$ENDIF} - IUnknown(resvar.Dta^) := nil; - if (TObject(invar.Dta^)= nil) or (not TObject(invar.dta^).GetInterface(TPSTypeRec_Interface(ResVar.aType).Guid, IUnknown(resvar.Dta^))) then + SetInterfaceVar(Pointer(resvar.Dta^), nil); + { a nil object casts to nil, as in Delphi } + if (TObject(invar.Dta^) <> nil) and not TObject(invar.dta^).GetInterface(TPSTypeRec_Interface(ResVar.aType).Guid, IUnknown(resvar.Dta^)) then begin Caller.CMD_Err2(erCustomError, tbtString(RPS_CannotCastInterface)); Result := False; @@ -11332,13 +12686,16 @@ function CastProc(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStac exit; end; + Result := True; try TObject(ResVar.Dta^) := TObject(InVar.Dta^) as FSelf; except Result := False; Caller.CMD_Err2(erCustomError, tbtString(RPS_CannotCastObject)); - exit; end; + { left after the handler: Delphi XE3 to XE5 for Win64 keep the exception object of a handler left by a jump } + if not Result then + exit; end else begin Result := False; @@ -11366,7 +12723,7 @@ function NilProc(Caller: TPSExec; p: TPSExternalProcRec; Global, Stack: TPSStack if IUnknown(n.Dta^) <> nil then IUnknown(n.Dta^).Release; {$ENDIF} - IUnknown(n.Dta^) := nil; + SetInterfaceVar(Pointer(n.Dta^), nil); end else {$ENDIF} Pointer(n.Dta^) := nil; @@ -11456,6 +12813,24 @@ function InterfaceProc(Sender: TPSExec; p: TPSExternalProcRec; Tag: Pointer): Bo end; +{ Whether aValue lies in the range of the Delphi type of aProp, a published + property, where that type is an enumeration; True for any other kind. A + script enumeration can have more members than the Delphi type of its name + (TBorderStyle, a subrange in Delphi), and SetOrdProp stores whatever it is + given. } +function _InPropertyRange(aProp: PPropInfo; aValue: Longint): Boolean; +var + lType : PTypeInfo; + lData : PTypeData; +begin + lType := aProp^.PropType{$IFNDEF FPC}^{$ENDIF}; + Result := True; + if lType^.Kind = tkEnumeration then begin + lData := GetTypeData(lType); + Result := (aValue >= lData^.MinValue) and (aValue <= lData^.MaxValue); + end; +end; + function getMethodNo(P: TMethod; SE: TPSExec): Cardinal; begin if (p.Code <> @MyAllMethodsHandler) or (p.Data = nil)or (PScriptMethodInfo(p.Data)^.Se <> se) then @@ -11494,20 +12869,58 @@ function ClassCallProcProperty(Caller: TPSExec; p: TPSExternalProcRec; Global, S n := NewTPSVariantIFC(Stack[Stack.Count -2], false); if (PPropInfo(p.Ext1)^.PropType^.Kind = tkMethod) and ((n.aType.BaseType = btu32) or (n.aType.BaseType = btProcPtr))then begin - SetMethodProp(TObject(FSelf), PPropInfo(p.Ext1), MkMethod(Caller, tbtu32(n.dta^))); + if n.aType.BaseType = btProcPtr then + SetMethodProp(TObject(FSelf), PPropInfo(p.Ext1), ProcPtrToMethod(Caller, n.dta)) + else begin + { a number names a script routine, as a procedural value's does: a method made of any other number + read past the routine list when native code called it } + if (tbtu32(n.dta^) <> 0) and (tbtu32(n.dta^) <> InvalidVal) and + ((tbtu32(n.dta^) >= Cardinal(Caller.FProcs.Count)) or (tbtu32(n.dta^) = Caller.FMainProc)) then + begin + Caller.CMD_Err(erOutOfProcRange); + Result := False; + Exit; + end; + SetMethodProp(TObject(FSelf), PPropInfo(p.Ext1), MkMethod(Caller, tbtu32(n.dta^))); + end; end else case n.aType.BaseType of btSet: begin + if TPSTypeRec_Set(n.aType).aByteSize > SizeOf(ltemp) then begin + Caller.CMD_Err(erOutOfRange); + Result := False; + Exit; + end; ltemp := 0; move(Byte(n.Dta^), ltemp, TPSTypeRec_Set(n.aType).aByteSize); SetOrdProp(TObject(FSelf), PPropInfo(p.Ext1), ltemp); end; - btChar, btU8: SetOrdProp(TObject(FSelf), PPropInfo(p.Ext1), tbtu8(n.Dta^)); + btChar, btU8: + if (n.aType.BaseType = btChar) and (PPropInfo(p.Ext1)^.PropType^.Kind = tkWChar) then + SetOrdProp(TObject(FSelf), PPropInfo(p.Ext1), Ord(PSAnsiCharToWideChar(tbtchar(n.Dta^)))) + else if not _InPropertyRange(PPropInfo(p.Ext1), tbtu8(n.Dta^)) then begin + Caller.CMD_Err(erOutOfRange); + Result := False; + Exit; + end else + SetOrdProp(TObject(FSelf), PPropInfo(p.Ext1), tbtu8(n.Dta^)); btS8: SetOrdProp(TObject(FSelf), PPropInfo(p.Ext1), tbts8(n.Dta^)); - {$IFNDEF PS_NOWIDESTRING}btwidechar, {$ENDIF}btU16: SetOrdProp(TObject(FSelf), PPropInfo(p.Ext1), tbtu16(n.Dta^)); + {$IFNDEF PS_NOWIDESTRING}btwidechar, {$ENDIF}btU16: + if not _InPropertyRange(PPropInfo(p.Ext1), tbtu16(n.Dta^)) then begin + Caller.CMD_Err(erOutOfRange); + Result := False; + Exit; + end else + SetOrdProp(TObject(FSelf), PPropInfo(p.Ext1), tbtu16(n.Dta^)); btS16: SetOrdProp(TObject(FSelf), PPropInfo(p.Ext1), tbts16(n.Dta^)); - btU32: SetOrdProp(TObject(FSelf), PPropInfo(p.Ext1), tbtu32(n.Dta^)); + btU32: + if not _InPropertyRange(PPropInfo(p.Ext1), Longint(tbtu32(n.Dta^))) then begin + Caller.CMD_Err(erOutOfRange); + Result := False; + Exit; + end else + SetOrdProp(TObject(FSelf), PPropInfo(p.Ext1), tbtu32(n.Dta^)); btS32: SetOrdProp(TObject(FSelf), PPropInfo(p.Ext1), tbts32(n.Dta^)); {$IFNDEF PS_NOINT64} btS64: SetInt64Prop(TObject(FSelf), PPropInfo(p.Ext1), tbts64(n.Dta^)); @@ -11521,9 +12934,9 @@ function ClassCallProcProperty(Caller: TPSExec; p: TPSExternalProcRec; Global, S btClass: SetOrdProp(TObject(FSelf), P.Ext1, IPointer(n.Dta^)); {$IFDEF DELPHI6UP} {$IFNDEF PS_NOWIDESTRING} -{$IFNDEF DELPHI2009UP}btUnicodeString,{$ENDIF} +{$IFDEF WIDESTRING_EQUAL_UNICODESTRING}btUnicodeString,{$ENDIF} btWideString: SetWideStrProp(TObject(FSelf), P.Ext1, tbtWidestring(n.dta^)); -{$IFDEF DELPHI2009UP} +{$IFNDEF WIDESTRING_EQUAL_UNICODESTRING} btUnicodeString: {$IFDEF DELPHI_TOKYO_UP}SetStrProp{$ELSE}SetUnicodeStrProp{$ENDIF}(TObject(FSelf), P.Ext1, tbtUnicodestring(n.dta^)); {$ENDIF} {$ENDIF} @@ -11558,7 +12971,8 @@ function ClassCallProcProperty(Caller: TPSExec; p: TPSExternalProcRec; Global, S begin m := GetMethodProp(TObject(FSelf), PPropInfo(p.Ext1)); Cardinal(n.Dta^) := GetMethodNo(m, Caller); - if Cardinal(n.dta^) = 0 then + { only a procedural value holds the method beside its number: a number is four bytes } + if (Cardinal(n.dta^) = 0) and (n.aType.BaseType = btProcPtr) then begin Pointer(Pointer((IPointer(n.dta)+PointerSize))^) := m.Data; Pointer(Pointer((IPointer(n.dta)+PointerSize2))^) := m.Code; @@ -11567,10 +12981,19 @@ function ClassCallProcProperty(Caller: TPSExec; p: TPSExternalProcRec; Global, S case n.aType.BaseType of btSet: begin + if TPSTypeRec_Set(n.aType).aByteSize > SizeOf(ltemp) then begin + Caller.CMD_Err(erOutOfRange); + Result := False; + Exit; + end; ltemp := GetOrdProp(TObject(FSelf), PPropInfo(p.Ext1)); move(ltemp, Byte(n.Dta^), TPSTypeRec_Set(n.aType).aByteSize); end; - btChar, btU8: tbtu8(n.Dta^) := GetOrdProp(TObject(FSelf), p.Ext1); + btChar, btU8: + if (n.aType.BaseType = btChar) and (PPropInfo(p.Ext1)^.PropType^.Kind = tkWChar) then + tbtchar(n.Dta^) := PSWideCharToAnsiChar(WideChar(Word(GetOrdProp(TObject(FSelf), p.Ext1)))) + else + tbtu8(n.Dta^) := GetOrdProp(TObject(FSelf), p.Ext1); btS8: tbts8(n.Dta^) := GetOrdProp(TObject(FSelf), p.Ext1); {$IFNDEF PS_NOWIDESTRING}btwidechar, {$ENDIF}btU16: tbtu16(n.Dta^) := GetOrdProp(TObject(FSelf), p.Ext1); btS16: tbts16(n.Dta^) := GetOrdProp(TObject(FSelf), p.Ext1); @@ -11587,7 +13010,7 @@ function ClassCallProcProperty(Caller: TPSExec; p: TPSExternalProcRec; Global, S btClass: IPointer(n.dta^) := GetOrdProp(TObject(FSelf), p.Ext1); {$IFDEF DELPHI6UP} {$IFNDEF PS_NOWIDESTRING} - {$IFDEF DELPHI2009UP} + {$IFNDEF WIDESTRING_EQUAL_UNICODESTRING} btUnicodeString: tbtUnicodeString(n.dta^) := {$IFDEF DELPHI_TOKYO_UP}GetStrProp{$ELSE}GetUnicodeStrProp{$ENDIF}(TObject(FSelf), P.Ext1); {$ELSE} btUnicodeString, @@ -11721,11 +13144,14 @@ function ClassCallProcPropertyHelperName(Caller: TPSExec; p: TPSExternalProcRec; for i := Stack.Count -3 downto Longint(Stack.Count) - ParamCount -2 do Params.Add(NewPPSVariantIFC(Stack[I], False)); tt := CreateHeapVariant(Caller.FindType2(btString)); - if tt <> nil then + if tt = nil then begin - PPSVariantAString(tt).Data := p.Name; - Params.Add(NewPPSVariantIFC(tt, false)); + DisposePPSVariantIFCList(Params); + Result := False; + exit; end; + PPSVariantAString(tt).Data := p.Name; + Params.Add(NewPPSVariantIFC(tt, false)); try Result := Caller.InnerfuseCall(FSelf, p.Ext1, cdRegister, Params, nil); finally @@ -11755,11 +13181,14 @@ function ClassCallProcPropertyHelperName(Caller: TPSExec; p: TPSExternalProcRec; Params.Add(NewPPSVariantIFC(Stack[I], false)); end; tt := CreateHeapVariant(Caller.FindType2(btString)); - if tt <> nil then + if tt = nil then begin - PPSVariantAString(tt).Data := p.Name; - Params.Add(NewPPSVariantIFC(tt, false)); + DisposePPSVariantIFCList(Params); + Result := False; + exit; end; + PPSVariantAString(tt).Data := p.Name; + Params.Add(NewPPSVariantIFC(tt, false)); try Result := Caller.InnerfuseCall(FSelf, p.Ext2, cdregister, Params, nil); finally @@ -11832,13 +13261,19 @@ function ClassCallProcEventPropertyHelper(Caller: TPSExec; p: TPSExternalProcRec Params.Add(NewPPSVariantIFC(Stack[i], False)); try Result := Caller.InnerfuseCall(FSelf, p.Ext1, cdRegister, Params, nil); - finally - Cardinal(n.Dta^) := getMethodNo(data, Caller); - if Cardinal(n.Dta^) = 0 then + { the event is stored only when the read helper returned: Delphi leaves a destination as it was when + a getter raises } + if Result then begin - Pointer(Pointer((IPointer(n.dta)+PointerSize))^) := data.Data; - Pointer(Pointer((IPointer(n.dta)+PointerSize2))^) := data.Code; + Cardinal(n.Dta^) := getMethodNo(data, Caller); + { only a procedural value holds the method beside its number: a number is four bytes } + if (Cardinal(n.Dta^) = 0) and (n.aType.BaseType = btProcPtr) then + begin + Pointer(Pointer((IPointer(n.dta)+PointerSize))^) := data.Data; + Pointer(Pointer((IPointer(n.dta)+PointerSize2))^) := data.Code; + end; end; + finally DestroyHeapVariant(n2); DisposePPSVariantIFCList(Params); end; @@ -11857,13 +13292,21 @@ function ClassCallProcEventPropertyHelper(Caller: TPSExec; p: TPSExternalProcRec Result := False; exit; end; - n := NewTPSVariantIFC(Stack[Longint(Stack.Count) - 2], false); + { the value lies below an indexed property's indices } + n := NewTPSVariantIFC(Stack[Longint(Stack.Count) - ParamCount - 2], false); if (n.Dta = nil) or ((n.aType.BaseType <> btu32) and (n.aType.BaseType <> btProcPtr)) then begin result := false; Caller.CMD_Err(erNullPointerException); exit; end; + { the write helper takes a method, and a number would reach it as one } + if n.aType.BaseType = btU32 then + begin + Result := False; + Caller.CMD_Err(erTypeMismatch); + exit; + end; (*n2 := CreateHeapVariant(Caller.FindType2(btPchar)); if n2 = nil then begin @@ -11879,14 +13322,13 @@ function ClassCallProcEventPropertyHelper(Caller: TPSExec; p: TPSExternalProcRec Params := TPSList.Create; Params.Add(@n); - // for i := Stack.Count -2 downto Longint(Stack.Count) - ParamCount -1 do - // begin -// Params.Add(NewPPSVariantIFC(Stack[I], False)); -// end; + for i := Stack.Count -2 downto Longint(Stack.Count) - ParamCount -1 do + Params.Add(NewPPSVariantIFC(Stack[I], False)); try Result := Caller.InnerfuseCall(FSelf, p.Ext2, cdregister, Params, nil); finally - Params.Clear; + { the value is n itself, which the list does not own } + Params.Delete(0); //DestroyHeapVariant(n2); DisposePPSVariantIFCList(Params); end; @@ -12193,14 +13635,18 @@ function TPSExec.InvokeExternalMethod(At: TPSTypeRec_ProcPtr; Slf, end; if s[1] <> #0 then begin - res := NewPPSVariantIFC(FStack[CurrStack + 1], True); + res := NewPPSVariantIFC(FStack[CurrStack], True); end else res := nil; - Result := InnerfuseCall(Slf, Ptr, cdRegister, MyList, Res); - - DisposePPSVariantIFC(res); - DisposePPSVariantIFCList(mylist); + try + Result := InnerfuseCall(Slf, Ptr, cdRegister, MyList, Res); + finally + DisposePPSVariantIFC(res); + DisposePPSVariantIFCList(mylist); + end; end; +{ The Last* functions: with exception frames, the exception of the nearest + except handler running (none outside one); with none, the last exception. } function TPSExec.LastEx: TPSError; var pp: TPSExceptionHandler; @@ -12209,8 +13655,11 @@ function TPSExec.LastEx: TPSError; result := ExEx; exit; end; - pp := fExceptionStack[fExceptionStack.Count-1]; - result := pp.ExceptionData; + pp := _HandlerFrame(FExceptionStack); + if pp = nil then + result := ENoError + else + result := pp.ExceptionData; end; function TPSExec.LastExParam: tbtString; @@ -12221,8 +13670,11 @@ function TPSExec.LastExParam: tbtString; result := ExParam; exit; end; - pp := fExceptionStack[fExceptionStack.Count-1]; - result := pp.ExceptionParam; + pp := _HandlerFrame(FExceptionStack); + if pp = nil then + result := '' + else + result := pp.ExceptionParam; end; function TPSExec.LastExPos: Integer; @@ -12233,9 +13685,11 @@ function TPSExec.LastExPos: Integer; result := ExPos; exit; end; - pp := fExceptionStack[fExceptionStack.Count-1]; - result := pp.ExceptOffset; - + pp := _HandlerFrame(FExceptionStack); + if pp = nil then + result := Integer(InvalidVal) + else + result := Integer(pp.ExceptionPos); end; function TPSExec.LastExProc: Integer; @@ -12246,8 +13700,11 @@ function TPSExec.LastExProc: Integer; result := ExProc; exit; end; - pp := fExceptionStack[fExceptionStack.Count-1]; - result := FProcs.IndexOf(pp.CurrProc); + pp := _HandlerFrame(FExceptionStack); + if pp = nil then + result := Integer(InvalidVal) + else + result := Integer(pp.ExceptionProcNo); end; function TPSExec.LastExObject: TObject; @@ -12258,8 +13715,11 @@ function TPSExec.LastExObject: TObject; result := ExObject; exit; end; - pp := fExceptionStack[fExceptionStack.Count-1]; - result := pp.ExceptionObject; + pp := _HandlerFrame(FExceptionStack); + if pp = nil then + result := nil + else + result := pp.ExceptionObject; end; { TPSRuntimeClass } @@ -12444,8 +13904,10 @@ constructor TPSRuntimeClassImporter.CreateAndRegister(Exec: TPSExec; inherited Create; FClasses := TPSList.Create; RegisterClassLibraryRuntime(Exec, Self); + { not a resource: Clear releases those, and loading a script begins with a + Clear, where the importer is needed next } if AutoFree then - Exec.AddResource(@RCIFreeProc, Self); + Exec.FOwnedImporters.Add(Self); end; destructor TPSRuntimeClassImporter.Destroy; @@ -12503,7 +13965,15 @@ function AlwaysAsVariable(aType: TPSTypeRec): Boolean; {$IFDEF CPU64} { See the btSet/btRecord/btStaticArray comment in x64.inc } btSet: Result := not (atype.RealSize in [1, 2, 3, 4{$IFDEF DELPHI}{$IFNDEF DELPHI_RIO_UP}, 5, 6, 7, 8{$ENDIF}{$ENDIF}]); - btRecord, btStaticArray: Result := not (atype.RealSize in [1, 2, 4{$IFDEF DELPHI}{$IFNDEF DELPHI_RIO_UP}, 5, 6, 7, 8{$ENDIF}{$ENDIF}]); +{$IF defined(FPC) and defined(MSWINDOWS)} + { Every record and static array by reference, as the FPC arm of the + btSet/btRecord/btStaticArray case in x64.inc passes them. Free Pascal x86_64 + compiles no method handler (empty_methods_handler), so no call reaches this + arm there. } + btRecord, btStaticArray: Result := True; +{$ELSE} + btRecord, btStaticArray: Result := not (atype.RealSize in [1, 2, 4{$IFDEF DELPHI}{$IFNDEF DELPHI_RIO_UP}, 8{$ENDIF}{$ENDIF}]); +{$IFEND} {$ELSE} btSet, btRecord, btStaticArray: Result := atype.RealSize > PointerSize; {$ENDIF} @@ -12517,16 +13987,6 @@ function ParamAsVariable(const Modifier: tbtchar; aType: TPSTypeRec): Boolean; Result := (Modifier = '%') or (Modifier = '!') or AlwaysAsVariable(aType); end; -{$ifdef fpc} - {$if defined(cpupowerpc) or defined(cpuarm) or defined(cpu64)} - {$define empty_methods_handler} - {$ifend} -{$else} - {$if defined(cpuarm) or defined(cpuarm64)} - {$define empty_methods_handler} - {$ifend} -{$endif} - {$ifdef empty_methods_handler} procedure MyAllMethodsHandler; begin @@ -12534,10 +13994,113 @@ procedure MyAllMethodsHandler; {$else} +{ Copies a value parameter native code hands a script procedure it calls as a + method; aCopied turns False when the copy fails (CopyArrayContents takes the + exception) } +procedure CopyNativeParameter(aDest, aSrc: Pointer; aType: TPSTypeRec; var aCopied: Boolean); +begin + if not CopyArrayContents(aDest, aSrc, 1, aType) then + aCopied := False; +end; + +{ Refuses a call into a script procedure one of whose parameters could not be + copied, after freeing the parameters made for it, as a Delphi routine's + failed copy of a parameter raises to its caller before the routine runs. + The copy's own exception is gone, so the caller gets Invalid parameter } +procedure RefuseNativeParameters(aParams: TPSList); +begin + FreePIFVariantList(aParams); + raise Exception.Create(RPS_InvalidParameter); +end; + +{ A parameter the native caller passes by reference (ParamAsVariable): a var + parameter is the caller's variable; a value or const one -- a Variant, a + large set, record or static array -- is the routine's own copy of it, as a + Delphi routine copies such a value before it writes to it; aCopied turns + False when that copy fails } +function NativeReferenceParameter(Se: TPSExec; const Modifier: tbtchar; aType: TPSTypeRec; + aData: Pointer; var aCopied: Boolean): PPSVariant; +begin + if (Modifier = '%') or (Modifier = '!') then + begin + Result := CreateHeapVariant(Se.FindType2(btPointer)); + PPSVariantPointer(Result).DestType := aType; + PPSVariantPointer(Result).DataDest := aData; + end else + begin + Result := CreateHeapVariant(aType); + CopyNativeParameter(@PPSVariantData(Result)^.Data, aData, aType, aCopied); + end; +end; + +{ The procedural value a method stands for, written at aProcPtr: the number of + the script procedure when the method is one of Se's procedures made a method, + otherwise number 0 with the method beside it -- as a script holds an event + Delphi had assigned } +procedure MethodToProcPtr(Se: TPSExec; const aMethod: TMethod; aProcPtr: Pointer); +begin + tbtu32(aProcPtr^) := getMethodNo(aMethod, Se); + if tbtu32(aProcPtr^) = 0 then + begin + Pointer(Pointer(IPointer(aProcPtr)+PointerSize)^) := aMethod.Data; + Pointer(Pointer(IPointer(aProcPtr)+PointerSize2)^) := aMethod.Code; + end; +end; + +{ The procedural-type parameter aIdx of a script procedure that native code + calls as a method: a value of its own made from the method the caller passed + at aNative. A var or out parameter sets aWriteBacks[aIdx] to aNative, where + StoreMethodParameters puts it back as a method after the call -- unless an + earlier one names the same variable: then it points at that one's value, as + two var parameters of one variable share it } +function MethodParameter(Se: TPSExec; const aModifier: tbtchar; aType: TPSTypeRec; aNative: Pointer; + Params: TPSList; var aWriteBacks: array of Pointer; aIdx: Integer): PPSVariant; +var + lIdx: Integer; +begin + if (aModifier = '%') or (aModifier = '!') then + begin + for lIdx := 0 to High(aWriteBacks) do + if aWriteBacks[lIdx] = aNative then + begin + Result := CreateHeapVariant(Se.FindType2(btPointer)); + PPSVariantPointer(Result).DestType := aType; + PPSVariantPointer(Result).DataDest := @PPSVariantData(Params[lIdx])^.Data; + Exit; + end; + aWriteBacks[aIdx] := aNative; + end; + Result := CreateHeapVariant(aType); + MethodToProcPtr(Se, TMethod(aNative^), @PPSVariantData(Result)^.Data); +end; + +procedure StoreMethodParameters(Se: TPSExec; Params: TPSList; const aWriteBacks: array of Pointer); +var + lIdx: Integer; +begin + for lIdx := 0 to High(aWriteBacks) do + if aWriteBacks[lIdx] <> nil then + TMethod(aWriteBacks[lIdx]^) := ProcPtrToMethod(Se, @PPSVariantData(Params[lIdx])^.Data); +end; + +{$IFNDEF CPU64} +{ Whether a 32-bit native caller passes a method parameter by reference: a var + or out one always, one by value on Free Pascal; Delphi pushes a method by + value as its two slots } +function MethodByReference(const aModifier: tbtchar): Boolean; +begin + {$IFDEF FPC} + Result := True; + {$ELSE} + Result := (aModifier = '%') or (aModifier = '!'); + {$ENDIF} +end; +{$ENDIF} + {$IFDEF CPU64} function MyAllMethodsHandler64(Self: PScriptMethodInfo; _RDX, _R8, _R9:Pointer; Stack: PPointer; _XMM1, _XMM2, _XMM3: Pointer; {$IFDEF DELPHI} ResPtr: Pointer {$ENDIF}): Integer; forward; {$ELSE} -function MyAllMethodsHandler32(Self: PScriptMethodInfo; const Stack: PPointer; _EDX, _ECX: Pointer{$IFDEF DELPHI}; ResPtr: Pointer{$ENDIF}): Integer; forward; +function MyAllMethodsHandler32(Self: PScriptMethodInfo; const Stack: PPointer; _EDX, _ECX: Pointer{$IF defined(DELPHI) or (defined(FPC) and defined(CPUI386))}; ResPtr: Pointer{$IFEND}): Integer; forward; {$ENDIF} procedure MyAllMethodsHandler; @@ -12574,12 +14137,9 @@ procedure MyAllMethodsHandler; // RCX (Self), RDX, R8, R9 already contain the values we need lea rax, [rbp+80] // Stack ptr mov [rsp+32], rax - movq rax, xmm1 // XMM1 raw value - mov [rsp+40], rax - movq rax, xmm2 // XMM2 raw value - mov [rsp+48], rax - movq rax, xmm3 // XMM3 raw value - mov [rsp+56], rax + movsd qword ptr [rsp+40], xmm1 // XMM1 raw value + movsd qword ptr [rsp+48], xmm2 // XMM2 raw value + movsd qword ptr [rsp+56], xmm3 // XMM3 raw value lea rax, [rbp+0] // ResPtr mov [rsp+64], rax // 64+8 = 72 @@ -12588,7 +14148,7 @@ procedure MyAllMethodsHandler; add rsp, 80 // Return ResPtr in both XMM0 and RAX, allowing the caller to choose correct one - movq xmm0, [rbp+0] + movsd xmm0, qword ptr [rbp+0] mov rax, [rbp+0] end; {$ELSE} @@ -12621,7 +14181,7 @@ procedure MyAllMethodsHandler; // EAX = Self pointer // EDX, ECX = param1 and param2 // STACK = param3... paramcount -{$IFDEF DELPHI} +{$IF defined(DELPHI) or (defined(FPC) and defined(CPUI386))} asm // Like the Win64 stub: the stub owns an 8-byte result slot and passes its // address to MyAllMethodsHandler32 as ResPtr, so that an Int64/UInt64 @@ -12658,7 +14218,7 @@ procedure MyAllMethodsHandler; mov [esp], edx mov eax, ecx end; -{$ENDIF} +{$IFEND} {$endif CPU64} function ResultAsRegister(b: TPSTypeRec): Boolean; @@ -12701,7 +14261,12 @@ function ResultAsRegister(b: TPSTypeRec): Boolean; {$ENDIF} btSet: Result := b.RealSize <= PointerSize; {$IFNDEF DELPHI} - btStaticArray: Result := b.RealSize <= PointerSize; + { Free Pascal i386 returns every static array through the hidden result + pointer, and on Windows a record of 1, 2 or 4 bytes with no managed + field in EAX } +{$IFDEF MSWINDOWS} + btRecord: Result := (b.RealSize in [1, 2, 4]) and not IsManagedType(b); +{$ENDIF} {$ENDIF} else Result := false; @@ -12743,10 +14308,11 @@ function SupportsRegister(b: TPSTypeRec): Boolean; by-reference boundary: 3 (by reference) rounds to 4 (by value), while the rounding of 5-7 to 8 does not (all by reference) } btSet: Result := b.RealSize in [1, 2, 3, 4{$IFDEF CPU64}{$IFNDEF DELPHI_RIO_UP}, 5, 6, 7, 8{$ENDIF}{$ENDIF}]; - btRecord, btStaticArray: Result := b.RealSize in [1, 2, 4{$IFDEF CPU64}{$IFNDEF DELPHI_RIO_UP}, 5, 6, 7, 8{$ENDIF}{$ENDIF}]; + btRecord, btStaticArray: Result := b.RealSize in [1, 2, 4{$IFDEF CPU64}{$IFNDEF DELPHI_RIO_UP}, 8{$ENDIF}{$ENDIF}]; {$ELSE} + { Free Pascal i386 passes a set of up to 4 bytes in a register, and a + value static array of up to 4 bytes on the stack } btSet: Result := b.RealSize <= PointerSize; - btStaticArray: Result := b.RealSize <= PointerSize; {$ENDIF} {$IFDEF CPU64} btSingle, @@ -12783,6 +14349,10 @@ function MyAllMethodsHandler64(Self: PScriptMethodInfo; _RDX, _R8, _R9:Pointer; s,e: tbtString; FStack: pointer; ex: TPSExceptionHandler; + lPosition, lStackBase, lRaised: Cardinal; + lNative, lResultDest: Pointer; + lWriteBacks: array of Pointer; + lCopied: Boolean; begin {$IFDEF LOG} __Log('RDX=$'+ IntToHex(IPointer(_RDX))); @@ -12793,6 +14363,13 @@ function MyAllMethodsHandler64(Self: PScriptMethodInfo; _RDX, _R8, _R9:Pointer; __Log('XMM2=$'+ FloatToStr(Double(_XMM2))); __Log('XMM3=$'+ FloatToStr(Double(_XMM3))); {$ENDIF} + { a method kept by native code after its script ended } + if not Assigned(Self^.Se) then + raise Exception.Create(RPS_EndedScriptMethod); + { a host routine's declaration in the script holds the modes of its parameters, not their types: its + arguments cannot be read } + if TObject(Self^.Se.FProcs[Self^.ProcNo]) is TPSExternalProcRec then + raise Exception.Create(RPS_HostRoutineAsMethod); Decl := TPSInternalProcRec(Self^.Se.FProcs[Self^.ProcNo]).ExportDecl; FStack := Stack; @@ -12804,8 +14381,11 @@ function MyAllMethodsHandler64(Self: PScriptMethodInfo; _RDX, _R8, _R9:Pointer; grfw(s); end; c := Params.Count; + SetLength(lWriteBacks, c); + lResultDest := nil; regno := 0; Result := 0; + lCopied := True; s := decl; e := grfw(s); @@ -12813,10 +14393,17 @@ function MyAllMethodsHandler64(Self: PScriptMethodInfo; _RDX, _R8, _R9:Pointer; if e <> '-1' then begin cpt := Self.Se.GetTypeNo(StrToInt(e)); if not ResultAsRegister(cpt) then begin - Res := CreateHeapVariant(Self.Se.FindType2(btPointer)); - PPSVariantPointer(Res).DestType := cpt; + lResultDest := Pointer(_RDX); + if cpt.BaseType = btProcPtr then + { the caller's result is a method: the script's procedural value is + made apart and stored as a method after the call } + Res := CreateHeapVariant(cpt) + else begin + Res := CreateHeapVariant(Self.Se.FindType2(btPointer)); + PPSVariantPointer(Res).DestType := cpt; + PPSVariantPointer(Res).DataDest := lResultDest; + end; Params.Add(Res); - PPSVariantPointer(Res).DataDest := Pointer(_RDX); inc(regno); end else begin @@ -12837,25 +14424,28 @@ function MyAllMethodsHandler64(Self: PScriptMethodInfo; _RDX, _R8, _R9:Pointer; fmod := e[1]; delete(e, 1, 1); cpt := Self.Se.GetTypeNo(StrToInt(e)); - if ParamAsVariable(fmod, cpt) and (RegNo < 3) then + if (cpt.BaseType = btProcPtr) and (RegNo < 3) then begin - tmp := CreateHeapVariant(self.Se.FindType2(btPointer)); - PPSVariantPointer(tmp).DestType := cpt; - Params[i] := tmp; + { a method is passed by reference, by value or not } case regno of - 0: begin - PPSVariantPointer(tmp).DataDest := Pointer(_RDX); - inc(regno); - end; - 1: begin - PPSVariantPointer(tmp).DataDest := Pointer(_R8); - inc(regno); - end; - 2: begin - PPSVariantPointer(tmp).DataDest := Pointer(_R9); - inc(regno); - end; + 0: lNative := _RDX; + 1: lNative := _R8; + else + lNative := _R9; end; + inc(regno); + Params[i] := MethodParameter(Self.Se, fmod, cpt, lNative, Params, lWriteBacks, i); + end + else if ParamAsVariable(fmod, cpt) and (RegNo < 3) then + begin + case regno of + 0: lNative := Pointer(_RDX); + 1: lNative := Pointer(_R8); + else + lNative := Pointer(_R9); + end; + inc(regno); + Params[i] := NativeReferenceParameter(Self.Se, fmod, cpt, lNative, lCopied); end else if SupportsRegister(cpt) and (RegNo < 3) then begin @@ -12866,21 +14456,21 @@ function MyAllMethodsHandler64(Self: PScriptMethodInfo; _RDX, _R8, _R9:Pointer; if cpt.BaseType in [btSingle, btDouble, btExtended] then CopyArrayContents(@PPSVariantData(tmp)^.Data, @_XMM1, 1, cpt) else - CopyArrayContents(@PPSVariantData(tmp)^.Data, @_RDX, 1, cpt); + CopyNativeParameter(@PPSVariantData(tmp)^.Data, @_RDX, cpt, lCopied); inc(regno); end; 1: begin if cpt.BaseType in [btSingle, btDouble, btExtended] then CopyArrayContents(@PPSVariantData(tmp)^.Data, @_XMM2, 1, cpt) else - CopyArrayContents(@PPSVariantData(tmp)^.Data, @_R8, 1, cpt); + CopyNativeParameter(@PPSVariantData(tmp)^.Data, @_R8, cpt, lCopied); inc(regno); end; 2: begin if cpt.BaseType in [btSingle, btDouble, btExtended] then CopyArrayContents(@PPSVariantData(tmp)^.Data, @_XMM3, 1, cpt) else - CopyArrayContents(@PPSVariantData(tmp)^.Data, @_R9, 1, cpt); + CopyNativeParameter(@PPSVariantData(tmp)^.Data, @_R9, cpt, lCopied); inc(regno); end; end; @@ -12895,20 +14485,21 @@ function MyAllMethodsHandler64(Self: PScriptMethodInfo; _RDX, _R8, _R9:Pointer; delete(e, 1, 1); if Params[i] <> nil then Continue; cpt := Self.Se.GetTypeNo(StrToInt(e)); - if ParamAsVariable(fmod, cpt) then begin - tmp := CreateHeapVariant(self.Se.FindType2(btPointer)); - PPSVariantPointer(tmp).DestType := cpt; - Params[i] := tmp; - PPSVariantPointer(tmp).DataDest := Pointer(FStack^); + if cpt.BaseType = btProcPtr then + Params[i] := MethodParameter(Self.Se, fmod, cpt, Pointer(FStack^), Params, lWriteBacks, i) + else if ParamAsVariable(fmod, cpt) then begin + Params[i] := NativeReferenceParameter(Self.Se, fmod, cpt, Pointer(FStack^), lCopied); end else begin tmp := CreateHeapVariant(cpt); Params[i] := tmp; - CopyArrayContents(@PPSVariantData(tmp)^.Data, Pointer(FStack), 1, cpt); + CopyNativeParameter(@PPSVariantData(tmp)^.Data, Pointer(FStack), cpt, lCopied); end; FStack := Pointer(IPointer(FStack) + PointerSize); Inc(Result, PointerSize); end; + if not lCopied then + RefuseNativeParameters(Params); ex := TPSExceptionHandler.Create; ex.FinallyOffset := InvalidVal; ex.ExceptOffset := InvalidVal; @@ -12918,12 +14509,22 @@ function MyAllMethodsHandler64(Self: PScriptMethodInfo; _RDX, _R8, _R9:Pointer; ex.BasePtr := Self.Se.FCurrStackBase; Ex.StackSize := Self.Se.FStack.Count; i := Self.Se.FExceptionStack.Add(ex); + { where the interpreter stands while the native code runs the script } + lPosition := Self.Se.FCurrentPosition; + lStackBase := Self.Se.FCurrStackBase; + lRaised := Self.Se.FRaisedCount; Self.Se.RunProc(Params, Self.ProcNo); if Self.Se.FExceptionStack[i] = ex then begin Self.Se.FExceptionStack.Remove(ex); ex.Free; + end else begin + { the script's exception ended the call at this frame, below the return + address: the interpreter is back where the native code called it } + Self.Se.FCurrentPosition := lPosition; + Self.Se.FCurrStackBase := lStackBase; end; + StoreMethodParameters(Self.Se, Params, lWriteBacks); if (Res <> nil) then begin Params.DeleteLast; if (ResultAsRegister(Res.FType)) then begin @@ -12946,8 +14547,10 @@ function MyAllMethodsHandler64(Self: PScriptMethodInfo; _RDX, _R8, _R9:Pointer; end; {$ENDIF} end{$IFDEF DELPHI} else begin + if (Res^.FType.BaseType = btProcPtr) and (Self.Se.ExEx = erNoError) then + TMethod(lResultDest^) := ProcPtrToMethod(Self.Se, @PPSVariantData(Res)^.Data); { The Win64 ABI requires returning the hidden result pointer in RAX } - PPointer(ResPtr)^ := PPSVariantPointer(Res).DataDest; + PPointer(ResPtr)^ := lResultDest; end{$ENDIF}; DestroyHeapVariant(res); end; @@ -12955,17 +14558,39 @@ function MyAllMethodsHandler64(Self: PScriptMethodInfo; _RDX, _R8, _R9:Pointer; DestroyHeapVariant(Params[i]); Params.Free; if Self.Se.ExEx <> erNoError then begin + { the exception goes to the native code, which may handle it and go on: + the executor holds it no longer, and counts it again only if the + native code lets it come back } if Self.Se.ExObject <> nil then begin FStack := Self.Se.ExObject; Self.Se.ExObject := nil; - raise TObject(FStack); end else - raise EPSException.Create(PSErrorToString(Self.SE.ExceptionCode, Self.Se.ExceptionString), Self.Se, Self.Se.ExProc, Self.Se.ExPos); + FStack := EPSException.Create(PSErrorToString(Self.SE.ExceptionCode, Self.Se.ExceptionString), Self.Se, Self.Se.ExProc, Self.Se.ExPos); + Self.Se.ExceptionProc(InvalidVal, InvalidVal, erNoError, '', nil); + Self.Se.FRaisedCount := lRaised; + raise TObject(FStack); end; end; {$ELSE} -function MyAllMethodsHandler32(Self: PScriptMethodInfo; const Stack: PPointer; _EDX, _ECX: Pointer{$IFDEF DELPHI}; ResPtr: Pointer{$ENDIF}): Integer; +type + { a real result of a script routine that native code called through a method + pointer, as the script held it: MyAllMethodsHandler32 puts it on the x87 + stack. No field precedes the variants, so each starts at the record's + first byte } + TPSMethodRealResult = record + case Byte of + 0: (VSingle: tbtSingle); + 1: (VDouble: tbtDouble); + 2: (VExtended: tbtExtended); + 3: (VCurrency: tbtCurrency); + end; + +{ MyAllMethodsHandler32's work but for putting a real result on the x87 stack: + a call that returns one sets aKind to its type -- btSingle, btDouble, + btExtended or btCurrency -- and aResult to its bytes } +function _MethodsHandler32Call(Self: PScriptMethodInfo; const Stack: PPointer; _EDX, _ECX: Pointer{$IF defined(DELPHI) or (defined(FPC) and defined(CPUI386))}; ResPtr: Pointer{$IFEND}; + var aKind: TPSBaseType; var aResult: TPSMethodRealResult): Integer; var Decl: tbtString; I, C, regno: Integer; @@ -12976,9 +14601,20 @@ function MyAllMethodsHandler32(Self: PScriptMethodInfo; const Stack: PPointer; _ s,e: tbtString; FStack: pointer; ex: TPSExceptionHandler; + lPosition, lStackBase, lRaised: Cardinal; + lNative, lResultDest: Pointer; + lWriteBacks: array of Pointer; + lCopied: Boolean; begin + { a method kept by native code after its script ended } + if not Assigned(Self^.Se) then + raise Exception.Create(RPS_EndedScriptMethod); + { a host routine's declaration in the script holds the modes of its parameters, not their types: its + arguments cannot be read } + if TObject(Self^.Se.FProcs[Self^.ProcNo]) is TPSExternalProcRec then + raise Exception.Create(RPS_HostRoutineAsMethod); Decl := TPSInternalProcRec(Self^.Se.FProcs[Self^.ProcNo]).ExportDecl; FStack := Stack; @@ -12991,8 +14627,11 @@ function MyAllMethodsHandler32(Self: PScriptMethodInfo; const Stack: PPointer; _ grfw(s); end; c := Params.Count; + SetLength(lWriteBacks, c); + lResultDest := nil; regno := 0; Result := 0; + lCopied := True; s := decl; grfw(s); for i := c-1 downto 0 do @@ -13001,21 +14640,23 @@ function MyAllMethodsHandler32(Self: PScriptMethodInfo; const Stack: PPointer; _ fmod := e[1]; delete(e, 1, 1); cpt := Self.Se.GetTypeNo(StrToInt(e)); - if ParamAsVariable(fmod, cpt) and (RegNo < 2) then + if (cpt.BaseType = btProcPtr) and (RegNo < 2) and MethodByReference(fmod) then begin - tmp := CreateHeapVariant(self.Se.FindType2(btPointer)); - PPSVariantPointer(tmp).DestType := cpt; - Params[i] := tmp; - case regno of - 0: begin - PPSVariantPointer(tmp).DataDest := Pointer(_EDX); - inc(regno); - end; - 1: begin - PPSVariantPointer(tmp).DataDest := Pointer(_ECX); - inc(regno); - end; - end; + if regno = 0 then + lNative := _EDX + else + lNative := _ECX; + inc(regno); + Params[i] := MethodParameter(Self.Se, fmod, cpt, lNative, Params, lWriteBacks, i); + end + else if ParamAsVariable(fmod, cpt) and (RegNo < 2) then + begin + if regno = 0 then + lNative := Pointer(_EDX) + else + lNative := Pointer(_ECX); + inc(regno); + Params[i] := NativeReferenceParameter(Self.Se, fmod, cpt, lNative, lCopied); end else if SupportsRegister(cpt) and (RegNo < 2) then begin @@ -13023,11 +14664,11 @@ function MyAllMethodsHandler32(Self: PScriptMethodInfo; const Stack: PPointer; _ Params[i] := tmp; case regno of 0: begin - CopyArrayContents(@PPSVariantData(tmp)^.Data, @_EDX, 1, cpt); + CopyNativeParameter(@PPSVariantData(tmp)^.Data, @_EDX, cpt, lCopied); inc(regno); end; 1: begin - CopyArrayContents(@PPSVariantData(tmp)^.Data, @_ECX, 1, cpt); + CopyNativeParameter(@PPSVariantData(tmp)^.Data, @_ECX, cpt, lCopied); inc(regno); end; end; @@ -13041,17 +14682,25 @@ function MyAllMethodsHandler32(Self: PScriptMethodInfo; const Stack: PPointer; _ cpt := Self.Se.GetTypeNo(StrToInt(e)); if not ResultAsRegister(cpt) then begin - Res := CreateHeapVariant(Self.Se.FindType2(btPointer)); - PPSVariantPointer(Res).DestType := cpt; - Params.Add(Res); case regno of - 0: PPSVariantPointer(Res).DataDest := Pointer(_EDX); - 1: PPSVariantPointer(Res).DataDest := Pointer(_ECX); + 0: lResultDest := Pointer(_EDX); + 1: lResultDest := Pointer(_ECX); else - PPSVariantPointer(Res).DataDest := Pointer(FStack^); + lResultDest := Pointer(FStack^); Inc(Result, PointerSize); FStack := Pointer(IPointer(FStack) + PointerSize); end; + if cpt.BaseType = btProcPtr then + { the caller's result is a method: the script's procedural value is + made apart and stored as a method after the call } + Res := CreateHeapVariant(cpt) + else + begin + Res := CreateHeapVariant(Self.Se.FindType2(btPointer)); + PPSVariantPointer(Res).DestType := cpt; + PPSVariantPointer(Res).DataDest := lResultDest; + end; + Params.Add(Res); end else begin Res := CreateHeapVariant(cpt); @@ -13067,12 +14716,24 @@ function MyAllMethodsHandler32(Self: PScriptMethodInfo; const Stack: PPointer; _ delete(e, 1, 1); if Params[i] <> nil then Continue; cpt := Self.Se.GetTypeNo(StrToInt(e)); - if ParamAsVariable(fmod, cpt) then + if cpt.BaseType = btProcPtr then begin - tmp := CreateHeapVariant(self.Se.FindType2(btPointer)); - PPSVariantPointer(tmp).DestType := cpt; - Params[i] := tmp; - PPSVariantPointer(tmp).DataDest := Pointer(FStack^); + if MethodByReference(fmod) then + begin + Params[i] := MethodParameter(Self.Se, fmod, cpt, Pointer(FStack^), Params, lWriteBacks, i); + FStack := Pointer(IPointer(FStack) + PointerSize); + Inc(Result, PointerSize); + end else + begin + { the method's two slots, on the stack } + Params[i] := MethodParameter(Self.Se, fmod, cpt, FStack, Params, lWriteBacks, i); + FStack := Pointer(IPointer(FStack) + SizeOf(TMethod)); + Inc(Result, SizeOf(TMethod)); + end; + end + else if ParamAsVariable(fmod, cpt) then + begin + Params[i] := NativeReferenceParameter(Self.Se, fmod, cpt, Pointer(FStack^), lCopied); FStack := Pointer(IPointer(FStack) + PointerSize); Inc(Result, PointerSize); end @@ -13087,11 +14748,13 @@ function MyAllMethodsHandler32(Self: PScriptMethodInfo; const Stack: PPointer; _ begin tmp := CreateHeapVariant(cpt); Params[i] := tmp; - CopyArrayContents(@PPSVariantData(tmp)^.Data, Pointer(FStack), 1, cpt); + CopyNativeParameter(@PPSVariantData(tmp)^.Data, Pointer(FStack), cpt, lCopied); FStack := Pointer((IPointer(FStack) + cpt.RealSize + 3) and not 3); Inc(Result, (cpt.RealSize + 3) and not 3); end; end; + if not lCopied then + RefuseNativeParameters(Params); ex := TPSExceptionHandler.Create; ex.FinallyOffset := InvalidVal; ex.ExceptOffset := InvalidVal; @@ -13101,13 +14764,24 @@ function MyAllMethodsHandler32(Self: PScriptMethodInfo; const Stack: PPointer; _ ex.BasePtr := Self.Se.FCurrStackBase; Ex.StackSize := Self.Se.FStack.Count; i := Self.Se.FExceptionStack.Add(ex); + { where the interpreter stands while the native code runs the script } + lPosition := Self.Se.FCurrentPosition; + lStackBase := Self.Se.FCurrStackBase; + lRaised := Self.Se.FRaisedCount; Self.Se.RunProc(Params, Self.ProcNo); if Self.Se.FExceptionStack[i] = ex then begin Self.Se.FExceptionStack.Remove(ex); ex.Free; + end else + begin + { the script's exception ended the call at this frame, below the return + address: the interpreter is back where the native code called it } + Self.Se.FCurrentPosition := lPosition; + Self.Se.FCurrStackBase := lStackBase; end; + StoreMethodParameters(Self.Se, Params, lWriteBacks); if (Res <> nil) then begin Params.DeleteLast; @@ -13116,27 +14790,28 @@ function MyAllMethodsHandler32(Self: PScriptMethodInfo; const Stack: PPointer; _ if (res^.FType.BaseType = btSingle) or (res^.FType.BaseType = btDouble) or (res^.FType.BaseType = btCurrency) or (res^.Ftype.BaseType = btExtended) then begin - case Res^.FType.BaseType of - btSingle: PutOnFPUStackExtended(PPSVariantSingle(res).Data); - btDouble: PutOnFPUStackExtended(PPSVariantDouble(res).Data); - btExtended: PutOnFPUStackExtended(PPSVariantExtended(res).Data); - { Currency is returned on the FPU stack as its scaled integer backing (FILD), not its logical value } - btCurrency: PutOnFPUStackCurrency(PPSVariantCurrency(res).Data); - end; + { kept for MyAllMethodsHandler32, which puts it on the x87 stack once + this routine has returned, after every release here. As its bytes: + a failed call raises below and its result goes nowhere, so nothing + may load what the script left there -- a signalling NaN would raise + in place of the script's exception } + aKind := Res^.FType.BaseType; + Move(PPSVariantData(Res)^.Data, aResult, Res^.FType.RealSize); DestroyHeapVariant(Res); Res := nil; end else begin -{$IFDEF DELPHI} +{$IF defined(DELPHI) or (defined(FPC) and defined(CPUI386))} CopyArrayContents(ResPtr, @PPSVariantData(res)^.Data, 1, Res^.FType); {$ELSE} {$IFNDEF PS_NOINT64} if (res^.FType.BaseType <> btS64) and (res^.FType.BaseType <> btU64) then {$ENDIF} CopyArrayContents(Pointer(IPointer(Stack)-PointerSize2), @PPSVariantData(res)^.Data, 1, Res^.FType); -{$ENDIF} +{$IFEND} end; - end; + end else if (Res^.FType.BaseType = btProcPtr) and (Self.Se.ExEx = erNoError) then + TMethod(lResultDest^) := ProcPtrToMethod(Self.Se, @PPSVariantData(Res)^.Data); DestroyHeapVariant(res); end; for i := 0 to Params.Count -1 do @@ -13144,13 +14819,39 @@ function MyAllMethodsHandler32(Self: PScriptMethodInfo; const Stack: PPointer; _ Params.Free; if Self.Se.ExEx <> erNoError then begin + { the exception goes to the native code, which may handle it and go on: + the executor holds it no longer, and counts it again only if the + native code lets it come back } if Self.Se.ExObject <> nil then begin FStack := Self.Se.ExObject; Self.Se.ExObject := nil; - raise TObject(FStack); end else - raise EPSException.Create(PSErrorToString(Self.SE.ExceptionCode, Self.Se.ExceptionString), Self.Se, Self.Se.ExProc, Self.Se.ExPos); + FStack := EPSException.Create(PSErrorToString(Self.SE.ExceptionCode, Self.Se.ExceptionString), Self.Se, Self.Se.ExProc, Self.Se.ExPos); + Self.Se.ExceptionProc(InvalidVal, InvalidVal, erNoError, '', nil); + Self.Se.FRaisedCount := lRaised; + raise TObject(FStack); + end; +end; + +{ Native code calling a script routine through a method pointer, from the stub + MyAllMethodsHandler. A real result goes on the x87 stack as the last act: + this routine holds nothing to release after it, so code a release reaches -- + a memory manager -- does not meet the result on the x87 stack } +function MyAllMethodsHandler32(Self: PScriptMethodInfo; const Stack: PPointer; _EDX, _ECX: Pointer{$IF defined(DELPHI) or (defined(FPC) and defined(CPUI386))}; ResPtr: Pointer{$IFEND}): Integer; +var + lKind: TPSBaseType; + lResult: TPSMethodRealResult; +begin + { btReturnAddress, the type of no result: none to put there } + lKind := btReturnAddress; + Result := _MethodsHandler32Call(Self, Stack, _EDX, _ECX{$IF defined(DELPHI) or (defined(FPC) and defined(CPUI386))}, ResPtr{$IFEND}, lKind, lResult); + { Currency is returned on the FPU stack as its scaled integer backing (FILD), not its logical value } + case lKind of + btSingle: PutOnFPUStackExtended(lResult.VSingle); + btDouble: PutOnFPUStackExtended(lResult.VDouble); + btExtended: PutOnFPUStackExtended(lResult.VExtended); + btCurrency: PutOnFPUStackCurrency(lResult.VCurrency); end; end; {$ENDIF CPU64} @@ -13408,6 +15109,29 @@ procedure TPSTypeRec_Set.CalcSize; const MemDelta = 4096; +type + PPSStackChunk = ^TPSStackChunk; + TPSStackChunk = record + Data: Pointer; + Capacity: Longint; + Length: Longint; { the length in use when the next chunk was begun } + end; + +{ The chunks from aFrom on, freed } +procedure _FreeStackChunks(var aChunks: array of Pointer; var aCount: Longint; aFrom: Longint); +var + lChunk: PPSStackChunk; +begin + while aCount > aFrom do + begin + Dec(aCount); + lChunk := aChunks[aCount]; + aChunks[aCount] := nil; + FreeMem(lChunk.Data); + Dispose(lChunk); + end; +end; + { TPSStack } procedure TPSStack.AdjustLength; @@ -13455,7 +15179,11 @@ destructor TPSStack.Destroy; if TPSTypeRec(v^).BaseType in NeedFinalization then FinalizeVariant(Pointer(IPointer(v)+PointerSize), Pointer(v^)); end; - FreeMem(FDataPtr, FCapacity); + if FChunked then + _FreeStackChunks(FChunks, FChunkCount, 0) + else + FreeMem(FDataPtr, FCapacity); + _FreeStackChunks(FRetired, FRetiredCount, 0); inherited Destroy; end; @@ -13605,30 +15333,73 @@ procedure TPSStack.Pop; c := count -1; p1 := Data[c]; DeleteLast; - FLength := IPointer(p1) - IPointer(FDataPtr); - if TPSTypeRec(p1^).BaseType in NeedFinalization then - FinalizeVariant(Pointer(IPointer(p1)+PointerSize), Pointer(p1^)); + { finalized while its storage is still the stack's: what the finalization + runs (a native destructor running a script event) pushes above it } + try + if TPSTypeRec(p1^).BaseType in NeedFinalization then + FinalizeVariant(Pointer(IPointer(p1)+PointerSize), Pointer(p1^)); + finally + if FChunked and (p1 = FDataPtr) and (FChunkIdx > 0) then + begin + { the chunk's first value: the stack goes on in the chunk before it, where + it stood when this one was begun } + Dec(FChunkIdx); + FDataPtr := PPSStackChunk(FChunks[FChunkIdx]).Data; + FCapacity := PPSStackChunk(FChunks[FChunkIdx]).Capacity; + FLength := PPSStackChunk(FChunks[FChunkIdx]).Length; + end + else + FLength := IPointer(p1) - IPointer(FDataPtr); + end; end; function TPSStack.Push(TotalSize: Longint): PPSVariant; var o: Cardinal; p: Pointer; -begin + lSize: Longint; +begin + { the stack's length and capacity are Longints: a size that would carry them past it allocated nothing, + and the value was then initialised past the stack } + if (TotalSize < 0) or (Int64(FLength) + TotalSize > High(Longint) - 3 * MemDelta) then + raise Exception.Create(RPS_OutOfMemory); + { the value's slot in the list first: when the list cannot grow, nothing has + changed, and when the data cannot, the slot is given back } + Add(nil); o := FLength; - FLength := (FLength + TotalSize); - //if FLength mod PointerSize <> 0 then - if FLength mod Longint(PointerSize) <> 0 then - //FLength := FLength + (PointerSize - (FLength mod PointerSize)); - FLength := FLength + (Longint(PointerSize) - Longint((FLength mod Longint(PointerSize)))); - if FLength > FCapacity then AdjustLength; + try + FLength := (FLength + TotalSize); + if FLength mod Longint(PointerSize) <> 0 then + FLength := FLength + (Longint(PointerSize) - Longint((FLength mod Longint(PointerSize)))); + if FLength > FCapacity then + begin + if FChunked then + begin + { the value goes at the start of the next chunk: the data on the stack + does not move } + lSize := FLength - Longint(o); + FLength := Longint(o); + NextChunk(lSize); + o := 0; + FLength := lSize; + end + else + AdjustLength; + end; + except + FLength := Longint(o); + DeleteLast; + raise; + end; p := Pointer(IPointer(FDataPtr) + IPointer(o)); - Add(p); + Data^[Count - 1] := p; Result := P; end; function TPSStack.PushType(aType: TPSTypeRec): PPSVariant; begin + if Int64(aType.RealSize) + SizeOf(Pointer) > High(Longint) then + raise Exception.Create(RPS_OutOfMemory); Result := Push(aType.RealSize + Sizeof(Pointer)); Result.FType := aType; InitializeVariant(Pointer(IPointer(Result)+PointerSize), aType); @@ -13658,6 +15429,33 @@ procedure TPSStack.SetCapacity(const Value: Longint); I: Longint; begin if Value < FLength then raise Exception.Create(RPS_CapacityLength); + if FChunked then + begin + { the chunks hold the data, and Push adds them: clearing the stack releases + them -- kept while a native call runs, which may still write where its + arguments were } + if Value = 0 then + begin + if FNativeCalls > 0 then + begin + if FRetiredCount + FChunkCount > High(FRetired) + 1 then + SetLength(FRetired, FRetiredCount + FChunkCount); + for I := 0 to FChunkCount - 1 do + begin + FRetired[FRetiredCount] := FChunks[I]; + Inc(FRetiredCount); + FChunks[I] := nil; + end; + FChunkCount := 0; + end + else + _FreeStackChunks(FChunks, FChunkCount, 0); + FChunkIdx := -1; + FDataPtr := nil; + FCapacity := 0; + end; + Exit; + end; if Value = 0 then begin if FDataPtr <> nil then @@ -13679,10 +15477,13 @@ procedure TPSStack.SetCapacity(const Value: Longint); OOFS := IPointer(P) - IPointer(FDataPtr); for i := Count -1 downto 0 do begin + { the slot a push has taken holds nil until its value's address is known } + if Data[i] = nil then + Continue; Data[i] := Pointer(IPointer(Data[i]) + OOFS); if Items[i].FType.FBaseType = btPointer then begin // check if pointer points to moved stack data if (IPointer(PPSVariantPointer(Data[i]).DataDest) >= IPointer(FDataPtr)) and - (IPointer(PPSVariantPointer(Data[i]).DataDest) < IPointer(FDataPtr)+IPointer(FLength)) then + (IPointer(PPSVariantPointer(Data[i]).DataDest) < IPointer(FDataPtr)+IPointer(FCapacity)) then PPSVariantPointer(Data[i]).DataDest := Pointer(IPointer(PPSVariantPointer(Data[i]).DataDest) + OOFS); end; end; @@ -13693,6 +15494,85 @@ procedure TPSStack.SetCapacity(const Value: Longint); FCapacity := Value; end; +procedure TPSStack.UseChunks; +var + lChunk: PPSStackChunk; +begin + if FChunked then + Exit; + SetLength(FChunks, 4); + FChunkCount := 0; + FChunkIdx := -1; + if FDataPtr <> nil then + begin + New(lChunk); + lChunk.Data := FDataPtr; + lChunk.Capacity := FCapacity; + lChunk.Length := 0; + FChunks[0] := lChunk; + FChunkCount := 1; + FChunkIdx := 0; + end; + { last: until here the block is still the stack's own, and Destroy frees it } + FChunked := True; +end; + +{ A value of aSize bytes does not fit in the chunk in use: it goes at the start + of the next one -- a spare one kept from before when it is large enough -- and + the values already on the stack stay where they are } +procedure TPSStack.NextChunk(aSize: Longint); +var + lChunk: PPSStackChunk; + lCapacity: Longint; +begin + if (FChunkIdx + 1 < FChunkCount) and + (PPSStackChunk(FChunks[FChunkIdx + 1]).Capacity < aSize) then + _FreeStackChunks(FChunks, FChunkCount, FChunkIdx + 1); + if FChunkIdx + 1 >= FChunkCount then + begin + if FChunkCount = 0 then + lCapacity := MemDelta + else if PPSStackChunk(FChunks[FChunkCount - 1]).Capacity > 128 * MemDelta then + lCapacity := 256 * MemDelta + else + lCapacity := 2 * PPSStackChunk(FChunks[FChunkCount - 1]).Capacity; + if lCapacity < aSize then + lCapacity := ((aSize + MemDelta - 1) div MemDelta) * MemDelta; + if FChunkCount > High(FChunks) then + SetLength(FChunks, 2 * FChunkCount + 4); + New(lChunk); + try + GetMem(lChunk.Data, lCapacity); + except + Dispose(lChunk); + raise; + end; + lChunk.Capacity := lCapacity; + lChunk.Length := 0; + FChunks[FChunkCount] := lChunk; + Inc(FChunkCount); + end; + if FChunkIdx >= 0 then + PPSStackChunk(FChunks[FChunkIdx]).Length := FLength; + Inc(FChunkIdx); + lChunk := FChunks[FChunkIdx]; + FDataPtr := lChunk.Data; + FCapacity := lChunk.Capacity; + Assert(aSize <= FCapacity); +end; + +procedure TPSStack.NativeCallStarts; +begin + Inc(FNativeCalls); +end; + +procedure TPSStack.NativeCallEnds; +begin + Dec(FNativeCalls); + if FNativeCalls = 0 then + _FreeStackChunks(FRetired, FRetiredCount, 0); +end; + procedure TPSStack.SetClass(ItemNo: Longint; const Data: TObject); var val: PPSVariant; @@ -13861,7 +15741,9 @@ procedure TPSStack.SetWideString(ItemNo: Longint; const LOCALE_SYSTEM_DEFAULT = 2 shl 10; // Delphi 2 doesn't define this -function IDispatchInvoke(Self: IDispatch; PropertySet: Boolean; const Name: tbtString; const Par: array of Variant): Variant; +{ the work of IDispatchInvoke, into aResult, which it is handed empty } +procedure _IDispatchInvokeInto(const Self: IDispatch; PropertySet: Boolean; const Name: tbtString; + const Par: array of Variant; var aResult: Variant); var Param: Word; i, ArgErr: Longint; @@ -13894,6 +15776,8 @@ function IDispatchInvoke(Self: IDispatch; PropertySet: Boolean; const Name: tbtS if PropertySet then begin + if High(Par) < 0 then + raise Exception.Create(RPS_InvalidParameter); Param := DISPATCH_PROPERTYPUT; DispParam.cNamedArgs := 1; DispParam.rgdispidNamedArgs := @DispPropertyPut; @@ -13934,7 +15818,7 @@ function IDispatchInvoke(Self: IDispatch; PropertySet: Boolean; const Name: tbtS PVariant(DispParam.rgvarg[i].pvarVal)^ := Par[High(Par)-i]; end; end; - i :=Self.Invoke(DispatchId, GUID_NULL, LOCALE_SYSTEM_DEFAULT, Param, DispParam, @Result, @ExceptInfo, @ArgErr); + i :=Self.Invoke(DispatchId, GUID_NULL, LOCALE_SYSTEM_DEFAULT, Param, DispParam, @aResult, @ExceptInfo, @ArgErr); {$IFNDEF Delphi3UP} try if not Succeeded(i) then @@ -13986,6 +15870,20 @@ function IDispatchInvoke(Self: IDispatch; PropertySet: Boolean; const Name: tbtS WSFreeList.Free; end; end; + +function IDispatchInvoke(Self: IDispatch; PropertySet: Boolean; const Name: tbtString; const Par: array of Variant): Variant; +var + lResult: Variant; +begin + try + _IDispatchInvokeInto(Self, PropertySet, Name, Par, lResult); + finally + { written only now, and on every road out -- a raise included, as Delphi's + late binding does: releasing what the destination holds can run a script + event, which can free the container it lies in } + MoveIntoVariant(@Result, lResult); + end; +end; {$ENDIF} diff --git a/Source/uPSUtils.pas b/Source/uPSUtils.pas index 61f767e4..92da5eeb 100644 --- a/Source/uPSUtils.pas +++ b/Source/uPSUtils.pas @@ -262,17 +262,18 @@ function MakeHash(const s: TbtString): Longint; 1 = end of first finally
2 = end of except
3 = end of second finally
+ 4 = a jump leaving the frame (Break, Continue)

} cm_poexh = 20; { Script internal command: Integer NOT
Command: TPSCommand;
- Where: Cardinal;
+ Var: TPSVariable;
} cm_in = 21; {Script internal command: Set Stack Pointer To Copy
Command: TPSCommand;
- Where: Cardinal;
+ VarDest, VarSrc: TPSVariable;
} cm_spc = 22; {Script internal command: Inc
@@ -345,7 +346,7 @@ function MakeHash(const s: TbtString): Longint; {$IFDEF FPC} IPointer = PtrUInt; {$ELSE} - {$IFDEF DELPHI2009UP} + {$IFDEF DELPHI16UP} IPointer = NativeUInt; {$ELSE} IPointer = Cardinal; @@ -453,6 +454,10 @@ TPSUnit = class(TObject) function HasUses(pUnitName: TbtString): Boolean; + { the position, among the units this one's uses clause names, of its last + naming of the unit pUnitName; -1 where it names none so } + function UsesIndex(const pUnitName: TbtString): Longint; + {$WARNINGS OFF} property UnitName: TbtString read fUnitName write SetUnitName; {$WARNINGS ON} @@ -592,6 +597,8 @@ TPSPascalParser = class(TObject) FData: TbtString; FText: {$IFDEF DELPHI4UP}PAnsiChar{$ELSE}PChar{$ENDIF}; FLastEnterPos, FRow, FRealPosition, FTokenLength: Cardinal; + { where the current token starts: its row and that row's first position } + FTokenRow, FTokenLineStart: Cardinal; FTokenId: TPSPasToken; FToken: TbtString; FOriginalToken: TbtString; @@ -616,7 +623,7 @@ TPSPascalParser = class(TObject) property CurrTokenID: TPSPasToken read FTokenId; - property Row: Cardinal read FRow; + property Row: Cardinal read FTokenRow; property Col: Cardinal read GetCol; @@ -645,6 +652,19 @@ function FastUpperCase(const s: TbtString): TbtString; function GRFW(var s: TbtString): TbtString; function GRLW(var s: TbtString): TbtString; +{ aText as ANSI text in aBuffer, which holds aBufSize bytes: at most aBufSize - 1 of them, ending on a + whole character, and a #0 after them. Returns the bytes copied; nothing is written where aBuffer is + nil or aBufSize is not positive. A trailing half of a character in aText -- a lead byte, or a high + surrogate whose low one is missing -- is dropped. } +function PSTextToAnsiBuffer(const aText: string; aBuffer: PAnsiChar; aBufSize: Integer): Integer; + +{ A script character -- an ANSI character -- as the 16-bit character the ANSI code page maps it to, + and the reverse, each converted as the system converts text to and from the ANSI code page: a + 16-bit character the code page lacks becomes its best-fit character there where it has one, and + '?' where it has none or needs two bytes for it. } +function PSAnsiCharToWideChar(aChar: AnsiChar): WideChar; +function PSWideCharToAnsiChar(aChar: WideChar): AnsiChar; + const FCapacityInc = 32; @@ -659,6 +679,73 @@ function WideLowerCase(const S: WideString): WideString; {$ENDIF} implementation +{ aCount less any high surrogate its characters of aText end on } +function _WholeCharCount(const aText: string; aCount: Integer): Integer; +begin + Result := aCount; + {$IFDEF UNICODE} + while (Result > 0) and (Ord(aText[Result]) >= $D800) and (Ord(aText[Result]) <= $DBFF) do + Dec(Result); + {$ENDIF} +end; + +function PSTextToAnsiBuffer(const aText: string; aBuffer: PAnsiChar; aBufSize: Integer): Integer; +var + lAnsi : AnsiString; + lLow : Integer; + lHigh : Integer; + lMid : Integer; +begin + Result := 0; + if (aBuffer = nil) or (aBufSize <= 0) then + Exit; + lHigh := _WholeCharCount(aText, Length(aText)); + lAnsi := AnsiString(Copy(aText, 1, lHigh)); + if Length(lAnsi) >= aBufSize then begin + { the longest beginning that fits, by halves: a longer beginning never + converts to fewer bytes } + lLow := 0; + while lHigh - lLow > 1 do begin + lMid := lLow + (lHigh - lLow) div 2; + if Length(AnsiString(Copy(aText, 1, lMid))) < aBufSize then + lLow := lMid + else + lHigh := lMid; + end; + lAnsi := AnsiString(Copy(aText, 1, _WholeCharCount(aText, lLow))); + end; + Result := Length(lAnsi); + {$IFNDEF UNICODE} + if (Result > 0) and (ByteType(lAnsi, Result) = mbLeadByte) then + Dec(Result); + {$ENDIF} + if Result > 0 then + Move(PAnsiChar(lAnsi)^, aBuffer^, Result); + aBuffer[Result] := #0; +end; + +function PSAnsiCharToWideChar(aChar: AnsiChar): WideChar; +var + lText : WideString; +begin + lText := WideString(AnsiString(aChar)); + if Length(lText) = 1 then + Result := lText[1] + else + Result := '?'; +end; + +function PSWideCharToAnsiChar(aChar: WideChar): AnsiChar; +var + lText : AnsiString; +begin + lText := AnsiString(WideString(aChar)); + if Length(lText) = 1 then + Result := lText[1] + else + Result := '?'; +end; + {$IFDEF DELPHI3UP } resourceString {$ELSE } @@ -861,7 +948,18 @@ procedure TPSList.Recreate; FCheckCount := 0; NewCapacity := mm(FCount, FCapacityInc); if NewCapacity < 64 then NewCapacity := 64; - GetMem(NewData, NewCapacity * PointerSize); + { trimming the block is no part of the list's state: when the new block + cannot be had, the list keeps its own } + NewData := nil; + try + GetMem(NewData, NewCapacity * PointerSize); + except + on EOutOfMemory do + NewData := nil; + end; + { left after the handler: Delphi XE3 to XE5 for Win64 keep the exception object of a handler left by a jump } + if NewData = nil then + Exit; for I := 0 to Longint(FCount) -1 do begin NewData^[i] := FData^[I]; @@ -878,8 +976,9 @@ function TPSList.Add(P: Pointer): Longint; begin if FCount >= FCapacity then begin - Inc(FCapacity, FCapacityInc);// := FCount + 1; - ReAllocMem(FData, FCapacity * PointerSize); + { the block first: when it cannot grow, the list is as it was } + ReAllocMem(FData, (FCapacity + FCapacityInc) * PointerSize); + Inc(FCapacity, FCapacityInc); end; FData[FCount] := P; // Instead of SetItem Result := FCount; @@ -893,18 +992,28 @@ function TPSList.Add(P: Pointer): Longint; procedure TPSList.AddBlock(List: PPointerList; Count: Longint); var L: Longint; + lNew: PPointerList; + lOld: PPointerList; begin + lOld := nil; if Longint(FCount) + Count > Longint(FCapacity) then begin + { the block added may lie in this list, so the old block stands until it + has been read; when the new one cannot be had, the list is as it was } + GetMem(lNew, (FCapacity + Cardinal(mm(Count, FCapacityInc))) * PointerSize); + Move(FData^, lNew^, FCount * PointerSize); + lOld := FData; + FData := lNew; Inc(FCapacity, mm(Count, FCapacityInc)); - ReAllocMem(FData, FCapacity *PointerSize); end; for L := 0 to Count -1 do begin FData^[FCount] := List^[L]; Inc(FCount); end; + if Assigned(lOld) then + FreeMem(lOld); {$IFNDEF PS_NOSMARTLIST} Inc(FCheckCount); if FCheckCount > FMaxCheckCount then Recreate; @@ -1199,7 +1308,7 @@ TRTab = record function TPSPascalParser.GetCol: Cardinal; begin - Result := FRealPosition - FLastEnterPos + 1; + Result := FRealPosition - FTokenLineStart + 1; end; procedure TPSPascalParser.Next; @@ -1256,6 +1365,7 @@ procedure TPSPascalParser.Next; ct, ci: Cardinal; hs: Boolean; p: {$IFDEF DELPHI4UP}PAnsiChar{$ELSE}PChar{$ENDIF}; + lOpenRow, lOpenLineStart: Cardinal; begin ParseToken := iNoError; ct := CurrTokenPos; @@ -1422,7 +1532,10 @@ procedure TPSPascalParser.Next; begin if FText[ct + 1] = '*' then begin - ci := ct + 1; + lOpenRow := FRow; + lOpenLineStart := FLastEnterPos; + { past the opener: its '*' does not close it as '(*)' } + ci := ct + 2; while (FText[ci] <> #0) do begin if (FText[ci] = '*') and (FText[ci + 1] = ')') then Break; @@ -1443,6 +1556,9 @@ procedure TPSPascalParser.Next; begin CurrTokenId := CSTIINT_Comment; ParseToken := iCommentError; + { reported where the comment opens } + FRow := lOpenRow; + FLastEnterPos := lOpenLineStart; end else begin CurrTokenId := CSTIINT_Comment; @@ -1565,6 +1681,8 @@ procedure TPSPascalParser.Next; end; '{': begin + lOpenRow := FRow; + lOpenLineStart := FLastEnterPos; ci := ct + 1; while (FText[ci] <> #0) and (FText[ci] <> '}') do begin if FText[ci] = #13 then @@ -1584,6 +1702,9 @@ procedure TPSPascalParser.Next; begin CurrTokenId := CSTIINT_Comment; ParseToken := iCommentError; + { reported where the comment opens } + FRow := lOpenRow; + FLastEnterPos := lOpenLineStart; end else CurrTokenId := CSTIINT_Comment; CurrTokenLen := ci - ct + 1; @@ -1607,6 +1728,10 @@ procedure TPSPascalParser.Next; end; repeat FRealPosition := FRealPosition + Cardinal(FTokenLength); + { a token's place is where it starts: its scan counts the line breaks + inside it } + FTokenRow := FRow; + FTokenLineStart := FLastEnterPos; Err := ParseToken(FRealPosition, Cardinal(FTokenLength), FTokenID); if Err <> iNoError then begin @@ -1662,6 +1787,8 @@ procedure TPSPascalParser.SetText(const Data: TbtString); FTokenId := CSTI_EOF; FLastEnterPos := 0; FRow := 1; + FTokenRow := 1; + FTokenLineStart := 0; Next; end; @@ -1751,9 +1878,32 @@ destructor TPSUnit.Destroy; inherited; end; +{ Whether aUnit is aUnitName or uses it, directly or not, searching each unit + once: searched route by route, units that share the units they use would + take twice as long with each level of sharing } +function _UnitReaches(aUnit: TPSUnit; const aUnitName: TbtString; aVisited: TPSList): Boolean; +var + lIdx: Integer; + lUsed: TPSUnit; +begin + Result := aUnit.fUnitName = aUnitName; + if Result then + exit; + aVisited.Add(aUnit); + for lIdx := 0 to aUnit.fUnits.Count - 1 do + begin + lUsed := TPSUnit(aUnit.fUnits[lIdx]); + if (aVisited.IndexOf(lUsed) < 0) and _UnitReaches(lUsed, aUnitName, aVisited) then + begin + Result := True; + exit; + end; + end; +end; + function TPSUnit.HasUses(pUnitName: TbtString): Boolean; var - Dummy: Integer; + lVisited: TPSList; begin pUnitName:=FastUpperCase(pUnitName); @@ -1764,16 +1914,31 @@ function TPSUnit.HasUses(pUnitName: TbtString): Boolean; end; result:=false; + if fUnits.Count = 0 then + exit; - for Dummy:=0 to fUnits.Count-1 do - begin - result:=TPSUnit(fUnits[Dummy]).HasUses(pUnitName); - - if result then - exit; + lVisited := TPSList.Create; + try + result := _UnitReaches(Self, pUnitName, lVisited); + finally + lVisited.Free; end; end; +function TPSUnit.UsesIndex(const pUnitName: TbtString): Longint; +var + lName : TbtString; + lIdx : Longint; +begin + lName := FastUpperCase(pUnitName); + for lIdx := Pred(fUnits.Count) downto 0 do + if TPSUnit(fUnits[lIdx]).fUnitName = lName then begin + Result := lIdx; + Exit; + end; + Result := -1; +end; + procedure TPSUnit.SetUnitName(const Value: TbtString); begin fUnitName := FastUpperCase(Value); diff --git a/Source/x64.inc b/Source/x64.inc index d06ba115..523cd510 100644 --- a/Source/x64.inc +++ b/Source/x64.inc @@ -58,11 +58,12 @@ const c_loc_offs__rax = c_loc_offs_adress + 1*c_sz_ptr; // == 584 c_loc_offs__xmm0 = c_loc_offs_adress + 2*c_sz_ptr; // == 592 c_loc_offs_reginfo = c_loc_offs_adress + 4*c_sz_ptr; // == 608 + c_frame_params = c_loc_offs_reginfo div c_sz_ptr + 1; // == 77: a frame holding the four saved registers //c_reg_packed = ((SizeOf(TRegisters) mod c_sz_ptr) + c_sz_ptr - 1) div c_sz_ptr; // 1 - packed records; 0 - aligned asm {$ifdef DELPHI} - .params c_params // There's actually room for c_loc_count, assembler is saving locals for "Address,_RAX,_XMM0,RegInfo" + .params c_frame_params // room for the stack parameters and the saved Address, _RAX, _XMM0 and RegInfo {$else} // TODO: FPC: GPF on exception push rbp sub rsp, $210 // ? $268 @@ -205,7 +206,14 @@ asm *) //{$IFDEF FPC} push rbp + {$IF Defined(FPC) and Defined(MSWINDOWS)} + .seh_pushreg rbp + {$IFEND} mov rbp,rsp + {$IF Defined(FPC) and Defined(MSWINDOWS)} + .seh_setframe rbp, 0 + .seh_endprologue + {$IFEND} //{$ENDIF} push rcx // address ;rbp -8 push rdx // @_rax ;rbp -16 @@ -505,7 +513,7 @@ end; {$IFDEF DELPHI}{$IFDEF WINDOWS}{$DEFINE DELPHI_and_WINDOWS}{$ENDIF}{$ENDIF} -function TPSExec.InnerfuseCall(_Self, Address: Pointer; CallingConv: TPSCallingConvention; Params: TPSList; res: PPSVariantIFC): Boolean; +function TPSExec.PlatformInnerfuseCall(_Self, Address: Pointer; CallingConv: TPSCallingConvention; Params: TPSList; res: PPSVariantIFC): Boolean; var Stack: array of Byte; _RAX: IPointer; @@ -552,6 +560,16 @@ _XMM0: Double; ((res^.aType.RealSize <> 8) or IsManagedType(res^.aType)) else {$ENDIF} + {$IF defined(FPC) and defined(WINDOWS)} + { Free Pascal Win64: a record result is returned in RAX only at 1, 2, 4 or 8 bytes + with no managed field, a set only at 1 to 4 bytes; every other one is written + through the hidden result pointer } + if res^.aType.BaseType = btRecord then + Result := not (res^.aType.RealSize in [1, 2, 4, 8]) or IsManagedType(res^.aType) + else if res^.aType.BaseType = btSet then + Result := res^.aType.RealSize > 4 + else + {$IFEND} Result := res^.aType.RealSize > PointerSize; end; {$IFDEF WINDOWS} @@ -686,15 +704,84 @@ _XMM0: Double; StoreReg(RegData); end; - {$IFDEF DELPHI} + {$IF defined(DELPHI) or (defined(FPC) and defined(MSWINDOWS))} type TMethodCallData = record AType: Byte; { Must be first field, matching uPSRuntime's TOpenArray } Data: TMethod; end; PMethodCallData = ^TMethodCallData; + {$IFEND} + + {$IFDEF FPC} + { Free Pascal's RTL and fcl-db keep an enumeration or a set of up to 32 members in 4 bytes (their + units are compiled in objfpc mode), where the script holds it in 1 to 3: a native routine writing + such a var parameter would overrun the script's value. It gets a zero-extended copy instead, + whose script-sized part is written back after the call } + type + TNarrowedVar = record + AType : Byte; { 1; must be first, matching uPSRuntime's TOpenArray } + Size : Longint; + Target : Pointer; + Data : array[0..31] of Byte; + end; + PNarrowedVar = ^TNarrowedVar; + + function NarrowedVar(aTarget: Pointer; aSize: Longint): Pointer; + var + lRec: PNarrowedVar; + lIdx: Longint; + begin + { the same script value passed twice by reference shares one copy, as it shares one address on Delphi } + if CallData <> nil then + for lIdx := 0 to CallData.Count - 1 do + begin + lRec := CallData[lIdx]; + if (lRec^.AType = 1) and (lRec^.Target = aTarget) then + begin + Result := @lRec^.Data; + Exit; + end; + end; + New(lRec); + FillChar(lRec^, SizeOf(lRec^), 0); + lRec^.AType := 1; + lRec^.Size := aSize; + lRec^.Target := aTarget; + Move(aTarget^, lRec^.Data, aSize); + if CallData = nil then + CallData := TPSList.Create; + CallData.Add(lRec); + Result := @lRec^.Data; + end; {$ENDIF} + {$IF defined(DELPHI_RIO_UP) and defined(WINDOWS)} + { A set Delphi holds in 8 bytes and the script in 5 to 8, passed by + reference: the routine gets a copy zero-extended to 8 bytes, kept until + the call ends } + type + TNativeSetCopy = record + AType : Byte; { 2; must be first, matching uPSRuntime's TOpenArray } + Data : UInt64; + end; + PNativeSetCopy = ^TNativeSetCopy; + + function NativeSetCopy(fVar: PPSVariantIFC): Pointer; + var + lRec: PNativeSetCopy; + begin + New(lRec); + lRec^.AType := 2; + lRec^.Data := 0; + Move(fVar.Dta^, lRec^.Data, fVar^.aType.RealSize); + if CallData = nil then + CallData := TPSList.Create; + CallData.Add(lRec); + Result := @lRec^.Data; + end; + {$IFEND} + function GetPtr(fVar: PPSVariantIFC): Boolean; var varPtr: Pointer; @@ -711,13 +798,25 @@ _XMM0: Double; begin if Copy(fvar.aType.ExportName, 1, 10) = '!OPENARRAY' then begin - p := CreateOpenArray(True, Self, FVar); + p := CreateOpenArray(True, Self, FVar, CallData); if p = nil then exit; if CallData = nil then CallData := TPSList.Create; CallData.Add(p); + {$IFDEF FPC} + { Free Pascal has a cdecl routine take an array of const only as an + external one, whose values go one by one as C varargs: refused } + if (CallingConv = cdCdecl) and (TPSTypeRec_Array(fvar.aType).ArrayType.BaseType = btPointer) then + Exit; + {$ENDIF} StoreReg(IPointer(POpenArray(p)^.Data)); + {$IFDEF FPC} + { Free Pascal passes a cdecl open array as its data alone, with no high bound } + if CallingConv <> cdCdecl then + StoreReg(IPointer(POpenArray(p)^.ItemCount -1)); + {$ELSE} StoreReg(IPointer(POpenArray(p)^.ItemCount -1)); + {$ENDIF} Result := True; Exit; end else begin @@ -741,6 +840,12 @@ _XMM0: Double; exit; //invalid type end; end; {case} + {$IFDEF FPC} + if fvar.aType.BaseType in [btU8, btS8, btU16, btS16] then + VarPtr := NarrowedVar(VarPtr, fvar.aType.RealSize) + else if (fvar.aType.BaseType = btSet) and (TPSTypeRec_Set(fvar.aType).aByteSize < 32) then + VarPtr := NarrowedVar(VarPtr, TPSTypeRec_Set(fvar.aType).aByteSize); + {$ENDIF} StoreReg(IPointer(VarPtr)); end else begin @@ -750,21 +855,29 @@ _XMM0: Double; begin if Copy(fvar^.aType.ExportName, 1, 10) = '!OPENARRAY' then begin - p := CreateOpenArray(False, SElf, FVar); + p := CreateOpenArray(False, SElf, FVar, CallData); if p =nil then exit; if CallData = nil then CallData := TPSList.Create; CallData.Add(p); + {$IFDEF FPC} + { Free Pascal has a cdecl routine take an array of const only as an + external one, whose values go one by one as C varargs: refused } + if (CallingConv = cdCdecl) and (TPSTypeRec_Array(fvar.aType).ArrayType.BaseType = btPointer) then + Exit; + {$ENDIF} StoreReg(IPointer(POpenArray(p)^.Data)); + {$IFDEF FPC} + { Free Pascal passes a cdecl open array as its data alone, with no high bound } + if CallingConv <> cdCdecl then + StoreReg(IPointer(POpenArray(p)^.ItemCount -1)); + {$ELSE} StoreReg(IPointer(POpenArray(p)^.ItemCount -1)); + {$ENDIF} Result := True; exit; end else begin - {$IFDEF FPC} - StoreReg(IPointer(FVar.Dta)); - {$ELSE} StoreReg(IPointer(FVar.Dta^)); - {$ENDIF} end; end; btSet, @@ -776,36 +889,57 @@ _XMM0: Double; { Delphi Win64 ABI: a record or static array is passed by value (in a register) at sizes 1, 2, or 4 and for stdcall/cdecl/safecall also at size 8; all other sizes (3, 5, 6, 7, and > 8) are passed - by reference. A set follows the same rules, except that it has no - 8-byte stdcall/cdecl/safecall by-value case (not in the blog - below, found empirically; likely because C has no sets) and that Delphi - rounds set storage up (a native set is never 3 bytes, and on Win64 - never 5-7 bytes), so a 3-byte ROPS set is a native 4-byte set - passed by value, and a 5-8 byte ROPS set is a native 8-byte set - passed by reference. Before Rio 10.3 the register convention - additionally passed sizes 5, 6, 7, and 8 by value, see - https://blogs.embarcadero.com/abi-changes-in-rad-studio-10-3/ } + by reference. Before Rio 10.3 the register convention + additionally passed a record or static array of 8 bytes by + value, see + https://blogs.embarcadero.com/abi-changes-in-rad-studio-10-3/ ; + a record or static array of 5, 6 or 7 bytes went by reference + there too (measured with XE2 and 10.2 Tokyo). Delphi rounds set + storage up (a native set is never 3 bytes, and on Win64 never + 5-7 bytes), so a 3-byte ROPS set is a native 4-byte set passed + by value, and a 5-8 byte ROPS set is a native 8-byte set: passed + by value under every convention before Rio 10.3, under + stdcall/cdecl/safecall only in Rio 10.3, and by reference from + Sydney 10.4 (measured on every Win64 compiler from XE2 to 13 + Florence) -- by reference as a copy zero-extended to 8 bytes, + since the routine reads all of them } + if (fvar^.aType.BaseType = btSet) and (fvar^.aType.RealSize in [5, 6, 7, 8]) then + begin + {$IFDEF DELPHI_RIO_UP} + {$IFNDEF DELPHI_SYDNEY_UP} + if CallingConv in [cdCdecl, cdStdCall, cdSafeCall] then + StoreRegBytes(fvar.Dta, fvar^.aType.RealSize) + else + {$ENDIF} + StoreReg(IPointer(NativeSetCopy(fVar))); + {$ELSE} + StoreRegBytes(fvar.Dta, fvar^.aType.RealSize); + {$ENDIF} + end else if (fvar^.aType.RealSize in [1, 2, 4]) or ((fvar^.aType.BaseType = btSet) and (fvar^.aType.RealSize = 3)) or ((fvar^.aType.BaseType <> btSet) and (fvar^.aType.RealSize = 8) and (CallingConv in [cdCdecl, cdStdCall, cdSafeCall])) {$IFNDEF DELPHI_RIO_UP} - or ((fvar^.aType.RealSize in [5, 6, 7, 8]) and not (CallingConv in [cdCdecl, cdStdCall, cdSafeCall])) + or ((fvar^.aType.RealSize = 8) and + not (CallingConv in [cdCdecl, cdStdCall, cdSafeCall])) {$ENDIF} then StoreRegBytes(fvar.Dta, fvar^.aType.RealSize) else StoreReg(IPointer(fVar.Dta)); {$ELSE} - { FPC Win64 ABI: a record is passed by value (in a register) only - at sizes 1, 2, 4, or 8, a set only when it is a small set of at - most 4 bytes, and a static array never, for all calling - conventions. See aggregate_in_registers_win64 and the arraydef - and setdef cases of push_addr_param in + { FPC Win64 ABI: a value record is passed by value (in a register) + only at sizes 1, 2, 4, or 8 and a const record by reference at + every size; a set by value only when it is a small set of at most + 4 bytes; a static array never; for all calling conventions. The + script compiler keeps no const flag, so every record goes by + reference here, as a const one: a value record of 1, 2, 4 or 8 + bytes is the stated gap. See aggregate_in_registers_win64 and + the arraydef and setdef cases of push_addr_param in https://gitlab.com/freepascal.org/fpc/source/-/blob/main/compiler/x86_64/cpupara.pas and is_smallset in https://gitlab.com/freepascal.org/fpc/source/-/blob/main/compiler/defutil.pas } - if ((fvar^.aType.BaseType = btRecord) and (fvar^.aType.RealSize in [1, 2, 4, 8])) or - ((fvar^.aType.BaseType = btSet) and (fvar^.aType.RealSize in [1, 2, 3, 4])) then + if (fvar^.aType.BaseType = btSet) and (fvar^.aType.RealSize in [1, 2, 3, 4]) then StoreRegBytes(fvar.Dta, fvar^.aType.RealSize) else StoreReg(IPointer(fVar.Dta)); @@ -864,7 +998,7 @@ _XMM0: Double; btProcPtr: begin - {$IFDEF DELPHI} + {$IF defined(DELPHI) or (defined(FPC) and defined(MSWINDOWS))} p := New(PMethodCallData); TMethodCallData(p^).AType := 255; if CallData = nil then @@ -873,14 +1007,14 @@ _XMM0: Double; // Uncomment when Handler will be implemented //TMethodCallData(p^).Data.Code:=nil; //TMethodCallData(p^).Data.Data:=nil; - TMethodCallData(p^).Data := MKMethod(Self, Longint(fvar.dta^)); // It requires the implementation of "Handled" + TMethodCallData(p^).Data := ProcPtrToMethod(Self, fvar.dta); StoreReg(IPointer(@TMethodCallData(p^).Data)); {$ELSE} GetMem(p, PointerSize2); - TMethod(p^) := MKMethod(Self, Longint(FVar.Dta^)); + TMethod(p^) := ProcPtrToMethod(Self, FVar.Dta); StoreStack(p^, Pointersize2); FreeMem(p); - {$ENDIF} + {$IFEND} end; {$IFNDEF PS_NOINT64} bts64: @@ -911,7 +1045,7 @@ begin {$ENDIF} IsSafeCall := CallingConv = cdSafeCall; - InnerfuseCall := False; + PlatformInnerfuseCall := False; if Address = nil then exit; // need address SetLength(Stack, 0); @@ -959,6 +1093,12 @@ begin begin if ResultUsesResultPointer(res) then GetPtr(res); end; + btSingle, btDouble, btExtended, btChar, btU8, btS8, {$IFNDEF PS_NOWIDESTRING}btWideChar, {$ENDIF}btU16, + btS16, btClass, btU32, btS32, btPChar, {$IFNDEF PS_NOINT64}btS64, btU64, {$ENDIF}btCurrency + {$IFNDEF x64_string_result_as_varparameter}, btUnicodeString, btWideString, btString{$ENDIF}: + ; { returned in RAX or XMM0 } + else + exit; { a result the call layer does not return: the routine is not called } end; end; {$ENDIF} @@ -966,8 +1106,9 @@ begin begin if not GetPtr(rp(Params[I])) then Exit; end; - if assigned(res) and IsSafeCall then - GetPtr(res); { SafeCall: res is actually passed as last parameter } + { SafeCall: res is actually passed as last parameter } + if assigned(res) and IsSafeCall and not GetPtr(res) then + exit; if assigned(res) and not IsSafeCall then begin {$IFNDEF PS_RESBEFOREPARAMETERS} case res^.aType.BaseType of @@ -999,10 +1140,10 @@ begin case res^.aType.BaseType of btRecord, btSet{$IFDEF DELPHI_and_WINDOWS}, btStaticArray{$ENDIF}: begin - {$IFDEF DELPHI_and_WINDOWS} + {$IF defined(DELPHI_and_WINDOWS) or (defined(FPC) and defined(WINDOWS))} { A result that used the hidden result pointer is already in place } if not ResultUsesResultPointer(res) then - {$ENDIF} + {$IFEND} begin case res.aType.RealSize of 1: byte(res.Dta^) := _RAX; @@ -1070,7 +1211,14 @@ begin pp := CallData[i]; case pp^ of 0: DestroyOpenArray(Self, Pointer(pp)); - {$IFDEF DELPHI} 255: Dispose(PMethodCallData(pp)); {$ENDIF} + {$IF defined(DELPHI) or (defined(FPC) and defined(MSWINDOWS))} 255: Dispose(PMethodCallData(pp)); {$IFEND} + {$IF defined(DELPHI_RIO_UP) and defined(WINDOWS)} 2: Dispose(PNativeSetCopy(pp)); {$IFEND} +{$IFDEF FPC} + 1: begin + Move(PNarrowedVar(pp)^.Data, PNarrowedVar(pp)^.Target^, PNarrowedVar(pp)^.Size); + Dispose(PNarrowedVar(pp)); + end; +{$ENDIF} end; end; CallData.Free; diff --git a/Source/x86.inc b/Source/x86.inc index ec5dbda0..01edc7eb 100644 --- a/Source/x86.inc +++ b/Source/x86.inc @@ -1,7 +1,4 @@ { implementation of x86 abi } -{$ifdef FPC} -{$define PS_ARRAY_ON_STACK} -{$endif} { Pure assembler: Delphi 12.3 sometimes generates a bad instruction for the Result of a float function that contains an asm block } function RealFloatCall_Register(p: Pointer; @@ -206,12 +203,13 @@ begin mov r, ecx @@5: mov ecx, stackdatalen - jecxz @@7 + jecxz @@8 @@6: pop eax dec ecx or ecx, ecx jnz @@6 + @@8: mov ecx, resedx jecxz @@7 mov [ecx], edx @@ -236,7 +234,7 @@ const {$IFDEF DELPHI_ATHENS_UP}{$DEFINE DELPHI_SMALL_MANAGED_BORROW}{$ENDIF} {$ENDIF} -function TPSExec.InnerfuseCall(_Self, Address: Pointer; CallingConv: TPSCallingConvention; Params: TPSList; res: PPSVariantIFC): Boolean; +function TPSExec.PlatformInnerfuseCall(_Self, Address: Pointer; CallingConv: TPSCallingConvention; Params: TPSList; res: PPSVariantIFC): Boolean; var Stack: ansistring; I: Longint; @@ -245,7 +243,6 @@ var pp: ^Byte; {$IFDEF FPC} IsConstructor,IsVirtualCons: Boolean; - MethodData: TMethod; {$ENDIF} EAX, EDX, ECX: Longint; @@ -279,6 +276,17 @@ var ((res^.aType.RealSize <> 4) or IsManagedType(res^.aType)) else {$ENDIF} + {$IF defined(FPC) and defined(MSWINDOWS)} + { Free Pascal Win32: a record result is returned in EAX at 1, 2 or 4 bytes, + and by a cdecl routine in EAX:EDX up to 8 bytes; a larger one, one + holding a managed field, and a pascal routine's are written through the + hidden result pointer } + if res^.aType.BaseType = btRecord then + Result := IsManagedType(res^.aType) or (CallingConv = cdPascal) or + ((CallingConv = cdCdecl) and (res^.aType.RealSize > 8)) or + ((CallingConv <> cdCdecl) and not (res^.aType.RealSize in [1, 2, 4])) + else + {$IFEND} begin {$IFDEF MSWINDOWS} Result := res^.aType.RealSize > 4; @@ -288,6 +296,55 @@ var end; end; + {$IFDEF FPC} + { Free Pascal's RTL and fcl-db keep an enumeration or a set of up to 32 members in 4 bytes (their + units are compiled in objfpc mode), where the script holds it in 1 to 3: a native routine writing + such a var parameter would overrun the script's value. It gets a zero-extended copy instead, + whose script-sized part is written back after the call } + type + TNarrowedVar = record + AType : Byte; { 1; must be first, matching uPSRuntime's TOpenArray } + Size : Longint; + Target : Pointer; + Data : array[0..31] of Byte; + end; + PNarrowedVar = ^TNarrowedVar; + { a method pointer passed by reference: a copy per parameter, alive until the call returns } + TMethodCallData = record + AType : Byte; { 255; must be first, matching uPSRuntime's TOpenArray } + Data : TMethod; + end; + PMethodCallData = ^TMethodCallData; + + function NarrowedVar(aTarget: Pointer; aSize: Longint): Pointer; + var + lRec: PNarrowedVar; + lIdx: Longint; + begin + { the same script value passed twice by reference shares one copy, as it shares one address on Delphi } + if CallData <> nil then + for lIdx := 0 to CallData.Count - 1 do + begin + lRec := CallData[lIdx]; + if (lRec^.AType = 1) and (lRec^.Target = aTarget) then + begin + Result := @lRec^.Data; + Exit; + end; + end; + New(lRec); + FillChar(lRec^, SizeOf(lRec^), 0); + lRec^.AType := 1; + lRec^.Size := aSize; + lRec^.Target := aTarget; + Move(aTarget^, lRec^.Data, aSize); + if CallData = nil then + CallData := TPSList.Create; + CallData.Add(lRec); + Result := @lRec^.Data; + end; + {$ENDIF} + function GetPtr(fVar: PPSVariantIFC): Boolean; var varPtr: Pointer; @@ -305,9 +362,32 @@ var begin if Copy(fvar.aType.ExportName, 1, 10) = '!OPENARRAY' then begin - p := CreateOpenArray(True, Self, FVar); + p := CreateOpenArray(True, Self, FVar, CallData); if p = nil then exit; CallData.Add(p); + {$IFDEF FPC} + if (RegUsage >= 3) and (CallingConv = cdCdecl) then + begin + { Free Pascal has a cdecl routine take an array of const only as an + external one, whose values go one by one as C varargs: refused } + if TPSTypeRec_Array(fvar.aType).ArrayType.BaseType = btPointer then + Exit; + { Free Pascal passes a cdecl open array as its data alone, with no high bound } + Stack := StringOfChar(AnsiChar(#0),4) + Stack; + Pointer((@Stack[1])^) := POpenArray(p)^.Data; + Result := True; + Exit; + end; + {$ENDIF} + if (RegUsage >= 3) and (CallingConv in [cdCdecl, cdStdCall, cdSafeCall]) then + begin + { pushed from right to left: the data pointer sits below the high bound } + Stack := StringOfChar(AnsiChar(#0),8) + Stack; + Pointer((@Stack[1])^) := POpenArray(p)^.Data; + Longint((@Stack[5])^) := POpenArray(p)^.ItemCount -1; + Result := True; + Exit; + end; case RegUsage of 0: begin EAX := Longint(POpenArray(p)^.Data); Inc(RegUsage); end; 1: begin EDX := Longint(POpenArray(p)^.Data); Inc(RegUsage); end; @@ -352,6 +432,12 @@ var exit; //invalid type end; end; {case} + {$IFDEF FPC} + if fvar.aType.BaseType in [btU8, btS8, btU16, btS16] then + VarPtr := NarrowedVar(VarPtr, fvar.aType.RealSize) + else if (fvar.aType.BaseType = btSet) and (TPSTypeRec_Set(fvar.aType).aByteSize < 32) then + VarPtr := NarrowedVar(VarPtr, TPSTypeRec_Set(fvar.aType).aByteSize); + {$ENDIF} case RegUsage of 0: begin EAX := Longint(VarPtr); Inc(RegUsage); end; 1: begin EDX := Longint(VarPtr); Inc(RegUsage); end; @@ -420,20 +506,70 @@ var cardinal((@tempstr[1])^) := cardinal(fvar.dta^); end; {$ELSE} + {$IFDEF FPC} + 3: Move(fvar.dta^, tempstr[1], 3); + 4: cardinal((@tempstr[1])^) := cardinal(fvar.dta^); + {$ELSE} 3, 4: cardinal((@tempstr[1])^) := cardinal(fvar.dta^); {$ENDIF} + {$ENDIF} else pointer((@tempstr[1])^) := fvar.dta; end; end; + {$IFDEF FPC} + { Free Pascal Win32: a record of 1-4 bytes is passed by value on the + stack, never in a register, and under cdecl and stdcall a larger one + is passed by value on the stack too, rounded up to whole 4-byte slots } + if fVar^.aType.BaseType = btRecord then + if DataSize <= 4 then + UseReg := False + else if (CallingConv in [cdCdecl, cdStdCall]) and not IsManagedType(fVar^.aType) then + begin + UseReg := False; + tempstr := StringOfChar(AnsiChar(#0), ((DataSize + 3) div 4) * 4); + Move(fvar.dta^, tempstr[1], DataSize); + end; + { and so is a set larger than 4 bytes under cdecl, which every other + convention passes by reference } + if (fVar^.aType.BaseType = btSet) and (DataSize > 4) and (CallingConv = cdCdecl) then + begin + UseReg := False; + tempstr := StringOfChar(AnsiChar(#0), ((DataSize + 3) div 4) * 4); + Move(fvar.dta^, tempstr[1], DataSize); + end; + {$ENDIF} end; btArray: begin if Copy(fvar^.aType.ExportName, 1, 10) = '!OPENARRAY' then begin - p := CreateOpenArray(False, SElf, FVar); + p := CreateOpenArray(False, SElf, FVar, CallData); if p =nil then exit; CallData.Add(p); + {$IFDEF FPC} + if (RegUsage >= 3) and (CallingConv = cdCdecl) then + begin + { Free Pascal has a cdecl routine take an array of const only as an + external one, whose values go one by one as C varargs: refused } + if TPSTypeRec_Array(fvar.aType).ArrayType.BaseType = btPointer then + Exit; + { Free Pascal passes a cdecl open array as its data alone, with no high bound } + Stack := StringOfChar(AnsiChar(#0),4) + Stack; + Pointer((@Stack[1])^) := POpenArray(p)^.Data; + Result := True; + Exit; + end; + {$ENDIF} + if (RegUsage >= 3) and (CallingConv in [cdCdecl, cdStdCall, cdSafeCall]) then + begin + { pushed from right to left: the data pointer sits below the high bound } + Stack := StringOfChar(AnsiChar(#0),8) + Stack; + Pointer((@Stack[1])^) := POpenArray(p)^.Data; + Longint((@Stack[5])^) := POpenArray(p)^.ItemCount -1; + Result := True; + Exit; + end; case RegUsage of 0: begin EAX := Longint(POpenArray(p)^.Data); Inc(RegUsage); end; 1: begin EDX := Longint(POpenArray(p)^.Data); Inc(RegUsage); end; @@ -491,6 +627,18 @@ var UseReg := False; end else {$ENDIF} + {$IFDEF FPC} + { Free Pascal Win32: a static array of 1-4 bytes is passed by value + on the stack, never in a register, under every convention but + cdecl, which passes every static array by reference } + if (fVar^.aType.BaseType = btStaticArray) and + (fvar^.aType.RealSize <= 4) and (CallingConv <> cdCdecl) then + begin + tempstr := StringOfChar(AnsiChar(#0),4); + Move(fvar.dta^, tempstr[1], fvar^.aType.RealSize); + UseReg := False; + end else + {$ENDIF} begin TempStr := StringOfChar(AnsiChar(#0),4); Pointer((@TempStr[1])^) := Pointer(fvar.Dta); @@ -520,7 +668,14 @@ var btChar, btU8, btS8: begin + {$IFDEF FPC} + { joined, an AnsiChar goes through the compile host's code page: 200 arrives as 195 + under a UTF-8 run-time page } + TempStr := StringOfChar(AnsiChar(#0),4); + tbtchar((@TempStr[1])^) := tbtchar(fVar^.dta^); + {$ELSE} TempStr := tbtchar(fVar^.dta^) + tbtstring(StringOfChar(AnsiChar(#0),3)); + {$ENDIF} end; {$IFNDEF PS_NOWIDESTRING}btWideChar, {$ENDIF} btu16, btS16: begin @@ -558,12 +713,25 @@ var btProcPtr: begin {$IFDEF FPC} - MethodData := MKMethod(Self, Longint(FVar.Dta^)); - TempStr := StringOfChar(AnsiChar(#0),4); - Pointer((@TempStr[1])^) := @MethodData; + { Free Pascal Win32 passes a method pointer by value under cdecl and by + reference under the other conventions, each one in a copy of its own } + if CallingConv = cdCdecl then + begin + TempStr := StringOfChar(AnsiChar(#0),8); + TMethod((@TempStr[1])^) := ProcPtrToMethod(Self, FVar.Dta); + UseReg := False; + end else + begin + p := New(PMethodCallData); + PMethodCallData(p)^.AType := 255; + CallData.Add(p); + PMethodCallData(p)^.Data := ProcPtrToMethod(Self, FVar.Dta); + TempStr := StringOfChar(AnsiChar(#0),4); + Pointer((@TempStr[1])^) := @PMethodCallData(p)^.Data; + end; {$ELSE} TempStr := StringOfChar(AnsiChar(#0),8); - TMethod((@TempStr[1])^) := MKMethod(Self, Longint(FVar.Dta^)); + TMethod((@TempStr[1])^) := ProcPtrToMethod(Self, FVar.Dta); UseReg := false; {$ENDIF} end; @@ -607,6 +775,22 @@ var end; Result := True; end; +{$IFDEF FPC} + { Free Pascal passes a cdecl or stdcall method Self ahead of its hidden result pointer, where Delphi + passes the result pointer first: called right after GetPtr(res) has put that pointer in front of + Self, this exchanges the two } + procedure SelfAheadOfResult; + var + lSelf: Pointer; + begin + if Assigned(_Self) then + begin + lSelf := Pointer((@Stack[5])^); + Pointer((@Stack[5])^) := Pointer((@Stack[1])^); + Pointer((@Stack[1])^) := lSelf; + end; + end; +{$ENDIF} begin {$IFDEF FPC} if (Integer(CallingConv) and 128) <> 0 then begin @@ -620,7 +804,7 @@ begin end else IsConstructor := false; {$ENDIF} - InnerfuseCall := False; + PlatformInnerfuseCall := False; if Address = nil then exit; // need address Stack := ''; @@ -757,22 +941,28 @@ begin end; if assigned(res) then begin case res^.aType.BaseType of - {$IFNDEF PS_NOWIDESTRING}btWideString, btUnicodeString, {$ENDIF}btInterface, btArray, btString, btVariant: GetPtr(res); + {$IFNDEF PS_NOWIDESTRING}btWideString, btUnicodeString, {$ENDIF}btInterface, btArray, btString, btVariant{$IFDEF FPC}, btStaticArray{$ENDIF}: GetPtr(res); btRecord{$IFDEF DELPHI_and_MSWINDOWS}, btStaticArray{$ENDIF}: begin if ResultUsesResultPointer(res) then GetPtr(res); end; - {$IFDEF DELPHI_and_MSWINDOWS} + {$IF Defined(DELPHI_and_MSWINDOWS) or Defined(FPC)} btSet: begin if TPSTypeRec_Set(res.aType).aByteSize > 4 then GetPtr(res); end; - {$ENDIF} + {$IFEND} end; end; if assigned(_Self) then begin + {$IFDEF FPC} + { Free Pascal pushes a pascal method's Self first, above every parameter } + Stack := Stack + StringOfChar(AnsiChar(#0),4); + Pointer((@Stack[Length(Stack)-3])^) := _Self; + {$ELSE} Stack := StringOfChar(AnsiChar(#0),4) +Stack; Pointer((@Stack[1])^) := _Self; + {$ENDIF} end; {$IFDEF DARWIN} if (length(Stack) mod 16) <> 0 then begin @@ -799,7 +989,7 @@ begin end; {$ENDIF} btVariant, {$IFNDEF PS_NOWIDESTRING}btUnicodeString, btWideString, {$ENDIF} - btInterface, btArray, btstring: RealCall_Other(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 0, nil); + btInterface, btArray, btstring{$IFDEF FPC}, btStaticArray{$ENDIF}: RealCall_Other(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 0, nil); btRecord{$IFDEF DELPHI_and_MSWINDOWS}, btStaticArray{$ENDIF}: begin if not ResultUsesResultPointer(res) then @@ -812,7 +1002,7 @@ begin else RealCall_Other(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 0, nil); end; - {$IFDEF DELPHI_and_MSWINDOWS} + {$IF Defined(DELPHI_and_MSWINDOWS) or Defined(FPC)} btSet: begin case TPSTypeRec_Set(res.aType).aByteSize of @@ -826,7 +1016,7 @@ begin else RealCall_Other(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 0, nil) end; end; - {$ENDIF} + {$IFEND} else exit; end; @@ -836,9 +1026,8 @@ begin end; cdSafeCall: begin RegUsage := 3; - if assigned(res) then begin - GetPtr(res); - end; + if assigned(res) and not GetPtr(res) then + exit; for I := Params.Count - 1 downto 0 do begin if not GetPtr(Params[i]) then Exit; end; @@ -857,13 +1046,13 @@ begin CdCdecl: begin RegUsage := 3; - if assigned(_Self) then begin - Stack := StringOfChar(AnsiChar(#0),4); - Pointer((@Stack[1])^) := _Self; - end; for I := Params.Count - 1 downto 0 do begin if not GetPtr(Params[I]) then Exit; end; + if assigned(_Self) then begin + Stack := StringOfChar(AnsiChar(#0),4) + Stack; + Pointer((@Stack[1])^) := _Self; + end; {$IFDEF DARWIN} if (length(Stack) mod 16) <> 0 then begin Stack := Stack + StringOfChar(ansichar(#32), 16 - (Length(Stack) mod 16)) ; @@ -889,23 +1078,37 @@ begin end; {$ENDIF} btVariant, {$IFNDEF PS_NOWIDESTRING}btUnicodeString, btWideString, {$ENDIF} - btInterface, btArray, btstring: begin GetPtr(res); RealCall_Cdecl(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 0, nil); end; + btInterface, btArray, btstring{$IFDEF FPC}, btStaticArray{$ENDIF}: begin GetPtr(res); {$IFDEF FPC}SelfAheadOfResult;{$ENDIF} RealCall_Cdecl(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 0, nil); end; btRecord{$IFDEF DELPHI_and_MSWINDOWS}, btStaticArray{$ENDIF}: begin if ResultUsesResultPointer(res) then begin GetPtr(res); + {$IFDEF FPC}SelfAheadOfResult;{$ENDIF} RealCall_Cdecl(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 0, nil); end else case res.aType.RealSize of 1: PByte(res.Dta)^ := RealCall_Cdecl(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 1, nil); 2: PWord(res.Dta)^ := RealCall_Cdecl(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 2, nil); + {$IFDEF FPC} + { Free Pascal returns a cdecl record of up to 8 bytes in EAX:EDX } + 3, 5..8: + begin + EAX := RealCall_Cdecl(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 4, @EDX); + if res.aType.RealSize < 4 then + Move(EAX, res.Dta^, res.aType.RealSize) + else begin + Move(EAX, res.Dta^, 4); + Move(EDX, Pointer(IPointer(res.Dta) + 4)^, res.aType.RealSize - 4); + end; + end; + {$ENDIF} else PCardinal(res.Dta)^ := RealCall_Cdecl(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 4, nil); end; end; - {$IFDEF DELPHI_and_MSWINDOWS} + {$IF Defined(DELPHI_and_MSWINDOWS) or Defined(FPC)} btSet: begin case TPSTypeRec_Set(res.aType).aByteSize of @@ -918,11 +1121,12 @@ begin 4: PCardinal(res.Dta)^ := RealCall_Cdecl(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 4, nil); else begin GetPtr(res); + {$IFDEF FPC}SelfAheadOfResult;{$ENDIF} RealCall_Cdecl(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 0, nil); end; end; end; - {$ENDIF} + {$IFEND} else exit; end; @@ -960,12 +1164,13 @@ begin end; {$ENDIF} btVariant, {$IFNDEF PS_NOWIDESTRING}btUnicodeString, btWideString, {$ENDIF} - btInterface, btArray, btstring: begin GetPtr(res); RealCall_Other(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 0, nil); end; + btInterface, btArray, btstring{$IFDEF FPC}, btStaticArray{$ENDIF}: begin GetPtr(res); {$IFDEF FPC}SelfAheadOfResult;{$ENDIF} RealCall_Other(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 0, nil); end; btRecord{$IFDEF DELPHI_and_MSWINDOWS}, btStaticArray{$ENDIF}: begin if ResultUsesResultPointer(res) then begin GetPtr(res); + {$IFDEF FPC}SelfAheadOfResult;{$ENDIF} RealCall_Other(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 0, nil); end else @@ -976,7 +1181,7 @@ begin PCardinal(res.Dta)^ := RealCall_Other(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 4, nil); end; end; - {$IFDEF DELPHI_and_MSWINDOWS} + {$IF Defined(DELPHI_and_MSWINDOWS) or Defined(FPC)} btSet: begin case TPSTypeRec_Set(res.aType).aByteSize of @@ -989,11 +1194,12 @@ begin 4: PCardinal(res.Dta)^ := RealCall_Other(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 4, nil); else begin GetPtr(res); + {$IFDEF FPC}SelfAheadOfResult;{$ENDIF} RealCall_Other(Address, @Stack[Length(Stack)-3], Length(Stack) div 4, 0, nil); end; end; end; - {$ENDIF} + {$IFEND} else exit; end; @@ -1009,6 +1215,13 @@ begin pp := CallData[i]; case pp^ of 0: DestroyOpenArray(Self, Pointer(pp)); +{$IFDEF FPC} + 1: begin + Move(PNarrowedVar(pp)^.Data, PNarrowedVar(pp)^.Target^, PNarrowedVar(pp)^.Size); + Dispose(PNarrowedVar(pp)); + end; + 255: Dispose(PMethodCallData(pp)); +{$ENDIF} end; end; CallData.Free;