Skip to content

Commit

Permalink
Expand let statements more
Browse files Browse the repository at this point in the history
  • Loading branch information
piegamesde committed May 5, 2023
1 parent 1142022 commit 2c1e36e
Show file tree
Hide file tree
Showing 9 changed files with 146 additions and 67 deletions.
16 changes: 13 additions & 3 deletions src/Nixfmt/Pretty.hs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,16 @@ absorbThen :: Expression -> Doc
absorbThen (Term t) | isAbsorbable t = hardspace <> prettyTerm t <> hardspace
absorbThen x = line <> nest 2 (group x) <> line

-- What is allowed to come on the same line as `in`?
-- Absorbable terms like sets
-- if, with, let
absorbIn :: Expression -> Doc
absorbIn (Term t) | isAbsorbable t = hardspace <> prettyTerm t <> hardspace
absorbIn x@(If _ _ _ _ _ _) = group x
absorbIn x@(With _ _ _ _) = group x
absorbIn x@(Let _ _ _ _) = group x
absorbIn x = line <> nest 2 (group x) <> line

absorbElse :: Expression -> Doc
absorbElse (If if_ cond then_ expr0 else_ expr1)
= hardspace <> pretty if_ <> hardspace <> group cond <> hardspace
Expand All @@ -212,9 +222,9 @@ instance Pretty Expression where

pretty (Let (Ann let_ letTrailing letLeading) binders
(Ann in_ inTrailing inLeading) expr)
= base $ group letPart <> line <> group inPart
where letPart = pretty let_ <> pretty letTrailing <> line <> letBody
inPart = pretty in_ <> hardspace <> pretty expr
= base $ group letPart <> line <> inPart
where letPart = pretty let_ <> pretty letTrailing <> hardline <> letBody
inPart = pretty in_ <> hardspace <> absorbIn expr
letBody = nest 2 $
pretty letLeading
<> sepBy hardline binders
Expand Down
5 changes: 3 additions & 2 deletions test/diff/apply/out.nix
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@
buildScript = "true";
installMethod = "copy";
});
in "${pkg}/lib/node_modules/${pname}/node_modules")
outputs.subPackages))
in
"${pkg}/lib/node_modules/${pname}/node_modules"
) outputs.subPackages))
}
''
{
Expand Down
4 changes: 3 additions & 1 deletion test/diff/comment/out.nix
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,9 @@

d = 1;
#7
in d)
in
d
)

({
a, # comment
Expand Down
38 changes: 26 additions & 12 deletions test/diff/idioms_lib_2/out.nix
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,11 @@ rec {
final value.
*/
pipe = val: functions:
let reverseApply = x: f: f x;
in builtins.foldl' reverseApply val functions;
let
reverseApply = x: f: f x;
in
builtins.foldl' reverseApply val functions
;

# note please don’t add a function like `compose = flip pipe`.
# This would confuse users, because the order of the functions
Expand Down Expand Up @@ -175,7 +178,8 @@ rec {
codeName = "Quokka";

# Returns the current nixpkgs version suffix as string.
versionSuffix = let suffixFile = ../.version-suffix;
versionSuffix = let
suffixFile = ../.version-suffix;
in if pathExists suffixFile then
lib.strings.fileContents suffixFile
else
Expand Down Expand Up @@ -352,12 +356,16 @@ rec {
Type: String -> List ComparableVal -> List ComparableVal -> a -> a
*/
checkListOfEnum = msg: valid: given:
let unexpected = lib.subtractLists valid given;
in lib.throwIfNot (unexpected == [ ]) "${msg}: ${
builtins.concatStringsSep ", " (builtins.map builtins.toString unexpected)
} unexpected; valid ones: ${
builtins.concatStringsSep ", " (builtins.map builtins.toString valid)
}";
let
unexpected = lib.subtractLists valid given;
in
lib.throwIfNot (unexpected == [ ]) "${msg}: ${
builtins.concatStringsSep ", "
(builtins.map builtins.toString unexpected)
} unexpected; valid ones: ${
builtins.concatStringsSep ", " (builtins.map builtins.toString valid)
}"
;

info = msg: builtins.trace "INFO: ${msg}";

Expand Down Expand Up @@ -422,7 +430,9 @@ rec {
"14" = "E";
"15" = "F";
}.${toString d};
in lib.concatMapStrings toHexDigit (toBaseDigits 16 i);
in
lib.concatMapStrings toHexDigit (toBaseDigits 16 i)
;

/* `toBaseDigits base i` converts the positive integer i to a list of its
digits in the given base. For example:
Expand All @@ -440,6 +450,10 @@ rec {
let
r = i - ((i / base) * base);
q = (i - r) / base;
in [ r ] ++ go q;
in assert (base >= 2); assert (i >= 0); lib.reverseList (go i);
in
[ r ] ++ go q
;
in
assert (base >= 2); assert (i >= 0); lib.reverseList (go i)
;
}
74 changes: 48 additions & 26 deletions test/diff/idioms_lib_3/out.nix
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,11 @@ in rec {
k: v: map (mkLine k) (if lib.isList v then v else [ v ])
else
k: v: [ (mkLine k v) ];
in attrs:
libStr.concatStrings
(lib.concatLists (libAttr.mapAttrsToList mkLines attrs));
in
attrs:
libStr.concatStrings
(lib.concatLists (libAttr.mapAttrsToList mkLines attrs))
;

# Generate an INI-style config file from an
# attrset of sections to an attrset of key-value pairs.
Expand Down Expand Up @@ -143,7 +145,9 @@ in rec {
[${mkSectionName sectName}]
'' + toKeyValue { inherit mkKeyValue listsAsDuplicateKeys; } sectValues;
# map input to ini sections
in mapAttrsToStringsSep "\n" mkSection attrsOfAttrs;
in
mapAttrsToStringsSep "\n" mkSection attrsOfAttrs
;

# Generate an INI-style config file from an attrset
# specifying the global section (no header), and an
Expand Down Expand Up @@ -233,8 +237,11 @@ in rec {

# generation for multiple ini values
mkKeyValue = k: v:
let mkKeyValue = mkKeyValueDefault { } " = " k;
in concatStringsSep "\n" (map (kv: " " + mkKeyValue kv) (lib.toList v));
let
mkKeyValue = mkKeyValueDefault { } " = " k;
in
concatStringsSep "\n" (map (kv: " " + mkKeyValue kv) (lib.toList v))
;

# converts { a.b.c = 5; } to { "a.b".c = 5; } for toINI
gitFlattenAttrs = let
Expand All @@ -248,11 +255,15 @@ in rec {
} else {
${head path} = value;
};
in attrs:
lib.foldl lib.recursiveUpdate { } (lib.flatten (recurse [ ] attrs));
in
attrs:
lib.foldl lib.recursiveUpdate { } (lib.flatten (recurse [ ] attrs))
;

toINI_ = toINI { inherit mkKeyValue mkSectionName; };
in toINI_ (gitFlattenAttrs attrs);
in
toINI_ (gitFlattenAttrs attrs)
;

# Generates JSON from an arbitrary (non-function) value.
# For more information see the documentation of the builtin.
Expand Down Expand Up @@ -293,14 +304,17 @@ in rec {
id;
mapAny = with builtins;
depth: v:
let evalNext = x: mapAny (depth + 1) (transform (depth + 1) x);
let
evalNext = x: mapAny (depth + 1) (transform (depth + 1) x);
in if isAttrs v then
mapAttrs (stepIntoAttr evalNext) v
else if isList v then
map evalNext v
else
transform (depth + 1) v;
in mapAny 0;
in
mapAny 0
;

# Pretty print a value, akin to `builtins.trace`.
# Should probably be a builtin as well.
Expand Down Expand Up @@ -360,10 +374,12 @@ in rec {
# The last line gets a special treatment: if it's empty, '' is on its own line at the "outer"
# indentation level. Otherwise, '' is appended to the last line.
lastLine = lib.last escapedLines;
in "''" + introSpace
+ concatStringsSep introSpace (lib.init escapedLines)
+ (if lastLine == "" then outroSpace else introSpace + lastLine)
+ "''";
in
"''" + introSpace
+ concatStringsSep introSpace (lib.init escapedLines)
+ (if lastLine == "" then outroSpace else introSpace + lastLine)
+ "''"
;
in if multiline && length lines > 1 then
multilineResult
else
Expand Down Expand Up @@ -410,7 +426,9 @@ in rec {
};") v) + outroSpace + "}"
else
abort "generators.toPretty: should never happen (v = ${v})";
in go indent;
in
go indent
;

# PLIST handling
toPlist = { }:
Expand Down Expand Up @@ -462,29 +480,33 @@ in rec {
(literal ind "</dict>")
];

attr = let attrFilter = name: value: name != "_module" && value != null;
in ind: x:
libStr.concatStringsSep "\n" (lib.flatten (lib.mapAttrsToList
(name: value:
lib.optionals (attrFilter name value) [
(key " ${ind}" name)
(expr " ${ind}" value)
]) x));
attr = let
attrFilter = name: value: name != "_module" && value != null;
in
ind: x:
libStr.concatStringsSep "\n" (lib.flatten (lib.mapAttrsToList
(name: value:
lib.optionals (attrFilter name value) [
(key " ${ind}" name)
(expr " ${ind}" value)
]) x))
;

in ''
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
${expr "" v}
</plist>'';
</plist>'' ;

# Translate a simple Nix expression to Dhall notation.
# Note that integers are translated to Integer and never
# the Natural type.
toDhall = { }@args:
v:
with builtins;
let concatItems = lib.strings.concatStringsSep ", ";
let
concatItems = lib.strings.concatStringsSep ", ";
in if isAttrs v then
"{ ${
concatItems (lib.attrsets.mapAttrsToList
Expand Down
13 changes: 8 additions & 5 deletions test/diff/idioms_nixos_1/out.nix
Original file line number Diff line number Diff line change
Expand Up @@ -359,11 +359,14 @@ in {
assertions = if config.boot.kernelPackages.kernel ? features then
[ ]
else
let cfg = config.boot.kernelPackages.kernel.config;
in map (attrs: {
assertion = attrs.assertion cfg;
inherit (attrs) message;
}) config.system.requiredKernelConfig;
let
cfg = config.boot.kernelPackages.kernel.config;
in
map (attrs: {
assertion = attrs.assertion cfg;
inherit (attrs) message;
}) config.system.requiredKernelConfig
;

})

Expand Down
13 changes: 8 additions & 5 deletions test/diff/idioms_pkgs_3/out.nix
Original file line number Diff line number Diff line change
Expand Up @@ -359,11 +359,14 @@ in {
assertions = if config.boot.kernelPackages.kernel ? features then
[ ]
else
let cfg = config.boot.kernelPackages.kernel.config;
in map (attrs: {
assertion = attrs.assertion cfg;
inherit (attrs) message;
}) config.system.requiredKernelConfig;
let
cfg = config.boot.kernelPackages.kernel.config;
in
map (attrs: {
assertion = attrs.assertion cfg;
inherit (attrs) message;
}) config.system.requiredKernelConfig
;

})

Expand Down
4 changes: 3 additions & 1 deletion test/diff/lambda/out.nix
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@
...
}:
let
in pkgs)
in
pkgs
)

(a:
{
Expand Down
46 changes: 34 additions & 12 deletions test/diff/let_in/out.nix
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,61 @@ let
a = let
b = 2;
c = 3;
in d;
a = let c = 1; in f;
in
d
;
a = let
c = 1;
in
f
;

a = let
c = 1;
# e
in f;
a = let c = 1; # d
in f;
in
f
;
a = let
c = 1; # d
in
f
;

a = let
c = 1; # d
# e
in f;
in
f
;
a = let # b
c = 1;
in f;
in
f
;
a = let # b
c = 1;
# e
in f;
in
f
;
a = let # b
c = 1; # d
in f;
in
f
;
a = let # b
c = 1; # d
# e
in f;
in
f
;

a = let
in [
1
2
];
] ;

in a
in
a

0 comments on commit 2c1e36e

Please sign in to comment.