From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from mp12.migadu.com ([2001:41d0:2:4a6f::]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits)) by ms0.migadu.com with LMTPS id ACX6OiH4zWFJRwEAgWs5BA (envelope-from ) for ; Thu, 30 Dec 2021 19:19:13 +0100 Received: from aspmx1.migadu.com ([2001:41d0:2:4a6f::]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits)) by mp12.migadu.com with LMTPS id IA2gNyH4zWH0PQAAauVa8A (envelope-from ) for ; Thu, 30 Dec 2021 19:19:13 +0100 Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by aspmx1.migadu.com (Postfix) with ESMTPS id B57E9656 for ; Thu, 30 Dec 2021 19:19:12 +0100 (CET) Received: from localhost ([::1]:40564 helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1n3019-0006yf-RZ for larch@yhetil.org; Thu, 30 Dec 2021 13:19:11 -0500 Received: from eggs.gnu.org ([209.51.188.92]:44494) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1n3013-0006y6-HY for guix-patches@gnu.org; Thu, 30 Dec 2021 13:19:05 -0500 Received: from debbugs.gnu.org ([209.51.188.43]:42890) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1n3010-0006aB-Dt for guix-patches@gnu.org; Thu, 30 Dec 2021 13:19:05 -0500 Received: from Debian-debbugs by debbugs.gnu.org with local (Exim 4.84_2) (envelope-from ) id 1n3010-0005qV-60 for guix-patches@gnu.org; Thu, 30 Dec 2021 13:19:02 -0500 X-Loop: help-debbugs@gnu.org Subject: [bug#51838] [PATCH v6 03/41] guix: node-build-system: Add JSON utilities. Resent-From: Liliana Marie Prikler Original-Sender: "Debbugs-submit" Resent-CC: guix-patches@gnu.org Resent-Date: Thu, 30 Dec 2021 18:19:02 +0000 Resent-Message-ID: Resent-Sender: help-debbugs@gnu.org X-GNU-PR-Message: followup 51838 X-GNU-PR-Package: guix-patches X-GNU-PR-Keywords: patch To: Philip McGrath , 51838@debbugs.gnu.org Cc: Timothy Sample , Pierre Langlois , Jelle Licht Received: via spool by 51838-submit@debbugs.gnu.org id=B51838.164088833922460 (code B ref 51838); Thu, 30 Dec 2021 18:19:02 +0000 Received: (at 51838) by debbugs.gnu.org; 30 Dec 2021 18:18:59 +0000 Received: from localhost ([127.0.0.1]:54436 helo=debbugs.gnu.org) by debbugs.gnu.org with esmtp (Exim 4.84_2) (envelope-from ) id 1n300w-0005qB-Cj for submit@debbugs.gnu.org; Thu, 30 Dec 2021 13:18:59 -0500 Received: from mail-wm1-f66.google.com ([209.85.128.66]:47031) by debbugs.gnu.org with esmtp (Exim 4.84_2) (envelope-from ) id 1n300u-0005pv-1M for 51838@debbugs.gnu.org; Thu, 30 Dec 2021 13:18:56 -0500 Received: by mail-wm1-f66.google.com with SMTP id d198-20020a1c1dcf000000b0034569cdd2a2so13706428wmd.5 for <51838@debbugs.gnu.org>; Thu, 30 Dec 2021 10:18:56 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112; h=message-id:subject:from:to:cc:date:in-reply-to:references :user-agent:mime-version:content-transfer-encoding; bh=c+WYZstX6sIBDXDG/xRhr+7t6L7XecofJraLA7aBGdU=; b=i/AlKOMYSx+qogcIHM6NPV4vNOHDAnG4mfG1aTA6iFDMiGpLUmLt0om16plcD3Q4Ol a9pvk/yrSSq99C+iWNUIDFPrMQ81THLwgT6LSmE62WsicEGCPzVCsC0YWTqLjP5T3/Bd BIgwcE2JkbIoZZUHsDs5PpNStW38SKsXbM+WljPoHVF6vOBJ9MCEntNUJPQSkkP+cXd4 2jnVPwC4oOpZAfhj+H7G2sLw7IuJ+kGt4UkM+KeozrOuCas+o7xYLgv9igWIJp+RdSiB z5WgFSns07RS5zntOhvKENC5NJAySH1naRE9nicm4B98Wen2hDvIhsQEUctsPC9WVf+8 mqOw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=x-gm-message-state:message-id:subject:from:to:cc:date:in-reply-to :references:user-agent:mime-version:content-transfer-encoding; bh=c+WYZstX6sIBDXDG/xRhr+7t6L7XecofJraLA7aBGdU=; b=zVypGmbAU/srALfBJnQYPBFee4uXKf2Evg1bhr0W+kgv88e10BVS81my2gf0FHkZZE zHA28mdE2F3pkdzZz5fE9/AVHu3+c639fnE++2GTx4zCwUaUNMjtPdBRsH8PGHlXpq86 bjQJu48CTncbGuA+irTpaPYExPvHFQxkR7JnJoGPDuNO6F3ZjuxWGPaoYqWMkHsYSUTC XpUjsYN6tXtlu6MmO5WY2i8+qVVkppGMZrtzuZarafnavvqwMzFGmo5UwvGbDlfpPQQe uq6BP/U5HpiaguImy15yBrMmXZEoM2k7gi1+9H/URUgVvi0cQehkn1dYvBUH1b4Zzrp/ NYYg== X-Gm-Message-State: AOAM531o5++uQ9CN3pxW7oe1ykHaV6hJx9ryxIyGNQlyyVGUow0ZE/Rf G2eWnPrRtp0lr1DUNmQVVuY= X-Google-Smtp-Source: ABdhPJxieE0idylyik6vXz8FrZjh6UKW8VtRvqWqEdrzO1O4CHsVlxvsG3utIvUheEA4NXMOVE8t2A== X-Received: by 2002:a7b:c4d7:: with SMTP id g23mr27472986wmk.13.1640888330044; Thu, 30 Dec 2021 10:18:50 -0800 (PST) Received: from nijino.fritz.box (85-127-52-93.dsl.dynamic.surfer.at. [85.127.52.93]) by smtp.gmail.com with ESMTPSA id l25sm23665694wmh.18.2021.12.30.10.18.48 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 30 Dec 2021 10:18:49 -0800 (PST) Message-ID: From: Liliana Marie Prikler Date: Thu, 30 Dec 2021 19:18:48 +0100 In-Reply-To: <20211230073919.30327-4-philip@philipmcgrath.com> References: <082a81964a43ae5f735ad2ca433d0dfe00859c35.camel@gmail.com> <20211230073919.30327-1-philip@philipmcgrath.com> <20211230073919.30327-4-philip@philipmcgrath.com> Content-Type: text/plain; charset="UTF-8" User-Agent: Evolution 3.42.1 MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-BeenThere: debbugs-submit@debbugs.gnu.org X-Mailman-Version: 2.1.18 Precedence: list X-BeenThere: guix-patches@gnu.org List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: guix-patches-bounces+larch=yhetil.org@gnu.org Sender: "Guix-patches" X-Migadu-Flow: FLOW_IN X-Migadu-Country: US ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=yhetil.org; s=key1; t=1640888353; h=from:from:sender:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding:resent-cc: resent-from:resent-sender:resent-message-id:in-reply-to:in-reply-to: references:references:list-id:list-help:list-unsubscribe: list-subscribe:list-post:dkim-signature; bh=qO2VTi25k7hO1QTfZ6Qk2Zj4C2qh1INRBzIfSVZLFBg=; b=ETJscsJ4CbeoYOYNuENRyZpXNXCVeZ+/HOOCwhq8jZzGLYf0geGGAnWFDtn8xR859JDyyk rolrS8o4WZCtfNE2r5KFlSaVIiNa5ai4Pb+D+e+aZWPMZkNfbNhbqV0VJP6WxjLeHZHKM3 hxVNxJ9MJA3l8O/AiTxF+7TNnXJFBICsl2pw+rpX//0tRxTiEEc1EaY0uQsM0TSH9ZyD5k dYd1PKxaxl5xcCwPP5ZPAGbCc5cIaTXY6KPVYCESJLdUIdhsdDCMHRT2soFEBnqfVW6doj GUlwivKCkqPRCGLXpg2BN56QP5xMyWzWXY5MX1Sx+60n59667bC1teAUdBrQLA== ARC-Seal: i=1; s=key1; d=yhetil.org; t=1640888353; a=rsa-sha256; cv=none; b=QDnix4KCqp2T7ZQcefGqVG51Wtrm/UBlKk0imUShC+Fid/uAoM9eQBJQPAG2jDfp18rZXg AzXjNR8Z/7nmZBfZc+6rP9E8hBSd98gU/uua2120l3l5Q0E0txtdaW6WBDUdjrjK0RaDdW kg3lS00ozArro+22NNpYitJYeZ0RcV75ir/HHKGMdtRFnFlOWh4bbPLZ0c6OQGQFJePfDE h2jzUCrY+8Pg7Bf6Z1zFqM0D5/Ziq/wdkzZpjg9AkD399y9IIkyr5XtORkrIA/1rVXJAOT lpF77dKsJiuMxZ5IDytstE4WdWBZxecKqBcmFcGXqPyjmNgfOr/AxqP3o3RMjw== ARC-Authentication-Results: i=1; aspmx1.migadu.com; dkim=fail ("body hash did not verify") header.d=gmail.com header.s=20210112 header.b="i/AlKOMY"; dmarc=fail reason="SPF not aligned (relaxed)" header.from=gmail.com (policy=none); spf=pass (aspmx1.migadu.com: domain of "guix-patches-bounces+larch=yhetil.org@gnu.org" designates 209.51.188.17 as permitted sender) smtp.mailfrom="guix-patches-bounces+larch=yhetil.org@gnu.org" X-Migadu-Spam-Score: -1.97 Authentication-Results: aspmx1.migadu.com; dkim=fail ("body hash did not verify") header.d=gmail.com header.s=20210112 header.b="i/AlKOMY"; dmarc=fail reason="SPF not aligned (relaxed)" header.from=gmail.com (policy=none); spf=pass (aspmx1.migadu.com: domain of "guix-patches-bounces+larch=yhetil.org@gnu.org" designates 209.51.188.17 as permitted sender) smtp.mailfrom="guix-patches-bounces+larch=yhetil.org@gnu.org" X-Migadu-Queue-Id: B57E9656 X-Spam-Score: -1.97 X-Migadu-Scanner: scn1.migadu.com X-TUID: W0KhDdI4IazR Having argued for these procedures to be moved into their own file in a separate mail, now it's time to bikeshed stylistic choices. Am Donnerstag, dem 30.12.2021 um 02:38 -0500 schrieb Philip McGrath: > +(define (jsobject-ref js key failure-result) > +  "Return the value assosciated with KEY in the json object JS.  If > KEY is not > +found and FAILURE-RESULT is a procedure, it is called in tail position > with > +zero arguments.  Otherwise, FAILURE-RESULT is returned." > +  ;; TODO: `failure-result` should be optional, but should the default > +  ;; `failure-result` be #f (like `assoc-ref`), a thunk raising an > exception, > +  ;; '(@), or something else?  Keep it mandatory until we discuss and > decide. > +  (match js > +    (('@ . alist) > +     (match (assoc key alist) > +       (#f > +        (if (procedure? failure-result) > +            (failure-result) > +            failure-result)) > +       ((_ . value) > +        value))))) We can safely replace failure-result by Guile's DEFAULT and leave error handling to the user. > +(define (alist-pop alist key) > +  "Return two values: the first pair in ALIST with the given KEY in > its > +'car' (or #f, if no such pair exists) and an assosciation list like > (and > +potentially sharing storage with) ALIST, but with no entry for KEY." > +  (match (assoc key alist) > +    ;; If key isn't present, we don't need to do any allocation > +    (#f > +     (values #f alist)) > +    (found > +     (values found > +             ;; Because we have `found`, we can find it more > +             ;; efficiently this time with `eq?`. We avoid using > +             ;; `delq` because it would copy pairs in a shared > +             ;; tail. We assume a sufficiently smart compiler to > +             ;; handle "tail recursion modulo cons" (vid. e.g. Indiana > +             ;; University Technical Report No. 19, Friedman & Wise > +             ;; 1975) at least as efficiently as a hand-written > +             ;; tail-recursive implementation with an accumulator. > +             (let loop ((alist alist)) > +               (match alist > +                 ;; We know that `found` is present, > +                 ;; so no need to check for '() > +                 ((this . alist) > +                  (if (eq? this found) > +                      alist > +                      (cons this (loop alist)))))))))) I think this can be more efficiently be done in a "single" loop. (let loop ((rest alist) (previous '())) (match rest (() (values #f alist)) ((first . rest) (if (eq? (car first) key) (values first (reverse! previous rest)) (loop rest (cons first previous)))))) Also, I don't think your version is tail-recursive. (loop alist) is not in tail position from what I can tell. We should also look into SRFI-1 span. > +;; Sadly, Guile's implementation of (@ (srfi srfi-1) alist-delete) > +;; performs unnecessary allocation, e.g. this currently evaluates to > #f: > +;; > +;;     (let ((alist `(("a" . 1)("b" . 2)("c" . 3)))) > +;;       (eq? alist (alist-delete "x" alist))) > +;; > +;; These functions generally choose to allocate a new outer pair > (with the '@ > +;; tag), even though in unusual cases the resulting object might not > have > +;; changed, for the sake of simplicity and to avoid retaining a > reference to > +;; the original alist longer than necessary. But that is O(1) > allocation that > +;; could only rarely be avoided: `alist-delete` would allocate O(n) > pairs, > +;; which would only be necessary in the worst case. > +(define (alist-delete* alist key) > +  "Return an assosciation list like (and potentially sharing storage > with) > +ALIST, but with no entry for KEY." > +  (define-values (_popped remaining) > +    (alist-pop alist key)) > +  remaining) That's a pretty long comment around something that could be done with call-with-values or SRFI-71 let. I think one of these two should be preferred. Note that both our versions of alist-pop only pop the first key (as they should). This means that alist-delete* should really be called alist-delete-1 as in "remove the first pair in ALIST belonging to KEY". For the larger JSON handling below, this makes no difference however. > +(define (jsobject-delete js key) > +  "Return a json object like JS, but with no entry for KEY." > +  (cons '@ (match js > +             (('@ . alist) > +              (alist-delete* alist key))))) Fair enough. > +(define (alist-set alist key value) > +  "Return an assosciation list like ALIST, but with KEY mapped to > VALUE, > +replacing any existing mapping for KEY." > +  (acons key value (alist-delete* alist key))) Is order relevant here? Because we could just as well reimplement our alist-delete* loop and cons the replacement onto the rest. WDYT? > +(define (jsobject-set js key value) > +  "Return a json object like JS, but with KEY mapped to VALUE, > replacing any > +existing mapping for KEY." > +  (cons '@ (match js > +             (('@ . alist) > +              (alist-set alist key value))))) I think it'd be wiser to put the cons inside the match. > +(define jsobject-set* > +  (case-lambda > +    "Return a json object like JS, but functionally extended by > mapping each > +KEY to each VALUE, replacing any existing mapping for each KEY.  The > update > +takes place from left to right, so later mappings overwrite earlier > mappings > +for the same KEY." > +    ((js) > +     js) > +    ((js key value) > +     (jsobject-set js key value)) > +    ((js . args) > +     (cons '@ (match js > +                (('@ . alist) > +                 (let loop ((alist alist) > +                            (args args)) > +                   (match args > +                     (() > +                     alist) > +                     ((key value . args) > +                      (loop (alist-set alist key value) > +                            args)))))))))) I'm not sure if I like this "syntax". I think I'd prefer (jsobject-set* obj (FIELD1 VALUE1) (FIELD2 VALUE2) ...) with FIELD1, FIELD2 being identifiers WDYT? > +(define (alist-update alist key failure-result updater) > +  "Return an assosciation list like ALIST, but with KEY mapped to > the result > +of applying UPDATER to the value to which KEY is mapped in ALIST.  > When ALIST > +does not have an existing mapping for KEY, FAILURE-RESULT is used as > with > +'jsobject-ref' to obtain the argument for UPDATER." > +  ;; Often, `updater` will be a lambda expression, so making it the > last > +  ;; argument may help to makes the code legible, and the most > likely > +  ;; `failure-result` arguments are all shorter than the keyword > +  ;; `#:failure-result`.  Plus, making `failure-result` mandatory > helps make > +  ;; `alist-update` consistent with `alist-update*`. Which alist-update* are you referring to here? Either way, the failure-result to default argument from above applies, but we could keyword it. > +  (define-values (popped tail-alist) > +    (alist-pop alist key)) > +  (acons key > +         (updater (match popped > +                    (#f > +                     (if (procedure? failure-result) > +                         (failure-result) > +                         failure-result)) > +                    ((_ . value) > +                     value))) > +         tail-alist)) SRFI-71 let says hi. Also the ordering question applies. I'm starting to think we should implement alist-pop, alist-set and alist-update in terms of a single more powerful function producing three values (or SRFI-1 span). > +(define (jsobject-update js key failure-result updater) > +  "Return a json object like JS, but with KEY mapped to the result > of applying > +UPDATER to the value to which KEY is mapped in JS.  When JS does not > have an > +existing mapping for KEY, FAILURE-RESULT is used as with 'jsobject- > ref' to > +obtain the argument for UPDATER." > +  (cons '@ (match js > +             (('@ . alist) > +              (alist-update alist key failure-result updater))))) Same default argument. Cons inside. > +(define jsobject-update* > +  (case-lambda > +    "Return a json object like JS, but functionally extended by > replacing the > +mapping for each KEY with the result of applying the corresponding > UPDATER to > +the value to which that KEY is mapped in JS---or, if no such mapping > exists, > +to a value based on the corresponding FAILURE-RESULT as with > 'jsobject-ref'. > +The update takes place from left to right, so later UPDATERs will > receive the > +values returned by earlier UPDATERs for the same KEY." > +    ((js) > +     js) > +    ((js key failure-result updater) > +     (jsobject-update js key failure-result updater)) > +    ((js . args) > +     (cons '@ (match js > +                (('@ . alist) > +                 (let loop ((alist alist) > +                            (args args)) > +                   (match args > +                     (() > +                     alist) > +                     ((key failure-result updater . args) > +                      (loop (alist-update alist key failure-result > updater) > +                            args)))))))))) Same default argument. Cons inside. > +(define* (jsobject-union #:key > +                         (combine (lambda (a b) b)) > +                         (combine/key (lambda (k a b) (combine a > b))) > +                         #:rest json-objects) > +  "Combine the given JSON-OBJECTS into a single json object.  The > JSON-OBJECTS > +are merged from left to right by adding each key/value pair of each > object to > +the aggregate object in turn.  When one of the JSON-OBJECTS contains > a mapping > +from some key KEY to a value VAL such that the aggregate object > already > +contains a mapping from KEY to a value VAL0, the aggregate object is > +functionally updated to instead map KEY to the value of (COMBINE/KEY > KEY VAL0 > +VAL).  The default COMBINE/KEY tail-calls (COMBINE VAL0 VAL), and > the default > +COMBINE simply returns its second argument, so, by default, mappings > in later > +JSON-OBJECTS supersede those in earlier ones." > +  (match (filter (lambda (v) > +                   (not (or (keyword? v) > +                            (procedure? v)))) > +                 json-objects) > +    (() > +     '(@)) > +    (((and js0 ('@ . _))) > +     js0) > +    ((('@ . alist0) ('@ . alist*) ...) > +     (cons '@ (fold (lambda (alist1 alist0) > +                      (if (null? alist0) > +                          alist1 > +                          (fold (lambda (k+v alist0) > +                                  (match k+v > +                                    ((k . v) > +                                     (define-values (popped tail- > alist) > +                                       (alist-pop alist0 k)) > +                                     (match popped > +                                       (#f > +                                        (cons k+v tail-alist)) > +                                       ((_ . v0) > +                                        (acons k > +                                               (combine/key k v0 v) > +                                               tail-alist)))))) > +                                alist0 > +                                alist1))) > +                    alist0 > +                    alist*))))) Same default argument. Cons inside. I think having a single combine function taking (k a b) would be less confusing than having two. Is there a rationale for the form you chose? > + > +;;; > +;;; Phases. > +;;; > + >  (define (set-home . _) >    (with-directory-excursion ".." >      (let loop ((i 0)) > @@ -49,7 +281,7 @@ (define (set-home . _) >  (define (module-name module) >    (let* ((package.json (string-append module "/package.json")) >           (package-meta (call-with-input-file package.json read- > json))) > -    (assoc-ref package-meta "name"))) > +    (jsobject-ref package-meta "name" #f))) >   >  (define (index-modules input-paths) >    (define (list-modules directory) > @@ -73,27 +305,24 @@ (define* (patch-dependencies #:key inputs > #:allow-other-keys) >   >    (define index (index-modules (map cdr inputs))) >   > -  (define (resolve-dependencies package-meta meta-key) > -    (fold (lambda (key+value acc) > -            (match key+value > -              ('@ acc) > -              ((key . value) (acons key (hash-ref index key value) > acc)))) > -          '() > -          (or (assoc-ref package-meta meta-key) '()))) > +  (define resolve-dependencies > +    (match-lambda > +      (('@ . alist) > +       (cons '@ (map (match-lambda > +                       ((key . value) > +                        (cons key (hash-ref index key value)))) > +                     alist))))) >   > -  (with-atomic-file-replacement "package.json" > -    (lambda (in out) > -      (let ((package-meta (read-json in))) > -        (assoc-set! package-meta "dependencies" > -                    (append > -                     '(@) > -                     (resolve-dependencies package-meta > "dependencies") > -                     (resolve-dependencies package-meta > "peerDependencies"))) > -        (assoc-set! package-meta "devDependencies" > -                    (append > -                     '(@) > -                     (resolve-dependencies package-meta > "devDependencies"))) > -        (write-json package-meta out)))) > +  (with-atomic-json-file-replacement "package.json" > +    (lambda (pkg-meta) > +      (jsobject-update* > +       pkg-meta > +       "devDependencies" '(@) resolve-dependencies > +       "dependencies" '(@) (lambda (deps) > +                             (resolve-dependencies > +                              (jsobject-union > +                               (jsobject-ref pkg-meta > "peerDependencies" '(@)) > +                               deps)))))) >    #t) We should probably add a function to our js utils that "generates an empty object", because '(@) is quite confusing to see in these circumstances. Otherwise LGTM with the aforementioned caveats.  Cheers