Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions documentation/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
- [JSON-in-KDL](./api/json.md)
- [Compabitility with KDL v1](./api/v1-compat.md)
- [(De)Serialization Tools](./api/dessert.md)
- [Node pipes (experimental)](./api/node-pipes.md)

# API Reference

Expand Down
121 changes: 121 additions & 0 deletions documentation/src/api/node-pipes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
# Node pipes (experimental)

> This is an experimental extension of KDL, enabled with the `experimentalNodePipes` [parser flag](./parse.md#parser-flags).
> Documents using it are not valid KDL for other parsers.

Node pipes let you write deeply nested single-child structures as a left-to-right chain.

```kdl
route "/users" { handler list-users #> auth role=admin #> cache ttl=60 #> log }

// is equivalent to

route "/users" { log { cache ttl=60 { auth role=admin { handler list-users } } } }
```

```js
import {parse} from "@bgotink/kdl";

const document = parse(
'task fetch url="https://example.com" #> timeout 5 #> retry times=3',
{flags: {experimentalNodePipes: true}},
);
```

## Semantics

`A #> B` is equivalent to `B { A }`: the node on the left becomes the sole child of the node on the right.
Chains are left-associative: `A #> B #> C` is equivalent to `C { B { A } }`.

The left-hand side of `#>` is always a single node, which may have children of its own:

```kdl
sprite hero { frame 1; frame 2 } #> loop 4 #> ease in-out #> delay 2

// is equivalent to

delay 2 { ease in-out { loop 4 { sprite hero { frame 1; frame 2 } } } }
```

The right-hand side of `#>` cannot have a children block. `text "Hello" #> padding 8 { border }` is invalid. Use the nested form instead.

The parsed document is identical to the nested form: queries, (de)serialization, and all other APIs see regular nested nodes.

## The `#>` token

`#>` is a pipe wherever it appears between nodes, with or without surrounding whitespace: `a #> b`, `a#>b`, and `a #>b` are all equivalent.

Parsers without this extension reject documents that use node pipes.
Enabling the flag doesn't change the meaning of any valid KDL document, and the rules about when strings must be quoted are unchanged.

When the [`experimentalSuffixedNumbers`](./parse.md#parser-flags) flag is also enabled, `#>` immediately after a number is parsed as a number suffix.
In `loop 4#> ease`, `4` has the suffix tag `>`.
Add whitespace before the pipe in that case: `loop 4 #> ease`.

## Multiline chains

Chains can span multiple lines, with `#>` either ending a line or starting the next one:

```kdl
source "orders.csv" #>
filter status=paid #>
group-by customer #>
sort total order=desc

source "orders.csv"
#> filter status=paid
#> group-by customer
#> sort total order=desc
```

Blank lines and comments are allowed between stages.
A line break never changes the meaning of a chain: a leading `#>` always continues the node right before it.
A semicolon ends the chain: `a; #> b` is an error, as is a `#>` at the start of a document or children block.

## Slashdash

A slashdash before the first node of a chain comments out the entire chain:

```kdl
/- image "photo.jpg" #> resize width=800 #> crop ratio="16/9" #> grayscale

/- image "photo.jpg"
#> resize width=800
#> crop ratio="16/9"
#> grayscale
```

A slashdash before a `#>` comments out that single stage:

```kdl
text "Hello" #> padding 8 /-#> border width=1 #> center

// is equivalent to

center { padding 8 { text "Hello" } }
```

## Formatting

Parsing a pipe chain retains the pipe formatting, so `format(parse(text))` writes the chain back as it was written.

The pipe form is only preserved while the node still has exactly one child, and that child is the same node object it was parsed with.
Editing that child in place (e.g. adding an argument) keeps the pipe form.
Removing the child, adding a second child, or replacing it with another node makes the formatter write the nested form instead.

There's no API to create pipe chains in code: pipe formatting only ever comes from parsing.
Both `clearFormat()` and `formatCompact()` drop pipe formatting and yield the nested form, which is valid KDL for any parser.

## Locations

When `storeLocations` is enabled, the location of each node in a chain covers only that node's own text.
For `text "Hello" #> padding 8`, the `padding` node's location spans `padding 8`, and the `text` node's location spans `text "Hello"`.

## Whitespace

Slashdashed stages are retained as part of the surrounding whitespace.
Parsing that whitespace with `parse(text, {as: "whitespace in document"})` yields a part `{type: "slashdash", pipe: true, preface, value}` where `value` is the commented-out node.

## Limitations

Only supported by the KDL v2 parser.
3 changes: 2 additions & 1 deletion documentation/src/api/parse.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,9 @@ There's also a 6.5x speed difference between the two methods, but even with `gra
## Parser flags

The `parse` function accepts optional flags to define parser behaviour.
There is currently a single flag:
The following flags are supported:

- [`experimentalNodePipes`](./node-pipes.md): if enabled, `A #> B` is equivalent to `B { A }`, allowing deeply nested single-child structures to be written as a chain, e.g. `text "Hello" #> padding 8 #> center` is equivalent to `center { padding 8 { text "Hello" } }`.
- [`experimentalSuffixedNumbers`](./reference/index/index.md#experimentalsuffixednumbers): if enabled, numbers can have a suffix tag (e.g. `10px` is equivalent to `(px)10`).
This suffix is used as tag for the value, which implies a number cannot have both a tag and a suffix.
The following limitations apply unless a `#` is used as separator:
Expand Down
12 changes: 12 additions & 0 deletions documentation/src/internals/parser.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,18 @@ The parser itself is greatly simplified and very lenient when it comes to string
All multiline quoted and raw strings are post-processed to remove leading whitespace.
All quoted strings are post-processed to replace any escapes.

## Node pipes

The experimental [node pipes](../api/node-pipes.md) add a `#>` token, which the tokenizer only yields if the `experimentalNodePipes` flag is enabled.
If the `experimentalSuffixedNumbers` flag is enabled too, a `#>` directly following a number is tokenized as a hashed suffix instead.

Pipe stages on a single line are parsed after the `base-node`, which doesn't require any look-ahead.
After consuming a slashdash, `base-node` checks whether `#>` follows.
If so, it leaves the pipe stage for its caller to parse.

A `#>` at the start of a line continues the chain of the preceding node.
Rather than looking ahead past the newline, the `document` parser reopens the node it already added: it removes that node from the document again and moves the whitespace it had consumed in between into the pipe formatting.

<script type="module" src="./grammar.js"></script>
<link rel="stylesheet" href="./grammar.css">

Expand Down
1 change: 1 addition & 0 deletions src/clear-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ function clearFormatNode(node) {
node.beforeChildren = undefined;
node.betweenTagAndName = undefined;
node.trailing = undefined;
node.pipe = undefined;

if (node.tag) {
clearFormatTag(node.tag);
Expand Down
17 changes: 15 additions & 2 deletions src/flags.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,16 @@
* @typedef {object} ParserFlags
* Flags to turn language features on or off
*
* @prop {boolean} experimentalNodePipes
* Support node pipes using a proposal that is not part of the language
*
* If enabled, `A #> B` is equivalent to `B { A }`, i.e. the node on the left
* becomes the sole child of the node on the right. Chains are left-associative:
* `A #> B #> C` is equivalent to `C { B { A } }`.
*
* If combined with `experimentalSuffixedNumbers`, a `#>` directly following a
* number is parsed as a number suffix.
*
* @prop {boolean} experimentalSuffixedNumbers
* Support suffixed numbers using a proposal that might not make it into the language
*
Expand All @@ -23,6 +33,9 @@
* @param {Partial<Readonly<ParserFlags>>} [flags]
* @returns {ParserFlags}
*/
export function resolveFlags({experimentalSuffixedNumbers = false} = {}) {
return {experimentalSuffixedNumbers};
export function resolveFlags({
experimentalNodePipes = false,
experimentalSuffixedNumbers = false,
} = {}) {
return {experimentalNodePipes, experimentalSuffixedNumbers};
}
32 changes: 29 additions & 3 deletions src/format.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,18 +150,44 @@ function formatEntry(entry) {
* @returns {string}
*/
function formatNode(node, indentation) {
return `${node.leading ?? "\t".repeat(indentation)}${formatTag(node.tag)}${
return `${node.leading ?? "\t".repeat(indentation)}${formatNodeContent(
node,
indentation,
)}${node.trailing ?? "\n"}`;
}

/**
* Format the node without leading and trailing whitespace
*
* @param {Node} node
* @param {number} indentation
* @returns {string}
*/
function formatNodeContent(node, indentation) {
const {pipe} = node;
const isPipe =
pipe != null &&
node.children?.nodes.length === 1 &&
node.children.nodes[0] === pipe.child;

return `${
isPipe ?
`${formatNodeContent(pipe.child, indentation)}${
pipe.beforePipe ?? " "
}#>${pipe.afterPipe ?? " "}`
: ""
}${formatTag(node.tag)}${
node.betweenTagAndName ?? ""
}${formatIdentifier(node.name)}${node.entries
.map((entry) => formatEntry(entry))
.join("")}${
node.children ?
node.children && !isPipe ?
`${node.beforeChildren ?? " "}{${formatDocument(
node.children,
indentation + 1,
)}}`
: ""
}${node.trailing ?? "\n"}`;
}`;
}

/**
Expand Down
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export {parse} from "./parse.js";
/** @typedef {import('./model/whitespace.js').InlineWhitespace} InlineWhitespace */
/** @typedef {import('./model/whitespace.js').LineSpace} LineSpace */
/** @typedef {import('./model/whitespace.js').SlashDashInDocument} SlashDashInDocument */
/** @typedef {import('./model/whitespace.js').SlashDashedPipeInDocument} SlashDashedPipeInDocument */
/** @typedef {import('./model/whitespace.js').MultilineComment} MultilineComment */
/** @typedef {import('./model/whitespace.js').Newline} Newline */
/** @typedef {import('./model/whitespace.js').NodeSpace} NodeSpace */
Expand Down
19 changes: 19 additions & 0 deletions src/model/node.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,16 @@ export class Node {
*/
betweenTagAndName;

/**
* Formatting of a node pipe, i.e. `child #> node`
*
* This formatting is only used if the node's children consist of just the given child.
*
* @type {{child: Node, beforePipe?: string, afterPipe?: string}=}
* @hidden
*/
pipe;

/**
* @param {Identifier} name
* @param {Entry[]} [entries]
Expand Down Expand Up @@ -134,6 +144,15 @@ export class Node {
clone.beforeChildren = this.beforeChildren;
clone.trailing = this.trailing;

const pipeChild =
this.pipe &&
clone.children?.nodes[
this.children?.nodes.indexOf(this.pipe.child) ?? -1
];
if (pipeChild) {
clone.pipe = {...this.pipe, child: pipeChild};
}

return clone;
}

Expand Down
33 changes: 32 additions & 1 deletion src/model/whitespace.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,38 @@ export interface SlashDashInDocument {
value: Node;
}

/**
* A slashdash comment of a pipe stage, i.e. a slashdash commented `#> node`
*
* This is only used if the `experimentalNodePipes` flag is enabled.
*/
export interface SlashDashedPipeInDocument {
/**
* A property to differentiate the different types of whitespace
*/
type: "slashdash";

/**
* A property to differentiate this from a slashdash commented node
*/
pipe: true;

/**
* Any whitespace between the slashdash token and the pipe
*/
preface: NodeSpace[];

/**
* The commented-out node. Its leading whitespace contains the whitespace between `#>` and the node.
*/
value: Node;
}

/**
* Whitespace in a document, i.e. before/after/between nodes
*/
export type WhitespaceInDocument = (LineSpace | SlashDashInDocument)[];
export type WhitespaceInDocument = (
| LineSpace
| SlashDashInDocument
| SlashDashedPipeInDocument
)[];
Loading