on master help sign in
detect when there really is an `else` branch next
98b963cEvan Czaplicki
compiler/src/Reporting/Error/Syntax.hs+36−17
@@ -3747,24 +3747,43 @@ toIfReport source context if_ startRow startCol =
3747 )
3747 )
3748
3748
3749 IfIndentElse row col ->
3749 IfIndentElse row col ->
3750+ case Code.nextLineStartsWithKeyword "else" source row of
3751+ Just (elseRow, elseCol) ->
3750− let
3752+ let
3751− surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
3753+ surroundings = A.Region (A.Position startRow startCol) (A.Position elseRow elseCol)
3752− region = toRegion row col
3754+ region = toWiderRegion elseRow elseCol 4
3753− in
3755+ in
3754− Report.Report "UNFINISHED IF" region [] $
3756+ Report.Report "WEIRD ELSE BRANCH" region [] $
3755− Code.toSnippet source surroundings (Just region)
3757+ Code.toSnippet source surroundings (Just region)
3756− (
3758+ (
3757− D.reflow $
3759+ D.reflow $
3758− "I was expecting to see an `else` branch after this:"
3760+ "I was partway through an `if` expression when I got stuck here:"
3759− ,
3761+ ,
3760− D.stack
3761− [ D.fillSep
3762+ D.fillSep $
3762− ["I","know","what","to","do","when","the","condition","is","True,"
3763+ ["I","think","this",D.cyan "else","keyword","needs","to","be","indented","more."
3763− ,"but","what","happens","when","it","is","False?"
3764+ ,"Try","adding","some","spaces","before","it."
3764− ,"Add","an",D.cyan "else","branch","to","handle","that","scenario!"
3765 ]
3765 ]
3766− ]
3766+ )
3767+
3768+ Nothing ->
3769+ let
3770+ surroundings = A.Region (A.Position startRow startCol) (A.Position row col)
3771+ region = toRegion row col
3772+ in
3773+ Report.Report "UNFINISHED IF" region [] $
3774+ Code.toSnippet source surroundings (Just region)
3775+ (
3776+ D.reflow $
3777+ "I was expecting to see an `else` branch after this:"
3778+ ,
3779+ D.stack
3780+ [ D.fillSep
3781+ ["I","know","what","to","do","when","the","condition","is","True,"
3782+ ,"but","what","happens","when","it","is","False?"
3783+ ,"Add","an",D.cyan "else","branch","to","handle","that","scenario!"
3784+ ]
3785+ ]
3767− )
3786+ )
3768
3787
3769
3788
3770
3789
compiler/src/Reporting/Render/Code.hs+14
@@ -7,6 +7,7 @@ module Reporting.Render.Code
7 , toPair
7 , toPair
8 , Next(..)
8 , Next(..)
9 , whatIsNext
9 , whatIsNext
10+ , nextLineStartsWithKeyword
10 )
11 )
11 where
12 where
12
13
@@ -245,3 +246,16 @@ startsWithKeyword restOfLine keyword =
245
246
246 c:_ ->
247 c:_ ->
247 not (Char.isAlphaNum c || c == '_')
248 not (Char.isAlphaNum c || c == '_')
249+
250+
251+nextLineStartsWithKeyword :: [Char] -> Source -> Row -> Maybe (Row, Col)
252+nextLineStartsWithKeyword keyword (Source sourceLines) row =
253+ case List.lookup (row + 1) sourceLines of
254+ Nothing ->
255+ Nothing
256+
257+ Just line ->
258+ if startsWithKeyword (dropWhile (==' ') line) keyword then
259+ Just (row + 1, 1 + fromIntegral (length (takeWhile (==' ') line)))
260+ else
261+ Nothing