GraphQL.NET Parser

repository·master·Indexed 42 days ago

https://github.com/graphql-dotnet/parser

A high-performance lexer, parser, and AST model for GraphQL compatible with the October 2021 specification. It features memory-efficient processing using ReadOnlyMemory<char>, an ASTVisitor for document traversal, an SDLPrinter for generating Schema Definition Language, and an SDLSorter for AST organization.

Tokens
1.3K
Snippets
5
Records
6
Agent score
3%

What's inside GraphQL.NET Parser

  1. Traverse the AST with ASTVisitor

    master
    The ASTVisitor provides an API to traverse the AST of a parsed GraphQL document. The default implementation visits all nodes. To implement custom processing logic, inherit from ASTVisitor and override the specific methods for the nodes you wish to handle.
  2. Sort an AST document with SDLSorter

    master

    The SDLSorter sorts an AST document based on a predefined order. By default, it uses a culture-invariant, case-insensitive comparison. You can customize the sorting behavior by deriving from SDLSorterOptions and overriding the Compare methods.

    var document = Parser.Parse("query { hero { name age } }");
    SDLSorter.Sort(document);
    var sdl = new SDLPrinter().Print(document);
  3. Debug AST structure with StructurePrinter

    master

    The StructurePrinter is a visitor that prints the AST into a TextWriter as a hierarchical representation of node types. This is primarily used for debugging to visualize the internal structure of the parsed document.

    public static async Task PrintStructure(string sdl)
    {
        var document = Parser.Parse(sdl);
        using var writer = new StringWriter(); 
        var printer = new StructurePrinter();
        await printer.PrintAsync(document, writer);
        var rendered = writer.ToString();
        Console.WriteLine(rendered);
    }
  4. Parse GraphQL expressions into an AST with Parser

    master

    The Parser converts GraphQL expressions into an Abstract Syntax Tree (AST). It supports parsing entire GraphQLDocument objects or specific concrete AST nodes using generic overloads.

    To optimize memory usage, you can use ParserOptions to ignore comments or token locations. Setting IgnoreOptions.All maximizes memory savings by omitting both comments and location information.

    // Parse a full document with default options
    var ast1 = Parser.Parse(@"
    {
      field
    }");
    
    // Parse ignoring comments
    var ast2 = Parser.Parse(@"
    {
      field
    }", new ParserOptions { Ignore = IgnoreOptions.Comments });
    
    // Parse a specific node type
    string text1 = "enum Color { RED }";
    var ast3 = Parser.Parse<GraphQLEnumTypeDefinition>(text1);
    
    // Parse a value (returns GraphQLObjectValue)
    string text2 = "{ a: 1, b: \"abc\", c: RED, d: $id }";
    var ast4 = Parser.Parse<GraphQLValue>(text2);
  5. Print SDL from an AST with SDLPrinter

    master

    SDLPrinter is an optimized visitor used to output GraphQL Schema Definition Language (SDL) from an AST into a TextWriter. It is designed to be asynchronous and non-blocking, often avoiding managed heap allocations.

    Available methods include:

    • Print(document): Returns the SDL as a string.
    • Print(document, stringBuilder): Writes the SDL to a StringBuilder.
    • PrintAsync(document, writer, cancellationToken): Asynchronously writes the SDL to a TextWriter.
    var document = Parser.Parse("query { hero { name age } }");
    
    // Print to a string with default options
    var sdl = new SDLPrinter().Print(document);
    
    // Print to a string builder
    var sb = new StringBuilder();
    new SDLPrinter().Print(document, sb);
    
    // Print to a string with custom options
    var sdlPrinter = new SDLPrinter(
        new SDLPrinterOptions
        {
            PrintComments = true,
            EachDirectiveLocationOnNewLine = true,
            EachUnionMemberOnNewLine = true,
        });
    var sdlCustom = sdlPrinter.Print(document);
    
    // Print to a stream asynchronously
    using var writer = new StreamWriter(stream);
    await sdlPrinter.PrintAsync(document, writer, default);
    await writer.FlushAsync();
  6. Lex the input text with Lexer

    master

    The Lexer generates tokens based on input text. It is optimized to use ReadOnlyMemory<char> and typically avoids managed heap allocations. The Lex method returns the first token found in the input.

    var token = Lexer.Lex("\"str\"");