-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.hs
792 lines (710 loc) · 31 KB
/
Main.hs
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
import System.Console.Haskeline
import System.Console.Haskeline.History (historyLines)
import System.IO (readFile)
import System.Exit (exitSuccess)
import System.Console.Haskeline.Completion(CompletionFunc)
import System.Console.GetOpt (getOpt, ArgOrder(..), OptDescr(..), ArgDescr(..))
import System.Environment (getArgs)
import Network
import GHC.IO.Handle
import Data.List (intercalate, find, isPrefixOf,
isSuffixOf, dropWhileEnd, dropWhile)
import Data.Maybe (fromMaybe, fromJust)
import GHC.Word (Word16, Word32, Word8)
import Network.Socket.Internal (PortNumber(..))
import Control.Monad.Trans (liftIO, lift)
import Control.Applicative ((<$>), Applicative)
import Control.Monad.Error (runErrorT, ErrorT, MonadError(..), Error(..))
import Control.Monad.State (StateT(..), MonadState(..), evalStateT)
import Control.Monad.IO.Class (MonadIO)
import Control.Applicative ((<$>), (<*>))
import Control.Monad (liftM, forM, forM_, filterM, void, when)
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as B8
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Char
import Data.Char (isSpace)
import qualified JarFind as JF
import qualified Language.Java.Parser as JP
import qualified Language.Java.Syntax as JS
import Language.Java.Pretty (prettyPrint)
import qualified Language.Java.Jdi as J
import qualified Language.Java.Jdi.VirtualMachine as Vm
import qualified Language.Java.Jdi.Event as E
import qualified Language.Java.Jdi.EventSet as ES
import qualified Language.Java.Jdi.EventRequest as ER
import qualified Language.Java.Jdi.Field as F
import qualified Language.Java.Jdi.ReferenceType as RT
import qualified Language.Java.Jdi.ArrayReference as AR
import qualified Language.Java.Jdi.StringReference as SR
import qualified Language.Java.Jdi.Value as V
import qualified Language.Java.Jdi.StackFrame as SF
import qualified Language.Java.Jdi.ThreadReference as TR
import qualified Language.Java.Jdi.ObjectReference as OR
import qualified Language.Java.Jdi.ThreadGroupReference as TG
import qualified Language.Java.Jdi.Method as M
import qualified Language.Java.Jdi.Location as L
import qualified Language.Java.Jdi.LocalVariable as LV
import qualified Vim.Netbeans as N
data Flag = Version
| Port { port :: String }
| Host { host :: String }
| VimPort { vimPort :: String }
| VimHost { vimHost :: String }
| ClassPath { path :: String }
| SourcePath { path :: String }
deriving (Show, Eq)
options :: [OptDescr Flag]
options =
[ Option ['v'] ["version"] (NoArg Version) "show version number"
, Option ['p'] ["port"] (ReqArg Port "PORT") "port number"
, Option ['h'] ["host"] (ReqArg Host "HOST") "host number"
, Option [] ["vim-port"] (ReqArg VimPort "VIM-PORT") "port number"
, Option [] ["vim-host"] (ReqArg VimHost "VIM-HOST") "host number"
, Option ['c'] ["class-path"] (ReqArg ClassPath "CLASS-PATH")
"class-path path"
, Option ['s'] ["source-path"] (ReqArg SourcePath "SOURCE-PATH")
"source-path path"
]
isPort :: Flag -> Bool
isPort (Port _) = True
isPort _ = False
isHost :: Flag -> Bool
isHost (Host _) = True
isHost _ = False
isVimPort :: Flag -> Bool
isVimPort (VimPort _) = True
isVimPort _ = False
isVimHost :: Flag -> Bool
isVimHost (VimHost _) = True
isVimHost _ = False
isClassPath :: Flag -> Bool
isClassPath (ClassPath _) = True
isClassPath _ = False
isSourcePath :: Flag -> Bool
isSourcePath (SourcePath _) = True
isSourcePath _ = False
getPort :: [Flag] -> PortID
getPort opts = PortNumber $ fromIntegral $ fromMaybe 2044 portValue
where
portValue :: Maybe Int
portValue = do
v <- find isPort opts
return $ read $ port v
getHost :: [Flag] -> String
getHost opts = fromMaybe "localhost" $ find isHost opts >>= return . host
getVimPort :: [Flag] -> PortID
getVimPort opts = PortNumber $ fromIntegral $ fromMaybe 4444 portValue
where
portValue :: Maybe Int
portValue = do
v <- find isVimPort opts
return $ read $ vimPort v
getVimHost :: [Flag] -> String
getVimHost opts = fromMaybe "localhost" $ find isVimHost opts >>= return . vimHost
extractClassFileSource :: [Flag] -> JF.ClassFileSource
extractClassFileSource fs = JF.ClassPath $ map spToCfp $ filter isClassPath fs
where spToCfp (ClassPath path) =
if ".jar" `isSuffixOf` path
then JF.JarFile path
else if ".class" `isSuffixOf` path
then JF.ClassFile path
else error $ "unknown extension of the file: " ++ path
data CommandElement m st = CommandName String
(CharParser st String)
(CompletionFunc m)
| ClassName String
(CharParser st String)
(CompletionFunc m)
| MethodName String
| LineNum Int
cmdList = [ "backtrace"
, "breakpoint"
, "continue"
, "down"
, "frame"
, "list"
, "next"
, "print"
, "quit"
, "step"
, "threads"
, "up"
, "version"
]
trim = dropWhileEnd isSpace . (dropWhile isSpace)
buildCompletions = map (\name -> Completion name name True)
isMethod :: JF.Member -> Bool
isMethod (JF.Method {}) = True
isMethod _ = False
commandLineComplete :: Monad m => [JF.Class] -> CompletionFunc m
commandLineComplete classes (leftLine, _) = do
if ("breakpoint " `isPrefixOf` line) || ("b " `isPrefixOf` line)
then do
case (length w, whiteSpaceTerminated) of
(1, True) -> return (leftLine,
buildCompletions $ allClassesNames)
(2, False) -> return (drop (length $ w !! 1) leftLine,
buildCompletions
$ filter ((w !! 1) `isPrefixOf`)
allClassesNames)
(2, True) -> return (leftLine,
buildCompletions $ listMethodsNames (w !! 1))
(3, False) -> return (drop (length $ w !! 2) leftLine,
buildCompletions
$ filter ((w !! 2) `isPrefixOf`)
$ listMethodsNames (w !! 1))
(3, True) -> return (leftLine, [])
else return ("", ncl)
where
w = words line
whiteSpaceTerminated = " " `isSuffixOf` line
ncl = buildCompletions $ filter (line `isPrefixOf`) cmdList
line = reverse leftLine
listMethodsNames = map JF.mName . methodsOfClass
myClasses className = filter ((className ==) . JF.clsName) classes
allMembersOfClass = concat . map JF.clsMembers . myClasses
allClassesNames = map JF.clsName classes
methodsOfClass = filter isMethod . allMembersOfClass
allAvailablePrintables = []
cmdArgsErrMsg :: [String] -> String
cmdArgsErrMsg errors =
"There are errors in command args parsing:\n\n"
++ concat errors
main :: IO ()
main = do
args <- getArgs
let (opts, unparsed, errors) = getOpt Permute options args
when (not $ null errors) $ fail $ cmdArgsErrMsg errors
when (Version `elem` opts) $ putStrLn "0.0.1" >> exitSuccess
when (((not . isPort) `all` opts) && ((not . isHost) `all` opts))
$ fail "Host and port arguments are required"
cpClasses <- map snd <$> (JF.parseFileSource $ extractClassFileSource opts)
let sourceFiles = map path $ filter isSourcePath opts
res <- runInputT (Settings (commandLineComplete cpClasses) Nothing True)
$ runErrorT $ evalStateT (N.runNetbeans
(getVimPort opts)
"password"
(N.NetbeansCallbacks
(liftIO $ putStrLn "Waiting for netbeans connection")
(\e -> case e of
N.StartupDone -> liftIO $ putStrLn "Successful handshake over netbeans protocol"
_ -> return ()
)
)
(Vm.runVirtualMachine
(getHost opts)
(getPort opts)
(initialSetup >> eventLoop)))
(DebugConfig [] Nothing sourceFiles [] 0)
case res of
Left e -> putStrLn $ "Error during execution: " ++ e
Right v -> putStrLn $ "Success"
data DebugConfig = DebugConfig
{ breakpoints :: [Command] -- breakpoints whose classes are not loaded yet.
, currentThread :: Maybe TR.ThreadReference
, sourceFiles :: [String]
, bufferIdMap :: [(String, (N.BufId, N.AnnoTypeNum, N.AnnoNum))] -- TODO replace with actual map
, currentFrameNumber :: Int
}
getBufIdByPath :: (MonadIO m, Applicative m) => String -> Debugger m (Maybe (N.BufId, N.AnnoTypeNum, N.AnnoNum))
getBufIdByPath path = do
mp <- bufferIdMap <$> get
return $ lookup path mp
updateAnnoNum :: (MonadIO m, Applicative m) => String -> N.AnnoNum -> Debugger m ()
updateAnnoNum path annoNum = do
dc <- get
let mp = bufferIdMap dc
let newMp = flip map mp $ \(s, (bufid, atn, at)) ->
if s == path
then (s, (bufid, atn, annoNum))
else (s, (bufid, atn, at))
put $ dc { bufferIdMap = newMp }
addBufIdByPath :: (MonadIO m, Applicative m) => String -> N.BufId -> N.AnnoTypeNum -> N.AnnoNum -> Debugger m ()
addBufIdByPath path bid annoTypeNum annoNum = do
dc <- get
let mp = bufferIdMap dc
put $ dc { bufferIdMap = (path, (bid, annoTypeNum, annoNum)) : mp }
getCurrentLocation :: (MonadIO m, Error e, MonadError e m)
=> Vm.VirtualMachine (N.Netbeans (Debugger m)) L.Location
getCurrentLocation = do
fr <- getCurrentFrame
SF.location fr
getCurrentFrame :: (MonadIO m, Error e, MonadError e m)
=> Vm.VirtualMachine (N.Netbeans (Debugger m)) SF.StackFrame
getCurrentFrame = do
tr <- lift $ lift getCurrentThread
cf <- lift $ lift $ currentFrameNumber `liftM` get
TR.frame tr cf
getCurrentFrameNumber :: Monad m => Debugger m Int
getCurrentFrameNumber = currentFrameNumber `liftM` get
setCurrentFrameNumber :: Monad m => Int -> Debugger m ()
setCurrentFrameNumber f = do
dc <- get
put $ dc {currentFrameNumber = f}
type Debugger = StateT DebugConfig
alignNum :: Int -> Int -> String
alignNum width number = replicate (width - length s) ' ' ++ s ++ " "
where s = show number
fullPathFromSourceName :: (MonadIO m, Error e, MonadError e m)
=> String -> Debugger m String
fullPathFromSourceName sourceName = do
sourceList <- filter (sourceName `isSuffixOf`) `liftM` getSourceFiles
if length sourceList > 1
then throwError $ strMsg "there are more than one source file"
else if null sourceList
then throwError $ strMsg "no source name"
else return $ head sourceList
linesFromSourceName :: (MonadIO m, Error e, MonadError e m)
=> String -> Debugger m [String]
linesFromSourceName sourceName = do
sourceList <- filter (sourceName `isSuffixOf`) `liftM` getSourceFiles
when (length sourceList > 1) $
throwError $ strMsg "there are more than one source file"
if null sourceList
then return []
else do
rawLines <- lines `liftM` (liftIO . readFile) (head sourceList)
let l = (length rawLines)
let width = length $ show l
return $ zipWith (++) (map (alignNum width) [1..l]) rawLines
printSourceLines :: Vm.VirtualMachine (N.Netbeans (Debugger (ErrorT String (InputT IO)))) ()
printSourceLines = do
l <- getCurrentLocation
sn <- L.sourceName l
let ln = L.lineNumber l
dat <- lift $ lift $ linesFromSourceName sn
when (null dat) $
throwError $ sn ++ ":" ++ show ln ++ " - source unavailable"
let blockStart = max 0 (ln - 5)
liftIO $ putStrLn $ intercalate "\n" $ take 10 $ drop blockStart $ dat
`catchError` (\e -> liftIO $ putStrLn e)
addBreakpoint :: Monad m => Command -> Debugger m ()
addBreakpoint c = do
dc <- get
put $ dc {breakpoints = c : breakpoints dc}
setPendingBreakpoints :: Monad m => [Command] -> Debugger m ()
setPendingBreakpoints bs = do
dc <- get
put $ dc {breakpoints = bs}
listPendingBreakpoints :: Monad m => Debugger m [Command]
listPendingBreakpoints = breakpoints `liftM` get
setCurrentThread :: Monad m => TR.ThreadReference -> Debugger m ()
setCurrentThread tr = do
dc <- get
put $ dc {currentThread = Just tr}
initialSetup :: Vm.VirtualMachine (N.Netbeans (Debugger (ErrorT String (InputT IO)))) ()
initialSetup = do
ER.enable ER.createClassPrepareRequest
return ()
getSourceFiles :: (Error e, MonadError e m) => Debugger m [String]
getSourceFiles = sourceFiles `liftM` get
printSourceLine :: Vm.VirtualMachine (N.Netbeans (Debugger (ErrorT String (InputT IO)))) ()
printSourceLine = do
l <- getCurrentLocation
let ln = L.lineNumber l
sn <- L.sourceName l
dat <- lift $ lift $ linesFromSourceName sn
when (null dat) $
throwError $ sn ++ ":" ++ show ln ++ " - source unavailable"
liftIO $ putStrLn $ dat !! (ln - 1)
`catchError` (\e -> liftIO $ putStrLn e)
calcOffset :: N.BufId -> Int -> N.Netbeans (Debugger (ErrorT String (InputT IO))) Int
calcOffset bufId ln = do
txt <- N.getText bufId
let ls = lines txt
let contents = concat $ take (ln - 1) ls -- ln - 1 because we count lines from 1
return $ length contents + ln -- ln - number of newline symbols. haskell has '\n' symbol always.
notifyVimAboutSoureLine :: Vm.VirtualMachine (N.Netbeans (Debugger (ErrorT String (InputT IO)))) ()
notifyVimAboutSoureLine = do
l <- getCurrentLocation
let ln = L.lineNumber l
sn <- L.sourceName l
fullPath <- lift $ lift $ fullPathFromSourceName sn
mbi <- lift $ lift $ getBufIdByPath fullPath
case mbi of
Just (bufId, annoTypeNum, annoNum) -> do
lift $ N.setVisible bufId
offset <- lift $ calcOffset bufId ln
lift $ N.removeAnno bufId annoNum
newAnnoNum <- lift $ N.addAnno bufId annoTypeNum offset
lift $ lift $ updateAnnoNum fullPath newAnnoNum
Nothing -> do
newBufId <- lift $ N.editFile fullPath
annoTypeNum <- lift $ N.defineAnnoType newBufId "IP" "IP" "=>" N.Black N.LightRed
offset <- lift $ calcOffset newBufId ln
annoNum <- lift $ N.addAnno newBufId annoTypeNum offset
lift $ lift $ addBufIdByPath fullPath newBufId annoTypeNum annoNum
eventLoop :: Vm.VirtualMachine (N.Netbeans (Debugger (ErrorT String (InputT IO)))) ()
eventLoop = do
es <- ES.removeEvent
let event = head $ ES.events es
continue <- case E.eventKind event of
E.ClassPrepare -> do
setupBreakpoints $ E.referenceType event
ES.resume es
return True
E.Breakpoint -> do
lift . lift . setCurrentThread =<< E.thread event
lift $ lift $ setCurrentFrameNumber 0
printSourceLine
notifyVimAboutSoureLine `catchError` (\e -> return ())
commandLoop
E.SingleStep -> do
lift . lift . setCurrentThread =<< E.thread event
lift $ lift $ setCurrentFrameNumber 0
printSourceLine
notifyVimAboutSoureLine `catchError` (\e -> return ())
commandLoop
E.VmDeath -> do
return False
otherwise -> do
commandLoop
if continue
then eventLoop
else return ()
className :: Command -> String
className (BreakpointLineCommand cn _) = cn
className (BreakpointMethodCommand cn _) = cn
setupBreakpoints :: RT.ReferenceType
-> Vm.VirtualMachine (N.Netbeans (Debugger (ErrorT String (InputT IO)))) ()
setupBreakpoints refType = do
let refName = RT.name refType
allBreakpoints <- lift $ lift listPendingBreakpoints
let bpList = filter ((refName ==) . className) allBreakpoints
let reminder = filter ((refName /=) . className) allBreakpoints
when (not $ null bpList) $ liftIO $ putStrLn
$ "Setting up breakpoints for class " ++ refName
forM_ bpList (setupBreakpoint refType)
lift $ lift $ setPendingBreakpoints reminder
setupBreakpoint :: RT.ReferenceType
-> Command
-> Vm.VirtualMachine (N.Netbeans (Debugger (ErrorT String (InputT IO)))) ()
setupBreakpoint refType (BreakpointLineCommand nm line) = do
lineLocations <- RT.allLineLocations refType
let matchingLines = filter ((line ==) . L.lineNumber) lineLocations
if null matchingLines
then liftIO . putStrLn
$ "there is no executable source code for line: " ++ show line
else void $ ER.enable $ ER.createBreakpointRequest (head matchingLines)
setupBreakpoint refType (BreakpointMethodCommand nm method) = do
methods <- RT.methods refType
let matchingMethods = filter ((method ==) . M.name) methods
if null matchingMethods
then liftIO . putStrLn $ "there is no method with name: " ++ method
else do
l <- M.location $ head matchingMethods
let br = ER.createBreakpointRequest l
void $ ER.enable br
getCurrentThread :: (Error e, MonadError e m) => Debugger m TR.ThreadReference
getCurrentThread = do
value <- currentThread `liftM` get
case value of
Just v -> return v
Nothing -> throwError (strMsg "No current thread is available")
calcSyntaxTree :: MonadException m
=> JS.Exp
-> Vm.VirtualMachine (N.Netbeans (Debugger (ErrorT String (InputT m)))) V.Value
calcSyntaxTree (JS.ExpName (JS.Name ((JS.Ident name):[]))) = do
ct <- lift $ lift getCurrentThread
allFrames <- TR.allFrames ct
let fr = head allFrames
loc <- SF.location fr
let curMethod = L.method loc
vars <- M.variables curMethod
args <- M.arguments curMethod
let ref = L.declaringType loc
fields <- RT.fields ref
let allVars = filter ((name ==) . LV.name) (vars ++ args)
let allFields = filter ((name ==) . F.name) fields
let staticFields = filter F.isStatic allFields
let instanceFields =
if not $ M.isStatic curMethod
then filter (not . F.isStatic) allFields
else []
when (null allVars && null allFields)
$ throwError $ "Scope doesn't have variable: " ++ name
if not $ null allVars
then case allVars of
[] -> throwError $ "Scope doesn't have variable: " ++ name
(f:_) -> SF.getValue fr f
else if null instanceFields
then case staticFields of
[] -> throwError $ "Scope doesn't have variable: " ++ name
(f:_) -> RT.getValue ref f
else do
thisObject <- SF.thisObject fr
case instanceFields of
[] -> throwError $ "Scope doesn't have variable: " ++ name
(f:_) -> OR.getValue thisObject f
calcSyntaxTree (JS.ArrayAccess (JS.ArrayIndex arrExp indExp)) = do
arr <- calcSyntaxTree arrExp
ind <- calcSyntaxTree indExp
case (arr, ind) of
((V.ArrayValue ref), (V.IntValue i)) -> AR.getValue ref i
otherwise -> throwError $ "Type error"
calcSyntaxTree (JS.Lit (JS.Int v)) = return (V.IntValue $ fromIntegral v)
calcSyntaxTree e = throwError
$ "Processing of this expression is not implemented yet: " ++ (show e)
showValue :: MonadException m =>
V.Value
-> Vm.VirtualMachine (N.Netbeans (Debugger (ErrorT String (InputT m)))) String
showValue (V.CharValue c) = return [c]
showValue (V.LongValue c) = return $ show c
showValue (V.IntValue c) = return $ show c
showValue (V.StringValue s) = show <$> SR.value s
showValue (V.ArrayValue a) = do
av <- AR.getValues a
vs <- mapM showValue av
return $ "[" ++ intercalate ", " vs ++ "]"
showValue v = return $ show v
showStackFrame :: (Error e, MonadIO m, MonadError e m)
=> SF.StackFrame -> Vm.VirtualMachine m String
showStackFrame sf = do
loc <- SF.location sf
let method = L.method loc
srcName <- L.sourceName loc
let lineNum = L.lineNumber loc
return $ (M.name method) ++ " at " ++ srcName ++ ": " ++ show lineNum
printThreadTree :: (Error e, MonadIO m, MonadError e m)
=> Vm.VirtualMachine m ()
printThreadTree = do
tgs <- Vm.topLevelThreadGroups
mapM_ (printThreadGroup 0) tgs
formatThread :: (Error e, MonadIO m, MonadError e m)
=> TR.ThreadReference -> Vm.VirtualMachine m String
formatThread tr = do
threadStatus <- TR.status tr
suspended <- TR.isSuspended tr
return $ TR.name tr
++ " " ++
show threadStatus
++ " " ++
if suspended
then "suspended"
else "resumed"
printThreadGroup depth tg = do
let is = " "
let indent = concat $ replicate depth is
liftIO $ putStrLn ""
liftIO $ putStrLn $ indent ++ "Group: " ++ (TG.name tg)
ts <- mapM formatThread =<< (TG.threads tg)
liftIO $ putStrLn $ intercalate "\n" $ map ((indent ++ is) ++) ts
mapM_ (printThreadGroup $ depth + 1) =<< TG.threadGroups tg
printCurrentFrame :: Vm.VirtualMachine (N.Netbeans (Debugger (ErrorT String (InputT IO)))) ()
printCurrentFrame = do
cf <- lift $ lift getCurrentFrameNumber
fr <- getCurrentFrame
frameString <- (showStackFrame fr)
liftIO $ putStrLn $ "#" ++ (show cf) ++ " " ++ frameString
liftInpTtoVM = lift . lift . lift . lift
commandLoop :: Vm.VirtualMachine (N.Netbeans (Debugger (ErrorT String (InputT IO)))) Bool
commandLoop = do
minput <- liftInpTtoVM $ getInputLine "(jdb) "
case minput of
Nothing -> do -- Ctrl-D was pressed.
return False
Just input -> do -- Something was entered. Empty line as an option.
line <- if input == ""
then do
hlines <- historyLines <$> liftInpTtoVM getHistory
if null hlines
then return ""
else return $ head hlines
else return input
case parseCommand line of
QuitCommand -> return False
VersionCommand -> do
p <- Vm.version
liftIO $ putStrLn $ show p
commandLoop
ContinueCommand ->
Vm.resume >> return True
BacktraceCommand -> do
ct <- lift $ lift getCurrentThread
frames <- TR.allFrames ct
res <- mapM showStackFrame frames
let l = (length res)
let width = length $ show l
let lineNumbers = (map (("#" ++) . alignNum width)
[0..l - 1])
let numberedLines = zipWith
(++)
lineNumbers
res
liftIO $ putStrLn $ intercalate "\n" numberedLines
commandLoop
cmd@(BreakpointLineCommand name line) -> do
lift . lift . addBreakpoint $ BreakpointLineCommand name line
ac <- filter ((name ==) . RT.name) <$> Vm.allClasses
when (null ac) $ liftIO $ putStrLn
$ "No classes with name "
++ name
++ " are loaded. Breakpoint setup is postponed."
mapM setupBreakpoints ac
commandLoop
cmd@(BreakpointMethodCommand name method) -> do
lift . lift . addBreakpoint $ BreakpointMethodCommand name method
ac <- filter ((name ==) . RT.name) <$> Vm.allClasses
when (null ac) $ liftIO $ putStrLn
$ "No classes with name "
++ name
++ " are loaded. Breakpoint setup is postponed."
mapM setupBreakpoints ac
commandLoop
ListCommand -> do
printSourceLines
commandLoop
UpCommand -> do
(do
tr <- lift $ lift getCurrentThread
frCnt <- TR.frameCount tr
cf <- lift $ lift getCurrentFrameNumber
if cf >= (frCnt - 1)
then liftIO $ putStrLn "Initial frame selected; you cannot go up."
else do
lift $ lift $ setCurrentFrameNumber (cf + 1)
printCurrentFrame
) `catchError` (\e -> liftIO $ putStrLn e)
commandLoop
DownCommand -> do
(do
cf <- lift $ lift getCurrentFrameNumber
if cf == 0
then liftIO $ putStrLn "Bottom frame selected; you cannot go down."
else do
lift $ lift $ setCurrentFrameNumber (cf - 1)
printCurrentFrame
) `catchError` (\e -> liftIO $ putStrLn e)
commandLoop
FrameCommand -> do
printCurrentFrame `catchError` (\e -> liftIO . putStrLn $ show e)
commandLoop
ThreadsCommand -> do
printThreadTree
commandLoop
PrintCommand arg -> do
case JP.parser JP.exp arg of
Right st -> do
v <- calcSyntaxTree st
sv <- showValue v
liftIO $ putStrLn sv
`catchError` (\e -> liftIO $ putStrLn e)
Left e ->
liftIO . putStrLn $ "SyntaxError " ++ (show e)
commandLoop
NextCommand -> do
ct <- lift $ lift getCurrentThread
ER.enable $ ER.addCountFilter
1
(ER.createStepRequest
ct
J.StepLine
J.StepOver)
Vm.resume
return True
`catchError` (\e -> do
liftIO $ putStrLn e
commandLoop)
StepCommand -> do
ct <- lift $ lift getCurrentThread
ER.enable $ ER.addCountFilter
1
(ER.createStepRequest
ct
J.StepLine
J.StepInto)
Vm.resume
return True
`catchError` (\e -> do
liftIO $ putStrLn e
commandLoop)
ErroneousCommand error -> do
liftIO $ putStrLn
$ "Error during parsing the command: " ++ error
commandLoop
data Command = BacktraceCommand
| BreakpointLineCommand String Int -- class line
| BreakpointMethodCommand String String -- class method
| ContinueCommand
| DownCommand
| ErroneousCommand String
| FrameCommand
| ListCommand
| NextCommand
| PrintCommand String
| QuitCommand
| StepCommand
| ThreadsCommand
| UpCommand
| VersionCommand
deriving Show
parseCommand :: String -> Command
parseCommand "" = ErroneousCommand "Empty line. No previous history."
parseCommand input = case parse commandParser "(unknown)" input of
Left parseError -> ErroneousCommand $ show parseError
Right command -> command
commandParser :: CharParser st Command
commandParser = parseVersion
<|> parseContinue
<|> parseQuit
<|> try parseBreakpointCommand
<|> try parseBacktrace
<|> parseList
<|> parseNext
<|> parseStep
<|> parseThreads
<|> parseUp
<|> parseDown
<|> parseFrame
<|> parsePrint
parseUp :: CharParser st Command
parseUp = string "up" >> return UpCommand
parseDown :: CharParser st Command
parseDown = string "down" >> return DownCommand
parseFrame :: CharParser st Command
parseFrame = string "frame" >> return FrameCommand
parseThreads :: CharParser st Command
parseThreads = string "threads" >> return ThreadsCommand
parseNext :: CharParser st Command
parseNext = do
(try $ string "next") <|> string "n"
return NextCommand
parseStep :: CharParser st Command
parseStep = do
(try $ string "step") <|> string "s"
return StepCommand
parseList :: CharParser st Command
parseList = string "list" >> return ListCommand
parseBacktrace :: CharParser st Command
parseBacktrace = do
try (string "backtrace") <|> (string "bt")
return BacktraceCommand
parseBreakpointCommand :: CharParser st Command
parseBreakpointCommand = do
parseBreakpoint
className <- parseClassName
char ' '
((return . (BreakpointMethodCommand className) =<< parseMethod) <|>
(return . (BreakpointLineCommand className) =<< parseLineNum))
parseBreakpoint :: CharParser st String
parseBreakpoint = try (string "breakpoint ") <|> (string "b ")
parseClassName :: CharParser st String
parseClassName = many1 (noneOf " ")
parseMethod :: CharParser st String
parseMethod = many1 (noneOf " 0123456789")
parseLineNum :: CharParser st Int
parseLineNum = read <$> many1 digit
parseVersion :: CharParser st Command
parseVersion = string "version" >> return VersionCommand
parseContinue :: CharParser st Command
parseContinue = do
try (string "continue") <|> (string "c")
return ContinueCommand
parseQuit :: CharParser st Command
parseQuit = string "quit" >> return QuitCommand
parsePrint :: CharParser st Command
parsePrint = do
string "print "
s <- many1 (noneOf "")
return $ PrintCommand s