source: proto/RE/Haskell/hgrep.hs @ 4223

Last change on this file since 4223 was 3888, checked in by cameron, 5 years ago

removeNullablePrefix, removeNullableSuffix optimizations

File size: 2.2 KB
Line 
1--
2-- A Haskell grep prototype (egrep RE syntax).
3-- Demonstrating parallel bit stream algorithms
4
5module Main (main) where 
6
7import CanonicalRE
8import Nullable
9import REparse
10import RunPablo
11import REcompile
12import Data.List
13
14import System.Environment
15import System.Console.GetOpt
16import System.IO (stdout,stderr,hPutStr,hPutStrLn)
17import System.Exit (ExitCode(..),exitWith)
18import Control.Monad
19--
20-- Search for matching lines in a list of lines
21search_all :: (RE, [String]) -> [String]
22search_all(re, [])  = []
23search_all(re, line1:more)
24  | searchRE(re, line1 ++ "\n") == Bitstream 0    = search_all(re, more)
25  | otherwise                             = line1:(search_all(re, more))
26
27
28
29header = "Usage: hgrep (-h | -v | [-c] regexp file)"
30version = "hgrep 0.8"
31
32data GrepFlags = CountLines | Help | Version deriving Eq
33hgrepOptions :: [OptDescr GrepFlags]
34hgrepOptions =
35       [Option ['c'] ["count"]   (NoArg CountLines)  "Count the number of matching lines.",
36        Option ['h'] ["help"]    (NoArg Help)        "Display help and exit.",
37        Option ['v'] ["version"] (NoArg Version)     "Show the version number and exit."]
38
39usageMsg = usageInfo header hgrepOptions
40
41main = do
42  hgrepArgs <- getArgs
43  let (opts, args, errs) = getOpt Permute hgrepOptions hgrepArgs
44
45  when (not (null errs)) $ do
46       hPutStrLn stderr "Errors:"
47       mapM_ (hPutStrLn stderr) errs
48       exitWith (ExitFailure 1)
49  when (opts == [Version]) $ do
50       hPutStrLn stderr version
51       exitWith ExitSuccess
52  when (opts == [Help]) $ do
53       hPutStrLn stderr usageMsg
54       exitWith ExitSuccess
55  when (length(args) /= 2) $ do
56       hPutStrLn stderr usageMsg
57       exitWith (ExitFailure 1)
58  let [regexp, srcfile] = args
59  case parseRE(regexp) of
60         (ParseSuccess r) -> do
61            srcText <- readFile srcfile
62            let r1 = simplify(removeNullableSuffix(removeNullablePrefix(r)))
63                matches = search_all(r1, lines srcText)
64            if (opts == [CountLines]) then do
65                hPutStrLn stdout (show (length matches))
66            else do
67                hPutStr stdout (unlines matches)
68            exitWith ExitSuccess
69         (ParseFailure m) -> do
70            hPutStrLn stderr ("Bad regexp: " ++ m)
71            exitWith (ExitFailure 1)
72
Note: See TracBrowser for help on using the repository browser.