forked from pyscripter/pyscripter
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcPyDebugger.pas
1510 lines (1343 loc) · 47.5 KB
/
cPyDebugger.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-----------------------------------------------------------------------------
Unit Name: cPyDebugger
Author: Kiriakos Vlahos
Date: 23-Feb-2005
Purpose: Interpreter and Debugger based on P4D PythonEngine
History: Origianlly Based on SynEdit IDE Demo debugger
-----------------------------------------------------------------------------}
unit cPyDebugger;
interface
uses
Windows, SysUtils, Classes, uEditAppIntfs, PythonEngine, Forms, Contnrs,
cPyBaseDebugger;
type
TFrameInfo = class(TBaseFrameInfo)
private
fPyFrame : Variant;
protected
// Implementation of the Base class for the internal debugger
function GetFunctionName : string; override;
function GetFileName : string; override;
function GetLine : integer; override;
public
constructor Create(Frame : Variant);
property PyFrame : Variant read fPyFrame;
end;
TPyObjectInfo = record
Initialized,
Has__dict__,
IsModule,
IsMethod,
IsFunction,
IsClass : Boolean;
IsDict : Boolean;
end;
TNameSpaceItem = class(TBaseNameSpaceItem)
// Implementation of the Base class for the internal debugger
protected
fChildCount : integer;
fChildNodes : TStringList;
fName : string;
fObjectType : string; // for caching ObjectType
fObjectInfo : TPyObjectInfo;
protected
function GetName : string; override;
function GetObjectType : string; override;
function GetValue : string; override;
function GetDocString : string; override;
function GetChildCount : integer; override;
function GetChildNode(Index: integer): TBaseNameSpaceItem; override;
function GetObjectInfo : TPyObjectInfo;
procedure ExtractObjectInfo(PyObjectInfo : PPyObject);
procedure FillObjectInfo; virtual;
public
constructor Create(aName : string; aPyObject : Variant);
destructor Destroy; override;
function IsClass : Boolean; override;
function IsDict : Boolean; override;
function IsModule : Boolean; override;
function IsFunction : Boolean; override;
function IsMethod : Boolean; override;
function Has__dict__ : Boolean; override;
function IndexOfChild(AName : string): integer; override;
procedure GetChildNodes; override;
property ObjectInfo : TPyObjectInfo read GetObjectInfo;
end;
TPyInternalInterpreter = class(TPyBaseInterpreter)
private
fII : Variant; // Python VarPyth wrapper to the interactive interpreter
fDebugger : Variant;
fOldargv : Variant;
protected
procedure CreateMainModule; override;
public
constructor Create(II : Variant);
function SysPathAdd(const Path : string) : boolean; override;
function SysPathRemove(const Path : string) : boolean; override;
procedure SysPathToStrings(Strings : TStrings); override;
procedure StringsToSysPath(Strings : TStrings); override;
function Compile(ARunConfig : TRunConfiguration) : Variant;
function GetGlobals : TBaseNameSpaceItem; override;
procedure GetModulesOnPath(Path : Variant; SL : TStrings); override;
function NameSpaceFromExpression(const Expr : string) : TBaseNameSpaceItem; override;
function CallTipFromExpression(const Expr : string;
var DisplayString, DocString : string) : Boolean; override;
procedure SetCommandLine(ARunConfig : TRunConfiguration); override;
procedure RestoreCommandLine; override;
function ImportModule(Editor : IEditor; AddToNameSpace : Boolean = False) : Variant; override;
procedure RunNoDebug(ARunConfig : TRunConfiguration); override;
function SyntaxCheck(Editor : IEditor; Quiet : Boolean = False) : Boolean;
function RunSource(Const Source, FileName : Variant; symbol : string = 'single') : boolean; override;
function EvalCode(const Expr : string) : Variant; override;
function GetObjectType(Ob : Variant) : string; override;
function UnitTestResult : Variant; override;
function NameSpaceItemFromPyObject(aName : string; aPyObject : Variant): TBaseNameSpaceItem; override;
property Debugger : Variant read fDebugger;
property PyInteractiveInterpreter : Variant read fII;
end;
TPyInternalDebugger = class(TPyBaseDebugger)
// pdb based internal debugger
private
fDebuggerCommand : TDebuggerCommand;
fCurrentFrame : Variant;
fLineCache : Variant;
fOldPS1, fOldPS2 : string;
protected
procedure SetCommandLine(ARunConfig : TRunConfiguration); override;
procedure RestoreCommandLine; override;
procedure SetDebuggerBreakpoints; override;
procedure LoadLineCache;
procedure UserCall(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject);
procedure UserLine(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject);
procedure UserReturn(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject);
procedure UserException(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject);
procedure UserYield(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject);
property CurrentFrame : Variant read fCurrentFrame;
public
constructor Create;
destructor Destroy; override;
// Python Path
function SysPathAdd(const Path : string) : boolean; override;
function SysPathRemove(const Path : string) : boolean; override;
// Debugging
procedure Run(ARunConfig : TRunConfiguration; InitStepIn : Boolean = False;
RunToCursorLine : integer = -1); override;
procedure RunToCursor(Editor : IEditor; ALine: integer); override;
procedure StepInto; override;
procedure StepOver; override;
procedure StepOut; override;
procedure Resume; override;
procedure Pause; override;
procedure Abort; override;
// Evaluate expression in the current frame
procedure Evaluate(const Expr : string; out ObjType, Value : string); overload; override;
function Evaluate(const Expr : string) : TBaseNamespaceItem; overload; override;
// Like the InteractiveInterpreter runsource but for the debugger frame
function RunSource(Const Source, FileName : Variant; symbol : string = 'single') : boolean; override;
// Fills in CallStackList with TBaseFrameInfo objects
procedure GetCallStack(CallStackList : TObjectList); override;
// functions to get TBaseNamespaceItems corresponding to a frame's gloabals and locals
function GetFrameGlobals(Frame : TBaseFrameInfo) : TBaseNameSpaceItem; override;
function GetFrameLocals(Frame : TBaseFrameInfo) : TBaseNameSpaceItem; override;
function NameSpaceFromExpression(const Expr : string) : TBaseNameSpaceItem; override;
procedure MakeFrameActive(Frame : TBaseFrameInfo); override;
// post mortem stuff
function HaveTraceback : boolean; override;
procedure EnterPostMortem; override;
procedure ExitPostMortem; override;
end;
var
InternalInterpreter : TPyInternalInterpreter = nil;
implementation
uses dmCommands, frmPythonII, Variants, VarPyth, frmMessages, frmPyIDEMain,
MMSystem, Math, uCommonFunctions,
cParameters, StringResources, Dialogs, JvDSADialogs,
gnugettext, cRefactoring;
{ TFrameInfo }
constructor TFrameInfo.Create(Frame: Variant);
begin
fPyFrame := Frame;
inherited Create;
end;
function TFrameInfo.GetFileName: string;
begin
Result := fPyFrame.f_code.co_filename;
end;
function TFrameInfo.GetFunctionName: string;
begin
Result := fPyFrame.f_code.co_name;
end;
function TFrameInfo.GetLine: integer;
begin
Result := fPyFrame.f_lineno;
end;
{ TNameSpaceItem }
constructor TNameSpaceItem.Create(aName : string; aPyObject: Variant);
begin
Assert(VarIsPython(aPyObject));
fName := aName;
fPyObject := aPyObject;
fChildCount := -1; // unknown
fObjectInfo.Initialized := False;
fExpandSequences := True;
end;
destructor TNameSpaceItem.Destroy;
Var
i : integer;
begin
if Assigned(fChildNodes) then begin;
for i := 0 to fChildNodes.Count - 1 do
fChildNodes.Objects[i].Free;
fChildNodes.Free;
end;
inherited;
end;
procedure TNameSpaceItem.ExtractObjectInfo(PyObjectInfo: PPyObject);
begin
fObjectInfo.Initialized := True;
fObjectInfo.Has__dict__ := False;
fObjectInfo.IsModule := False;
fObjectInfo.IsMethod := False;
fObjectInfo.IsFunction := False;
fObjectInfo.IsClass := False;
if Assigned(PyObjectInfo) then with GetPythonEngine do begin
fObjectInfo.Has__dict__ := PyObject_IsTrue(PyTuple_GetItem(PyObjectInfo, 0)) = 1;
fObjectInfo.IsModule := PyObject_IsTrue(PyTuple_GetItem(PyObjectInfo, 1)) = 1;
fObjectInfo.IsMethod := PyObject_IsTrue(PyTuple_GetItem(PyObjectInfo, 2)) = 1;
fObjectInfo.IsFunction := PyObject_IsTrue(PyTuple_GetItem(PyObjectInfo, 3)) = 1;
fObjectInfo.IsClass := PyObject_IsTrue(PyTuple_GetItem(PyObjectInfo, 4)) = 1;
fObjectInfo.IsDict := PyObject_IsTrue(PyTuple_GetItem(PyObjectInfo, 5)) = 1;
end;
end;
function TNameSpaceItem.GetChildCount: integer;
var
SuppressOutput : IInterface;
begin
if Assigned(fChildNodes) then
Result := fChildNodes.Count
else if fChildCount >= 0 then
Result := fChildCount
else begin
SuppressOutput := PythonIIForm.OutputSuppressor; // Do not show errors
try
Result := InternalInterpreter.PyInteractiveInterpreter.membercount(fPyObject, True,
ExpandCommonTypes, ExpandSequences);
except
Result := 0;
end;
fChildCount := Result;
end;
end;
function TNameSpaceItem.GetChildNode(Index: integer): TBaseNameSpaceItem;
begin
Assert(Index >= 0, 'TNameSpaceItem.GetChildNode');
if not Assigned(fChildNodes) then
GetChildNodes;
Assert(Index < fChildNodes.Count, 'TNameSpaceItem.GetChildNode');
Result := fChildNodes.Objects[Index] as TBaseNameSpaceItem;
end;
procedure TNameSpaceItem.GetChildNodes;
Var
FullInfoTuple, APyObject: Variant;
PyFullInfoTuple, PyMemberInfo, PyFullInfo: PPyObject;
i : integer;
ObjName : string;
NameSpaceItem : TNameSpaceItem;
SuppressOutput : IInterface;
begin
if not (Assigned(fChildNodes) or GotChildNodes) then begin
GotChildNodes := True;
SuppressOutput := PythonIIForm.OutputSuppressor; // Do not show errors
try
FullInfoTuple := InternalInterpreter.PyInteractiveInterpreter.safegetmembersfullinfo(fPyObject, True,
ExpandCommonTypes, ExpandSequences);
fChildCount := len(FullInfoTuple);
if fChildCount > 0 then begin
fChildNodes := TStringList.Create;
fChildNodes.CaseSensitive := True;
PyFullInfoTuple := ExtractPythonObjectFrom(FullInfoTuple);
for i := 0 to fChildCount - 1 do with GetPythonEngine do begin
PyMemberInfo := PyTuple_GetItem(PyFullInfoTuple, i);
ObjName := PyString_AsWideString(PyTuple_GetItem(PyMemberInfo, 0));
PyFullInfo := PyTuple_GetItem(PyMemberInfo, 1);
APyObject := VarPythonCreate(PyTuple_GetItem(PyFullInfo, 0));
NameSpaceItem := TNameSpaceItem.Create(ObjName, APyObject);
NameSpaceItem.ExpandCommonTypes := ExpandCommonTypes;
NameSpaceItem.ExpandSequences := ExpandSequences;
NameSpaceItem.BufferedValue := PyString_AsWideString(PyTuple_GetItem(PyFullInfo, 1));
NameSpaceItem.GotBufferedValue := True;
NameSpaceItem.fObjectType := PyString_AsWideString(PyTuple_GetItem(PyFullInfo, 2));
NameSpaceItem.ExtractObjectInfo(PyTuple_GetItem(PyFullInfo, 3));
NameSpaceItem.fChildCount := PyInt_AsLong(PyTuple_GetItem(PyFullInfo, 4));
fChildNodes.AddObject(ObjName, NameSpaceItem);
end;
GetPythonEngine.CheckError;
if (ObjectType <> 'list') and (ObjectType <> 'tuple') then
fChildNodes.CustomSort(ComparePythonIdents);
end;
except
fChildCount := 0;
Dialogs.MessageDlg(Format(_(SErrorGettingNamespace), [fName]), mtError, [mbAbort], 0);
SysUtils.Abort;
end;
end;
end;
function TNameSpaceItem.GetDocString: string;
Var
SuppressOutput : IInterface;
begin
SuppressOutput := PythonIIForm.OutputSuppressor; // Do not show errors
try
Result := Import('inspect').getdoc(fPyObject);
except
Result := '';
end;
end;
function TNameSpaceItem.GetName: string;
begin
Result := fName;
end;
procedure TNameSpaceItem.FillObjectInfo;
var
SuppressOutput : IInterface;
PyObjectInfo : PPyObject;
begin
SuppressOutput := PythonIIForm.OutputSuppressor; // Do not show errors
try
PyObjectInfo := ExtractPythonObjectFrom(InternalInterpreter.PyInteractiveInterpreter.objectinfo(fPyObject));
except
PyObjectInfo := nil;
end;
ExtractObjectInfo(PyObjectInfo);
end;
function TNameSpaceItem.GetObjectType: string;
begin
if fObjectType <> '' then
Result := fObjectType
else begin
Result := InternalInterpreter.GetObjectType(fPyObject);
fObjectType := Result;
end;
end;
function TNameSpaceItem.GetValue: string;
Var
SuppressOutput : IInterface;
begin
SuppressOutput := PythonIIForm.OutputSuppressor; // Do not show errors
try
Result := InternalInterpreter.PyInteractiveInterpreter.saferepr(fPyObject);
except
Result := '';
end;
end;
function TNameSpaceItem.Has__dict__: Boolean;
begin
Result := ObjectInfo.Has__dict__;
end;
function TNameSpaceItem.IndexOfChild(AName: string): integer;
var
L, H, I, C: Integer;
Found : Boolean;
begin
if not Assigned(fChildNodes) then
GetChildNodes;
if Assigned(fChildNodes) then begin
// Child nodes are sorted with ComparePythonIdents
// Do a quick search
Result := -1;
Found := False;
L := 0;
H := fChildNodes.Count - 1;
while L <= H do
begin
I := (L + H) shr 1;
C := ComparePythonIdents(fChildNodes[I], AName);
if C < 0 then L := I + 1 else
begin
H := I - 1;
if C = 0 then
begin
Found := True;
L := I;
end;
end;
end;
if Found then
Result := L;
//Result := fChildNodes.IndexOf(AName)
end else
Result := -1;
end;
function TNameSpaceItem.IsClass: Boolean;
begin
Result := ObjectInfo.IsClass;
end;
function TNameSpaceItem.IsDict: Boolean;
begin
Result := ObjectInfo.IsDict;
end;
function TNameSpaceItem.IsFunction: Boolean;
begin
Result := ObjectInfo.IsFunction;
end;
function TNameSpaceItem.IsMethod: Boolean;
begin
Result := ObjectInfo.IsMethod;
end;
function TNameSpaceItem.IsModule: Boolean;
begin
Result := ObjectInfo.IsModule;
end;
function TNameSpaceItem.GetObjectInfo: TPyObjectInfo;
begin
if not fObjectInfo.Initialized then
FillObjectInfo;
Result := fObjectInfo;
end;
{ TPyDebugger }
constructor TPyInternalDebugger.Create;
begin
inherited Create;
fLineCache := Import('linecache');
fDebuggerCommand := dcNone;
PyControl.BreakPointsChanged := True;
end;
destructor TPyInternalDebugger.Destroy;
begin
with PythonIIForm.DebugIDE.Events do begin
Items[0].OnExecute := nil;
Items[1].OnExecute := nil;
Items[2].OnExecute := nil;
Items[3].OnExecute := nil;
Items[4].OnExecute := nil;
end;
inherited;
end;
procedure TPyInternalDebugger.EnterPostMortem;
Var
TraceBack : Variant;
begin
if not (HaveTraceback and (PyControl.DebuggerState = dsInactive)) then
Exit;
with PythonIIForm do begin
fOldPS1 := PS1;
PS1 := PMPrefix + PS1;
fOldPS2 := PS2;
PS2 := PMPrefix + PS2;
AppendPrompt;
end;
TraceBack := SysModule.last_traceback;
InternalInterpreter.Debugger.botframe := TraceBack.tb_frame;
while not VarIsNone(TraceBack.tb_next) do
TraceBack := TraceBack.tb_next;
fCurrentFrame := TraceBack.tb_frame;
PyControl.DoStateChange(dsPostMortem);
DSAMessageDlg(dsaPostMortemInfo, 'PyScripter', _(SPostMortemInfo),
mtInformation, [mbOK], 0, dckActiveForm, 0, mbOK);
end;
function TPyInternalDebugger.Evaluate(const Expr: string): TBaseNamespaceItem;
Var
SuppressOutput : IInterface;
V : Variant;
begin
Result := nil;
if PyControl.DebuggerState in [dsPaused, dsPostMortem] then begin
SuppressOutput := PythonIIForm.OutputSuppressor; // Do not show errors
try
// evalcode knows we are in the debugger and uses current frame locals/globals
V := InternalInterpreter.PyInteractiveInterpreter.evalcode(Expr);
Result := TNameSpaceItem.Create(Expr, V);
except
// fail quitely
end;
end;
end;
procedure TPyInternalDebugger.Evaluate(const Expr : string; out ObjType, Value : string);
Var
SuppressOutput : IInterface;
V : Variant;
begin
ObjType := _(SNotAvailable);
Value := _(SNotAvailable);
if PyControl.DebuggerState in [dsPaused, dsPostMortem] then begin
SuppressOutput := PythonIIForm.OutputSuppressor; // Do not show errors
try
// evalcode knows we are in the debugger and uses current frame locals/globals
V := InternalInterpreter.PyInteractiveInterpreter.evalcode(Expr);
ObjType := InternalInterpreter.PyInteractiveInterpreter.objecttype(V);
Value := InternalInterpreter.PyInteractiveInterpreter.saferepr(V);
except
// fail quitely
end;
end;
end;
procedure TPyInternalDebugger.ExitPostMortem;
begin
with PythonIIForm do begin
PS1 := fOldPS1;
PS2 := fOldPS2;
AppendText(sLineBreak+PS1);
end;
VarClear(fCurrentFrame);
MakeFrameActive(nil);
PyControl.DoStateChange(dsInactive);
end;
procedure TPyInternalDebugger.GetCallStack(CallStackList: TObjectList);
Var
Frame : Variant;
begin
CallStackList.Clear;
if not (PyControl.DebuggerState in [dsPaused, dsPostMortem]) then
Exit;
Frame := CurrentFrame;
if VarIsPython(Frame) then
while not VarIsNone(Frame.f_back) and not VarIsNone(Frame.f_back.f_back) do begin
CallStackList.Add(TFrameInfo.Create(Frame));
Frame := Frame.f_back;
if VarIsSame(Frame, InternalInterpreter.Debugger.botframe) then
break;
end;
end;
function TPyInternalDebugger.GetFrameGlobals(Frame: TBaseFrameInfo): TBaseNameSpaceItem;
begin
Result := nil;
if not (PyControl.DebuggerState in [dsPaused, dsPostMortem]) then
Exit;
Result := TNameSpaceItem.Create('globals', (Frame as TFrameInfo).fPyFrame.f_globals);
end;
function TPyInternalDebugger.GetFrameLocals(Frame: TBaseFrameInfo): TBaseNameSpaceItem;
begin
Result := nil;
if not (PyControl.DebuggerState in [dsPaused, dsPostMortem]) then
Exit;
Result := TNameSpaceItem.Create('locals', (Frame as TFrameInfo).fPyFrame.f_locals);
end;
function TPyInternalDebugger.HaveTraceback: boolean;
begin
try
Result := VarModuleHasObject(SysModule, 'last_traceback');
except
Result := False;
end;
end;
procedure TPyInternalDebugger.Pause;
begin
fDebuggerCommand := dcPause;
end;
// Timer callback function
procedure TPyInternalDebugger.RestoreCommandLine;
begin
InternalInterpreter.RestoreCommandLine;
end;
procedure TPyInternalDebugger.Resume;
begin
fDebuggerCommand := dcRun;
end;
procedure TPyInternalDebugger.Run(ARunConfig: TRunConfiguration;
InitStepIn: Boolean = False; RunToCursorLine : integer = -1);
var
Code : Variant;
Path, OldPath : string;
PythonPathAdder : IInterface;
ReturnFocusToEditor: Boolean;
CanDoPostMortem : Boolean;
Editor : IEditor;
begin
CanDoPostMortem := False;
// Repeat here to make sure it is set right
MaskFPUExceptions(CommandsDataModule.PyIDEOptions.MaskFPUExceptions);
fDebuggerCommand := dcRun;
Assert(PyControl.DebuggerState = dsInactive);
//Compile
Code := InternalInterpreter.Compile(ARunConfig);
if VarIsPython(Code) then begin
Path := ExtractFileDir(ARunConfig.ScriptName);
SysPathRemove('');
if Length(Path) > 1 then
// Add the path of the executed file to the Python path - Will be automatically removed
PythonPathAdder := AddPathToPythonPath(Path);
if ARunConfig.WorkingDir <> '' then
Path := Parameters.ReplaceInText(ARunConfig.WorkingDir);
OldPath := GetCurrentDir;
// Change the current path
try
SetCurrentDir(Path)
except
Dialogs.MessageDlg(_(SCouldNotSetDirectory), mtWarning, [mbOK], 0);
end;
PyControl.DoStateChange(dsRunning);
MessagesWindow.ClearMessages;
Editor := GI_ActiveEditor;
ReturnFocusToEditor := Assigned(Editor);
// Set the layout to the Debug layout is it exists
if PyIDEMainForm.Layouts.IndexOf('Debug') >= 0 then begin
PyIDEMainForm.SaveLayout('Current');
PyIDEMainForm.LoadLayout('Debug');
Application.ProcessMessages;
end else
PyIDEMainForm.actNavInterpreterExecute(nil);
try
with PythonIIForm do begin
fOldPS1 := PS1;
PS1 := DebugPrefix + PS1;
fOldPS2 := PS2;
PS2 := DebugPrefix + PS2;
AppendPrompt;
end;
//attach debugger callback routines
with PythonIIForm.DebugIDE.Events do begin
Items[0].OnExecute := UserCall;
Items[1].OnExecute := UserLine;
Items[2].OnExecute := UserReturn;
Items[3].OnExecute := UserException;
Items[4].OnExecute := UserYield;
end;
//set breakpoints
SetDebuggerBreakPoints;
if RunToCursorLine >= 0 then // add temp breakpoint
InternalInterpreter.Debugger.set_break(Code.co_filename, RunToCursorLine, 1);
// New Line for output
PythonIIForm.AppendText(sLineBreak);
// Set the command line parameters
SetCommandLine(ARunConfig);
InternalInterpreter.Debugger.InitStepIn := InitStepIn;
try
InternalInterpreter.Debugger.run(Code);
except
// CheckError already called by VarPyth
on E: EPythonError do begin
InternalInterpreter.HandlePyException(E, 2);
ReturnFocusToEditor := False;
Dialogs.MessageDlg(E.Message, mtError, [mbOK], 0);
CanDoPostMortem := True;
SysUtils.Abort;
end;
end;
finally
VarClear(fCurrentFrame);
MakeFrameActive(nil);
with PythonIIForm do begin
PS1 := fOldPS1;
PS2 := fOldPS2;
AppendText(sLineBreak+PS1);
end;
// Restore the command line parameters
RestoreCommandLine;
// Add again the empty path
SysPathAdd('');
// Change the back current path
SetCurrentDir(OldPath);
if PyIDEMainForm.Layouts.IndexOf('Debug') >= 0 then
PyIDEMainForm.LoadLayout('Current');
PyControl.DoStateChange(dsInactive);
if ReturnFocusToEditor then
Editor.Activate;
if CanDoPostMortem and CommandsDataModule.PyIDEOptions.PostMortemOnException then
EnterPostMortem;
end;
end;
end;
function TPyInternalDebugger.RunSource(Const Source, FileName : Variant; symbol : string = 'single') : boolean;
// The internal interpreter RunSource calls II.runsource which differs
// according to whether we debugging or not
Var
OldCurrentPos : TEditorPos;
begin
OldCurrentPos := TEditorPos.Create;
OldCurrentPos.Assign(PyControl.CurrentPos);
try
Result := InternalInterpreter.RunSource(Source, FileName, symbol);
PyControl.CurrentPos.Assign(OldCurrentPos);
PyControl.DoCurrentPosChanged;
finally
OldCurrentPos.Free;
end;
end;
procedure TPyInternalDebugger.RunToCursor(Editor : IEditor; ALine: integer);
Var
FName : string;
begin
Assert(PyControl.DebuggerState = dsPaused);
// Set Temporary breakpoint
SetDebuggerBreakPoints; // So that this one is not cleared
FName := Editor.FileName;
if FName = '' then
FName := '<'+Editor.FileTitle+'>';
InternalInterpreter.Debugger.set_break(VarPythonCreate(FName), ALine, 1);
fDebuggerCommand := dcRunToCursor;
end;
procedure TPyInternalDebugger.StepInto;
begin
fDebuggerCommand := dcStepInto;
end;
procedure TPyInternalDebugger.StepOver;
begin
fDebuggerCommand := dcStepOver;
end;
function TPyInternalDebugger.SysPathAdd(const Path: string): boolean;
begin
Result := InternalInterpreter.SysPathAdd(Path);
end;
function TPyInternalDebugger.SysPathRemove(const Path: string): boolean;
begin
Result := InternalInterpreter.SysPathRemove(Path);
end;
procedure TPyInternalDebugger.StepOut;
begin
fDebuggerCommand := dcStepOut;
end;
procedure TPyInternalDebugger.Abort;
begin
if PyControl.DebuggerState = dsPostMortem then
ExitPostMortem
else
fDebuggerCommand := dcAbort;
end;
procedure TPyInternalDebugger.UserCall(Sender: TObject; PSelf, Args: PPyObject;
var Result: PPyObject);
begin
// PythonIIForm.AppendText('UserCall'+sLineBreak);
Result := GetPythonEngine.ReturnNone;
end;
procedure TPyInternalDebugger.UserException(Sender: TObject; PSelf,
Args: PPyObject; var Result: PPyObject);
begin
// PythonIIForm.AppendText('UserException'+sLineBreak);
Result := GetPythonEngine.ReturnNone;
end;
procedure TPyInternalDebugger.UserLine(Sender: TObject; PSelf, Args: PPyObject;
var Result: PPyObject);
Var
Frame : Variant;
FName : string;
begin
Result := GetPythonEngine.ReturnNone;
Frame := VarPythonCreate(Args).__getitem__(0);
FName := Frame.f_code.co_filename;
if (FName[1] ='<') and (FName[Length(FName)] = '>') then
FName := Copy(FName, 2, Length(FName)-2);
// PythonIIForm.AppendText('UserLine '+ FName + ' ' + IntToStr(Frame.f_lineno) +sLineBreak);
if PyIDEMainForm.ShowFilePosition(FName, Frame.f_lineno, 1, 0, True, False) and
(Frame.f_lineno > 0) then
begin
PyControl.CurrentPos.Editor := GI_EditorFactory.GetEditorByNameOrTitle(FName);
PyControl.CurrentPos.Line := Frame.f_lineno;
FCurrentFrame := Frame;
if PyControl.DebuggerState = dsRunning then
PyControl.DoStateChange(dsPaused);
FDebuggerCommand := dcNone;
While FDebuggerCommand = dcNone do
PyControl.DoYield(True);
if PyControl.BreakPointsChanged then SetDebuggerBreakpoints;
PyControl.DoStateChange(dsRunning);
end;
case fDebuggerCommand of
dcRun : InternalInterpreter.Debugger.set_continue();
dcStepInto : InternalInterpreter.Debugger.set_step();
dcStepOver : InternalInterpreter.Debugger.set_next(Frame);
dcStepOut : InternalInterpreter.Debugger.set_return(Frame);
dcRunToCursor : InternalInterpreter.Debugger.set_continue;
dcPause : InternalInterpreter.Debugger.set_step();
dcAbort : begin
InternalInterpreter.Debugger.set_quit();
MessagesWindow.AddMessage(_(SDebuggingAborted));
MessagesWindow.ShowWindow;
end;
end;
VarClear(fCurrentFrame);
end;
procedure TPyInternalDebugger.UserReturn(Sender: TObject; PSelf, Args: PPyObject;
var Result: PPyObject);
begin
// PythonIIForm.AppendText('UserReturn'+sLineBreak);
Result := GetPythonEngine.ReturnNone;
end;
procedure TPyInternalDebugger.UserYield(Sender: TObject; PSelf, Args: PPyObject;
var Result: PPyObject);
begin
PyControl.DoYield(False);
if fDebuggerCommand = dcAbort then begin
InternalInterpreter.Debugger.set_quit();
MessagesWindow.AddMessage(_(SDebuggingAborted));
MessagesWindow.ShowWindow;
end else if fDebuggerCommand = dcPause then
InternalInterpreter.Debugger.set_step();
Result := GetPythonEngine.ReturnNone;
end;
procedure TPyInternalDebugger.SetCommandLine(ARunConfig : TRunConfiguration);
begin
InternalInterpreter.SetCommandLine(ARunConfig);
end;
procedure TPyInternalDebugger.SetDebuggerBreakpoints;
var
i, j : integer;
FName : string;
begin
if not PyControl.BreakPointsChanged then Exit;
LoadLineCache;
InternalInterpreter.Debugger.clear_all_breaks();
for i := 0 to GI_EditorFactory.Count - 1 do
with GI_EditorFactory.Editor[i] do begin
FName := FileName;
if FName = '' then
FName := '<'+FileTitle+'>';
for j := 0 to BreakPoints.Count - 1 do begin
if not TBreakPoint(BreakPoints[j]).Disabled then begin
if TBreakPoint(BreakPoints[j]).Condition <> '' then begin
InternalInterpreter.Debugger.set_break(VarPythonCreate(FName),
TBreakPoint(BreakPoints[j]).LineNo,
0, VarPythonCreate(TBreakPoint(BreakPoints[j]).Condition));
end else begin
InternalInterpreter.Debugger.set_break(VarPythonCreate(FName),
TBreakPoint(BreakPoints[j]).LineNo);
end;
end;
end;
end;
PyControl.BreakPointsChanged := False;
end;
procedure TPyInternalDebugger.LoadLineCache;
Var
i : integer;
FName, Source, LineList : Variant;
begin
// inject unsaved code into LineCache
fLineCache.cache.clear();
for i := 0 to GI_EditorFactory.Count - 1 do
with GI_EditorFactory.Editor[i] do
if HasPythonfile and (FileName = '') then
begin
if GetPythonEngine.IsPython3000 then
Source := CleanEOLs(SynEdit.Text)+WideLF
else
Source := CleanEOLs(EncodedText)+#10;
LineList := VarPythonCreate(Source);
LineList := LineList.splitlines(True);
FName := '<'+FileTitle+'>';
fLineCache.cache.SetItem(VarPythonCreate(FName),
VarPythonCreate([Length(Source), None, LineList, FName], stTuple));
end;
end;
procedure TPyInternalDebugger.MakeFrameActive(Frame: TBaseFrameInfo);
begin
if Assigned(Frame) then
InternalInterpreter.Debugger.currentframe := (Frame as TFrameInfo).fPyFrame
else
InternalInterpreter.Debugger.currentframe := None;
end;
function TPyInternalDebugger.NameSpaceFromExpression(
const Expr: string): TBaseNameSpaceItem;
// The internal interpreter knows whether we are debugging and
// adjusts accordingly (in II.debugger.evalcode)
begin
Result := InternalInterpreter.NameSpaceFromExpression(Expr);
end;
{ TPyInternalInterpreter }
constructor TPyInternalInterpreter.Create(II: Variant);
begin
fEngineType := peInternal;
fII := II;
fDebugger := II.debugger;
// sys.displayhook
fII.setupdisplayhook()
end;
procedure TPyInternalInterpreter.CreateMainModule;
begin
fMainModule := TModuleProxy.CreateFromModule(VarPyth.MainModule, self);
end;
function TPyInternalInterpreter.EvalCode(const Expr: string): Variant;
begin
// may raise exceptions
Result := fII.evalcode(Expr);
end;
function TPyInternalInterpreter.CallTipFromExpression(const Expr: string;
var DisplayString, DocString: string) : Boolean;
var
LookupObj, ArgText, PyDocString: Variant;
SuppressOutput : IInterface;
begin
Result := False;
DisplayString := '';
DocString := '';
if Expr = '' then Exit;
SuppressOutput := PythonIIForm.OutputSuppressor; // Do not show errors
try
//Evaluate the lookup expression and get the hint text
LookupObj := fII.evalcode(Expr);
ArgText := fII.get_arg_text(LookupObj);
DisplayString := ArgText.__getitem__(0);
PyDocString := ArgText.__getitem__(1);
Result := True;
if not VarIsNone(PyDocString) then begin
//DocString := GetNthLine(PyDocString, 1)
DocString := PyDocString;
DocString := GetLineRange(DocString, 1, 20); // first 20 lines
end else
DocString := '';
except
end;
end;
function TPyInternalInterpreter.Compile(ARunConfig: TRunConfiguration): Variant;
Var
co : PPyObject;
FName, Source : AnsiString;
Editor : IEditor;