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

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

Append newline to end of each input line for matching with $

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