-- | Recursive descent expression parser for the Nix language.---- Precedence levels, lowest (top) to highest (deepest), as upstream-- Nix's grammar declares them:---- @-- lambda / -> / || / && / == != / < > <= >= / //-- ! / + - / * \\/ / ++ / ? / negate / application / selection-- @---- The infix operators are read by precedence climbing ('parseBounded'),-- and a prefix operator's operand runs as far as the operators tighter-- than it, as upstream Nix's parser reads one: @-x ? a@ is @(-x) ? a@,-- and @a + !b + c@ is @a + !(b + c)@.-- Entirely pure. No IO, no Megaparsec, no Parsec.---- The parser notes each name ('recordName') where upstream's parser-- interns one, in the order it does. Bison runs a rule's action once-- the rule's whole right-hand side is parsed, so a name a rule's own-- action interns comes after the names inside it: a function's argument-- after its body, a formal after its default. Upstream's GLR parser-- defers the actions of a split stack and runs them in that same order-- once one reading survives (glr.c in bison 3.8), so a split never-- changes the order. A reading this parser backtracks out of drops its-- names with it.module Nix.Parser.Expr ( -- * Entry point parseTopLevel, -- * Expression parsers (exported for testing) parseExpr, )whereimport Control.Monad (foldM, when)import Data.ByteString (ByteString)import Data.Map.Strict (Map)import qualified Data.Map.Strict as Mapimport Data.Text (Text)import qualified Data.Text.Encoding as TEimport Nix.Expr.Typesimport Nix.Parser.Internalimport Nix.Parser.Lexer (Token (..))import Nix.Parser.ParseError (ParseError (..))-- ----------------------------------------------------------------------------- Top level-- ----------------------------------------------------------------------------- | Parse a complete Nix file (one expression, then EOF).parseTopLevel :: Parser ExprparseTopLevel = do expr <- parseExpr done <- atEnd if done then pure expr else do tok <- peek parseError ("unexpected " <> showToken tok <> " after expression")-- ----------------------------------------------------------------------------- Expression (entry point for precedence climbing)-- ----------------------------------------------------------------------------- | Parse a full expression. Tries lambda first, falls back to implication.parseExpr :: Parser ExprparseExpr = do tok <- peek case tok of TokLBrace -> parseLambdaOrAttrSet TokIdent _ -> parseLambdaOrIdent _ -> parseOperators-- ----------------------------------------------------------------------------- Lambda detection-- ----------------------------------------------------------------------------- | Identifier at start: could be @x: body@ or @name\@{...}: body@ or just expr.-- A lambda header (@ident :@, or @ident \@ { formals } :@) is-- grammatically unambiguous, so once one parses we are committed and a-- failure in the body propagates from where it happened; it must not-- backtrack into the expression reading, whose partial success would-- otherwise leave the outer parser complaining at the stray colon.-- When no reading parses, the deepest failure is the one reported.parseLambdaOrIdent :: Parser ExprparseLambdaOrIdent = do simple <- tryParserKeepError trySimpleLambdaHeader case simple of Right body -> body Left simpleErr -> do named <- tryParserKeepError tryNamedSetLambdaHeader case named of Right body -> body Left namedErr -> do plain <- tryParserKeepError parseOperators case plain of Right e -> pure e Left plainErr -> failWithError (deeperError simpleErr (deeperError namedErr plainErr))-- | The header of @x: body@; on success, returns the committed body parse.-- The argument's name is noted after the body's names, as upstream's-- rule interns it (@expr_function@ in parser.y).trySimpleLambdaHeader :: Parser (Parser Expr)trySimpleLambdaHeader = do name <- expectIdent expect TokColon pure ((\body -> ELambda (FormalName name) body NoCaptureInfo) <$> parseExpr <* recordName name)-- | The header of @name\@{ formals }: body@; on success, returns the-- committed body parse. The name is noted after the formals' and the-- body's names, as upstream's rule interns it (@expr_function@ in-- parser.y).tryNamedSetLambdaHeader :: Parser (Parser Expr)tryNamedSetLambdaHeader = do name <- expectIdent expect TokAt expect TokLBrace (formals, hasEllipsis) <- parseFormalsBody expect TokColon pure ((\body -> ELambda (FormalNamedSet name formals hasEllipsis) body NoCaptureInfo) <$> parseExpr <* recordName name)-- | Brace at start: could be @{ formals }: body@, @{ formals }\@name: body@, or attr set.-- Same commitment rule as 'parseLambdaOrIdent': @... } :@ and-- @... } \@ name :@ never follow an attr set, so a parsed lambda-- header commits, and a body failure is reported from its own-- position (so a real error at line 410 of a formals-lambda file is not-- reported as an attr-set complaint at line 2). When both readings-- fail, the deeper failure wins, so a malformed formal beats the-- attr-set branch's earlier stumble over the first comma.parseLambdaOrAttrSet :: Parser ExprparseLambdaOrAttrSet = do headed <- tryParserKeepError trySetLambdaHeader case headed of Right body -> body Left lambdaErr -> do alt <- tryParserKeepError parseOperators case alt of Right e -> pure e Left attrErr -> failWithError (deeperError lambdaErr attrErr)-- | The header of @{ a, b ? default, ... }: body@ or-- @{ a, b }\@name: body@; on success, returns the committed body parse.-- An \@-name is noted after the formals' and the body's names, as-- upstream's rule interns it (@expr_function@ in parser.y).trySetLambdaHeader :: Parser (Parser Expr)trySetLambdaHeader = do expect TokLBrace (formals, hasEllipsis) <- parseFormalsBody -- Check for @name after the closing brace tok <- peek case tok of TokColon -> do _ <- advance pure ((\body -> ELambda (FormalSet formals hasEllipsis) body NoCaptureInfo) <$> parseExpr) TokAt -> do _ <- advance name <- expectIdent expect TokColon pure ((\body -> ELambda (FormalNamedSet name formals hasEllipsis) body NoCaptureInfo) <$> parseExpr <* recordName name) _ -> parseError ("expected ':' or '@' after formals, got " <> showToken tok)-- | Parse the inside of @{ ... }@ formals (comma-separated, optional defaults,-- optional ellipsis). Expects the closing @}@.parseFormalsBody :: Parser ([Formal], Bool)parseFormalsBody = do tok <- peek case tok of TokRBrace -> do _ <- advance pure ([], False) TokEllipsis -> do _ <- advance expect TokRBrace pure ([], True) _ -> parseFormalsList []parseFormalsList :: [Formal] -> Parser ([Formal], Bool)parseFormalsList acc = do name <- expectIdent -- Upstream rejects a repeated formal name at parse time. when (any ((== name) . fName) acc) $ parseError ("duplicate formal function argument '" <> name <> "'") -- Check for default value hasDefault <- match TokQuestion defVal <- if hasDefault then Just <$> parseExpr else pure Nothing -- Upstream interns a formal's name once the formal, its default -- included, is parsed (the formal rule of parser.y). recordName name let formal = Formal {fName = name, fDefault = defVal} newAcc = formal : acc tok <- peek case tok of TokComma -> do _ <- advance -- Check for ellipsis after comma next <- peek case next of TokEllipsis -> do _ <- advance expect TokRBrace pure (reverse newAcc, True) TokRBrace -> do _ <- advance pure (reverse newAcc, False) _ -> parseFormalsList newAcc TokRBrace -> do _ <- advance pure (reverse newAcc, False) _ -> parseError ("expected ',' or '}' in formals, got " <> showToken tok)-- ----------------------------------------------------------------------------- Operators-- ----------------------------------------------------------------------------- | How tightly an operator binds, loosest first: the precedence each-- operator of upstream Nix's grammar declares.data Level = LevelImplication | LevelOr | LevelAnd | LevelEquality | LevelComparison | LevelUpdate | LevelNot | LevelAddition | LevelMultiplication | LevelConcat | LevelHasAttr | LevelNegate deriving (Eq, Ord)-- | How an infix operator meets another of its own level: grouped to the-- left, grouped to the right, or refused.data Grouping = GroupsLeft | GroupsRight | GroupsNone-- | What an infix operator builds from its left operand and what follows.data Operation = -- | A binary operator over two expressions. Binary !BinaryOp | -- | @?@, whose right operand is an attribute path. Nothing can follow -- an attribute path inside it, so a @?@ after one applies to the -- whole, as it does upstream, where the grammar's no-chaining rule for -- @?@ never meets a second one: @a ? b ? c@ is @(a ? b) ? c@. HasAttr-- | An infix operator: its level, grouping and operation.data Infix = Infix !Level !Grouping !Operation-- | The infix operator a token is, if it is one.infixOperator :: Token -> Maybe InfixinfixOperator tok = case tok of TokImpl -> Just (Infix LevelImplication GroupsRight (Binary OpImpl)) TokOr -> Just (Infix LevelOr GroupsLeft (Binary OpOr)) TokAnd -> Just (Infix LevelAnd GroupsLeft (Binary OpAnd)) TokEq -> Just (Infix LevelEquality GroupsNone (Binary OpEq)) TokNeq -> Just (Infix LevelEquality GroupsNone (Binary OpNeq)) TokLt -> Just (Infix LevelComparison GroupsNone (Binary OpLt)) TokGt -> Just (Infix LevelComparison GroupsNone (Binary OpGt)) TokLte -> Just (Infix LevelComparison GroupsNone (Binary OpLte)) TokGte -> Just (Infix LevelComparison GroupsNone (Binary OpGte)) TokUpdate -> Just (Infix LevelUpdate GroupsRight (Binary OpUpdate)) TokPlus -> Just (Infix LevelAddition GroupsLeft (Binary OpAdd)) TokMinus -> Just (Infix LevelAddition GroupsLeft (Binary OpSub)) TokStar -> Just (Infix LevelMultiplication GroupsLeft (Binary OpMul)) TokSlash -> Just (Infix LevelMultiplication GroupsLeft (Binary OpDiv)) TokConcat -> Just (Infix LevelConcat GroupsRight (Binary OpConcat)) TokQuestion -> Just (Infix LevelHasAttr GroupsLeft HasAttr) _ -> Nothing-- | Which levels an operator expression takes in.data Bound = -- | This level and every tighter one. AtLeast !Level | -- | Only the levels tighter than this one. Tighter !Level-- | Whether a bound takes in an operator of a level.admits :: Bound -> Level -> Booladmits (AtLeast lowest) level = level >= lowestadmits (Tighter lowest) level = level > lowest-- | An operator expression: an operand and every infix operator after it.parseOperators :: Parser ExprparseOperators = parseBounded (AtLeast LevelImplication)-- | An operand and the infix operators the bound takes in after it, as-- upstream's grammar resolves its precedences. A prefix operator's-- operand runs to the end of the tighter operators after it, so-- @!a + b@ is @!(a + b)@, @1 + !a + b@ is @1 + !(a + b)@ and @-a ? b@ is-- @(-a) ? b@. Two operators of a level that groups neither way, such as-- @a == b == c@ or @a < b > c@, are refused at the second.parseBounded :: Bound -> Parser ExprparseBounded bound = parseOperand >>= extend where extend lhs = do next <- peekMaybe case next >>= infixOperator of Just (Infix level grouping operation) | admits bound level -> do _ <- advance combined <- case operation of Binary op -> EBinary op lhs <$> parseBounded (rightBound grouping level) HasAttr -> EHasAttr lhs <$> parseAttrPath refuseRepeat grouping level extend combined _ -> pure lhs-- | The bound of an infix operator's right operand.rightBound :: Grouping -> Level -> BoundrightBound grouping level = case grouping of GroupsRight -> AtLeast level GroupsLeft -> Tighter level GroupsNone -> Tighter level-- | Refuse an operator of the level just parsed when that level groups-- neither way.refuseRepeat :: Grouping -> Level -> Parser ()refuseRepeat grouping level = case grouping of GroupsNone -> do next <- peekMaybe case next of Just tok | Just (Infix nextLevel _ _) <- infixOperator tok, nextLevel == level -> parseError ("unexpected " <> showToken tok <> ": the operator does not chain") _ -> pure () GroupsLeft -> pure () GroupsRight -> pure ()-- | An operand: a prefix operator and its operand, or an application.-- @!@'s operand takes in the operators tighter than it, and @-@'s none.parseOperand :: Parser ExprparseOperand = do tok <- peek case tok of TokNot -> advance *> (EUnary OpNot <$> parseBounded (Tighter LevelNot)) TokMinus -> advance *> (EUnary OpNegate <$> parseBounded (Tighter LevelNegate)) _ -> parseApp-- | Function application (juxtaposition, left-associative).parseApp :: Parser ExprparseApp = do func <- parseSelect loopApp func where loopApp func = do tok <- peekMaybe case tok of Just t | canStartAtom t -> do arg <- parseSelect loopApp (EApp func arg) _ -> pure func-- | Attribute selection (@e.a@, @e.a or default@).parseSelect :: Parser ExprparseSelect = do expr <- parseAtom selectLoop exprselectLoop :: Expr -> Parser ExprselectLoop expr = do tok <- peekMaybe case tok of Just TokDot -> do _ <- advance path <- parseAttrPath -- Check for 'or' default orDefault <- tryParser parseOrDefault selectLoop (ESelect expr path orDefault) _ -> pure expr-- | Parse the @or default@ part after @e.path@.parseOrDefault :: Parser ExprparseOrDefault = do tok <- peek case tok of TokIdent "or" -> do _ <- advance parseSelect _ -> parseError "expected 'or'"-- ----------------------------------------------------------------------------- Atoms-- ---------------------------------------------------------------------------parseAtom :: Parser ExprparseAtom = do tok <- peek case tok of TokInt n -> advance >> pure (ELit (NixInt n)) TokFloat d -> advance >> pure (ELit (NixFloat d)) TokTrue -> advance >> pure (ELit (NixBool True)) TokFalse -> advance >> pure (ELit (NixBool False)) TokNull -> advance >> pure (ELit NixNull) TokUri u -> advance >> pure (ELit (NixUri u)) TokPath p -> advance >> pure (ELit (NixPath p)) TokPathInterpStart headPiece -> advance >> EPathStr headPiece <$> parsePathParts TokSearchPath name -> advance >> pure (searchPathCall name) TokIdent name | name == curPosIdentifier -> EPos <$> currentPos <* advance -- Upstream interns a variable's name where it reads it -- (expr_simple in parser.y), however the variable is later bound. | otherwise -> advance >> EVar name <$ recordName name TokStringOpen -> parseString TokIndStringOpen -> parseIndString TokLParen -> parseParen TokLBracket -> parseList TokLBrace -> do _ <- advance parseAttrSet False TokRec -> do _ <- advance expect TokLBrace parseAttrSet True TokLet -> parseLet TokIf -> parseIf TokWith -> parseWith TokAssert -> parseAssert _ -> parseError ("unexpected " <> showToken tok)-- | The identifier upstream's parser reads as the position it is written-- at rather than as a variable, wherever it is an expression (the @ID@-- rule of @expr_simple@, parser.y at 2.24.9). Only that rule checks the-- name: an @inherit@ copies a variable of any name, @__curPos@ included.curPosIdentifier :: TextcurPosIdentifier = "__curPos"-- | The call a search path @\<name\>@ parses as, @__findFile __nixPath-- "name"@, as upstream's parser makes it (the @SPATH@ rule of-- @expr_simple@, parser.y at 2.24.9). Both are variables, so a binding-- of either in scope is the one the call uses. Upstream interns both-- names as its evaluator starts ("Nix.Eval.StartupSymbols"), so the-- parser notes neither for the interning order.searchPathCall :: Text -> ExprsearchPathCall name = EApp (EApp (EVar findFileVariable) (EVar nixPathVariable)) (EStr [StrLit (TE.encodeUtf8 name)])-- | The variables a search path's call names: upstream's @findFile@ and-- @nixPath@ symbols.findFileVariable, nixPathVariable :: TextfindFileVariable = "__findFile"nixPathVariable = "__nixPath"-- ----------------------------------------------------------------------------- Strings-- ---------------------------------------------------------------------------parseString :: Parser ExprparseString = do expect TokStringOpen parts <- parseStringParts TokStringClose pure (EStr parts)parseIndString :: Parser ExprparseIndString = do expect TokIndStringOpen parts <- parseStringParts TokIndStringClose pure (EIndStr parts)parseStringParts :: Token -> Parser [StringPart]parseStringParts closer = go [] where go acc = do tok <- peek case tok of _ | tok == closer -> do _ <- advance pure (reverse acc) TokStringLit txt -> do _ <- advance go (StrLit txt : acc) TokStringEsc txt -> do _ <- advance go (StrEsc txt : acc) TokInterpOpen -> do _ <- advance expr <- parseExpr expect TokInterpClose go (StrInterp expr : acc) _ -> parseError ("unexpected " <> showToken tok <> " in string")-- | The pieces of an interpolated path literal, after the opening head-- piece: literal chunks and interpolations until the lexer's-- synthesized 'TokPathEnd'. The lexer emits nothing else between the-- opener and the end, so the trailing case is a defect signal, not a-- user-facing grammar error.parsePathParts :: Parser [StringPart]parsePathParts = go [] where go acc = do tok <- peek case tok of TokPathEnd -> do _ <- advance pure (reverse acc) TokPathLit txt -> do _ <- advance go (StrLit (TE.encodeUtf8 txt) : acc) TokInterpOpen -> do _ <- advance expr <- parseExpr expect TokInterpClose go (StrInterp expr : acc) _ -> parseError ("unexpected " <> showToken tok <> " in path")-- ----------------------------------------------------------------------------- Compound expressions-- ---------------------------------------------------------------------------parseParen :: Parser ExprparseParen = do expect TokLParen expr <- parseExpr expect TokRParen pure exprparseList :: Parser ExprparseList = do expect TokLBracket EList <$> parseListElemsparseListElems :: Parser [Expr]parseListElems = go [] where go acc = do tok <- peek case tok of TokRBracket -> do _ <- advance pure (reverse acc) _ | canStartAtom tok -> do elem_ <- parseSelect go (elem_ : acc) _ -> parseError ("unexpected " <> showToken tok <> " in list")parseAttrSet :: Bool -> Parser ExprparseAttrSet isRec = (\bs -> EAttrs isRec bs NoCaptureInfo) <$> parseBindingsparseBindings :: Parser [Binding]parseBindings = go [] >>= normalizeBindings where go acc = do tok <- peek case tok of TokRBrace -> do _ <- advance pure (reverse acc) TokInherit -> do inherited <- parseInherit go (reverse inherited ++ acc) _ -> do binding <- parseNamedBinding go (binding : acc)-- ----------------------------------------------------------------------------- Binding normalization (upstream parser.y addAttr semantics)-- ----------------------------------------------------------------------------- | Accumulated definition while normalizing one binding list.data NormEntry = -- | @name = value@ at its first definition's position - mergeable when -- the value is a plain attrset literal. StaticEntry !SrcPos !Text !Expr | -- | An @inherit@ - its names are never mergeable. InheritEntry !Binding | -- | A dynamic-key binding - collisions surface at eval time. DynamicEntry !Binding-- | How a name was defined, for duplicate checking.data DefKind = DefStatic | DefInherit-- | Normalize a binding list the way upstream's parser (@addAttr@) does,-- over bindings 'parseNamedBinding' has already hoisted to one key each:---- * two definitions of one key merge recursively when BOTH values are-- attrset literals - so @a.b = 1; a.c = 2;@ and @a = { b = 1; }; a.c = 2;@-- both work, with inner duplicates checked recursively. A @rec@ marker-- on the existing set governs the merged result; one on the new set is-- discarded, exactly as upstream. The key keeps its first definition's-- position and each merged binding its own, as upstream's do;-- * any other duplicate definition is a parse error, as upstream-- (@a = 1; a = 2;@, an @inherit@ name reused, merging into a-- non-literal value).---- After normalization every static top-level key appears exactly once --- which also makes the positional (slot-based) eval path applicable to-- sets and lets that use nested attrpaths.normalizeBindings :: [Binding] -> Parser [Binding]normalizeBindings bindings = case normalizeBindingList bindings of Left err -> parseError err Right normalized -> pure normalized-- | Pure core of 'normalizeBindings'; recurses into merged literals.normalizeBindingList :: [Binding] -> Either Text [Binding]normalizeBindingList bindings = do (entriesRev, _defined) <- foldM step ([], Map.empty) bindings pure (map renderEntry (reverse entriesRev)) where step :: ([NormEntry], Map Text DefKind) -> Binding -> Either Text ([NormEntry], Map Text DefKind) step (entries, defined) binding = case binding of NamedBinding pos (StaticKey key) value -> case Map.lookup key defined of Nothing -> Right (StaticEntry pos key value : entries, Map.insert key DefStatic defined) Just DefStatic -> do updated <- mergeIntoEntries key value entries Right (updated, defined) Just DefInherit -> Left (duplicateAttr key) b@(NamedBinding {}) -> Right (DynamicEntry b : entries, defined) b@(Inherit _ name _) -> inheritEntry b [name] b@(InheritFrom _ names) -> inheritEntry b [name | InheritedName _ name <- names] where -- One name at a time, so a name repeated within the clause is a -- duplicate too, as upstream's per-name dupAttr check makes it. inheritEntry b names = do updated <- foldM defineInherited defined names Right (InheritEntry b : entries, updated) defineInherited acc name | Map.member name acc = Left (duplicateAttr name) | otherwise = Right (Map.insert name DefInherit acc) -- Replace the existing entry for @key@ with the merged value. mergeIntoEntries key newValue entries = case entries of [] -> Left (duplicateAttr key) (StaticEntry existingPos existingKey existingValue : rest) | existingKey == key -> do merged <- mergeAttrValues key existingValue newValue Right (StaticEntry existingPos existingKey merged : rest) (entry : rest) -> (entry :) <$> mergeIntoEntries key newValue rest -- Upstream's addAttr (parser-state.hh) merges ANY two attrset -- literals without consulting ->recursive on either side: the -- EXISTING set's rec marker governs the merged result and the new -- set's marker is DISCARDED (upstream's own comment documents the -- discard). The merged binding list is re-normalized so inner -- duplicates are caught. mergeAttrValues _ (EAttrs existingRec existingBindings _) (EAttrs _ newBindings _) = (\merged -> EAttrs existingRec merged NoCaptureInfo) <$> normalizeBindingList (existingBindings ++ newBindings) mergeAttrValues key _ _ = Left (duplicateAttr key) renderEntry (StaticEntry pos key value) = NamedBinding pos (StaticKey key) value renderEntry (InheritEntry b) = b renderEntry (DynamicEntry b) = b duplicateAttr key = "attribute '" <> key <> "' already defined"-- | @a.b.c = v;@ as one binding under its first key, the rest of the-- path hoisted into nested set literals, one per level: @a = { b = { c =-- v; }; };@, as upstream's @addAttr@ builds them, every level at the-- path's position.parseNamedBinding :: Parser BindingparseNamedBinding = do pos <- currentPos firstKey <- parseAttrKey rest <- dottedKeys expect TokAssign val <- parseExpr expect TokSemicolon let nestUnder [] value = value nestUnder (key : keys) value = EAttrs False [NamedBinding pos key (nestUnder keys value)] NoCaptureInfo pure (NamedBinding pos firstKey (nestUnder rest val))-- | An @inherit@ clause: one 'InheritFrom' for @inherit (from) x y;@, one-- 'Inherit' per name for @inherit x y;@, each holding the variable it copies.-- Each name is at its own position, as upstream's parser.y records them.parseInherit :: Parser [Binding]parseInherit = do expect TokInherit tok <- peek case tok of TokLParen -> do _ <- advance from <- parseExpr expect TokRParen names <- parseInheritNames expect TokSemicolon pure [InheritFrom from names] _ -> do names <- parseInheritNames expect TokSemicolon pure [Inherit pos name (EVar name) | InheritedName pos name <- names]-- | The names of an @inherit@, each noted as upstream's parser interns it-- (the @attrs@ rule of parser.y).parseInheritNames :: Parser [InheritedName]parseInheritNames = go [] where go acc = do pos <- currentPos tok <- peek let inherited name = recordName name >> go (InheritedName pos name : acc) case tok of TokIdent name -> advance >> inherited name _ | Just name <- identifierKeywordText tok -> advance >> inherited name _ | startsStringAttr tok -> do key <- parseStringAttr case key of StaticKey name -> inherited name -- Upstream refuses the key once it is parsed, at its -- start (the attrs rule of parser.y). DynamicKey _ -> failAt pos "dynamic attributes not allowed in inherit" _ -> pure (reverse acc)parseAttrPath :: Parser AttrPathparseAttrPath = do first <- parseAttrKey rest <- dottedKeys pure (first : rest)-- | The keys after an attribute path's first, each after a dot. A dot-- commits to the key after it, as upstream's LR grammar does (the-- @attrpath@ rule, parser.y at 2.24.9), so a key that fails to parse-- reports its own error, a string key that is not UTF-8 among them,-- rather than backtracking to blame the dot.dottedKeys :: Parser [AttrKey]dottedKeys = go [] where go acc = do dotted <- match TokDot if dotted then do key <- parseAttrKey go (key : acc) else pure (reverse acc)-- | One key of an attribute path, a static one's name noted as upstream's-- parser interns it (the @attrpath@ rule of parser.y).parseAttrKey :: Parser AttrKeyparseAttrKey = do tok <- peek key <- case tok of TokIdent name -> StaticKey name <$ advance _ | Just name <- identifierKeywordText tok -> StaticKey name <$ advance _ -> parseStringAttr key <$ noteStatic key where noteStatic (StaticKey name) = recordName name noteStatic (DynamicKey _) = pure ()-- | Whether a token opens a key written as a string or as @${ expr }@.startsStringAttr :: Token -> BoolstartsStringAttr TokStringOpen = TruestartsStringAttr TokInterpOpen = TruestartsStringAttr _ = False-- | A key written as a string or as @${ expr }@ (upstream's @string_attr@-- in parser.y). Upstream's @attrpath@ and @attrs@ rules make such a key a-- name when its expression is an @ExprString@, and dynamic otherwise-- (parser.y), so @let ${\"x\"} = 1; in x@ and @inherit ${\"x\"};@ are legal.-- A double-quoted string with no interpolation is one, and so is a URI-- (@string_parts@ and @expr_simple@ in parser.y), parentheses around either-- included, since upstream's parser and this one both make a parenthesized-- expression the expression itself (@expr_simple@ in parser.y). An indented-- string is one when @stripIndentation@ (parser-state.hh) leaves it a single-- piece; such a key stays dynamic here, since an indented string is held as-- its unstripped pieces until it is evaluated.parseStringAttr :: Parser AttrKeyparseStringAttr = do pos <- currentPos tok <- peek expr <- case tok of TokStringOpen -> parseString TokInterpOpen -> do _ <- advance inner <- parseExpr -- In expression context, the lexer doesn't track interpolation -- mode - } is TokRBrace rather than TokInterpClose. expect TokRBrace pure inner _ -> parseError ("expected attribute key, got " <> showToken tok) case plainStringBytes expr of Just bytes -> StaticKey <$> attrNameText pos bytes Nothing -> pure (DynamicKey expr)-- | The bytes of an expression upstream's parser builds as a plain string-- (an @ExprString@): a double-quoted string with no interpolation, whose-- parts become one string (@string_parts@ in parser.y), or a URI-- (@expr_simple@ in parser.y).plainStringBytes :: Expr -> Maybe ByteStringplainStringBytes (EStr parts) = mconcat <$> traverse literalPart parts where literalPart (StrLit bytes) = Just bytes literalPart (StrEsc bytes) = Just bytes literalPart (StrInterp _) = NothingplainStringBytes (ELit (NixUri uri)) = Just (TE.encodeUtf8 uri)plainStringBytes _ = Nothing-- | The name a string attribute key spells, the key starting at the-- position given. Attribute names are text here, so a key whose bytes are-- not UTF-8 is a syntax error at the key, where upstream makes a symbol of-- any bytes (the @attrpath@ and @attrs@ rules, parser.y at 2.24.9).attrNameText :: SrcPos -> ByteString -> Parser TextattrNameText pos bytes = case TE.decodeUtf8' bytes of Right name -> pure name Left _ -> failAt pos "attribute name is not valid UTF-8"-- | Fail at a position the parser has already read past.failAt :: SrcPos -> Text -> Parser afailAt (SrcPos origin line col) message = failWithError ParseError { peFile = sourceName origin, peLine = line, peCol = col, peMessage = message }-- | The name of a token this lexer reads as a keyword and upstream's as-- an identifier (its @ID@ rule in lexer.l): @true@, @false@ and @null@, which-- upstream binds as names in its base environment. An attribute name is an-- identifier, @or@ among them here, or one of these, as upstream's @attr@-- rule takes an @ID@ or @or@ (parser.y); every other keyword is upstream's-- own token (lexer.l's keyword rules) and no attribute name, so an attribute-- named like one is written as a string, @{ \"if\" = 1; }@.identifierKeywordText :: Token -> Maybe TextidentifierKeywordText TokTrue = Just "true"identifierKeywordText TokFalse = Just "false"identifierKeywordText TokNull = Just "null"identifierKeywordText _ = NothingparseLet :: Parser ExprparseLet = do expect TokLet bindings <- parseLetBindings expect TokIn (\body -> ELet bindings body NoCaptureInfo) <$> parseExprparseLetBindings :: Parser [Binding]parseLetBindings = go [] >>= normalizeBindings where go acc = do tok <- peek case tok of TokIn -> pure (reverse acc) TokInherit -> do inherited <- parseInherit go (reverse inherited ++ acc) _ -> do binding <- parseNamedBinding -- Upstream rejects a dynamic TOP-LEVEL key in a let at parse time; -- nested dynamic keys (let a.${k} = 1) live in a nested attrset -- and are fine. case binding of NamedBinding _ (DynamicKey _) _ -> parseError "dynamic attributes not allowed in let" _ -> go (binding : acc)parseIf :: Parser ExprparseIf = do expect TokIf cond <- parseExpr expect TokThen thenExpr <- parseExpr expect TokElse EIf cond thenExpr <$> parseExprparseWith :: Parser ExprparseWith = do expect TokWith env <- parseExpr expect TokSemicolon EWith env <$> parseExprparseAssert :: Parser ExprparseAssert = do expect TokAssert cond <- parseExpr expect TokSemicolon EAssert cond <$> parseExpr-- ----------------------------------------------------------------------------- Helpers-- ----------------------------------------------------------------------------- | Can this token start an atomic expression (for application parsing)?canStartAtom :: Token -> BoolcanStartAtom (TokIdent _) = TruecanStartAtom (TokInt _) = TruecanStartAtom (TokFloat _) = TruecanStartAtom TokTrue = TruecanStartAtom TokFalse = TruecanStartAtom TokNull = TruecanStartAtom (TokUri _) = TruecanStartAtom (TokPath _) = TruecanStartAtom (TokPathInterpStart _) = TruecanStartAtom (TokSearchPath _) = TruecanStartAtom TokStringOpen = TruecanStartAtom TokIndStringOpen = TruecanStartAtom TokLParen = TruecanStartAtom TokLBrace = TruecanStartAtom TokLBracket = TruecanStartAtom TokRec = TruecanStartAtom TokLet = TruecanStartAtom TokIf = TruecanStartAtom TokWith = TruecanStartAtom TokAssert = TruecanStartAtom _ = False