Skip to content

Instantly share code, notes, and snippets.

@osa1
Created June 10, 2012 09:00
Show Gist options
  • Save osa1/2904582 to your computer and use it in GitHub Desktop.
Save osa1/2904582 to your computer and use it in GitHub Desktop.
counting indentations in alex
getLexerIndentLevel :: Alex Int
getLexerIndentLevel = Alex $ \s@AlexState{alex_ust=ust} -> Right (s, indentation ust)
setLexerIndentLevel :: Int -> Alex ()
setLexerIndentLevel i = Alex $ \s@AlexState{alex_ust=ust} -> Right (s{alex_ust=(AlexUserState i)}, ())
collectIndent :: AlexInput -> Int -> Alex Lexeme
collectIndent input@(p, _, _, str) i = do
lastIndent <- getLexerIndentLevel
currIndent <- countIndent (drop 1 str) 0
if (lastIndent < currIndent) then
do setLexerIndentLevel currIndent
mkL LIndent input i
else if (lastIndent > currIndent) then
do setLexerIndentLevel currIndent
mkL LDedent input i
else alexMonadScan
where
countIndent str total
| take 1 str == "\t" = do skip input 1
countIndent (drop 1 str) (total+1)
| take 4 str == " " = do skip input 4
countIndent (drop 4 str) (total+1)
| otherwise = return total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment