-- | The Vibe parser: tokens to Vibe's syntax tree, by Python's grammar and precedence -- (vibe-syntax 5.2). A syntax error is a numbered diagnostic (B0101 and the shared syntax -- codes); parsing stops at the first one. module Verada.Vibe.Parser ( parseModule ) where import Verada.Diagnostics (Diagnostic (..), Label (..), Phase (..), diagnostic) import Verada.Diagnostics.Codes (DiagCode (..)) import Verada.Vibe.Lexer (lexSource) import Verada.Vibe.Syntax import Verada.Vibe.Token (Keyword (..), Token (..), TokenKind (..), describeToken) import Verada.Result (Result (..)) import Verada.Source (SourceFile (..), Span (..), mkSourceFile) import Verada.Syntax.ParseDiagnostic (ContextToken (..), TokenRole (..), expectedSummary, withSyntaxContext) import Verada.Syntax.Stream (TokenStream (..), tokenStream) import Control.Monad (join, void) import Data.ByteString qualified as ByteString import Data.Functor (($>)) import Data.List.NonEmpty qualified as NonEmpty import Data.Maybe (fromMaybe, isJust) import Data.Set qualified as Set import Data.Text (Text) import Data.Text qualified as Text import Data.Text.Encoding (decodeUtf8Lenient) import Data.Void (Void) import Text.Megaparsec ((<|>)) import Text.Megaparsec qualified as M type Parser = M.Parsec Void (TokenStream Token) -- | A Vibe file's syntax tree, with every lexical and syntax error. parseModule :: SourceFile -> Result Module parseModule sf = case filter (not . inAplText) lexed.diagnostics of ds@(_ : _) -> Result {diagnostics = ds, value = Nothing} [] -> case M.runParser (moduleP <* M.eof) sf.path (tokenStream tokens) of Right m -> Result {diagnostics = [], value = Just m} Left bundle -> Result {diagnostics = [convert (NonEmpty.head (M.bundleErrors bundle))], value = Nothing} where lexed = lexSource sf tokens = fromMaybe [] lexed.value -- (APL's glyphs are an `apl("...")` string's own, which is APL text, not a Latin-1 -- string: apl-variant.md 5.4) aplTexts = [t.span | (Token {kind = Name "apl"}, Token {kind = Op "("}, t@Token {kind = StringLiteral _}) <- zip3 tokens (drop 1 tokens) (drop 2 tokens)] inAplText d = d.code == NonLatin1Literal && maybe False (\l -> any (\a -> a.start <= l.span.start && l.span.end <= a.end) aplTexts) d.primary tokenAt i = case drop i tokens of t : _ -> Just t [] -> Nothing convert err = let offset = M.errorOffset err eof = ByteString.length sf.bytes (s, found) = case tokenAt offset of Just t -> (t.span, describeToken t.kind) Nothing -> (Span {file = sf.fileId, start = eof, end = eof}, "the end of the file") wanted = case err of M.TrivialError _ _ expected -> [Text.pack (NonEmpty.toList cs) | M.Label cs <- Set.toList expected] _ -> [] message = maybe ("unexpected " <> found) (\w -> "expected " <> w <> ", found " <> found) (expectedSummary wanted) base = (diagnostic UnexpectedToken Syntax message) {primary = Just Label {span = s, text = Just "unexpected here"}} in withSyntaxContext sf (map contextToken tokens) offset wanted validates base validates bytes = let candidate = lexSource (mkSourceFile sf.fileId sf.path bytes) in null candidate.diagnostics && case candidate.value of Just ts -> case M.runParser (moduleP <* M.eof) sf.path (tokenStream ts) of Right _ -> True Left _ -> False Nothing -> False contextToken t = ContextToken {sourceSpan = t.span, spelling, role} where spelling = case t.kind of Newline -> "\n" EndOfInput -> "" _ -> decodeUtf8Lenient (ByteString.take (t.span.end - t.span.start) (ByteString.drop t.span.start sf.bytes)) role = case t.kind of Name _ -> NameToken StringLiteral _ -> ValueToken IntLiteral _ -> ValueToken FloatLiteral _ _ -> ValueToken Reserved k | k `elem` [KwTrue, KwFalse, KwNone] -> ValueToken Newline -> BoundaryToken Indent -> BoundaryToken Dedent -> BoundaryToken EndOfInput -> BoundaryToken Op ";" -> BoundaryToken _ -> OtherToken -- * Tokens satisfyKind :: (TokenKind -> Maybe a) -> Parser a satisfyKind f = M.token (\t -> f t.kind) Set.empty op :: Text -> Parser Span op o = M.label ("`" <> Text.unpack o <> "`") (M.token (\t -> if t.kind == Op o then Just t.span else Nothing) Set.empty) kw :: Keyword -> Parser Span kw k = M.token (\t -> if t.kind == Reserved k then Just t.span else Nothing) Set.empty name :: Parser (Text, Span) name = M.label "a name" (M.token (\t -> case t.kind of Name n -> Just (n, t.span); _ -> Nothing) Set.empty) -- | A soft keyword: a name spelt so. soft :: Text -> Parser Span soft w = M.token (\t -> if t.kind == Name w then Just t.span else Nothing) Set.empty newline :: Parser () newline = M.label "the end of the line" (void (satisfyKind (\case Newline -> Just (); _ -> Nothing))) indent, dedent :: Parser () indent = M.label "an indented block" (void (satisfyKind (\case Indent -> Just (); _ -> Nothing))) dedent = void (satisfyKind (\case Dedent -> Just (); _ -> Nothing)) endOfInput :: Parser () endOfInput = void (satisfyKind (\case EndOfInput -> Just (); _ -> Nothing)) -- | The span from the first to the last of two spans. joinSpans :: Span -> Span -> Span joinSpans a b = a {end = max a.end b.end} -- * Statements moduleP :: Parser Module moduleP = do stmts <- concat <$> M.many statement endOfInput pure Module {body = stmts} statement :: Parser [PyStmt] statement = (pure <$> compound) <|> simpleStatements simpleStatements :: Parser [PyStmt] simpleStatements = do first <- small rest <- M.many (M.try (op ";" *> small)) _ <- M.optional (op ";") newline pure (first : rest) block :: Parser [PyStmt] block = do _ <- op ":" (newline *> indent *> (concat <$> M.some statement) <* dedent) <|> simpleStatements small :: Parser PyStmt small = M.choice [ simple Pass <$> kw KwPass , simple Break <$> kw KwBreak , simple Continue <$> kw KwContinue , returnStmt , raiseStmt , delStmt , assertStmt , importStmt , fromImport , scopeDeclaration , M.try typeAlias , expressionStatement ] where simple n s = PyStmt {span = s, node = n} returnStmt :: Parser PyStmt returnStmt = do s <- kw KwReturn v <- M.optional testList pure PyStmt {span = maybe s (joinSpans s . (.span)) v, node = Return v} raiseStmt :: Parser PyStmt raiseStmt = do s <- kw KwRaise v <- M.optional expression pure PyStmt {span = maybe s (joinSpans s . (.span)) v, node = Raise v} delStmt :: Parser PyStmt delStmt = do s <- kw KwDel xs <- M.sepBy1 expression (op ",") pure PyStmt {span = joinSpans s (lastSpan s xs), node = Del xs} assertStmt :: Parser PyStmt assertStmt = do s <- kw KwAssert c <- expression m <- M.optional (op "," *> expression) pure PyStmt {span = joinSpans s (maybe c.span (.span) m), node = Assert c m} dotted :: Parser ([Text], Span) dotted = do parts <- M.sepBy1 name (op ".") s <- maybe M.empty pure (spansOf parts) pure (map fst parts, s) importStmt :: Parser PyStmt importStmt = do s <- kw KwImport (path, e) <- dotted alias <- M.optional (kw KwAs *> name) pure PyStmt {span = joinSpans s (maybe e snd alias), node = Import path (fst <$> alias)} fromImport :: Parser PyStmt fromImport = do s <- kw KwFrom (path, _) <- dotted _ <- kw KwImport parenthesised <- isJust <$> M.optional (op "(") items <- M.sepEndBy1 ((,) <$> (name <|> ((\sp -> ("*", sp)) <$> op "*")) <*> M.optional (kw KwAs *> name)) (op ",") e <- if parenthesised then op ")" else maybe M.empty (pure . snd . fst) (lastMaybe items) pure PyStmt {span = joinSpans s e, node = FromImport path [(fst n, fst <$> a) | (n, a) <- items]} typeAlias :: Parser PyStmt typeAlias = do s <- soft "type" (n, _) <- name _ <- op "=" v <- expression pure PyStmt {span = joinSpans s v.span, node = TypeAlias n v} expressionStatement :: Parser PyStmt expressionStatement = do first <- testList M.choice [ do _ <- op ":" annotation <- expression v <- M.optional (op "=" *> testList) pure PyStmt {span = joinSpans first.span (maybe annotation.span (.span) v), node = AnnAssign first annotation v} , do o <- M.choice [augmented a | a <- ["+=", "-=", "*=", "/=", "//=", "%=", "**=", "&=", "|=", "^=", "<<=", ">>="]] v <- testList pure PyStmt {span = joinSpans first.span v.span, node = AugAssign first o v} , do values <- M.some (op "=" *> testList) value <- maybe M.empty pure (lastMaybe values) let targets = first : take (length values - 1) values pure PyStmt {span = joinSpans first.span value.span, node = Assign targets value} , pure PyStmt {span = first.span, node = ExprStmt first} ] where augmented a = op a $> Text.dropEnd 1 a compound :: Parser PyStmt compound = M.choice [ifStmt, whileStmt, forStmt, tryStmt, withStmt, asyncStmt, decorated, functionDef [], classDef [], M.try matchStmt] -- | @with a as b, c:@ and its block. withStmt :: Parser PyStmt withStmt = do s <- kw KwWith items <- M.sepBy1 ((,) <$> expression <*> M.optional (kw KwAs *> bitOr)) (op ",") b <- block -- (its span is its first line's, which a diagnostic about it marks) let header = joinSpans s (maybe s (\(v, t) -> maybe v.span (.span) t) (lastMaybe items)) pure PyStmt {span = header, node = With items b} -- * Python's statements that Vibe excludes (vibe-syntax section 8): each parsed whole, so -- that it is one diagnostic that says why, and the file is read on past it -- | @async def@, @async for@, @async with@. asyncStmt :: Parser PyStmt asyncStmt = do s <- kw KwAsync inner <- functionDef [] <|> forStmt <|> withStmt pure PyStmt {span = s, node = ExcludedStmt asyncReason [inner]} asyncReason :: Text asyncReason = "`async` and `await` are not in Vibe: Verada's concurrency is tasks (`@task`) and protected objects (a class of `Protected`), which the prover checks" -- | @global x@ (the module's variable, which the function assigns) and @nonlocal x@. scopeDeclaration :: Parser PyStmt scopeDeclaration = do (s, isGlobal) <- ((,True) <$> kw KwGlobal) <|> ((,False) <$> kw KwNonlocal) names <- M.sepBy1 name (op ",") let whole = joinSpans s (maybe s snd (lastMaybe names)) pure PyStmt {span = whole, node = if isGlobal then Global names else Nonlocal names} ifStmt :: Parser PyStmt ifStmt = do s <- kw KwIf c <- namedExpression b <- block elifs <- M.many ((,) <$> (kw KwElif *> namedExpression) <*> block) e <- M.option [] (kw KwElse *> block) pure PyStmt {span = joinSpans s (lastStmtSpan s (b <> concatMap snd elifs <> e)), node = If ((c, b) : elifs) e} whileStmt :: Parser PyStmt whileStmt = do s <- kw KwWhile c <- namedExpression b <- block e <- M.option [] (kw KwElse *> block) pure PyStmt {span = joinSpans s (lastStmtSpan s (b <> e)), node = While c b e} tryStmt :: Parser PyStmt tryStmt = do s <- kw KwTry b <- block clauses <- M.many do cs <- kw KwExcept what <- M.optional expression as <- M.optional (kw KwAs *> name) body <- block pure ExceptClause {span = joinSpans cs (lastStmtSpan cs body), exceptions = what, name = fst <$> as, body} orElse <- M.option [] (kw KwElse *> block) final <- M.option [] (kw KwFinally *> block) let ending = case (final <> orElse, reverse clauses) of (later@(_ : _), _) -> lastStmtSpan s later ([], c : _) -> c.span ([], []) -> lastStmtSpan s b pure PyStmt {span = joinSpans s ending, node = Try b clauses orElse final} forStmt :: Parser PyStmt forStmt = do s <- kw KwFor t <- targetList _ <- kw KwIn src <- testList b <- block e <- M.option [] (kw KwElse *> block) pure PyStmt {span = joinSpans s (lastStmtSpan s (b <> e)), node = For t src b e} matchStmt :: Parser PyStmt matchStmt = do s <- soft "match" subject <- testList _ <- op ":" newline indent cases <- M.some caseClause dedent pure PyStmt {span = joinSpans s (lastStmtSpan s (concatMap (.body) cases)), node = Match subject cases} where caseClause = do _ <- soft "case" p <- orExpression g <- M.optional (kw KwIf *> expression) b <- block pure MatchCase {pattern = p, guard = g, body = b} decorated :: Parser PyStmt decorated = do ds <- M.some (op "@" *> expression <* newline) functionDef ds <|> classDef ds functionDef :: [PyExpr] -> Parser PyStmt functionDef decorators = do s <- kw KwDef (n, ns) <- name tps <- M.option [] (op "[" *> M.sepEndBy1 typeParameter (op ",") <* op "]") _ <- op "(" ps <- M.sepEndBy parameter (op ",") _ <- op ")" r <- M.optional (op "->" *> expression) b <- block pure PyStmt {span = joinSpans s (lastStmtSpan s b), node = FunctionStmt FunctionDef {name = n, nameSpan = ns, decorators, typeParameters = tps, parameters = ps, returns = r, body = b}} where parameter = do (pn, ps) <- name <|> ((\sp -> ("/", sp)) <$> op "/") <|> starred "*" <|> starred "**" a <- M.optional (op ":" *> expression) d <- M.optional (op "=" *> expression) pure Parameter {span = ps, name = pn, annotation = a, defaultValue = d} -- (`*` alone, a marker, or `*args`; `**kwargs`) starred o = do sp <- op o named <- M.optional name pure case named of Just (n, e) -> (o <> n, joinSpans sp e) Nothing -> (o, sp) -- | PEP 695's type parameter, `T` or `T: Bound`. typeParameter :: Parser (Text, Span, Maybe Text) typeParameter = do (t, sp) <- name bound <- M.optional (op ":" *> name) pure (t, sp, fst <$> bound) classDef :: [PyExpr] -> Parser PyStmt classDef decorators = do s <- kw KwClass (n, ns) <- name tps <- M.option [] (op "[" *> M.sepEndBy1 typeParameter (op ",") <* op "]") args <- M.option [] (op "(" *> M.sepEndBy argument (op ",") <* op ")") b <- block pure PyStmt { span = joinSpans s (lastStmtSpan s b) , node = ClassStmt ClassDef {name = n, nameSpan = ns, typeParameters = tps, decorators, bases = [a.value | a <- args, Nothing <- [a.keyword]], keywords = [(k, a.value) | a <- args, Just k <- [a.keyword]], body = b} } -- * Expressions -- | Expressions joined by commas: a tuple without parentheses (@a, b = b, a@). testList :: Parser PyExpr testList = do first <- item rest <- M.many (M.try (op "," *> item)) trailing <- isJust <$> M.optional (op ",") pure case rest of [] | not trailing -> first _ -> PyExpr {span = joinSpans first.span (lastSpan first.span rest), node = TupleLit (first : rest)} where -- (`*rest` among a tuple's items: a starred target, `a, *rest = xs`) item = starred <|> namedExpression starred = do s <- op "*" v <- bitOr pure PyExpr {span = joinSpans s v.span, node = Starred v} -- | Assignment targets of a @for@: names or a tuple of names. targetList :: Parser PyExpr targetList = do first <- bitOr rest <- M.many (M.try (op "," *> bitOr)) pure case rest of [] -> first _ -> PyExpr {span = joinSpans first.span (lastSpan first.span rest), node = TupleLit (first : rest)} -- | An expression, or @n := e@ (the walrus), which binds n to e's value. namedExpression :: Parser PyExpr namedExpression = walrus <|> expression where walrus = do (n, s) <- M.try (name <* op ":=") v <- expression pure PyExpr {span = joinSpans s v.span, node = NamedExpr n v} expression :: Parser PyExpr expression = lambdaExpression <|> yieldExpression <|> conditional -- | @yield e@ and @yield from e@: a generator's, which Vibe excludes. yieldExpression :: Parser PyExpr yieldExpression = do s <- kw KwYield _ <- M.optional (kw KwFrom) v <- M.optional testList pure PyExpr {span = maybe s (joinSpans s . (.span)) v, node = ExcludedExpr "`yield` is not in Vibe: a Vibe function returns once, with its result; build a `list` and return it, or loop over a container where the values are used" (maybe [] pure v)} lambdaExpression :: Parser PyExpr lambdaExpression = do s <- kw KwLambda ps <- M.sepBy (fst <$> name) (op ",") _ <- op ":" body <- expression pure PyExpr {span = joinSpans s body.span, node = Lambda ps body} conditional :: Parser PyExpr conditional = do v <- orExpression M.option v do _ <- kw KwIf c <- orExpression _ <- kw KwElse e <- expression pure PyExpr {span = joinSpans v.span e.span, node = IfExp c v e} orExpression :: Parser PyExpr orExpression = boolChain KwOr "or" andExpression andExpression :: Parser PyExpr andExpression = boolChain KwAnd "and" notExpression boolChain :: Keyword -> Text -> Parser PyExpr -> Parser PyExpr boolChain k o next = do first <- next rest <- M.many (kw k *> next) pure case rest of [] -> first _ -> PyExpr {span = joinSpans first.span (lastSpan first.span rest), node = BoolOp o (first : rest)} notExpression :: Parser PyExpr notExpression = ( do s <- kw KwNot x <- notExpression pure PyExpr {span = joinSpans s x.span, node = UnaryOp "not" x} ) <|> comparison comparison :: Parser PyExpr comparison = do first <- bitOr rest <- M.many ((,) <$> comparator <*> bitOr) pure case rest of [] -> first _ -> PyExpr {span = joinSpans first.span (maybe first.span ((.span) . snd) (lastMaybe rest)), node = Compare first rest} where comparator = M.choice [ op "<" $> "<" , op ">" $> ">" , op "==" $> "==" , op ">=" $> ">=" , op "<=" $> "<=" , op "!=" $> "!=" , M.try (kw KwNot *> kw KwIn) $> "not in" , kw KwIn $> "in" , M.try (kw KwIs *> kw KwNot) $> "is not" , kw KwIs $> "is" ] binaryLevel :: [Text] -> Parser PyExpr -> Parser PyExpr binaryLevel ops next = do first <- next rest <- M.many ((,) <$> M.choice [op o $> o | o <- ops] <*> next) pure (foldl (\l (o, r) -> PyExpr {span = joinSpans l.span r.span, node = BinOp o l r}) first rest) bitOr, bitXor, bitAnd, shiftExpr, arith, term :: Parser PyExpr bitOr = binaryLevel ["|"] bitXor bitXor = binaryLevel ["^"] bitAnd bitAnd = binaryLevel ["&"] shiftExpr shiftExpr = binaryLevel ["<<", ">>"] arith arith = binaryLevel ["+", "-"] term term = binaryLevel ["*", "/", "//", "%", "@"] factor factor :: Parser PyExpr factor = ( do (o, s) <- M.choice [(,) "-" <$> op "-", (,) "+" <$> op "+", (,) "~" <$> op "~"] x <- factor pure PyExpr {span = joinSpans s x.span, node = UnaryOp o x} ) <|> power -- | @**@ binds tighter than unary minus on its left and is right-associative. power :: Parser PyExpr power = do b <- awaited <|> primary M.option b do _ <- op "**" e <- factor pure PyExpr {span = joinSpans b.span e.span, node = BinOp "**" b e} -- | @await e@, which Vibe excludes. awaited :: Parser PyExpr awaited = do s <- kw KwAwait v <- primary pure PyExpr {span = joinSpans s v.span, node = ExcludedExpr asyncReason [v]} primary :: Parser PyExpr primary = do a <- atom trailers a where trailers x = M.option x $ M.choice [ do _ <- op "(" args <- M.sepEndBy argument (op ",") e <- op ")" trailers PyExpr {span = joinSpans x.span e, node = Call x args} , do _ <- op "[" is <- M.sepEndBy1 subscriptItem (op ",") e <- op "]" trailers PyExpr {span = joinSpans x.span e, node = Subscript x is} , do _ <- op "." (n, e) <- name trailers PyExpr {span = joinSpans x.span e, node = Attribute x n} ] subscriptItem = do s <- M.getInput let startSpan = case s.tokens of t : _ -> t.span [] -> Span {file = undefinedFile, start = 0, end = 0} undefinedFile = case s.previous of Just t -> t.span.file Nothing -> startSpan.file lo <- M.optional expression colon <- M.optional (op ":") case colon of Nothing -> maybe (M.fancyFailure Set.empty) pure lo Just c -> do hi <- M.optional expression step <- M.optional (op ":" *> M.optional expression) let ending = case (step, hi) of (Just (Just x), _) -> x.span (_, Just x) -> x.span _ -> c pure PyExpr {span = joinSpans (maybe startSpan (.span) lo) ending, node = Slice lo hi (join step)} argument :: Parser Argument argument = unpacked <|> M.try ( do (k, _) <- name _ <- op "=" v <- expression pure Argument {keyword = Just k, value = v} ) <|> do v <- expression -- a generator as the only argument: `all(p for x in xs)` M.option Argument {keyword = Nothing, value = v} do cs <- M.some comprehension pure Argument {keyword = Nothing, value = PyExpr {span = v.span, node = GeneratorExp v cs}} -- | @*xs@ and @**d@ in a call: argument unpacking, which Vibe excludes. unpacked :: Parser Argument unpacked = do (o, s) <- ((,) "*" <$> op "*") <|> ((,) "**" <$> op "**") v <- expression pure Argument {keyword = Nothing, value = PyExpr {span = joinSpans s v.span, node = ExcludedExpr ("argument unpacking (`" <> o <> "`) is not in Vibe: a Vibe call passes each argument, by position or by name") [v]}} comprehension :: Parser Comprehension comprehension = do _ <- kw KwFor t <- targetList _ <- kw KwIn s <- orExpression cs <- M.many (kw KwIf *> orExpressionNoCond) pure Comprehension {target = t, source = s, conditions = cs} where orExpressionNoCond = orExpression atom :: Parser PyExpr atom = M.label "an expression" $ M.choice [ (\(n, s) -> PyExpr {span = s, node = NameRef n}) <$> name , M.token (\t -> case t.kind of IntLiteral v -> Just PyExpr {span = t.span, node = IntLit v}; _ -> Nothing) Set.empty , M.token (\t -> case t.kind of FloatLiteral v w -> Just PyExpr {span = t.span, node = FloatLit v w}; _ -> Nothing) Set.empty , strings , fstring , (\s -> PyExpr {span = s, node = BoolLit True}) <$> kw KwTrue , (\s -> PyExpr {span = s, node = BoolLit False}) <$> kw KwFalse , (\s -> PyExpr {span = s, node = NoneLit}) <$> kw KwNone , (\s -> PyExpr {span = s, node = NameRef "..."}) <$> op "..." , parenthesised , listDisplay , braceDisplay ] where -- adjacent strings are one string strings = do parts <- M.some (M.token (\t -> case t.kind of StringLiteral v -> Just (v, t.span); _ -> Nothing) Set.empty) s <- maybe M.empty pure (spansOf parts) pure PyExpr {span = s, node = StrLit (mconcat (map fst parts))} -- `f"text {e} text"`: its text and fields in order fstring = do s <- M.token (\t -> case t.kind of FStringStart -> Just t.span; _ -> Nothing) Set.empty parts <- concat <$> M.many ((pure <$> textPart) <|> fieldPart) e <- M.token (\t -> case t.kind of FStringEnd -> Just t.span; _ -> Nothing) Set.empty pure PyExpr {span = joinSpans s e, node = FString parts} textPart = M.token (\t -> case t.kind of FStringMiddle v -> Just (Left v); _ -> Nothing) Set.empty -- (`{x=}` writes the field's text, then the value: its repr, unless a conversion or a -- spec says otherwise) fieldPart = do _ <- op "{" v <- expression debug <- M.optional (M.token (\t -> case t.kind of FStringDebug d -> Just d; _ -> Nothing) Set.empty) conversion <- M.optional (M.token (\t -> case t.kind of FStringConversion c -> Just c; _ -> Nothing) Set.empty) spec <- M.optional (M.token (\t -> case t.kind of FStringSpec f -> Just f; _ -> Nothing) Set.empty) e <- op "}" let conversion' = case (debug, conversion, spec) of (Just _, Nothing, Nothing) -> Just 'r' _ -> conversion field = case (conversion', spec) of (Nothing, Nothing) -> v _ -> PyExpr {span = joinSpans v.span e, node = FormatField v conversion' spec} pure (maybe [Right field] (\d -> [Left d, Right field]) debug) -- `{}` and `{k: v, ...}` are dicts, `{a, b}` a set braceDisplay = do s <- op "{" M.choice [ do e <- op "}" pure PyExpr {span = joinSpans s e, node = DictLit []} , do first <- expression M.choice [ do _ <- op ":" v <- expression M.choice [ do cs <- M.some comprehension e <- op "}" pure PyExpr {span = joinSpans s e, node = DictComp first v cs} , do more <- M.many (M.try (op "," *> ((,) <$> expression <* op ":" <*> expression))) _ <- M.optional (op ",") e <- op "}" pure PyExpr {span = joinSpans s e, node = DictLit ((first, v) : more)} ] , do cs <- M.some comprehension e <- op "}" pure PyExpr {span = joinSpans s e, node = SetComp first cs} , do rest <- M.many (M.try (op "," *> expression)) _ <- M.optional (op ",") e <- op "}" pure PyExpr {span = joinSpans s e, node = SetLit (first : rest)} ] ] parenthesised = do s <- op "(" M.choice [ do e <- op ")" pure PyExpr {span = joinSpans s e, node = TupleLit []} , do first <- namedExpression M.choice [ do cs <- M.some comprehension e <- op ")" pure PyExpr {span = joinSpans s e, node = GeneratorExp first cs} , do rest <- M.many (M.try (op "," *> expression)) trailing <- isJust <$> M.optional (op ",") e <- op ")" pure case rest of [] | not trailing -> PyExpr {span = joinSpans s e, node = first.node} _ -> PyExpr {span = joinSpans s e, node = TupleLit (first : rest)} ] ] -- (`[*xs, 4]`: a starred element, each of xs's in turn) starredElement = do s <- op "*" v <- bitOr pure PyExpr {span = joinSpans s v.span, node = Starred v} listDisplay = do s <- op "[" M.choice [ do e <- op "]" pure PyExpr {span = joinSpans s e, node = ListLit []} , do first <- starredElement <|> expression M.choice [ do cs <- M.some comprehension e <- op "]" pure PyExpr {span = joinSpans s e, node = ListComp first cs} , do rest <- M.many (M.try (op "," *> (starredElement <|> expression))) _ <- M.optional (op ",") e <- op "]" pure PyExpr {span = joinSpans s e, node = ListLit (first : rest)} ] ] -- * Lists lastMaybe :: [a] -> Maybe a lastMaybe = foldl (\_ x -> Just x) Nothing -- | The span from the first to the last of spanned items. spansOf :: [(a, Span)] -> Maybe Span spansOf xs = case (xs, lastMaybe xs) of ((_, a) : _, Just (_, b)) -> Just (joinSpans a b) _ -> Nothing lastSpan :: Span -> [PyExpr] -> Span lastSpan d xs = case reverse xs of x : _ -> x.span [] -> d lastStmtSpan :: Span -> [PyStmt] -> Span lastStmtSpan d xs = case reverse xs of x : _ -> x.span [] -> d