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

Allow to parse value literals #295

Merged
merged 1 commit into from
Apr 16, 2023
Merged
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 src/GraphQLParser.ApiTests/GraphQLParser.approved.txt
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,7 @@ namespace GraphQLParser
public static class Parser
{
public static GraphQLParser.AST.GraphQLDocument Parse(GraphQLParser.ROM source, GraphQLParser.ParserOptions options = default) { }
public static GraphQLParser.AST.GraphQLValue ParseValue(GraphQLParser.ROM source, GraphQLParser.ParserOptions options = default) { }
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a note - it seems that we could make more methods public to allow parse concrete parts of document.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I was thinking like "couldn't we just have Parse" return whatever was parsed? Then cast it to whatever type was desired or something? But the problem is that the parser wouldn't know the initial state -- if, for example, it was parsing a list of arguments or a list of directives.

We could perhaps add Parse<T> where T is a node type, and then a switch typeof(T) logic to bump into the correct code.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then you could write Parse<GraphQLValue> if you want that, or Parse<List<GraphQLArgument>> if you are parsing that, etc, with very little API changes and somewhat intuitive behavior.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not really a fan of a million different public Parse... methods. Hopefully they are all exposed as protected methods or something so anyone CAN use them if needed.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a subject to discuss for v9.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}
public struct ParserOptions
{
Expand Down
22 changes: 22 additions & 0 deletions src/GraphQLParser.Tests/ParserTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Collections;
using System.Runtime.InteropServices;
using GraphQLParser.Exceptions;

namespace GraphQLParser.Tests;

Expand Down Expand Up @@ -979,6 +980,27 @@ public void Should_Parse_Empty_Types(string text, ASTNodeKind kind)
document.Definitions[0].Kind.ShouldBe(kind);
}

[Theory]
[InlineData("null", ASTNodeKind.NullValue)]
[InlineData("1", ASTNodeKind.IntValue)]
[InlineData("1.1", ASTNodeKind.FloatValue)]
[InlineData("\"abc\"", ASTNodeKind.StringValue, "abc")]
[InlineData("\"escaped \\n\\r\\b\\t\\f\"", ASTNodeKind.StringValue, "escaped \n\r\b\t\f")]
[InlineData("true", ASTNodeKind.BooleanValue)]
[InlineData("RED", ASTNodeKind.EnumValue)]
[InlineData("[ 1, 2, 3]", ASTNodeKind.ListValue)]
[InlineData("{ a: 1, b: \"abc\", c: RED}", ASTNodeKind.ObjectValue)]
public void Should_Parse_Value_Literal_But_Not_Entire_Document(string text, ASTNodeKind kind, string expected = null)
{
Should.Throw<GraphQLSyntaxErrorException>(() => Parser.Parse(text));

var value = Parser.ParseValue(text);
value.ShouldNotBeNull();
value.Kind.ShouldBe(kind);
if (expected != null)
((GraphQLStringValue)value).Value.ShouldBe(expected);
}

[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
Expand Down
4 changes: 2 additions & 2 deletions src/GraphQLParser/GraphQLParser.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
</ItemGroup>

<ItemGroup Condition="'$(IsTestProject)' != 'true'">
<InternalsVisibleTo Condition="'$(SignAssembly)' == 'true'" Include="$(MSBuildProjectName).Tests, $(_FriendAssembliesPublicKey);$(MSBuildProjectName).Benchmarks, $(_FriendAssembliesPublicKey)"/>
<InternalsVisibleTo Condition="'$(SignAssembly)' != 'true'" Include="$(MSBuildProjectName).Tests;$(MSBuildProjectName).Benchmarks"/>
<InternalsVisibleTo Condition="'$(SignAssembly)' == 'true'" Include="$(MSBuildProjectName).Tests, $(_FriendAssembliesPublicKey);$(MSBuildProjectName).Benchmarks, $(_FriendAssembliesPublicKey)" />
<InternalsVisibleTo Condition="'$(SignAssembly)' != 'true'" Include="$(MSBuildProjectName).Tests;$(MSBuildProjectName).Benchmarks" />
</ItemGroup>

</Project>
16 changes: 16 additions & 0 deletions src/GraphQLParser/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,20 @@ public static class Parser
/// <exception cref="GraphQLMaxDepthExceededException">In case of syntax error.</exception>
public static GraphQLDocument Parse(ROM source, ParserOptions options = default)
=> new ParserContext(source, options).ParseDocument();

/// <summary>
/// Generates AST of GraphQL value based on input text.
/// </summary>
/// <param name="source">Input data as a sequence of characters.</param>
/// <param name="options">Parser options.</param>
/// <returns>AST (Abstract Syntax Tree) for GraphQL value.</returns>
/// <exception cref="GraphQLSyntaxErrorException">In case when parser recursion depth exceeds <see cref="ParserOptions.MaxDepth"/>.</exception>
/// <exception cref="GraphQLMaxDepthExceededException">In case of syntax error.</exception>
public static GraphQLValue ParseValue(ROM source, ParserOptions options = default)
{
var context = new ParserContext(source, options);
var value = context.ParseValueLiteral(true);
context.Expect(TokenKind.EOF);
return value;
}
}
2 changes: 1 addition & 1 deletion src/GraphQLParser/ParserContext.Parse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1418,7 +1418,7 @@ private GraphQLUnionTypeExtension ParseUnionTypeExtension(int start, List<GraphQ
return extension;
}

private GraphQLValue ParseValueLiteral(bool isConstant)
internal GraphQLValue ParseValueLiteral(bool isConstant)
{
return _currentToken.Kind switch
{
Expand Down
46 changes: 23 additions & 23 deletions src/GraphQLParser/ParserContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,28 +46,28 @@ internal ref partial struct ParserContext

private static string[] DirectiveLocationOneOf { get; set; } = new[]
{
// http://spec.graphql.org/October2021/#ExecutableDirectiveLocation
"QUERY",
"MUTATION",
"SUBSCRIPTION",
"FIELD",
"FRAGMENT_DEFINITION",
"FRAGMENT_SPREAD",
"INLINE_FRAGMENT",
"VARIABLE_DEFINITION",
// http://spec.graphql.org/October2021/#TypeSystemDirectiveLocation
"SCHEMA",
"SCALAR",
"OBJECT",
"FIELD_DEFINITION",
"ARGUMENT_DEFINITION",
"INTERFACE",
"UNION",
"ENUM",
"ENUM_VALUE",
"INPUT_OBJECT",
"INPUT_FIELD_DEFINITION",
};
// http://spec.graphql.org/October2021/#ExecutableDirectiveLocation
"QUERY",
"MUTATION",
"SUBSCRIPTION",
"FIELD",
"FRAGMENT_DEFINITION",
"FRAGMENT_SPREAD",
"INLINE_FRAGMENT",
"VARIABLE_DEFINITION",
// http://spec.graphql.org/October2021/#TypeSystemDirectiveLocation
"SCHEMA",
"SCALAR",
"OBJECT",
"FIELD_DEFINITION",
"ARGUMENT_DEFINITION",
"INTERFACE",
"UNION",
"ENUM",
"ENUM_VALUE",
"INPUT_OBJECT",
"INPUT_FIELD_DEFINITION",
};

private delegate TResult ParseCallback<out TResult>(ref ParserContext context);

Expand Down Expand Up @@ -176,7 +176,7 @@ private void Advance(bool fromParseComment = false)
}
}

private void Expect(TokenKind kind, string? description = null)
internal void Expect(TokenKind kind, string? description = null)
{
if (_currentToken.Kind == kind)
{
Expand Down
2 changes: 1 addition & 1 deletion src/GraphQLParser/Visitors/SDLPrinter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1213,7 +1213,7 @@ public DefaultPrintContext(TextWriter writer)
public TextWriter Writer { get; }

/// <inheritdoc/>
public Stack<ASTNode> Parents { get; init; } = new Stack<ASTNode>();
public Stack<ASTNode> Parents { get; init; } = new();

/// <inheritdoc/>
public CancellationToken CancellationToken { get; init; }
Expand Down