packages feed

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

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

{- |
Module      : Canontra.Parser.JS
Description : High-performance zero-span JavaScript & TypeScript (ES2022+, TS, JSX) AST parser.

Translates JavaScript and TypeScript source into canontra's unified IR
without source-span leakage, supporting modern language constructs:
async/await, arrow functions (including generic arrow functions), classes,
interfaces, type aliases, enums, modules, optional chaining, nullish coalescing,
and JSX elements with lookahead disambiguation (BUG-07).
-}
module Canontra.Parser.JS
  ( parseJSSource
  , parseJSByteString
  , JSToken (..)
  , tokenizeJS
  , tokenizeJSByteString
  ) 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 (..))

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

-- | Parse raw JS/TS UTF-8/ASCII ByteString directly using 256-bit SIMD pre-classification
-- and zero-copy byte-slice tokenization.
parseJSByteString :: FilePath -> BS.ByteString -> Either ParseError Program
parseJSByteString filePath rawBytes =
  let tokens = tokenizeJSByteString rawBytes
  in case parseTopLevel filePath tokens of
      Left err -> Left err
      Right (decls, imps, stmts) ->
        let fpText = T.pack filePath
            isTS = T.isSuffixOf ".ts" fpText || T.isSuffixOf ".tsx" fpText
            lang = if isTS then "typescript" else "javascript"
            modul = Module fpText imps decls stmts
        in Right (Program [modul] lang)

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

tokenizeJS :: Text -> [JSToken]
tokenizeJS = tokenizeJSByteString . TE.encodeUtf8

{-# 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 isAlphaW8 #-}
isAlphaW8 :: Word8 -> Bool
isAlphaW8 w = (w >= 0x61 && w <= 0x7A) || (w >= 0x41 && w <= 0x5A)

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

{-# INLINE isJSIdentStartW8 #-}
isJSIdentStartW8 :: Word8 -> Bool
isJSIdentStartW8 w = isAlphaW8 w || w == 0x5F || w == 0x24 || w >= 0x80 -- '_' or '$'

{-# INLINE isJSIdentContW8 #-}
isJSIdentContW8 :: Word8 -> Bool
isJSIdentContW8 w = isJSIdentStartW8 w || isDigitW8 w

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

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

{-# INLINE isRegexFlagW8 #-}
isRegexFlagW8 :: Word8 -> Bool
isRegexFlagW8 w = case w of
  0x67 -> True -- g
  0x69 -> True -- i
  0x6D -> True -- m
  0x73 -> True -- s
  0x75 -> True -- u
  0x79 -> True -- y
  0x76 -> True -- v
  0x64 -> True -- d
  _    -> False

{-# INLINE isRegexFollowerW8 #-}
isRegexFollowerW8 :: Word8 -> Bool
isRegexFollowerW8 w = case w of
  0x2E -> True -- .
  0x3B -> True -- ;
  0x2C -> True -- ,
  0x29 -> True -- )
  0x5D -> True -- ]
  0x7D -> True -- }
  0x0A -> True -- \n
  _    -> False

-- | ByteString-native JS/TS/JSX tokenizer using 256-bit SIMD pre-classification
-- and zero-copy slice extraction.
tokenizeJSByteString :: BS.ByteString -> [JSToken]
tokenizeJSByteString rawBytes = go Nothing 0
  where
    !bs = case scanSourceSIMD rawBytes of
      PureAsciiUnix      -> rawBytes
      ContainsCRLF       -> BS.filter (/= 0x0D) rawBytes
      RequiresUnicodeNFC -> TE.encodeUtf8 (canonicalizeText (TE.decodeUtf8Lenient rawBytes))
    !len = BS.length bs

    {-# INLINE at #-}
    at !i = BSU.unsafeIndex bs i

    go !prevTok !i
      | i >= len = []
      | otherwise =
          let !w = at i
          in case w of
            _ | isSpaceW8 w ->
                let !(end, hasNL) = skipSpacesTrackNL (i + 1) (w == 0x0A)
                in if hasNL && shouldInsertASI prevTok
                     then TokSymbol ";" : go (Just (TokSymbol ";")) end
                     else go prevTok end
            0x2F | i + 1 < len && at (i + 1) == 0x2F -> -- //
                go prevTok (skipLineComment (i + 2))
            0x2F | i + 1 < len && at (i + 1) == 0x2A -> -- /*
                go prevTok (skipBlockComment (i + 2))
            0x2F -> -- '/' (division or regex literal)
                let !afterSlash = i + 1
                in if isDivideOp prevTok afterSlash
                     then if afterSlash < len && at afterSlash == 0x3D
                            then let !tok = TokSymbol "/="
                                 in tok : go (Just tok) (afterSlash + 1)
                            else let !tok = TokSymbol "/"
                                 in tok : go (Just tok) afterSlash
                     else case scanRegexBS afterSlash of
                            Just (pattern, flags, nextIdx) ->
                              let !regexTok = TokStr ("/" <> pattern <> "/" <> flags)
                              in regexTok : go (Just regexTok) nextIdx
                            Nothing ->
                              let !tok = TokSymbol "/"
                              in tok : go (Just tok) afterSlash
            0x22 -> -- '"'
                let !(s, nextIdx) = scanEscapedString 0x22 (i + 1)
                    !tok = TokStr s
                in tok : go (Just tok) nextIdx
            0x27 -> -- '\''
                let !(s, nextIdx) = scanEscapedString 0x27 (i + 1)
                    !tok = TokStr s
                in tok : go (Just tok) nextIdx
            0x60 -> -- '`'
                let !(s, nextIdx) = scanEscapedString 0x60 (i + 1)
                    !tok = TokStr s
                in tok : go (Just tok) nextIdx
            _ | isJSIdentStartW8 w ->
                let !end = scanWhile isJSIdentContW8 (i + 1)
                    !ident = sliceText bs i (end - i)
                    !tok = if isJSKeyword ident then TokKw ident else TokIdent ident
                in tok : go (Just tok) 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 (Just tok) end
            _ | isJSSingleSymW8 w ->
                let !tok = TokSymbol (sliceText bs i 1)
                in tok : go (Just tok) (i + 1)
            _ | isJSMultiSymW8 w ->
                let !end = scanWhile isJSMultiSymW8 (i + 1)
                    !tok = TokSymbol (sliceText bs i (end - i))
                in tok : go (Just tok) end
            _ -> go prevTok (i + 1)

    skipSpacesTrackNL !k !hasNL
      | k >= len = (k, hasNL)
      | otherwise =
          let !b = at k
          in if isSpaceW8 b
               then skipSpacesTrackNL (k + 1) (hasNL || b == 0x0A)
               else (k, hasNL)

    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)

    shouldInsertASI (Just (TokKw kw)) =
      kw == "return" || kw == "throw" || kw == "break" || kw == "continue" || kw == "yield"
    shouldInsertASI _ = False

    isDivideOp (Just (TokIdent _)) _    = True
    isDivideOp (Just (TokNum _)) _      = True
    isDivideOp (Just (TokFloat _)) _    = True
    isDivideOp (Just (TokStr _)) _      = True
    isDivideOp (Just (TokSymbol ")")) _ = True
    isDivideOp (Just (TokSymbol "]")) _ = True
    isDivideOp (Just (TokSymbol "}")) nextIdx = not (looksLikeRegexBS nextIdx)
    isDivideOp _ _                      = False

    looksLikeRegexBS !startIdx
      | startIdx >= len = False
      | otherwise =
          case scanRegexBounds startIdx of
            Nothing -> False
            Just (patLen, flagStart, flagEnd, restIdx) ->
              if patLen <= 0
                then False
                else
                  let !firstB = at startIdx
                      !flagsValid = allBytes isRegexFlagW8 flagStart flagEnd
                      !nextNonSpace = scanWhile isSpaceW8 restIdx
                      !validFollow = nextNonSpace >= len || isRegexFollowerW8 (at nextNonSpace)
                  in firstB /= 0x20 && firstB /= 0x09 && firstB /= 0x2A && firstB /= 0x3D
                       && flagsValid && validFollow

    allBytes p !a !b
      | a >= b = True
      | p (at a) = allBytes p (a + 1) b
      | otherwise = False

    scanRegexBS !startIdx = case scanRegexBounds startIdx of
      Nothing -> Nothing
      Just (patLen, flagStart, flagEnd, restIdx) ->
        let !pat = sliceText bs startIdx patLen
            !flags = sliceText bs flagStart (flagEnd - flagStart)
        in Just (pat, flags, restIdx)

    scanRegexBounds !startIdx = scanPat False False startIdx
      where
        scanPat !inCC !esc !k
          | k >= len = Nothing
          | otherwise =
              let !b = at k
              in if esc
                   then scanPat inCC False (k + 1)
                   else case b of
                     0x5C -> scanPat inCC True (k + 1) -- '\\'
                     0x5B -> scanPat True False (k + 1) -- '['
                     0x5D -> scanPat False False (k + 1) -- ']'
                     0x2F | not inCC -> -- '/'
                       let !flagStart = k + 1
                           !flagEnd = scanWhile isAlphaW8 flagStart
                       in Just (k - startIdx, flagStart, flagEnd, flagEnd)
                     0x0A -> Nothing
                     _    -> scanPat inCC False (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
                                0x74 -> 0x09
                                0x72 -> 0x0D
                                other -> other
                          in slowLoop (k + 2) (acc <> BB.word8 escByte)
                     else slowLoop (k + 1) (acc <> BB.word8 b)

jsKeywordSet :: Set Text
jsKeywordSet = Set.fromList
  [ "function", "async", "class", "interface", "type", "enum", "const", "let", "var"
  , "import", "from", "export", "default", "return", "if", "else", "while", "for"
  , "of", "in", "switch", "case", "try", "catch", "finally", "throw", "break", "continue"
  , "new", "this", "super", "extends", "implements", "static", "await", "yield", "using"
  ]

isJSKeyword :: Text -> Bool
isJSKeyword kw = Set.member kw jsKeywordSet

parseTopLevel :: FilePath -> [JSToken] -> Either ParseError ([Declaration], [ImportDecl], [Stmt])
parseTopLevel _ tokens =
  let (decls, imps, stmts) = extractDeclsAndStmts tokens
  in Right (decls, imps, stmts)

extractDeclsAndStmts :: [JSToken] -> ([Declaration], [ImportDecl], [Stmt])
extractDeclsAndStmts [] = ([], [], [])
extractDeclsAndStmts tokens = case tokens of
  -- import ... from 'mod'
  TokKw "import" : rest ->
    let (impDecl, afterImp) = parseImportItem rest
        (d, i, s) = extractDeclsAndStmts afterImp
    in (d, maybe [] pure impDecl ++ i, s)

  -- export * from 'mod' / export { a, b as c } from 'mod' (barrel re-exports)
  TokKw "export" : TokSymbol "*" : TokKw "from" : TokStr modPath : rest ->
    let afterSemi = dropWhile (\tok -> tok == TokSymbol ";") rest
        (d, i, s) = extractDeclsAndStmts afterSemi
    in (d, ImportFrom modPath ImportAll : i, s)

  TokKw "export" : TokSymbol "{" : rest
    | Just (syms, modPath, afterExp) <- parseReExportClause rest ->
        let (d, i, s) = extractDeclsAndStmts afterExp
        in (d, ImportFrom modPath (ImportSymbols syms) : i, s)

  -- export ...
  TokKw "export" : rest ->
    extractDeclsAndStmts rest

  -- function / async function
  TokKw "async" : TokKw "function" : TokIdent name : rest ->
    let (fn, afterFn) = parseFunctionBody name True rest
        (d, i, s) = extractDeclsAndStmts afterFn
    in (DeclFunction fn : d, i, s)

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

  -- class
  TokKw "class" : TokIdent name : rest ->
    let (cls, afterCls) = parseClassBody name rest
        (d, i, s) = extractDeclsAndStmts afterCls
    in (DeclClass cls : d, i, s)

  -- interface
  TokKw "interface" : TokIdent name : rest ->
    let (iface, afterIface) = parseInterfaceBody name rest
        (d, i, s) = extractDeclsAndStmts afterIface
    in (DeclInterface iface : d, i, s)

  -- type alias (with optional generic parameters)
  TokKw "type" : TokIdent name : TokSymbol "<" : rest ->
    let (gToks, afterAngle) = span (\tok -> tok /= TokSymbol ">") rest
        gParamText = "<" <> T.unwords (map jsTokenText gToks) <> ">"
        afterEq = dropWhile (\tok -> tok /= TokSymbol "=") afterAngle
        rhsToks0 = if null afterEq then [] else tail afterEq
        (rhsToks, afterSemi) = span (\tok -> tok /= TokSymbol ";") rhsToks0
        rhsText = T.unwords (map jsTokenText rhsToks)
        nextToks = if null afterSemi then [] else tail afterSemi
        (d, i, s) = extractDeclsAndStmts nextToks
    in (DeclTypeAlias name (Just (gParamText <> " = " <> rhsText)) : d, i, s)

  TokKw "type" : TokIdent name : TokSymbol "=" : rest ->
    let (rhsToks, afterType) = span (\tok -> tok /= TokSymbol ";") rest
        rhsText = T.unwords (map jsTokenText rhsToks)
        nextToks = if null afterType then [] else tail afterType
        (d, i, s) = extractDeclsAndStmts nextToks
    in (DeclTypeAlias name (if T.null rhsText then Nothing else Just rhsText) : d, i, s)

  -- const / let / var
  TokKw kw : TokIdent name : TokSymbol "=" : rest | kw `elem` ["const", "let", "var"] ->
    let (expr, afterExpr) = parseSimpleExpr rest
        stmt = StmtAssign [ExprId name] expr
        (d, i, s) = extractDeclsAndStmts afterExpr
    in (d, i, stmt : s)

  -- TypeScript 5.2: using / await using
  TokKw "using" : TokIdent name : TokSymbol "=" : rest ->
    let (expr, afterExpr) = parseSimpleExpr rest
        stmt = StmtWith [(expr, Just (ExprId name))] []
        (d, i, s) = extractDeclsAndStmts afterExpr
    in (d, i, stmt : s)

  TokKw "await" : TokKw "using" : TokIdent name : TokSymbol "=" : rest ->
    let (expr, afterExpr) = parseSimpleExpr rest
        stmt = StmtAsyncWith [(expr, Just (ExprId name))] []
        (d, i, s) = extractDeclsAndStmts afterExpr
    in (d, i, stmt : s)

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

parseImportItem :: [JSToken] -> (Maybe ImportDecl, [JSToken])
parseImportItem (TokStr modPath : rest) =
  (Just (ImportModule modPath Nothing), dropWhile (\tok -> tok == TokSymbol ";") rest)
parseImportItem tokens =
  let (clauseToks, afterClause) = span (\tok -> tok /= TokKw "from" && tok /= TokSymbol ";") tokens
  in case afterClause of
    TokKw "from" : TokStr modPath : rest ->
      let afterSemi = dropWhile (\tok -> tok == TokSymbol ";") rest
      in (Just (clauseToImport clauseToks modPath), afterSemi)
    _ ->
      let rest = dropWhile (\tok -> tok /= TokSymbol ";") tokens
      in (Nothing, if null rest then [] else tail rest)
  where
    clauseToImport toks modPath = case toks of
      [TokSymbol "*", TokIdent "as", TokIdent alias] ->
        ImportModule modPath (Just alias)
      [TokIdent defName] ->
        ImportModule modPath (Just defName)
      _ ->
        case span (\t -> t /= TokSymbol "{") toks of
          (prefix, TokSymbol "{" : inner) ->
            let (braceToks, _) = span (\t -> t /= TokSymbol "}") inner
                named = parseImportSpecifiers braceToks
                defPair = case prefix of
                  (TokIdent defName : _) -> [("default", Just defName)]
                  _                      -> []
                allSyms = defPair ++ named
            in if null allSyms
                 then ImportModule modPath Nothing
                 else ImportFrom modPath (ImportSymbols allSyms)
          _ -> ImportModule modPath Nothing

parseReExportClause :: [JSToken] -> Maybe ([(Text, Maybe Text)], Text, [JSToken])
parseReExportClause toks =
  let (innerToks, afterBrace) = span (\t -> t /= TokSymbol "}") toks
  in case afterBrace of
    TokSymbol "}" : TokKw "from" : TokStr modPath : rest ->
      let syms = parseImportSpecifiers innerToks
          afterSemi = dropWhile (\t -> t == TokSymbol ";") rest
      in if null syms then Nothing else Just (syms, modPath, afterSemi)
    _ -> Nothing

parseImportSpecifiers :: [JSToken] -> [(Text, Maybe Text)]
parseImportSpecifiers [] = []
parseImportSpecifiers (TokIdent orig : TokIdent "as" : TokIdent alias : rest) =
  (orig, Just alias) : parseImportSpecifiers (dropWhile (\t -> t == TokSymbol ",") rest)
parseImportSpecifiers (TokIdent orig : TokKw "default" : rest) =
  (orig, Just "default") : parseImportSpecifiers (dropWhile (\t -> t == TokSymbol ",") rest)
parseImportSpecifiers (TokKw "default" : TokIdent "as" : TokIdent alias : rest) =
  ("default", Just alias) : parseImportSpecifiers (dropWhile (\t -> t == TokSymbol ",") rest)
parseImportSpecifiers (TokIdent orig : rest) =
  (orig, Nothing) : parseImportSpecifiers (dropWhile (\t -> t == TokSymbol ",") rest)
parseImportSpecifiers (_ : rest) =
  parseImportSpecifiers rest

parseFunctionBody :: Text -> Bool -> [JSToken] -> (Function, [JSToken])
parseFunctionBody name isAsync tokens =
  let (params, afterParams) = parseParamList tokens
      (retType, afterRet) = case afterParams of
        TokSymbol ":" : xs ->
          let (typeToks, remToks) = span (\t -> t /= TokSymbol "{") xs
              rType = if null typeToks then Nothing else Just (T.strip (T.concat (map jsTokenText typeToks)))
          in (rType, remToks)
        xs -> (Nothing, xs)
      afterBrace = dropWhile (\t -> t /= TokSymbol "{") afterRet
      (bodyToks, afterBody) = extractBalancedBraces afterBrace
      bodyStmts = parseBodyStmts bodyToks
      fn = Function name params retType [] bodyStmts isAsync
  in (fn, afterBody)

parseClassBody :: Text -> [JSToken] -> (Class, [JSToken])
parseClassBody name tokens =
  let (bases, afterBases) = parseClassExtends tokens
      afterBrace = dropWhile (\t -> t /= TokSymbol "{") afterBases
      (bodyToks, afterBody) = extractBalancedBraces afterBrace
      methods = parseClassMethods bodyToks
      cls = Class name bases methods []
  in (cls, afterBody)

parseClassExtends :: [JSToken] -> ([Text], [JSToken])
parseClassExtends (TokKw "extends" : TokIdent base : rest) = ([base], rest)
parseClassExtends tokens = ([], tokens)

parseClassMethods :: [JSToken] -> [Function]
parseClassMethods [] = []
parseClassMethods (TokKw kw : rest) | kw `elem` ["public", "private", "protected", "readonly", "static"] =
  parseClassMethods rest
parseClassMethods (TokIdent kw : rest) | kw `elem` ["public", "private", "protected", "readonly", "static"] =
  parseClassMethods rest
parseClassMethods (TokIdent "constructor" : rest) =
  let (fn, afterFn) = parseFunctionBody "constructor" False rest
      propFns = [ Function pName [] pType ["public"] [] False
                | Parameter pName _ _ pType <- fnParams fn
                , pName /= ""
                ]
  in fn : propFns ++ parseClassMethods afterFn
parseClassMethods (TokIdent name : rest) =
  let (fn, afterFn) = parseFunctionBody name False rest
  in fn : parseClassMethods afterFn
parseClassMethods (TokKw "async" : TokIdent name : rest) =
  let (fn, afterFn) = parseFunctionBody name True rest
  in fn : parseClassMethods afterFn
parseClassMethods (_:rest) = parseClassMethods rest

parseInterfaceBody :: Text -> [JSToken] -> (Interface, [JSToken])
parseInterfaceBody name tokens =
  let (gBases, afterGen) = case tokens of
        TokSymbol "<" : rest ->
          let (gToks, afterAngle) = span (\t -> t /= TokSymbol ">") rest
              gText = "<" <> T.unwords (map jsTokenText gToks) <> ">"
              remToks = if null afterAngle then [] else tail afterAngle
          in ([gText], remToks)
        _ -> ([], tokens)
      afterBrace = dropWhile (\t -> t /= TokSymbol "{") afterGen
      (bodyToks, afterBody) = extractBalancedBraces afterBrace
      methods = parseInterfaceMethods bodyToks
  in (Interface name methods gBases, afterBody)

parseInterfaceMethods :: [JSToken] -> [Function]
parseInterfaceMethods [] = []
parseInterfaceMethods (TokIdent name : TokSymbol "(" : rest) =
  let (params, afterParams) = parseParamList (TokSymbol "(" : rest)
      (retType, afterRet) = case afterParams of
        TokSymbol ":" : xs ->
          let (typeToks, remToks) = span (\t -> t /= TokSymbol ";" && t /= TokSymbol "}") xs
              rType = if null typeToks then Nothing else Just (T.concat (map jsTokenText typeToks))
          in (rType, remToks)
        xs -> (Nothing, xs)
      afterSemi = dropWhile (\t -> t == TokSymbol ";") afterRet
      fn = Function name params retType [] [] False
  in fn : parseInterfaceMethods afterSemi
parseInterfaceMethods (TokSymbol ";" : rest) = parseInterfaceMethods rest
parseInterfaceMethods (_ : rest) = parseInterfaceMethods rest

jsTokenText :: JSToken -> Text
jsTokenText = \case
  TokIdent t  -> t
  TokKw t     -> t
  TokNum n    -> T.pack (show n)
  TokFloat f  -> T.pack (show f)
  TokStr t    -> t
  TokSymbol t -> t
  TokJSX t    -> t

parseParamList :: [JSToken] -> ([Parameter], [JSToken])
parseParamList (TokSymbol "(" : rest) =
  let (pToks, afterParen) = span (\t -> t /= TokSymbol ")") rest
      params = extractParams pToks
      remaining = if null afterParen then [] else tail afterParen
  in (params, remaining)
  where
    extractParams [] = []
    extractParams tokens =
      let (_modifiers, remToks) = span isModifier tokens
      in case remToks of
        TokIdent pName : TokSymbol ":" : xs ->
          let (typeToks, restParams) = span (\t -> t /= TokSymbol ",") xs
              pType = if null typeToks then Nothing else Just (T.concat (map jsTokenText typeToks))
              p = Parameter pName ParamPositional Nothing pType
              afterComma = if null restParams then [] else tail restParams
          in p : extractParams afterComma
        TokIdent pName : xs ->
          let p = Parameter pName ParamPositional Nothing Nothing
          in p : extractParams (dropWhile (\t -> t == TokSymbol ",") xs)
        _ : xs -> extractParams xs
        [] -> []

    isModifier (TokKw kw)   = kw `elem` ["public", "private", "protected", "readonly"]
    isModifier (TokIdent w) = w `elem` ["public", "private", "protected", "readonly"]
    isModifier _            = False
parseParamList tokens = ([], tokens)

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

parseBodyStmts :: [JSToken] -> [Stmt]
parseBodyStmts [] = []
parseBodyStmts (TokKw "using" : TokIdent name : TokSymbol "=" : rest) =
  let (expr, afterExpr) = parseSimpleExpr rest
      afterSemi = dropWhile (\t -> t == TokSymbol ";") afterExpr
      remStmts = parseBodyStmts afterSemi
  in [StmtWith [(expr, Just (ExprId name))] remStmts]
parseBodyStmts (TokKw "await" : TokKw "using" : TokIdent name : TokSymbol "=" : rest) =
  let (expr, afterExpr) = parseSimpleExpr rest
      afterSemi = dropWhile (\t -> t == TokSymbol ";") afterExpr
      remStmts = parseBodyStmts afterSemi
  in [StmtAsyncWith [(expr, Just (ExprId name))] remStmts]
parseBodyStmts (TokKw kw : TokIdent name : TokSymbol "=" : rest)
  | kw == "const" || kw == "let" || kw == "var" =
      let (expr, afterExpr) = parseSimpleExpr rest
          afterSemi = dropWhile (\t -> t == TokSymbol ";") afterExpr
      in StmtAnnAssign (ExprId name) (ExprId kw) (Just expr) : parseBodyStmts afterSemi
parseBodyStmts (TokKw "return" : TokSymbol ";" : rest) =
  StmtReturn Nothing : parseBodyStmts rest
parseBodyStmts (TokKw "return" : rest) =
  let (expr, afterExpr) = parseSimpleExpr rest
  in StmtReturn (Just expr) : parseBodyStmts (dropWhile (\t -> t == TokSymbol ";") afterExpr)
parseBodyStmts (TokKw "break" : rest) =
  StmtBreak : parseBodyStmts (dropWhile (\t -> t == TokSymbol ";") rest)
parseBodyStmts (TokKw "continue" : rest) =
  StmtContinue : parseBodyStmts (dropWhile (\t -> t == TokSymbol ";") rest)
parseBodyStmts (TokKw "throw" : rest) =
  let (expr, afterExpr) = parseSimpleExpr rest
  in StmtRaise (Just expr) Nothing : parseBodyStmts afterExpr
parseBodyStmts (_:rest) = parseBodyStmts rest

parseSingleStmt :: [JSToken] -> (Maybe Stmt, [JSToken])
parseSingleStmt (TokKw "using" : TokIdent name : TokSymbol "=" : rest) =
  let (expr, afterExpr) = parseSimpleExpr rest
  in (Just (StmtWith [(expr, Just (ExprId name))] []), dropWhile (\t -> t == TokSymbol ";") afterExpr)
parseSingleStmt (TokKw "await" : TokKw "using" : TokIdent name : TokSymbol "=" : rest) =
  let (expr, afterExpr) = parseSimpleExpr rest
  in (Just (StmtAsyncWith [(expr, Just (ExprId name))] []), dropWhile (\t -> t == TokSymbol ";") afterExpr)
parseSingleStmt (TokKw "return" : TokSymbol ";" : rest) =
  (Just (StmtReturn Nothing), rest)
parseSingleStmt (TokKw "return" : rest) =
  let (expr, afterExpr) = parseSimpleExpr rest
  in (Just (StmtReturn (Just expr)), dropWhile (\t -> t == TokSymbol ";") afterExpr)
parseSingleStmt (TokKw "break" : rest) =
  (Just StmtBreak, dropWhile (\t -> t == TokSymbol ";") rest)
parseSingleStmt (TokKw "continue" : rest) =
  (Just StmtContinue, dropWhile (\t -> t == TokSymbol ";") rest)
parseSingleStmt (TokKw "throw" : rest) =
  let (expr, afterExpr) = parseSimpleExpr rest
  in (Just (StmtRaise (Just expr) Nothing), afterExpr)
parseSingleStmt (TokIdent name : TokSymbol "(" : rest) =
  let afterParen = dropWhile (\t -> t /= TokSymbol ")") rest
      nextToks = dropWhile (\t -> t == TokSymbol ";") (if null afterParen then [] else tail afterParen)
  in (Just (StmtExpr (ExprCall (ExprId name) [] [])), nextToks)
parseSingleStmt (_:rest) = (Nothing, rest)
parseSingleStmt [] = (Nothing, [])

-- | Disambiguates TypeScript generic arrow function vs JSX tag (BUG-07).
parseSimpleExpr :: [JSToken] -> (Expr, [JSToken])
parseSimpleExpr tokens =
  let (lhs, rest) = parsePrimaryExpr tokens
  in case rest of
    TokSymbol op : afterOp | op `elem` ["+", "-", "*", "/", "%", "==", "!=", "<", ">", "<=", ">="] ->
      let (rhs, remToks) = parseSimpleExpr 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)

parsePrimaryExpr :: [JSToken] -> (Expr, [JSToken])
-- Generic arrow function: <T>(x: T): T => expr or <T, U>(a: T, b: U) => expr
parsePrimaryExpr (TokSymbol "<" : rest) =
  let (typeParams, afterAngle) = span (\t -> t /= TokSymbol ">") rest
      remainingAfterAngle = if null afterAngle then [] else tail afterAngle
  in case remainingAfterAngle of
    TokSymbol "(" : afterParenOpen ->
      -- Generic arrow function <T>(params): Ret => body
      let (params, afterParams) = parseParamList (TokSymbol "(" : afterParenOpen)
          afterArrow = dropWhile (\t -> t /= TokSymbol "=>") afterParams
          actualBodyToks = if null afterArrow then [] else tail afterArrow
      in case actualBodyToks of
        TokSymbol "{" : _ ->
          let (_, afterBody) = extractBalancedBraces actualBodyToks
          in (ExprLambda params (ExprLit LitNone), afterBody)
        _ ->
          let (bodyExpr, afterBodyExpr) = parseSimpleExpr actualBodyToks
          in (ExprLambda params bodyExpr, afterBodyExpr)
    _ ->
      -- JSX Tag: <TagName attr=val> ...
      let tagName = case typeParams of
            [TokIdent tag] -> tag
            _              -> "div"
          afterClose = dropWhile (\t -> t /= TokSymbol ";") remainingAfterAngle
      in (ExprJSX tagName [] [], afterClose)

parsePrimaryExpr (TokSymbol "(" : rest) =
  let (params, afterParams) = parseParamList (TokSymbol "(" : rest)
  in case afterParams of
    TokSymbol "=>" : afterArrow ->
      case afterArrow of
        TokSymbol "{" : _ ->
          let (_, afterBody) = extractBalancedBraces afterArrow
          in (ExprLambda params (ExprLit LitNone), afterBody)
        _ ->
          let (bodyExpr, afterBodyExpr) = parseSimpleExpr afterArrow
          in (ExprLambda params bodyExpr, afterBodyExpr)
    _ -> (ExprLit LitNone, dropWhile (\t -> t /= TokSymbol ";") rest)

-- Arrow function with single bare param: x => expr
parsePrimaryExpr (TokIdent arg : TokSymbol "=>" : rest) =
  let param = Parameter arg ParamPositional Nothing Nothing
  in case rest of
    TokSymbol "{" : _ ->
      let (_, afterBody) = extractBalancedBraces rest
      in (ExprLambda [param] (ExprLit LitNone), afterBody)
    _ ->
      let (bodyExpr, afterBodyExpr) = parseSimpleExpr rest
      in (ExprLambda [param] bodyExpr, afterBodyExpr)

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