packages feed

canontra-0.4.0.0: src/Canontra/Parser/Rust.hs

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}

{- |
Module      : Canontra.Parser.Rust
Description : High-performance zero-span Rust (2021+) AST parser.

Translates Rust source code into canontra's unified IR without source-span leakage,
supporting module hierarchies, use trees, structs, enums, traits, impl blocks,
pattern matching, macro calls with lifetime tokens (BUG-08), and visibility modifiers.
-}
module Canontra.Parser.Rust
  ( parseRustSource
  , parseRustByteString
  ) where

import Control.DeepSeq (NFData)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Builder as BB
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Unsafe as BSU
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Text.Read as TR
import Data.Word (Word8)
import GHC.Generics (Generic)

import Canontra.Canonical.FastScan (ScanResult (..))
import Canontra.Canonical.SIMDScan (scanSourceSIMD)
import Canontra.Canonical.Unicode (canonicalizeText)
import Canontra.IR.Declaration
import Canontra.IR.Dependency
import Canontra.IR.Expression
import Canontra.IR.Program
import Canontra.Types (ParseError (..))

parseRustSource :: FilePath -> Text -> Either ParseError Program
parseRustSource filePath input =
  parseRustByteString filePath (TE.encodeUtf8 input)

-- | Parse raw Rust UTF-8/ASCII ByteString directly using 256-bit SIMD pre-classification
-- and zero-copy byte-slice tokenization.
parseRustByteString :: FilePath -> BS.ByteString -> Either ParseError Program
parseRustByteString filePath rawBytes =
  let cleanBS = case scanSourceSIMD rawBytes of
        PureAsciiUnix      -> rawBytes
        ContainsCRLF       -> BS.filter (/= 0x0D) rawBytes
        RequiresUnicodeNFC -> TE.encodeUtf8 (canonicalizeText (TE.decodeUtf8Lenient rawBytes))
      tokens = tokenizeRustBS cleanBS
  in case parseRustTopLevel filePath tokens of
      Left err -> Left err
      Right (decls, imps, stmts) ->
        let modul = Module (T.pack filePath) imps decls stmts
        in Right (Program [modul] "rust")

data RustToken
  = TokIdent Text
  | TokKw Text
  | TokNum Integer
  | TokFloat Double
  | TokStr Text
  | TokSymbol Text
  deriving stock (Eq, Show, Generic)
  deriving anyclass (NFData)

{-# INLINE sliceText #-}
sliceText :: BS.ByteString -> Int -> Int -> Text
sliceText bs start len = TE.decodeUtf8Lenient (BS.take len (BS.drop start bs))

{-# INLINE isSpaceW8 #-}
isSpaceW8 :: Word8 -> Bool
isSpaceW8 w = w == 0x20 || w == 0x0A || w == 0x0D || w == 0x09 || w == 0x0C || w == 0x0B

{-# INLINE isDigitW8 #-}
isDigitW8 :: Word8 -> Bool
isDigitW8 w = w >= 0x30 && w <= 0x39

{-# INLINE isIdentStartW8 #-}
isIdentStartW8 :: Word8 -> Bool
isIdentStartW8 w =
  (w >= 0x61 && w <= 0x7A)
    || (w >= 0x41 && w <= 0x5A)
    || w == 0x5F
    || w >= 0x80

{-# INLINE isIdentContW8 #-}
isIdentContW8 :: Word8 -> Bool
isIdentContW8 w = isIdentStartW8 w || isDigitW8 w

{-# INLINE isSingleSymW8 #-}
isSingleSymW8 :: Word8 -> Bool
isSingleSymW8 w = case w of
  0x7B -> True -- {
  0x7D -> True -- }
  0x28 -> True -- (
  0x29 -> True -- )
  0x5B -> True -- [
  0x5D -> True -- ]
  0x3B -> True -- ;
  0x2C -> True -- ,
  0x3F -> True -- ?
  0x2E -> True -- .
  0x7E -> True -- ~
  _    -> False

{-# INLINE isMultiSymW8 #-}
isMultiSymW8 :: Word8 -> Bool
isMultiSymW8 w = case w of
  0x3D -> True -- =
  0x2B -> True -- +
  0x2D -> True -- -
  0x2A -> True -- *
  0x2F -> True -- /
  0x25 -> True -- %
  0x26 -> True -- &
  0x7C -> True -- |
  0x5E -> True -- ^
  0x21 -> True -- !
  0x3C -> True -- <
  0x3E -> True -- >
  0x3A -> True -- :
  _    -> False

tokenizeRustBS :: BS.ByteString -> [RustToken]
tokenizeRustBS !bs = go 0
  where
    !len = BS.length bs
    {-# INLINE at #-}
    at !i = BSU.unsafeIndex bs i

    go !i
      | i >= len = []
      | otherwise =
          let !w = at i
          in case w of
            _ | isSpaceW8 w -> go (skipSpaces (i + 1))
            0x2F | i + 1 < len && at (i + 1) == 0x2F -> -- //
                go (skipLineComment (i + 2))
            0x2F | i + 1 < len && at (i + 1) == 0x2A -> -- /*
                go (skipBlockComment (i + 2))
            0x22 -> -- '"'
                let !(s, nextIdx) = scanEscapedString 0x22 (i + 1)
                in TokStr s : go nextIdx
            0x27 -> -- '\'' (lifetime or char literal)
                if i + 3 < len && at (i + 1) == 0x5C && at (i + 3) == 0x27
                  then TokStr (sliceText bs (i + 2) 1) : go (i + 4)
                  else if i + 1 < len && isIdentStartW8 (at (i + 1)) && (i + 2 >= len || at (i + 2) /= 0x27)
                    then
                      let !end = scanWhile isIdentContW8 (i + 2)
                      in TokIdent (sliceText bs i (end - i)) : go end
                    else if i + 2 < len && at (i + 2) == 0x27
                      then TokStr (sliceText bs (i + 1) 1) : go (i + 3)
                      else TokSymbol "'" : go (i + 1)
            0x72 | i + 1 < len && at (i + 1) == 0x23 -> -- r#ident
                let !end = scanWhile isIdentContW8 (i + 2)
                in TokIdent (sliceText bs (i + 2) (end - i - 2)) : go end
            _ | isIdentStartW8 w ->
                let !end = scanWhile isIdentContW8 (i + 1)
                    !ident = sliceText bs i (end - i)
                    !tok = if isRustKeyword ident then TokKw ident else TokIdent ident
                in tok : go end
            _ | isDigitW8 w ->
                let !(end, hasDot) = scanNumber (i + 1) False
                    !numText = sliceText bs i (end - i)
                    !tok = if hasDot
                      then case TR.double numText of
                             Right (d, _) -> TokFloat d
                             Left _       -> TokFloat 0.0
                      else case TR.decimal numText of
                             Right (n, _) -> TokNum n
                             Left _       -> TokNum 0
                in tok : go end
            _ | isSingleSymW8 w ->
                TokSymbol (sliceText bs i 1) : go (i + 1)
            _ | isMultiSymW8 w ->
                let !end = scanWhile isMultiSymW8 (i + 1)
                in TokSymbol (sliceText bs i (end - i)) : go end
            _ -> go (i + 1)

    skipSpaces !k
      | k < len && isSpaceW8 (at k) = skipSpaces (k + 1)
      | otherwise = k

    skipLineComment !k
      | k < len && at k /= 0x0A = skipLineComment (k + 1)
      | k < len = k + 1
      | otherwise = len

    skipBlockComment !k
      | k + 1 < len && at k == 0x2A && at (k + 1) == 0x2F = k + 2
      | k < len = skipBlockComment (k + 1)
      | otherwise = len

    scanWhile p !k
      | k < len && p (at k) = scanWhile p (k + 1)
      | otherwise = k

    scanNumber !k !hasDot
      | k >= len = (k, hasDot)
      | otherwise =
          let !b = at k
          in if isDigitW8 b || b == 0x65 || b == 0x45
               then scanNumber (k + 1) hasDot
               else if b == 0x2E
                 then scanNumber (k + 1) True
                 else (k, hasDot)

    scanEscapedString !q !start = fastLoop start
      where
        fastLoop !k
          | k >= len = (sliceText bs start (len - start), len)
          | otherwise =
              let !b = at k
              in if b == q
                   then (sliceText bs start (k - start), k + 1)
                   else if b == 0x5C
                     then slowLoop k (BB.byteString (BS.take (k - start) (BS.drop start bs)))
                     else fastLoop (k + 1)

        slowLoop !k !acc
          | k >= len = (TE.decodeUtf8Lenient (BL.toStrict (BB.toLazyByteString acc)), len)
          | otherwise =
              let !b = at k
              in if b == q
                   then (TE.decodeUtf8Lenient (BL.toStrict (BB.toLazyByteString acc)), k + 1)
                   else if b == 0x5C && k + 1 < len
                     then let !escByte = case at (k + 1) of
                                0x6E -> 0x0A
                                0x74 -> 0x09
                                0x72 -> 0x0D
                                other -> other
                          in slowLoop (k + 2) (acc <> BB.word8 escByte)
                     else slowLoop (k + 1) (acc <> BB.word8 b)

rustKeywordSet :: Set Text
rustKeywordSet = Set.fromList
  [ "fn", "struct", "enum", "trait", "impl", "for", "type", "mod", "use", "pub", "crate"
  , "let", "mut", "const", "static", "if", "else", "match", "loop", "while", "return"
  , "async", "await", "self", "Self", "where", "break", "continue"
  ]

isRustKeyword :: Text -> Bool
isRustKeyword kw = Set.member kw rustKeywordSet

parseRustTopLevel :: FilePath -> [RustToken] -> Either ParseError ([Declaration], [ImportDecl], [Stmt])
parseRustTopLevel _ tokens =
  let (decls, imps, stmts) = extractRustDeclsAndStmts tokens
  in Right (decls, imps, stmts)

extractRustDeclsAndStmts :: [RustToken] -> ([Declaration], [ImportDecl], [Stmt])
extractRustDeclsAndStmts [] = ([], [], [])
extractRustDeclsAndStmts tokens = case tokens of
  -- use path::to::item; (including pub use / braced use trees / ::*)
  TokKw "use" : rest ->
    let (useToks, afterSemi) = span (\tok -> tok /= TokSymbol ";") rest
        imp = parseRustUseTree useToks
        remToks = if null afterSemi then [] else tail afterSemi
        (d, i, s) = extractRustDeclsAndStmts remToks
    in (d, imp : i, s)

  -- pub ...
  TokKw "pub" : rest ->
    extractRustDeclsAndStmts rest

  -- fn / async fn / const fn
  TokKw "async" : TokKw "fn" : TokIdent name : rest ->
    let (fn, afterFn) = parseRustFunctionBody name True rest
        (d, i, s) = extractRustDeclsAndStmts afterFn
    in (DeclFunction fn : d, i, s)

  TokKw "fn" : TokIdent name : rest ->
    let (fn, afterFn) = parseRustFunctionBody name False rest
        (d, i, s) = extractRustDeclsAndStmts afterFn
    in (DeclFunction fn : d, i, s)

  -- struct Name<T> { ... }
  TokKw "struct" : TokIdent name : rest ->
    let (gMethods, afterGen) = case rest of
          TokSymbol "<" : r ->
            let (gToks, afterAngle) = extractBalancedAngle r
                gText = "<" <> T.unwords [tokenText t | t <- gToks] <> ">"
            in ([Function gText [] Nothing [] [] False], afterAngle)
          _ -> ([], rest)
        afterBrace = dropWhile (\tok -> tok /= TokSymbol "{") afterGen
        (fieldsToks, afterBody) = extractBalancedBraces afterBrace
        fields = parseRustFields fieldsToks
        st = Struct name fields gMethods "pub"
        (d, i, s) = extractRustDeclsAndStmts afterBody
    in (DeclStruct st : d, i, s)

  -- trait Name<T> { ... }
  TokKw "trait" : TokIdent name : rest ->
    let (gSupers, afterGen) = case rest of
          TokSymbol "<" : r ->
            let (gToks, afterAngle) = extractBalancedAngle r
                gText = "<" <> T.unwords [tokenText t | t <- gToks] <> ">"
            in ([gText], afterAngle)
          _ -> ([], rest)
        afterBrace = dropWhile (\tok -> tok /= TokSymbol "{") afterGen
        (methodToks, afterBody) = extractBalancedBraces afterBrace
        methods = parseRustMethods methodToks
        tr = Trait name methods gSupers
        (d, i, s) = extractRustDeclsAndStmts afterBody
    in (DeclTrait tr : d, i, s)

  -- type Name<T> = ...;
  TokKw "type" : TokIdent name : rest ->
    let (mGen, afterGen) = case rest of
          TokSymbol "<" : r ->
            let (gToks, afterAngle) = extractBalancedAngle r
                gText = "<" <> T.unwords [tokenText t | t <- gToks] <> ">"
            in (Just gText, afterAngle)
          _ -> (Nothing, rest)
        afterEq = dropWhile (\tok -> tok /= TokSymbol "=") afterGen
        rhsToks0 = if null afterEq then [] else tail afterEq
        (rhsToks, afterSemi) = span (\tok -> tok /= TokSymbol ";") rhsToks0
        rhsText = T.unwords [tokenText t | t <- rhsToks]
        fullDef = case mGen of
          Just g  -> g <> " = " <> rhsText
          Nothing -> rhsText
        nextToks = if null afterSemi then [] else tail afterSemi
        (d, i, s) = extractRustDeclsAndStmts nextToks
    in (DeclTypeAlias name (Just fullDef) : d, i, s)

  -- impl Trait for Target { ... } or impl Target { ... }
  TokKw "impl" : rest ->
    let (implDecl, afterBody) = parseRustImpl rest
        (d, i, s) = extractRustDeclsAndStmts afterBody
    in (DeclImpl implDecl : d, i, s)

  t : ts ->
    let (stmt, rest) = parseRustSingleStmt (t:ts)
        (d, i, s) = extractRustDeclsAndStmts rest
    in (d, i, maybe [] pure stmt ++ s)

parseRustImpl :: [RustToken] -> (Impl, [RustToken])
parseRustImpl tokens =
  let (headerToks, afterHeader) = span (\t -> t /= TokSymbol "{") tokens
      (bodyToks, afterBody) = extractBalancedBraces afterHeader
      methods = parseRustMethods bodyToks
      (mTrait, target) = case headerToks of
        [TokIdent tr, TokKw "for", TokIdent tgt] -> (Just tr, tgt)
        [TokIdent tgt]                           -> (Nothing, tgt)
        _                                        -> (Nothing, "")
  in (Impl mTrait target methods, afterBody)

parseRustFunctionBody :: Text -> Bool -> [RustToken] -> (Function, [RustToken])
parseRustFunctionBody name isAsync tokens =
  let (mGenerics, afterGenerics) = case tokens of
        TokSymbol "<" : rest ->
          let (gToks, afterAngle) = extractBalancedAngle rest
              gStr = "<" <> T.concat [tokenText t | t <- gToks] <> ">"
          in (Just gStr, afterAngle)
        _ -> (Nothing, tokens)
      (params, afterParams) = parseRustParamList afterGenerics
      (retType, afterRet) = parseRustReturnType afterParams
      afterWhere = case afterRet of
        TokKw "where" : rest -> dropWhile (\t -> t /= TokSymbol "{" && t /= TokSymbol ";") rest
        _                    -> afterRet
      (bodyStmts, afterBody) = case afterWhere of
        TokSymbol ";" : rest -> ([], rest)
        _ ->
          let afterBrace = dropWhile (\t -> t /= TokSymbol "{") afterWhere
              (bodyToks, remToks) = extractBalancedBraces afterBrace
          in (parseRustBodyStmts bodyToks, remToks)
      decs = maybe [] pure mGenerics
      fn = Function name params retType decs bodyStmts isAsync
  in (fn, afterBody)

extractBalancedAngle :: [RustToken] -> ([RustToken], [RustToken])
extractBalancedAngle tokens = go (1 :: Int) [] tokens
  where
    go 0 acc remToks = (reverse acc, remToks)
    go _ acc [] = (reverse acc, [])
    go depth acc (TokSymbol "<" : xs) = go (depth + 1) (TokSymbol "<" : acc) xs
    go depth acc (TokSymbol ">" : xs) =
      if depth == 1
      then (reverse acc, xs)
      else go (depth - 1) (TokSymbol ">" : acc) xs
    go depth acc (x : xs) = go depth (x : acc) xs

parseRustParamList :: [RustToken] -> ([Parameter], [RustToken])
parseRustParamList (TokSymbol "(" : rest) =
  let (pToks, afterParen) = span (\t -> t /= TokSymbol ")") rest
      params = extractRustParams pToks
      remaining = if null afterParen then [] else tail afterParen
  in (params, remaining)
parseRustParamList tokens = ([], tokens)

extractRustParams :: [RustToken] -> [Parameter]
extractRustParams [] = []
extractRustParams (TokKw "self" : rest) =
  Parameter "self" ParamPositional Nothing Nothing : extractRustParams (dropWhile (\t -> t == TokSymbol ",") rest)
extractRustParams (TokSymbol "&" : TokKw "self" : rest) =
  Parameter "&self" ParamPositional Nothing Nothing : extractRustParams (dropWhile (\t -> t == TokSymbol ",") rest)
extractRustParams (TokSymbol "&" : TokKw "mut" : TokKw "self" : rest) =
  Parameter "&mut self" ParamPositional Nothing Nothing : extractRustParams (dropWhile (\t -> t == TokSymbol ",") rest)
extractRustParams (TokIdent pName : TokSymbol ":" : rest) =
  let (tyToks, afterTy) = span (\t -> t /= TokSymbol "," && t /= TokSymbol ")") rest
      tyStr = if null tyToks then Nothing else Just (T.strip (T.concat [typeTokenText t | t <- tyToks]))
      remToks = dropWhile (\t -> t == TokSymbol ",") afterTy
  in Parameter pName ParamPositional Nothing tyStr : extractRustParams remToks
extractRustParams (TokIdent pName : rest) =
  Parameter pName ParamPositional Nothing Nothing : extractRustParams (dropWhile (\t -> t == TokSymbol ",") rest)
extractRustParams (_:rest) = extractRustParams rest

parseRustReturnType :: [RustToken] -> (Maybe Text, [RustToken])
parseRustReturnType (TokSymbol "->" : rest) =
  let (tyToks, afterTy) = span (\t -> t /= TokSymbol "{" && t /= TokKw "where" && t /= TokSymbol ";") rest
      tyStr = if null tyToks then Nothing else Just (T.strip (T.concat [typeTokenText t | t <- tyToks]))
  in (tyStr, afterTy)
parseRustReturnType tokens = (Nothing, tokens)

parseRustFields :: [RustToken] -> [(Text, Maybe Text)]
parseRustFields [] = []
parseRustFields (TokKw "pub" : rest) = parseRustFields rest
parseRustFields (TokIdent fName : TokSymbol ":" : rest) =
  let (tyToks, afterTy) = span (\t -> t /= TokSymbol "," && t /= TokSymbol "}") rest
      tyStr = if null tyToks then Nothing else Just (T.strip (T.concat [typeTokenText t | t <- tyToks]))
      remToks = dropWhile (\t -> t == TokSymbol ",") afterTy
  in (fName, tyStr) : parseRustFields remToks
parseRustFields (_:rest) = parseRustFields rest

typeTokenText :: RustToken -> Text
typeTokenText (TokKw "mut") = "mut "
typeTokenText t             = tokenText t

parseRustMethods :: [RustToken] -> [Function]
parseRustMethods [] = []
parseRustMethods (TokKw "pub" : rest) = parseRustMethods rest
parseRustMethods (TokKw "fn" : TokIdent name : rest) =
  let (fn, afterFn) = parseRustFunctionBody name False rest
  in fn : parseRustMethods afterFn
parseRustMethods (TokKw "async" : TokKw "fn" : TokIdent name : rest) =
  let (fn, afterFn) = parseRustFunctionBody name True rest
  in fn : parseRustMethods afterFn
parseRustMethods (TokKw "type" : TokIdent name : rest) =
  let (headerToks, afterHeader) = span (\t -> t /= TokSymbol ";") rest
      remToks = if null afterHeader then [] else tail afterHeader
      gatSig = "<" <> T.concat [tokenText t | t <- headerToks] <> ">"
      fn = Function ("type:" <> name) [] (Just gatSig) [] [] False
  in fn : parseRustMethods remToks
parseRustMethods (_:rest) = parseRustMethods rest

extractBalancedBraces :: [RustToken] -> ([RustToken], [RustToken])
extractBalancedBraces (TokSymbol "{" : rest) = go (1 :: Int) [] rest
  where
    go 0 acc remaining = (reverse acc, remaining)
    go _ acc [] = (reverse acc, [])
    go depth acc (TokSymbol "{" : xs) = go (depth + 1) (TokSymbol "{" : acc) xs
    go depth acc (TokSymbol "}" : xs) =
      if depth == 1
      then (reverse acc, xs)
      else go (depth - 1) (TokSymbol "}" : acc) xs
    go depth acc (x:xs) = go depth (x : acc) xs
extractBalancedBraces tokens = ([], tokens)

parseRustBodyStmts :: [RustToken] -> [Stmt]
parseRustBodyStmts [] = []
parseRustBodyStmts (TokKw "loop" : rest) =
  let afterBrace = dropWhile (\t -> t /= TokSymbol "{") rest
      (bodyToks, afterBody) = extractBalancedBraces afterBrace
  in StmtLoop (parseRustBodyStmts bodyToks) : parseRustBodyStmts afterBody
parseRustBodyStmts tokens =
  case parseRustSingleStmt tokens of
    (Just stmt, afterStmt) -> stmt : parseRustBodyStmts afterStmt
    (Nothing, _:rest)      -> parseRustBodyStmts rest
    (Nothing, [])          -> []

parseRustSingleStmt :: [RustToken] -> (Maybe Stmt, [RustToken])
parseRustSingleStmt [] = (Nothing, [])
parseRustSingleStmt (TokKw "return" : rest) =
  let (expr, afterExpr) = parseRustSimpleExpr rest
  in (Just (StmtReturn (Just expr)), afterExpr)
parseRustSingleStmt (TokKw "let" : rest) =
  let restAfterMut = case rest of
        TokKw "mut" : r -> r
        _               -> rest
  in case restAfterMut of
       TokIdent name : TokSymbol ":" : afterName ->
         let afterType = dropWhile (\t -> t /= TokSymbol "=" && t /= TokSymbol ";") afterName
         in case afterType of
              TokSymbol "=" : exprToks ->
                let (expr, afterExpr) = parseRustSimpleExpr exprToks
                in (Just (StmtAnnAssign (ExprId name) (ExprId "let") (Just expr)), afterExpr)
              _ ->
                let nextToks = dropWhile (\t -> t == TokSymbol ";") afterType
                in (Just (StmtAnnAssign (ExprId name) (ExprId "let") (Just (ExprId "()"))), nextToks)
       TokIdent name : TokSymbol "=" : exprToks ->
         let (expr, afterExpr) = parseRustSimpleExpr exprToks
         in (Just (StmtAnnAssign (ExprId name) (ExprId "let") (Just expr)), afterExpr)
       TokIdent name : TokSymbol ";" : afterSemi ->
         (Just (StmtAnnAssign (ExprId name) (ExprId "let") (Just (ExprId "()"))), afterSemi)
       _ -> (Nothing, rest)
parseRustSingleStmt (TokIdent name : TokSymbol "!" : rest) =
  let (macroExpr, afterMacro) = parseRustSimpleExpr (TokIdent name : TokSymbol "!" : rest)
  in (Just (StmtExpr macroExpr), afterMacro)
parseRustSingleStmt (TokIdent name : TokSymbol "=" : rest) =
  let (expr, afterExpr) = parseRustSimpleExpr rest
  in (Just (StmtAssign [ExprId name] expr), afterExpr)
parseRustSingleStmt (TokIdent name : TokSymbol "(" : rest) =
  let (expr, afterExpr) = parseRustSimpleExpr (TokIdent name : TokSymbol "(" : rest)
  in (Just (StmtExpr expr), afterExpr)
parseRustSingleStmt (_:rest) = (Nothing, rest)

parseRustSimpleExpr :: [RustToken] -> (Expr, [RustToken])
parseRustSimpleExpr (TokSymbol ";" : rest) = (ExprLit LitNone, rest)
parseRustSimpleExpr tokens =
  let (primary, afterPrimary) = parseRustPrimary tokens
  in applyPostfixOps primary afterPrimary
  where
    applyPostfixOps !expr (TokSymbol "?" : rest) =
      applyPostfixOps (ExprTryOp expr) rest
    applyPostfixOps !expr rest =
      (expr, dropWhile (\t -> t == TokSymbol ";") rest)

    parseRustPrimary (TokIdent name : TokSymbol "!" : TokSymbol openB : rest)
      | openB `elem` ["(", "[", "{"] =
          let closeB = case openB of "(" -> ")"; "[" -> "]"; _ -> "}"
              (bodyToks, afterClose) = extractBalancedDelim openB closeB rest
              macroArgs = if null bodyToks then [] else [ExprId (T.concat [tokenText t | t <- bodyToks])]
          in (ExprMacroCall name macroArgs, afterClose)
    parseRustPrimary (TokIdent name : TokSymbol "(" : rest) =
      let afterParen = dropWhile (\t -> t /= TokSymbol ")") rest
          nextToks = if null afterParen then [] else tail afterParen
      in (ExprCall (ExprId name) [] [], nextToks)
    parseRustPrimary (TokNum n : rest) = (ExprLit (LitInt n), rest)
    parseRustPrimary (TokFloat f : rest) = (ExprLit (LitFloat f), rest)
    parseRustPrimary (TokStr s : rest) = (ExprLit (LitString s), rest)
    parseRustPrimary (TokIdent name : rest) = (ExprId name, rest)
    parseRustPrimary toks =
      let after = dropWhile (\t -> t /= TokSymbol ";") toks
      in (ExprLit LitNone, if null after then [] else tail after)

extractBalancedDelim :: Text -> Text -> [RustToken] -> ([RustToken], [RustToken])
extractBalancedDelim openB closeB tokens = go (1 :: Int) [] tokens
  where
    go 0 acc remToks = (reverse acc, remToks)
    go _ acc [] = (reverse acc, [])
    go depth acc (TokSymbol s : xs)
      | s == openB  = go (depth + 1) (TokSymbol s : acc) xs
      | s == closeB =
          if depth == 1
          then (reverse acc, xs)
          else go (depth - 1) (TokSymbol s : acc) xs
    go depth acc (x : xs) = go depth (x : acc) xs

tokenText :: RustToken -> Text
tokenText (TokIdent t)  = t
tokenText (TokKw t)     = t
tokenText (TokSymbol t) = t
tokenText (TokStr t)    = "\"" <> t <> "\""
tokenText (TokNum n)    = T.pack (show n)
tokenText (TokFloat f)  = T.pack (show f)

-- | Parse Rust @use@ path/tree into normalized 'ImportDecl' preserving module hierarchy,
-- braced symbol lists (@use a::b::{x, y as z}@), and wildcard re-exports (@use a::b::*@).
parseRustUseTree :: [RustToken] -> ImportDecl
parseRustUseTree toks =
  let (prefixToks, bracePart) = span (\t -> t /= TokSymbol "{") toks
      segNames = [p | t <- prefixToks, Just p <- [extractSeg t]]
      cleanSegs = filter (\s -> s /= "crate" && s /= "self" && s /= "super") segNames
  in case bracePart of
       TokSymbol "{" : inner ->
         let (bToks, _) = span (\t -> t /= TokSymbol "}") inner
             modPath = T.intercalate "." cleanSegs
             syms = parseRustUseBraced bToks
         in ImportFrom modPath (ImportSymbols syms)
       _ -> case reverse cleanSegs of
         ("*" : revParent) | not (null revParent) ->
           ImportFrom (T.intercalate "." (reverse revParent)) ImportAll
         (lastSeg : revParent) | not (null revParent) ->
           ImportFrom (T.intercalate "." (reverse revParent)) (ImportSymbols [(lastSeg, Nothing)])
         _ ->
           ImportModule (T.intercalate "." cleanSegs) Nothing
  where
    extractSeg (TokIdent p)  = Just p
    extractSeg (TokKw "self") = Just "self"
    extractSeg (TokKw "crate") = Just "crate"
    extractSeg (TokKw "super") = Just "super"
    extractSeg (TokSymbol "*") = Just "*"
    extractSeg _             = Nothing

    parseRustUseBraced [] = []
    parseRustUseBraced (TokIdent orig : TokKw "as" : TokIdent alias : r) =
      (orig, Just alias) : parseRustUseBraced (dropWhile (\t -> t == TokSymbol ",") r)
    parseRustUseBraced (TokIdent orig : r) =
      (orig, Nothing) : parseRustUseBraced (dropWhile (\t -> t == TokSymbol ",") r)
    parseRustUseBraced (_ : r) =
      parseRustUseBraced r