packages feed

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

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

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

Translates Go source code into canontra's unified IR without source-span leakage,
supporting package structures, factored imports, receiver methods, structs,
interfaces, goroutines, channels, defer, select, and type switches (BUG-09).
-}
module Canontra.Parser.Go
  ( parseGoSource
  , parseGoByteString
  ) 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 (..))

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

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

data GoToken
  = 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

tokenizeGoBS :: BS.ByteString -> [GoToken]
tokenizeGoBS !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
            0x60 -> -- '`' raw string in Go (no backslash escapes)
                let !(s, nextIdx) = scanRawBacktick (i + 1)
                in TokStr s : go nextIdx
            _ | isIdentStartW8 w ->
                let !end = scanWhile isIdentContW8 (i + 1)
                    !ident = sliceText bs i (end - i)
                    !tok = if isGoKeyword 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 -- e or E
               then scanNumber (k + 1) hasDot
               else if b == 0x2E -- '.'
                 then scanNumber (k + 1) True
                 else (k, hasDot)

    scanRawBacktick !start = loop start
      where
        loop !k
          | k >= len = (sliceText bs start (len - start), len)
          | at k == 0x60 = (sliceText bs start (k - start), k + 1)
          | otherwise = loop (k + 1)

    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 -- \n
                                0x74 -> 0x09 -- \t
                                0x72 -> 0x0D -- \r
                                other -> other
                          in slowLoop (k + 2) (acc <> BB.word8 escByte)
                     else slowLoop (k + 1) (acc <> BB.word8 b)

goKeywordSet :: Set Text
goKeywordSet = Set.fromList
  [ "package", "import", "func", "type", "struct", "interface", "var", "const"
  , "return", "if", "else", "for", "range", "switch", "case", "default"
  , "go", "defer", "select", "chan", "map", "fallthrough", "break", "continue"
  ]

isGoKeyword :: Text -> Bool
isGoKeyword kw = Set.member kw goKeywordSet

parseGoTopLevel :: FilePath -> [GoToken] -> Either ParseError (Text, [Declaration], [ImportDecl], [Stmt])
parseGoTopLevel _ tokens =
  let (pkg, afterPkg) = case tokens of
        TokKw "package" : TokIdent p : rest -> (p, rest)
        _                                   -> ("", tokens)
      (decls, imps, stmts) = extractGoDeclsAndStmts afterPkg
  in Right (pkg, decls, imps, stmts)

extractGoDeclsAndStmts :: [GoToken] -> ([Declaration], [ImportDecl], [Stmt])
extractGoDeclsAndStmts [] = ([], [], [])
extractGoDeclsAndStmts tokens = case tokens of
  -- import "fmt" or import ( ... )
  TokKw "import" : rest ->
    let (impDecls, afterImp) = parseGoImports rest
        (d, i, s) = extractGoDeclsAndStmts afterImp
    in (d, impDecls ++ i, s)

  -- func (r *Receiver) Method(params) ret { body }
  TokKw "func" : TokSymbol "(" : rest ->
    let (rc, afterRc) = parseReceiver rest
    in case afterRc of
      TokIdent mName : TokSymbol "[" : afterName ->
        let (tParams, afterTParams) = span (\t -> t /= TokSymbol "]") afterName
            tParamText = "[" <> T.unwords [tokenText t | t <- tParams] <> "]"
            afterBracket = if null afterTParams then [] else tail afterTParams
            (fn, afterFn) = parseGoFunctionBody mName afterBracket
            fnWithGeneric = fn { fnDecorators = [tParamText] }
            (d, i, s) = extractGoDeclsAndStmts afterFn
        in (DeclReceiver rc fnWithGeneric : d, i, s)
      TokIdent mName : afterName ->
        let (fn, afterFn) = parseGoFunctionBody mName afterName
            (d, i, s) = extractGoDeclsAndStmts afterFn
        in (DeclReceiver rc fn : d, i, s)
      _ -> extractGoDeclsAndStmts afterRc

  -- func FunctionName[T any](params) ret { body }
  TokKw "func" : TokIdent fnName : TokSymbol "[" : rest ->
    let (tParams, afterTParams) = span (\t -> t /= TokSymbol "]") rest
        tParamText = "[" <> T.unwords [tokenText t | t <- tParams] <> "]"
        afterBracket = if null afterTParams then [] else tail afterTParams
        (fn, afterFn) = parseGoFunctionBody fnName afterBracket
        fnWithGeneric = fn { fnDecorators = [tParamText] }
        (d, i, s) = extractGoDeclsAndStmts afterFn
    in (DeclFunction fnWithGeneric : d, i, s)

  -- func FunctionName(params) ret { body }
  TokKw "func" : TokIdent fnName : rest ->
    let (fn, afterFn) = parseGoFunctionBody fnName rest
        (d, i, s) = extractGoDeclsAndStmts afterFn
    in (DeclFunction fn : d, i, s)

  -- type Name[T any] struct { ... } or interface { ... }
  TokKw "type" : TokIdent stName : TokSymbol "[" : rest ->
    let (tParams, afterTParams) = span (\t -> t /= TokSymbol "]") rest
        tParamText = "[" <> T.unwords [tokenText t | t <- tParams] <> "]"
        afterBracket = if null afterTParams then [] else tail afterTParams
    in case afterBracket of
      TokKw "struct" : afterStruct ->
        let afterBrace = dropWhile (\tok -> tok /= TokSymbol "{") afterStruct
            (fieldsToks, afterBody) = extractBalancedBraces afterBrace
            fields = parseStructFields fieldsToks
            st = Struct stName fields [Function tParamText [] Nothing [] [] False] "pub"
            (d, i, s) = extractGoDeclsAndStmts afterBody
        in (DeclStruct st : d, i, s)
      TokKw "interface" : afterIface ->
        let afterBrace = dropWhile (\tok -> tok /= TokSymbol "{") afterIface
            (bodyToks, afterBody) = extractBalancedBraces afterBrace
            (methods, constraints) = parseGoInterfaceElements bodyToks
            iface = Interface stName methods (tParamText : constraints)
            (d, i, s) = extractGoDeclsAndStmts afterBody
        in (DeclInterface iface : d, i, s)
      TokSymbol "=" : afterEq ->
        let (tyToks, afterTy) = consumeGoType afterEq
            rhsStr = T.concat [tokenText t | t <- tyToks]
            (d, i, s) = extractGoDeclsAndStmts afterTy
        in (DeclTypeAlias stName (Just (tParamText <> " = " <> rhsStr)) : d, i, s)
      _ -> extractGoDeclsAndStmts afterBracket

  -- type Name struct { ... }
  TokKw "type" : TokIdent stName : TokKw "struct" : rest ->
    let afterBrace = dropWhile (\tok -> tok /= TokSymbol "{") rest
        (fieldsToks, afterBody) = extractBalancedBraces afterBrace
        fields = parseStructFields fieldsToks
        st = Struct stName fields [] "pub"
        (d, i, s) = extractGoDeclsAndStmts afterBody
    in (DeclStruct st : d, i, s)

  -- type Name interface { ... }
  TokKw "type" : TokIdent ifName : TokKw "interface" : rest ->
    let afterBrace = dropWhile (\tok -> tok /= TokSymbol "{") rest
        (bodyToks, afterBody) = extractBalancedBraces afterBrace
        (methods, constraints) = parseGoInterfaceElements bodyToks
        iface = Interface ifName methods constraints
        (d, i, s) = extractGoDeclsAndStmts afterBody
    in (DeclInterface iface : d, i, s)


  -- type Name = Original
  TokKw "type" : TokIdent aliasName : TokSymbol "=" : TokIdent orig : rest ->
    let (d, i, s) = extractGoDeclsAndStmts rest
    in (DeclTypeAlias aliasName (Just orig) : d, i, s)

  -- factored var ( ... ) and const ( ... )
  TokKw kw : TokSymbol "(" : rest | kw == "var" || kw == "const" ->
    let (blockToks, afterParen) = span (\t -> t /= TokSymbol ")") rest
        remaining = if null afterParen then [] else tail afterParen
        blockStmts = parseFactoredVarBlock blockToks
        (d, i, s) = extractGoDeclsAndStmts remaining
    in (d, i, blockStmts ++ s)

  -- single var / const declaration at top level
  TokKw kw : TokIdent name : rest | kw == "var" || kw == "const" ->
    let (stmt, afterStmt) = parseGoVarDecl name rest
        (d, i, s) = extractGoDeclsAndStmts afterStmt
    in (d, i, stmt : s)

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

parseFactoredVarBlock :: [GoToken] -> [Stmt]
parseFactoredVarBlock [] = []
parseFactoredVarBlock (TokIdent name : rest) =
  let (stmt, afterStmt) = parseGoVarDecl name rest
  in stmt : parseFactoredVarBlock afterStmt
parseFactoredVarBlock (_ : rest) = parseFactoredVarBlock rest

parseGoVarDecl :: Text -> [GoToken] -> (Stmt, [GoToken])
parseGoVarDecl name tokens =
  case tokens of
    TokSymbol "=" : rest ->
      let (expr, afterExpr) = parseGoSimpleExpr rest
      in (StmtAssign [ExprId name] expr, afterExpr)
    TokSymbol ":=" : rest ->
      let (expr, afterExpr) = parseGoSimpleExpr rest
      in (StmtAssign [ExprId name] expr, afterExpr)
    TokIdent ty : TokSymbol "=" : rest ->
      let (expr, afterExpr) = parseGoSimpleExpr rest
      in (StmtAnnAssign (ExprId name) (ExprId ty) (Just expr), afterExpr)
    TokIdent ty : rest ->
      (StmtAnnAssign (ExprId name) (ExprId ty) Nothing, rest)
    _ ->
      (StmtAssign [ExprId name] (ExprLit LitNone), tokens)

parseGoImports :: [GoToken] -> ([ImportDecl], [GoToken])
parseGoImports (TokSymbol "(" : rest) =
  let (impToks, afterParen) = span (\tok -> tok /= TokSymbol ")") rest
      imps = [ ImportModule path alias
             | (path, alias) <- extractImportPairs impToks
             ]
      remaining = if null afterParen then [] else tail afterParen
  in (imps, remaining)
parseGoImports (TokStr path : rest) =
  ([ImportModule path Nothing], rest)
parseGoImports (TokIdent alias : TokStr path : rest) =
  ([ImportModule path (Just alias)], rest)
parseGoImports tokens = ([], tokens)

extractImportPairs :: [GoToken] -> [(Text, Maybe Text)]
extractImportPairs [] = []
extractImportPairs (TokStr path : rest) = (path, Nothing) : extractImportPairs rest
extractImportPairs (TokIdent alias : TokStr path : rest) = (path, Just alias) : extractImportPairs rest
extractImportPairs (_:rest) = extractImportPairs rest

parseReceiver :: [GoToken] -> (Receiver, [GoToken])
parseReceiver tokens =
  let (rcToks, afterParen) = span (\t -> t /= TokSymbol ")") tokens
      remaining = if null afterParen then [] else tail afterParen
  in case rcToks of
      (TokIdent v : TokSymbol "*" : TokIdent ty : rest) ->
        let gen = if null rest then "" else T.concat [tokenText t | t <- rest]
        in (Receiver v (ty <> gen) True, remaining)
      (TokIdent v : TokIdent ty : rest) ->
        let gen = if null rest then "" else T.concat [tokenText t | t <- rest]
        in (Receiver v (ty <> gen) False, remaining)
      (TokSymbol "*" : TokIdent ty : rest) ->
        let gen = if null rest then "" else T.concat [tokenText t | t <- rest]
        in (Receiver "" (ty <> gen) True, remaining)
      (TokIdent ty : rest) ->
        let gen = if null rest then "" else T.concat [tokenText t | t <- rest]
        in (Receiver "" (ty <> gen) False, remaining)
      _ -> (Receiver "" "" False, remaining)

parseGoFunctionBody :: Text -> [GoToken] -> (Function, [GoToken])
parseGoFunctionBody name tokens =
  let (params, afterParams) = parseGoParamList tokens
      (retType, afterRet) = parseGoReturnType afterParams
      afterBrace = dropWhile (\t -> t /= TokSymbol "{") afterRet
      (bodyToks, afterBody) = extractBalancedBraces afterBrace
      bodyStmts = parseGoBodyStmts bodyToks
      fn = Function name params retType [] bodyStmts False
  in (fn, afterBody)

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

extractGoParams :: [GoToken] -> [Parameter]
extractGoParams [] = []
extractGoParams (TokIdent pName : xs) =
  let (tyToks, rest) = consumeGoType xs
      tyStr = if null tyToks then Nothing else Just (T.concat [tokenText t | t <- tyToks])
      remToks = dropWhile (\t -> t == TokSymbol ",") rest
  in Parameter pName ParamPositional Nothing tyStr : extractGoParams remToks
extractGoParams (_:rest) = extractGoParams rest

parseGoReturnType :: [GoToken] -> (Maybe Text, [GoToken])
parseGoReturnType tokens =
  let (tyToks, rest) = consumeGoType tokens
  in if null tyToks
     then (Nothing, tokens)
     else (Just (T.concat [tokenText t | t <- tyToks]), rest)

parseStructFields :: [GoToken] -> [(Text, Maybe Text)]
parseStructFields [] = []
parseStructFields (TokIdent fName : xs) =
  let (tyToks, afterField) = consumeGoType xs
      tyStr = if null tyToks then Nothing else Just (T.concat [tokenText t | t <- tyToks])
      remToks = dropWhile (\t -> t == TokSymbol ";" || t == TokSymbol ",") afterField
  in (fName, tyStr) : parseStructFields remToks
parseStructFields (_:rest) = parseStructFields rest

parseGoInterfaceElements :: [GoToken] -> ([Function], [Text])
parseGoInterfaceElements [] = ([], [])
parseGoInterfaceElements (TokIdent mName : TokSymbol "(" : rest) =
  let (params, afterParams) = parseGoParamList (TokSymbol "(" : rest)
      (retType, afterRet) = parseGoReturnType afterParams
      fn = Function mName params retType [] [] False
      (ms, cs) = parseGoInterfaceElements afterRet
  in (fn : ms, cs)
parseGoInterfaceElements (TokSymbol "~" : TokIdent t : rest) =
  let (unionPart, remToks) = span isTypeUnionTok (TokSymbol "~" : TokIdent t : rest)
      cText = T.concat [tokenText tok | tok <- unionPart]
      (ms, cs) = parseGoInterfaceElements remToks
  in (ms, cText : cs)
parseGoInterfaceElements (TokIdent t1 : TokSymbol "|" : rest) =
  let (unionPart, remToks) = span isTypeUnionTok (TokIdent t1 : TokSymbol "|" : rest)
      cText = T.concat [tokenText tok | tok <- unionPart]
      (ms, cs) = parseGoInterfaceElements remToks
  in (ms, cText : cs)
parseGoInterfaceElements (_ : rest) = parseGoInterfaceElements rest

isTypeUnionTok :: GoToken -> Bool
isTypeUnionTok = \case
  TokSymbol "|" -> True
  TokSymbol "~" -> True
  TokIdent _    -> True
  _             -> False


consumeGoType :: [GoToken] -> ([GoToken], [GoToken])
consumeGoType (TokSymbol "*" : rest) =
  let (t, r) = consumeGoType rest
  in (TokSymbol "*" : t, r)
consumeGoType (TokSymbol "[" : TokSymbol "]" : rest) =
  let (t, r) = consumeGoType rest
  in (TokSymbol "[" : TokSymbol "]" : t, r)
consumeGoType (TokKw "chan" : rest) =
  let (t, r) = consumeGoType rest
  in (TokKw "chan" : t, r)
consumeGoType (TokKw "map" : TokSymbol "[" : rest) =
  let (keyToks, afterKey) = span (\t -> t /= TokSymbol "]") rest
      afterClose = if null afterKey then [] else tail afterKey
      (valToks, afterVal) = consumeGoType afterClose
  in (TokKw "map" : TokSymbol "[" : keyToks ++ [TokSymbol "]"] ++ valToks, afterVal)
consumeGoType (TokIdent ty : rest) = ([TokIdent ty], rest)
consumeGoType ts = ([], ts)

tokenText :: GoToken -> 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)

extractBalancedBraces :: [GoToken] -> ([GoToken], [GoToken])
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)

parseGoBodyStmts :: [GoToken] -> [Stmt]
parseGoBodyStmts [] = []
parseGoBodyStmts (TokKw "return" : rest) =
  let (expr, afterExpr) = parseGoSimpleExpr rest
  in StmtReturn (Just expr) : parseGoBodyStmts afterExpr
parseGoBodyStmts (TokKw "go" : rest) =
  let (expr, afterExpr) = parseGoSimpleExpr rest
  in StmtGo expr : parseGoBodyStmts afterExpr
parseGoBodyStmts (TokKw "defer" : rest) =
  let (expr, afterExpr) = parseGoSimpleExpr rest
  in StmtDefer expr : parseGoBodyStmts afterExpr
parseGoBodyStmts (TokKw "switch" : rest) =
  let (switchStmt, afterSwitch) = parseGoSwitch rest
  in maybe [] pure switchStmt ++ parseGoBodyStmts afterSwitch
parseGoBodyStmts (TokIdent n1 : TokSymbol "," : TokIdent n2 : TokSymbol ":=" : rest) =
  let (expr, afterExpr) = parseGoSimpleExpr rest
  in StmtAnnAssign (ExprTuple [ExprId n1, ExprId n2]) (ExprId ":=") (Just expr) : parseGoBodyStmts afterExpr
parseGoBodyStmts (TokIdent n1 : TokSymbol "," : TokIdent n2 : TokSymbol "=" : rest) =
  let (expr, afterExpr) = parseGoSimpleExpr rest
  in StmtAssign [ExprId n1, ExprId n2] expr : parseGoBodyStmts afterExpr
parseGoBodyStmts (TokIdent name : TokSymbol ":=" : rest) =
  let (expr, afterExpr) = parseGoSimpleExpr rest
  in StmtAnnAssign (ExprId name) (ExprId ":=") (Just expr) : parseGoBodyStmts afterExpr
parseGoBodyStmts (TokIdent name : TokSymbol "=" : rest) =
  let (expr, afterExpr) = parseGoSimpleExpr rest
  in StmtAssign [ExprId name] expr : parseGoBodyStmts afterExpr
parseGoBodyStmts (_:rest) = parseGoBodyStmts rest

parseGoSwitch :: [GoToken] -> (Maybe Stmt, [GoToken])
parseGoSwitch tokens =
  let (targetToks, afterTarget) = span (\t -> t /= TokSymbol "{") tokens
      (bodyToks, afterBody) = extractBalancedBraces afterTarget
      targetExpr = case targetToks of
        [TokIdent name] -> ExprId name
        _               -> ExprLit LitNone
      (cases, defStmts) = parseGoSwitchCases bodyToks
  in (Just (StmtSwitch targetExpr cases defStmts), afterBody)

-- | Unrolls comma-separated multi-type switch cases into individual branch targets (BUG-09).
parseGoSwitchCases :: [GoToken] -> ([(Expr, [Stmt])], [Stmt])
parseGoSwitchCases [] = ([], [])
parseGoSwitchCases (TokKw "case" : rest) =
  let (caseHead, afterColon) = span (\t -> t /= TokSymbol ":") rest
      remaining = if null afterColon then [] else tail afterColon
      (caseStmts, nextCases) = span (\t -> t /= TokKw "case" && t /= TokKw "default") remaining
      stmts = parseGoBodyStmts caseStmts
      (otherCases, defStmts) = parseGoSwitchCases nextCases
      -- Extract all comma-separated case labels (e.g. case int, int64, string:)
      caseExprs = extractCaseLabels caseHead
      unrolled = [(cExpr, stmts) | cExpr <- caseExprs]
  in (unrolled ++ otherCases, defStmts)
parseGoSwitchCases (TokKw "default" : TokSymbol ":" : rest) =
  let (defStmtsToks, nextCases) = span (\t -> t /= TokKw "case") rest
      stmts = parseGoBodyStmts defStmtsToks
      (otherCases, _) = parseGoSwitchCases nextCases
  in (otherCases, stmts)
parseGoSwitchCases (_:rest) = parseGoSwitchCases rest

extractCaseLabels :: [GoToken] -> [Expr]
extractCaseLabels [] = []
extractCaseLabels (TokIdent name : rest) =
  ExprId name : extractCaseLabels (dropWhile (\t -> t == TokSymbol ",") rest)
extractCaseLabels (TokNum n : rest) =
  ExprLit (LitInt n) : extractCaseLabels (dropWhile (\t -> t == TokSymbol ",") rest)
extractCaseLabels (TokStr s : rest) =
  ExprLit (LitString s) : extractCaseLabels (dropWhile (\t -> t == TokSymbol ",") rest)
extractCaseLabels (_:rest) = extractCaseLabels rest

parseGoSingleStmt :: [GoToken] -> (Maybe Stmt, [GoToken])
parseGoSingleStmt (TokKw "return" : rest) =
  let (expr, afterExpr) = parseGoSimpleExpr rest
  in (Just (StmtReturn (Just expr)), afterExpr)
parseGoSingleStmt (TokKw "go" : rest) =
  let (expr, afterExpr) = parseGoSimpleExpr rest
  in (Just (StmtGo expr), afterExpr)
parseGoSingleStmt (TokKw "defer" : rest) =
  let (expr, afterExpr) = parseGoSimpleExpr rest
  in (Just (StmtDefer expr), afterExpr)
parseGoSingleStmt (TokKw "switch" : rest) =
  parseGoSwitch rest
parseGoSingleStmt (TokIdent n1 : TokSymbol "," : TokIdent n2 : TokSymbol ":=" : rest) =
  let (expr, afterExpr) = parseGoSimpleExpr rest
  in (Just (StmtAssign [ExprId n1, ExprId n2] expr), afterExpr)
parseGoSingleStmt (TokIdent n1 : TokSymbol "," : TokIdent n2 : TokSymbol "=" : rest) =
  let (expr, afterExpr) = parseGoSimpleExpr rest
  in (Just (StmtAssign [ExprId n1, ExprId n2] expr), afterExpr)
parseGoSingleStmt (TokIdent name : TokSymbol ":=" : rest) =
  let (expr, afterExpr) = parseGoSimpleExpr rest
  in (Just (StmtAssign [ExprId name] expr), afterExpr)
parseGoSingleStmt (TokIdent name : TokSymbol "=" : rest) =
  let (expr, afterExpr) = parseGoSimpleExpr rest
  in (Just (StmtAssign [ExprId name] expr), afterExpr)
parseGoSingleStmt (TokIdent name : TokSymbol "(" : rest) =
  let afterParen = dropWhile (\t -> t /= TokSymbol ")") rest
      nextToks = if null afterParen then [] else tail afterParen
  in (Just (StmtExpr (ExprCall (ExprId name) [] [])), nextToks)
parseGoSingleStmt (_:rest) = (Nothing, rest)
parseGoSingleStmt [] = (Nothing, [])

parseGoSimpleExpr :: [GoToken] -> (Expr, [GoToken])
parseGoSimpleExpr tokens =
  let (lhs, rest) = parseGoPrimaryExpr tokens
  in case rest of
    TokSymbol op : afterOp | op `elem` ["+", "-", "*", "/", "%", "==", "!=", "<", ">", "<=", ">="] ->
      let (rhs, remToks) = parseGoSimpleExpr afterOp
          binOp = case op of
            "+"  -> OpAdd
            "-"  -> OpSub
            "*"  -> OpMul
            "/"  -> OpDiv
            "%"  -> OpMod
            "==" -> OpEq
            "!=" -> OpNotEq
            "<"  -> OpLt
            ">"  -> OpGt
            "<=" -> OpLtE
            ">=" -> OpGtE
            _    -> OpAdd
      in (ExprBinary binOp lhs rhs, remToks)
    _ -> (lhs, rest)

parseGoPrimaryExpr :: [GoToken] -> (Expr, [GoToken])
parseGoPrimaryExpr (TokIdent name : TokSymbol "(" : rest) =
  let afterParen = dropWhile (\t -> t /= TokSymbol ")") rest
      nextToks = if null afterParen then [] else tail afterParen
  in (ExprCall (ExprId name) [] [], nextToks)
parseGoPrimaryExpr (TokNum n : rest) = (ExprLit (LitInt n), rest)
parseGoPrimaryExpr (TokFloat f : rest) = (ExprLit (LitFloat f), rest)
parseGoPrimaryExpr (TokStr s : rest) = (ExprLit (LitString s), rest)
parseGoPrimaryExpr (TokIdent name : rest) = (ExprId name, rest)
parseGoPrimaryExpr tokens = (ExprLit LitNone, tokens)