-- | The Vibe lexer: UTF-8 source bytes to spanned tokens, as Python's tokenizer makes them -- (vibe-syntax section 7.2). A logical line ends with 'Newline'; a line indented more than -- the one before opens a block ('Indent'), and one indented less closes blocks ('Dedent'), -- to the depth of an enclosing line. Inside brackets, and after a backslash at the end of a -- line, lines join. Comments are @#@ to the end of the line. Indentation is spaces: a tab -- in it, or a line that closes to no enclosing depth, is B0201. Lexical mistakes are -- numbered diagnostics, and lexing always continues. module Verada.Vibe.Lexer ( lexComments , lexSource ) where import Verada.Diagnostics (Diagnostic (..), Phase (..), diagnostic, label) import Verada.Diagnostics.Codes (DiagCode (..)) import Verada.Vibe.Token (Token (..), TokenKind (..), keywordFromText, operators) import Verada.Result (Result (..)) import Verada.Source (SourceFile (..), Span (..)) import Verada.Syntax.Frontend (Comment (..)) import Verada.Syntax.Scientific (Scientific (..), fit, fitProblem, realValue) import Data.ByteString qualified as ByteString import Data.Char (chr, digitToInt, isDigit, isHexDigit, isOctDigit) import Data.Maybe (listToMaybe) import Data.Text (Text) import Data.Text qualified as Text import Data.Text.Encoding (decodeUtf8Lenient) import Data.Word (Word8) data Lx = Lx { pos :: Int , tokens :: [Token] -- ^ newest first , diags :: [Diagnostic] , comments :: [Comment] , indents :: [Int] -- ^ the depths of the open blocks, innermost first (0 at the bottom) , depth :: Int -- ^ open brackets: lines join inside them , lineHasTokens :: Bool , atLineStart :: Bool } lexSource :: SourceFile -> Result [Token] lexSource sf = Result {diagnostics = reverse final.diags, value = Just (reverse final.tokens)} where final = lexAll sf lexComments :: SourceFile -> [Comment] lexComments sf = reverse (lexAll sf).comments lexAll :: SourceFile -> Lx lexAll sf = finish (go Lx {pos = 0, tokens = [], diags = [], comments = [], indents = [0], depth = 0, lineHasTokens = False, atLineStart = True}) where bs = sf.bytes len = ByteString.length bs sp a b = Span {file = sf.fileId, start = a, end = b} at i = ByteString.indexMaybe bs i is i c = at i == Just (fromIntegral (fromEnum c)) textOf a b = decodeUtf8Lenient (ByteString.take (b - a) (ByteString.drop a bs)) go lx | lx.pos >= len = lx | lx.atLineStart && lx.depth == 0 = go (lineStart lx) | otherwise = go (step lx) -- the indentation of a line that has tokens; blank and comment-only lines have none lineStart lx = let p = lx.pos spaces = length (takeWhile (\i -> at i == Just 32) [p .. len - 1]) q = p + spaces in case at q of Nothing -> lx {pos = q, atLineStart = False} Just b | b == 10 || b == 13 || b == 35 -> lx {pos = q, atLineStart = False} | b == 9 -> report InconsistentIndentation (sp q (q + 1)) "Vibe indents with spaces: a tab here makes the depth unclear" "a tab" (indentTo q spaces lx {pos = q + 1, atLineStart = False}) | otherwise -> indentTo q spaces lx {pos = q, atLineStart = False} indentTo q n lx = case lx.indents of top : _ | n > top -> emit (sp q q) Indent lx {indents = n : lx.indents} | n == top -> lx | otherwise -> let closing = takeWhile (> n) lx.indents rest = dropWhile (> n) lx.indents lx' = foldl (\l _ -> emit (sp q q) Dedent l) lx {indents = rest} closing in case rest of r : _ | r == n -> lx' _ -> report InconsistentIndentation (sp (q - n) q) "this line is indented less than the block it ends, but more than any block around it" "no block starts at this depth" lx' {indents = n : rest} [] -> lx {indents = [n]} step lx = case at lx.pos of Nothing -> lx {pos = len} Just b | b == 10 -> newline lx (lx.pos + 1) | b == 13 -> lx {pos = lx.pos + 1} | b == 32 || b == 9 || b == 12 -> lx {pos = lx.pos + 1} | b == 35 -> let e = lineEnd lx.pos in lx {pos = e, comments = Comment {span = sp lx.pos e, text = textOf (lx.pos + 1) e} : lx.comments} -- a backslash at the end of a line joins it to the next | b == 92 && (is (lx.pos + 1) '\n' || (is (lx.pos + 1) '\r' && is (lx.pos + 2) '\n')) -> lx {pos = lx.pos + (if is (lx.pos + 1) '\n' then 2 else 3)} | b == 34 || b == 39 -> stringLiteral lx lx.pos False | (b == 114 || b == 82) && (is (lx.pos + 1) '"' || is (lx.pos + 1) '\'') -> stringLiteral lx (lx.pos + 1) True | (b == 102 || b == 70) && (is (lx.pos + 1) '"' || is (lx.pos + 1) '\'') -> fstring lx (lx.pos + 1) False -- (`rf"..."` and `fr"..."`: a raw f-string) | b `elem` [102, 70, 114, 82] , Just b' <- at (lx.pos + 1) , b' `elem` [102, 70, 114, 82] , (b `elem` [102, 70]) /= (b' `elem` [102, 70]) , is (lx.pos + 2) '"' || is (lx.pos + 2) '\'' -> fstring lx (lx.pos + 2) True | (b == 98 || b == 66) && (is (lx.pos + 1) '"' || is (lx.pos + 1) '\'') -> let lx' = stringLiteral lx (lx.pos + 1) False in report InvalidCharacter (sp lx.pos (lx.pos + 1)) "bytes literals are not in Vibe" "a string prefix Vibe does not take" lx' -- (a prefix before its quote is not a name) | isNameStart b -> name lx | isDigit (toChar b) || (b == 46 && maybe False (isDigit . toChar) (at (lx.pos + 1))) -> number lx | otherwise -> operator lx newline lx next | lx.depth > 0 = lx {pos = next} | lx.lineHasTokens = (emit (sp lx.pos lx.pos) Newline lx) {pos = next, lineHasTokens = False, atLineStart = True} | otherwise = lx {pos = next, atLineStart = True} lineEnd p = case ByteString.elemIndex 10 (ByteString.drop p bs) of Just k -> let e = p + k in if e > p && at (e - 1) == Just 13 then e - 1 else e Nothing -> len name lx = let p = lx.pos e = firstOr len [i | i <- [p + 1 .. len], not (maybe False isNameByte (at i))] t = textOf p e kind = maybe (Name t) Reserved (keywordFromText t) in emit (sp p e) kind lx {pos = e} number lx = let p = lx.pos e = firstOr len [i | i <- [p + 1 .. len], not (maybe False numberByte (at i))] raw = textOf p e withExponentSign = extendExponent p e text = textOf p withExponentSign in case if underscoresBetweenDigits text then readNumber (Text.filter (/= '_') text) else Nothing of Just (Right k) -> emit (sp p withExponentSign) k lx {pos = withExponentSign} Just (Left (message, what)) -> report StaticValueOutOfRange (sp p withExponentSign) message what (emit (sp p withExponentSign) (FloatLiteral 0 raw) lx {pos = withExponentSign}) Nothing -> report MalformedNumber (sp p withExponentSign) ("`" <> raw <> "` is not a number Vibe reads") "not a number" lx {pos = withExponentSign} -- `1e-3`: the scan above stops at the `-` extendExponent p e | e > p, Just c <- at (e - 1), c == 101 || c == 69, not (isHexLiteral p), Just s <- at e, s == 43 || s == 45 = firstOr len [i | i <- [e + 1 .. len], not (maybe False (isDigit . toChar) (at i))] | otherwise = e isHexLiteral p = is p '0' && (is (p + 1) 'x' || is (p + 1) 'X') stringLiteral lx q raw = let p = lx.pos quote = at q triple = at (q + 1) == quote && at (q + 2) == quote open = if triple then q + 3 else q + 1 closes i = if triple then at i == quote && at (i + 1) == quote && at (i + 2) == quote else at i == quote scan i acc named | i >= len = Left i | not triple && is i '\n' = Left i | closes i = Right (i, reverse acc, reverse named) -- (in a raw string a backslash stays, and the character after it is the text's, -- a quote included, as in Python) | is i '\\' && raw = case at (i + 1) of Just c | c < 128, not (is (i + 1) '\n') || triple -> scan (i + 2) (toChar c : '\\' : acc) named _ -> scan (i + 1) ('\\' : acc) named | is i '\\' = case escape (i + 1) of Just (cs, n) -> scan (i + 1 + n) (reverse cs <> acc) named Nothing -> scan (i + 2) acc (NamedEscape i : named) | otherwise = case ByteString.indexMaybe bs i of Just c | c < 128 -> scan (i + 1) (toChar c : acc) named _ -> let n = utf8Width (at i) cs = Text.unpack (textOf i (i + n)) in scan (i + n) (reverse cs <> acc) named in case scan open [] [] of Right (i, s, named) -> let e = if triple then i + 3 else i + 1 in foldl stringProblem (emit (sp p e) (StringLiteral (Text.pack s)) lx {pos = e}) named Left i -> report UnterminatedString (sp p i) "this string is not closed" "no closing quote" lx {pos = i} stringProblem l = \case NamedEscape i -> namedEscape l i namedEscape l i = report InvalidEscape (sp i (i + 2)) "a named escape (`\\N{...}`) is not in Vibe: write the character, or `\\u` and its code" "named escape" l -- `f"text {expr} text"` (or triple-quoted, over lines; raw after `r`): the text runs -- (`{{` and `}}` are braces), and each field's expression lexed as usual, inside a -- bracket so that lines do not end; after the expression, `=` (the expression's text is -- written too), `!r` or `!s`, and `:spec` (a format spec, literal) end the field fstring lx q raw = let quote = at q triple = at (q + 1) == quote && at (q + 2) == quote open = if triple then q + 3 else q + 1 closing i = if triple then at i == quote && at (i + 1) == quote && at (i + 2) == quote else at i == quote closeWidth = if triple then 3 else 1 start = emit (sp lx.pos open) FStringStart lx {pos = open} text l i acc | i >= len || (is i '\n' && not triple) = report UnterminatedString (sp lx.pos i) "this f-string is not closed" "no closing quote" (middle l i acc) {pos = i} | closing i = emit (sp i (i + closeWidth)) FStringEnd (middle l i acc) {pos = i + closeWidth} | is i '{' && is (i + 1) '{' = text l (i + 2) ('{' : acc) | is i '}' && is (i + 1) '}' = text l (i + 2) ('}' : acc) | is i '{' = field (i + 1) (emit (sp i (i + 1)) (Op "{") (middle l i acc)) {pos = i + 1, depth = l.depth + 1} | is i '\\' && raw = text l (i + 1) ('\\' : acc) | is i '\\' = case escape (i + 1) of Just (cs, n) -> text l (i + 1 + n) (reverse cs <> acc) Nothing -> text (namedEscape l i) (i + 2) acc | otherwise = case at i of Just c | c < 128 -> text l (i + 1) (toChar c : acc) _ -> let n = utf8Width (at i) cs = Text.unpack (textOf i (i + n)) in text l (i + n) (reverse cs <> acc) middle l i acc = if null acc then l else emit (sp (i - length acc) i) (FStringMiddle (Text.pack (reverse acc))) l atField l = l.depth == lx.depth + 1 spaces i = firstOr len [k | k <- [i .. len - 1], not (is k ' ')] -- a field ends at its `}` at the field's own depth field from l | l.pos >= len || (is l.pos '\n' && not triple) = report UnterminatedString (sp lx.pos l.pos) "this f-string's field is not closed" "no `}`" l | is l.pos '}' && atField l = closeField l -- `{x=}`: the expression's text, then its value (its repr, unless a spec follows) | is l.pos '=' && atField l && not (is (l.pos + 1) '=') && not (any (is (l.pos - 1)) ("=!<>" :: String)) , let e = spaces (l.pos + 1) , is e '}' || is e '!' || is e ':' = field from (emit (sp from e) (FStringDebug (textOf from e)) l) {pos = e} | is l.pos '!' && atField l && not (is (l.pos + 1) '=') = case at (l.pos + 1) of Just c | toChar c `elem` ("rs" :: String), is (l.pos + 2) '}' || is (l.pos + 2) ':' -> afterConversion (emit (sp l.pos (l.pos + 2)) (FStringConversion (toChar c)) l) {pos = l.pos + 2} _ -> afterConversion (report InvalidCharacter (sp l.pos (l.pos + 2)) "an f-string's conversion is `!r` (Python's repr) or `!s` (its str): Vibe does not take `!a`" "conversion" l) {pos = min len (l.pos + 2)} | is l.pos ':' && atField l = spec l | closing l.pos = report UnterminatedString (sp lx.pos l.pos) "this f-string's field is not closed" "no `}`" l {depth = lx.depth} | otherwise = field from (step l) afterConversion l | is l.pos ':' = spec l | is l.pos '}' = closeField l | otherwise = report UnterminatedString (sp lx.pos l.pos) "this f-string's field is not closed" "no `}`" l {depth = lx.depth} -- `:spec`: the format spec's text, to the field's `}`; a field inside it is not taken spec l = let b = l.pos + 1 e = firstOr len [i | i <- [b .. len - 1], is i '}' || is i '{' || (is i '\n' && not triple) || closing i] l' = emit (sp b e) (FStringSpec (textOf b e)) l {pos = e} in if is e '{' then let e' = firstOr len [i | i <- [e .. len - 1], is i '}' && not (is (i + 1) '}') || closing i] in field b (report InvalidCharacter (sp e (e' + 1)) "a field inside a format spec is not in Vibe: write the spec itself, such as `{x:>8}`" "nested field" l' {pos = if is e' '}' then e' + 1 else e'}) else if is e '}' then closeField l' else report UnterminatedString (sp lx.pos e) "this f-string's field is not closed" "no `}`" l' {depth = lx.depth} closeField l = text (emit (sp l.pos (l.pos + 1)) (Op "}") l {depth = lx.depth}) (l.pos + 1) [] in text start open [] -- a backslash's escape, as Python reads it: the text it stands for, and how many bytes -- after the backslash it takes. An escape Python does not know keeps its backslash -- (`"a\\qb"` is four characters); a backslash at the end of a line joins the lines. -- `\\N{...}` is the one Vibe does not read (Nothing). escape i = case fmap toChar (at i) of Just 'n' -> Just ("\n", 1) Just 't' -> Just ("\t", 1) Just 'r' -> Just ("\r", 1) Just 'a' -> Just ("\a", 1) Just 'b' -> Just ("\b", 1) Just 'f' -> Just ("\f", 1) Just 'v' -> Just ("\v", 1) Just '\\' -> Just ("\\", 1) Just '\'' -> Just ("\'", 1) Just '"' -> Just ("\"", 1) Just '\n' -> Just ("", 1) Just 'x' | Just v <- hexDigits 2 -> Just ([chr v], 3) Just 'u' | Just v <- hexDigits 4 -> Just ([chr v], 5) Just 'U' | Just v <- hexDigits 8, v <= 0x10FFFF -> Just ([chr v], 9) Just 'N' | is (i + 1) '{' -> Nothing Just c | isOctDigit c -> let ds = takeWhile isOctDigit (take 3 [toChar d | Just d <- map at [i .. i + 2]]) in Just ([chr (foldl (\a d -> 8 * a + digitToInt d) 0 ds)], length ds) _ -> Just ("\\", 0) where hexDigits n = let ds = [toChar d | Just d <- map at [i + 1 .. i + n]] in if length ds == n && all isHexDigit ds then Just (foldl (\a d -> 16 * a + digitToInt d) 0 ds) else Nothing operator lx = let p = lx.pos candidates = [o | o <- operators, textOf p (p + Text.length o) == o] in case candidates of o : _ -> let e = p + Text.length o depth' | o `elem` ["(", "[", "{"] = lx.depth + 1 | o `elem` [")", "]", "}"] = max 0 (lx.depth - 1) | otherwise = lx.depth in emit (sp p e) (Op o) lx {pos = e, depth = depth'} [] -> let n = utf8Width (at p) in report InvalidCharacter (sp p (p + n)) ("`" <> textOf p (p + n) <> "` is not a character Vibe uses here") "not part of the language" lx {pos = p + n} emit s k lx = lx {tokens = Token {span = s, kind = k} : lx.tokens, lineHasTokens = lx.lineHasTokens || isLineToken k} isLineToken = \case Indent -> False Dedent -> False Newline -> False _ -> True report code s message what lx = lx {diags = (diagnostic code Lexical message) {primary = Just (label s what)} : lx.diags} -- the end of the file: the last logical line ends, and every open block closes finish lx = let e = sp len len ended = if lx.lineHasTokens then emit e Newline lx else lx closed = foldl (\l _ -> emit e Dedent l) ended (drop 1 lx.indents) in emit e EndOfInput closed -- | What a string literal holds that Vibe does not take, reported once it is read. data StringProblem = -- | @\\N{...}@, at its backslash NamedEscape Int firstOr :: a -> [a] -> a firstOr d = \case x : _ -> x [] -> d toChar :: Word8 -> Char toChar = toEnum . fromIntegral isNameStart :: Word8 -> Bool isNameStart b = (b >= 65 && b <= 90) || (b >= 97 && b <= 122) || b == 95 isNameByte :: Word8 -> Bool isNameByte b = isNameStart b || (b >= 48 && b <= 57) numberByte :: Word8 -> Bool numberByte b = isNameByte b || b == 46 utf8Width :: Maybe Word8 -> Int utf8Width = \case Just b | b >= 0xF0 -> 4 | b >= 0xE0 -> 3 | b >= 0xC0 -> 2 _ -> 1 -- | Whether each underscore of a number stands between two of its digits (`1_000`, `0x_ff` -- after a base's prefix), as Python requires: `1__0`, `1_` and `1_.5` are not numbers. underscoresBetweenDigits :: Text -> Bool underscoresBetweenDigits t = and [ok i | (i, '_') <- zip [0 ..] cs] where cs = Text.unpack (Text.toLower t) based = case cs of '0' : b : _ -> b `elem` ("xob" :: String) _ -> False digit c = if based then isHexDigit c else isDigit c at' i = if i >= 0 then listToMaybe (drop i cs) else Nothing ok :: Int -> Bool ok i = let before = at' (i - 1) after = at' (i + 1) in maybe False digit after && (maybe False digit before || (based && i == 2)) -- | An integer or floating-point literal as Python reads it (underscores already removed), or -- why no numeric type holds a floating-point one (expanded only when one does, D179). readNumber :: Text -> Maybe (Either (Text, Text) TokenKind) readNumber t = case Text.unpack (Text.toLower t) of '0' : 'x' : ds | not (null ds), all isHexDigit ds -> Just (Right (IntLiteral (digits 16 ds))) '0' : 'o' : ds | not (null ds), all isOctDigit ds -> Just (Right (IntLiteral (digits 8 ds))) '0' : 'b' : ds | not (null ds), all (`elem` ("01" :: String)) ds -> Just (Right (IntLiteral (digits 2 ds))) s | all isDigit s, not (null s) -> Just (Right (IntLiteral (digits 10 s))) | otherwise -> (\sci -> maybe (Right (FloatLiteral (realValue sci) t)) Left (fitProblem (fit sci))) <$> decimal s where digits :: Integer -> String -> Integer digits base = foldl (\acc c -> acc * base + toInteger (digitToInt c)) 0 decimal s = let (mantissa, rest) = break (== 'e') s (whole, fraction) = break (== '.') mantissa fractionDigits = drop 1 fraction scale = case rest of 'e' : '-' : ds | not (null ds), all isDigit ds -> Just (negate (digits 10 ds)) 'e' : '+' : ds | not (null ds), all isDigit ds -> Just (digits 10 ds) 'e' : ds | not (null ds), all isDigit ds -> Just (digits 10 ds) [] -> Just 0 _ -> Nothing ok = all isDigit whole && all isDigit fractionDigits && not (null whole && null fractionDigits) written x = Scientific {mantissa = digits 10 (whole <> fractionDigits), base = 10, exponent = x - toInteger (length fractionDigits)} in if ok then written <$> scale else Nothing