Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add parsing and prettier support for @example tags in liquid doc #725

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
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
16 changes: 11 additions & 5 deletions packages/liquid-html-parser/grammar/liquid-html.ohm
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,10 @@ Liquid <: Helpers {
liquidTagLiquidMarkup = tagMarkup

liquidTagContentFor = liquidTagRule<"content_for", liquidTagContentForMarkup>

liquidTagContentForMarkup =
contentForType (argumentSeparatorOptionalComma contentForTagArgument) (space* ",")? space*

contentForTagArgument = listOf<contentForNamedArgument<delimTag>, argumentSeparatorOptionalComma>
contentForNamedArgument<delim> = (variableSegment ("." variableSegment)*) space* ":" space* (liquidExpression<delim>)

Expand Down Expand Up @@ -217,7 +217,7 @@ Liquid <: Helpers {
commentBlockStart = "{%" "-"? space* ("comment" endOfIdentifier) space* tagMarkup "-"? "%}"
commentBlockEnd = "{%" "-"? space* ("endcomment" endOfIdentifier) space* tagMarkup "-"? "%}"

liquidDoc =
liquidDoc =
liquidDocStart
liquidDocBody
liquidDocEnd
Expand Down Expand Up @@ -392,20 +392,26 @@ LiquidDoc <: Helpers {
Node := (LiquidDocNode | TextNode)*
LiquidDocNode =
| paramNode
| exampleNode
| fallbackNode

// By default, space matches new lines as well. We override it here to make writing rules easier.
strictSpace = " " | "\t"
// We use this as an escape hatch to stop matching TextNode and try again when one of these characters is encountered
// We use this as an escape hatch to stop matching TextNode and try again when one of these characters is encountered
openControl:= "@" | end

fallbackNode = "@" anyExceptStar<endOfParam>
paramNode = "@param" strictSpace* paramType? strictSpace* paramName (strictSpace* "-")? strictSpace* paramDescription
paramType = "{" strictSpace* paramTypeContent strictSpace* "}"
paramTypeContent = anyExceptStar<("}"| strictSpace)>
paramName = identifierCharacter+
paramDescription = anyExceptStar<endOfParam>
endOfParam = strictSpace* (newline | end)

exampleNode = "@example" strictSpace* exampleContent
exampleContent = anyExceptStar<endOfExample>
endOfExample = strictSpace* ("@" | end)

fallbackNode = "@" anyExceptStar<endOfParam>
}

LiquidHTML <: Liquid {
Expand Down
81 changes: 79 additions & 2 deletions packages/liquid-html-parser/src/stage-1-cst.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1108,6 +1108,83 @@ describe('Unit: Stage 1 (CST)', () => {
expectPath(cst, '0.children.2.type').to.equal('TextNode');
expectPath(cst, '0.children.2.value').to.equal('@unsupported');
});

it('should parse a basic example tag', () => {
const testStr = `{% doc -%} @example {%- enddoc %}`;
cst = toCST(testStr);
expectPath(cst, '0.type').to.equal('LiquidRawTag');
expectPath(cst, '0.name').to.equal('doc');
expectPath(cst, '0.children.0.type').to.equal('LiquidDocExampleNode');
expectPath(cst, '0.children.0.exampleContent.value').to.equal('');
});

it('should parse example tag with content that has leading whitespace', () => {
const testStr = `{% doc %} @example hello there {%- enddoc %}`;
cst = toCST(testStr);
expectPath(cst, '0.type').to.equal('LiquidRawTag');
expectPath(cst, '0.name').to.equal('doc');
expectPath(cst, '0.children.0.type').to.equal('LiquidDocExampleNode');
expectPath(cst, '0.children.0.name').to.equal('example');
expectPath(cst, '0.children.0.exampleContent.value').to.equal('hello there');
});

it('should parse an example tag with a value', () => {
const testStr = `{% doc %}
@example
This is an example
It supports multiple lines
{% enddoc %}`;

cst = toCST(testStr);
expectPath(cst, '0.type').to.equal('LiquidRawTag');
expectPath(cst, '0.name').to.equal('doc');
expectPath(cst, '0.children.0.type').to.equal('LiquidDocExampleNode');
expectPath(cst, '0.children.0.name').to.equal('example');
expectPath(cst, '0.children.0.exampleContent.value').toEqual(
expect.stringContaining('This is an example'),
);
expectPath(cst, '0.children.0.exampleContent.value').toEqual(
expect.stringContaining('It supports multiple lines'),
);
});

it('should parse example node and stop at the next @', () => {
const testStr = `{% doc %}
@example
This is an example
@param param1
{% enddoc %}`;
cst = toCST(testStr);
expectPath(cst, '0.children.0.type').to.equal('LiquidDocExampleNode');
expectPath(cst, '0.children.0.name').to.equal('example');
expectPath(cst, '0.children.0.exampleContent.value').toEqual(
expect.stringContaining('This is an example'),
);
expectPath(cst, '0.children.1.type').to.equal('LiquidDocParamNode');
expectPath(cst, '0.children.1.paramName.value').to.equal('param1');
});

it('should parse example node with whitespace and new lines', () => {
const testStr = `{% doc %}
@example hello there my friend
This is an example
It supports multiple lines
{% enddoc %}`;
cst = toCST(testStr);
expectPath(cst, '0.type').to.equal('LiquidRawTag');
expectPath(cst, '0.name').to.equal('doc');
expectPath(cst, '0.children.0.type').to.equal('LiquidDocExampleNode');
expectPath(cst, '0.children.0.name').to.equal('example');
expectPath(cst, '0.children.0.exampleContent.value').toEqual(
expect.stringContaining('hello there my friend'),
);
expectPath(cst, '0.children.0.exampleContent.value').toEqual(
expect.stringContaining('This is an example'),
);
expectPath(cst, '0.children.0.exampleContent.value').toEqual(
expect.stringContaining('It supports multiple lines'),
);
});
}
});
});
Expand Down Expand Up @@ -1304,8 +1381,8 @@ describe('Unit: Stage 1 (CST)', () => {
{ type: 'AttrSingleQuoted', name: 'single', quote: '‘' },
{ type: 'AttrSingleQuoted', name: 'single', quote: '’' },
{ type: 'AttrDoubleQuoted', name: 'double', quote: '"' },
{ type: 'AttrDoubleQuoted', name: 'double', quote: '' },
{ type: 'AttrDoubleQuoted', name: 'double', quote: '' },
{ type: 'AttrDoubleQuoted', name: 'double', quote: '"' },
{ type: 'AttrDoubleQuoted', name: 'double', quote: '"' },
{ type: 'AttrUnquoted', name: 'unquoted', quote: '' },
].forEach((testConfig) => {
[
Expand Down
18 changes: 17 additions & 1 deletion packages/liquid-html-parser/src/stage-1-cst.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ export enum ConcreteNodeTypes {
ContentForNamedArgument = 'ContentForNamedArgument',

LiquidDocParamNode = 'LiquidDocParamNode',
LiquidDocExampleNode = 'LiquidDocExampleNode',
}

export const LiquidLiteralValues = {
Expand Down Expand Up @@ -115,6 +116,12 @@ export interface ConcreteLiquidDocParamNode
paramType: ConcreteTextNode | null;
}

export interface ConcreteLiquidDocExampleNode
extends ConcreteBasicNode<ConcreteNodeTypes.LiquidDocExampleNode> {
name: 'example';
exampleContent: ConcreteTextNode;
}

export interface ConcreteHtmlNodeBase<T> extends ConcreteBasicNode<T> {
attrList?: ConcreteAttributeNode[];
}
Expand Down Expand Up @@ -454,7 +461,7 @@ export type LiquidHtmlCST = LiquidHtmlConcreteNode[];

export type LiquidCST = LiquidConcreteNode[];

export type LiquidDocConcreteNode = ConcreteLiquidDocParamNode;
export type LiquidDocConcreteNode = ConcreteLiquidDocParamNode | ConcreteLiquidDocExampleNode;

interface Mapping {
[k: string]: number | TemplateMapping | TopLevelFunctionMapping;
Expand Down Expand Up @@ -1346,6 +1353,15 @@ function toLiquidDocAST(source: string, matchingSource: string, offset: number)
paramTypeContent: textNode,
paramName: textNode,
paramDescription: textNode,
exampleNode: {
type: ConcreteNodeTypes.LiquidDocExampleNode,
name: 'example',
locStart,
locEnd,
source,
exampleContent: 2,
},
exampleContent: textNode,
fallbackNode: textNode,
};

Expand Down
49 changes: 49 additions & 0 deletions packages/liquid-html-parser/src/stage-2-ast.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1258,6 +1258,55 @@ describe('Unit: Stage 2 (AST)', () => {
expectPath(ast, 'children.0.body.nodes.2.value').to.eql(
'@unsupported this node falls back to a text node',
);

ast = toLiquidAST(`
{% doc -%}
@example simple inline example
{%- enddoc %}
`);
expectPath(ast, 'children.0.type').to.eql('LiquidRawTag');
expectPath(ast, 'children.0.name').to.eql('doc');
expectPath(ast, 'children.0.body.nodes.0.name').to.eql('example');
expectPath(ast, 'children.0.body.nodes.0.type').to.eql('LiquidDocExampleNode');
expectPath(ast, 'children.0.body.nodes.0.exampleContent.type').to.eql('TextNode');
expectPath(ast, 'children.0.body.nodes.0.exampleContent.value').to.eql(
'simple inline example',
);

ast = toLiquidAST(`
{% doc -%}
@example including inline code
This is a valid example
It can have multiple lines
{% enddoc %}
`);
expectPath(ast, 'children.0.body.nodes.0.type').to.eql('LiquidDocExampleNode');
expectPath(ast, 'children.0.body.nodes.0.name').to.eql('example');
expectPath(ast, 'children.0.body.nodes.0.exampleContent.value').to.eql(
'including inline code\nThis is a valid example\nIt can have multiple lines',
);

ast = toLiquidAST(`
{% doc -%}
@example
This is a valid example
It can have multiple lines
@param {String} paramWithDescription - param with description
{% enddoc %}
`);
expectPath(ast, 'children.0.type').to.eql('LiquidRawTag');
expectPath(ast, 'children.0.name').to.eql('doc');
expectPath(ast, 'children.0.body.nodes.0.type').to.eql('LiquidDocExampleNode');
expectPath(ast, 'children.0.body.nodes.0.name').to.eql('example');
expectPath(ast, 'children.0.body.nodes.0.exampleContent.value').to.eql(
'This is a valid example\nIt can have multiple lines',
);
expectPath(ast, 'children.0.body.nodes.1.type').to.eql('LiquidDocParamNode');
expectPath(ast, 'children.0.body.nodes.1.name').to.eql('param');
expectPath(ast, 'children.0.body.nodes.1.paramName.value').to.eql('paramWithDescription');
expectPath(ast, 'children.0.body.nodes.1.paramDescription.value').to.eql(
'param with description',
);
});

it('should parse unclosed tables with assignments', () => {
Expand Down
31 changes: 30 additions & 1 deletion packages/liquid-html-parser/src/stage-2-ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ export type LiquidHtmlNode =
| LiquidLogicalExpression
| LiquidComparison
| TextNode
| LiquidDocParamNode;
| LiquidDocParamNode
| LiquidDocExampleNode;

/** The root node of all LiquidHTML ASTs. */
export interface DocumentNode extends ASTNode<NodeTypes.Document> {
Expand Down Expand Up @@ -765,6 +766,14 @@ export interface LiquidDocParamNode extends ASTNode<NodeTypes.LiquidDocParamNode
/** Optional type annotation for the parameter (e.g. "{string}", "{number}") */
paramType: TextNode | null;
}

/** Represents a `@example` node in a LiquidDoc comment - `@example @exampleContent` */
export interface LiquidDocExampleNode extends ASTNode<NodeTypes.LiquidDocExampleNode> {
name: 'example';
/** The contents of the example (e.g. "{{ product }}"). Can be multiline. */
exampleContent: TextNode;
}

export interface ASTNode<T> {
/**
* The type of the node, as a string.
Expand Down Expand Up @@ -1297,6 +1306,26 @@ function buildAst(
break;
}

case ConcreteNodeTypes.LiquidDocExampleNode: {
builder.push({
type: NodeTypes.LiquidDocExampleNode,
name: node.name,
position: position(node),
source: node.source,
exampleContent: {
type: NodeTypes.TextNode,
value: node.exampleContent.value
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
.join('\n'),
position: position(node.exampleContent),
source: node.exampleContent.source,
},
});
break;
}

default: {
assertNever(node);
}
Expand Down
1 change: 1 addition & 0 deletions packages/liquid-html-parser/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export enum NodeTypes {
RenderMarkup = 'RenderMarkup',
RenderVariableExpression = 'RenderVariableExpression',
LiquidDocParamNode = 'LiquidDocParamNode',
LiquidDocExampleNode = 'LiquidDocExampleNode',
}

// These are officially supported with special node types
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ function getCssDisplay(node: AugmentedNode<WithSiblings>, options: LiquidParserO
case NodeTypes.LogicalExpression:
case NodeTypes.Comparison:
case NodeTypes.LiquidDocParamNode:
case NodeTypes.LiquidDocExampleNode:
return 'should not be relevant';

default:
Expand Down Expand Up @@ -235,6 +236,7 @@ function getNodeCssStyleWhiteSpace(
case NodeTypes.LogicalExpression:
case NodeTypes.Comparison:
case NodeTypes.LiquidDocParamNode:
case NodeTypes.LiquidDocExampleNode:
return 'should not be relevant';

default:
Expand Down
25 changes: 25 additions & 0 deletions packages/prettier-plugin-liquid/src/printer/print/liquid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
isBranchedTag,
RawMarkup,
LiquidDocParamNode,
LiquidDocExampleNode,
} from '@shopify/liquid-html-parser';
import { Doc, doc } from 'prettier';

Expand Down Expand Up @@ -536,6 +537,30 @@ export function printLiquidDocParam(
return parts;
}

export function printLiquidDocExample(
path: AstPath<LiquidDocExampleNode>,
options: LiquidParserOptions,
_print: LiquidPrinter,
_args: LiquidPrinterArgs,
): Doc {
const node = path.getValue();
const parts: Doc[] = ['@example'];

if (node.exampleContent?.value) {
const content = node.exampleContent.value.trim();
if (content) {
parts.push(hardline);
const lines = content
.split('\n')
.map((line) => line.trim())
.filter(Boolean);
parts.push(join(hardline, lines));
}
}

return parts;
}

function innerLeadingWhitespace(node: LiquidTag | LiquidBranch) {
if (!node.firstChild) {
if (node.isDanglingWhitespaceSensitive && node.hasDanglingWhitespace) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
getConditionalComment,
LiquidDocExampleNode,
LiquidDocParamNode,
NodeTypes,
Position,
Expand Down Expand Up @@ -47,6 +48,7 @@ import {
printLiquidTag,
printLiquidVariableOutput,
printLiquidDocParam,
printLiquidDocExample,
} from './print/liquid';
import { printClosingTagSuffix, printOpeningTagPrefix } from './print/tag';
import { bodyLines, hasLineBreakInRange, isEmpty, isTextLikeNode, reindent } from './utils';
Expand Down Expand Up @@ -559,6 +561,10 @@ function printNode(
return printLiquidDocParam(path as AstPath<LiquidDocParamNode>, options, print, args);
}

case NodeTypes.LiquidDocExampleNode: {
return printLiquidDocExample(path as AstPath<LiquidDocExampleNode>, options, print, args);
}

default: {
return assertNever(node);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,9 @@ It should normalize the param description
{% doc %}
@param paramName - param with description
{% enddoc %}

It should push example content to the next line
{% doc %}
@example
This is a valid example
{% enddoc %}
Loading
Loading