Example #1
0
        internal ParseResult(
            Parser parser,
            CommandResult rootCommandResult,
            CommandResult commandResult,
            IDirectiveCollection directives,
            TokenizeResult tokenizeResult,
            IReadOnlyCollection <string> unparsedTokens,
            IReadOnlyCollection <string> unmatchedTokens,
            List <ParseError> errors = null,
            string rawInput          = null)
        {
            Parser            = parser;
            RootCommandResult = rootCommandResult;
            CommandResult     = commandResult;
            Directives        = directives;

            // skip the root command
            Tokens = tokenizeResult.Tokens.Skip(1).ToArray();

            UnparsedTokens  = unparsedTokens;
            UnmatchedTokens = unmatchedTokens;

            RawInput = rawInput;

            _errors = errors ?? new List <ParseError>();

            if (parser.Configuration.RootCommand.TreatUnmatchedTokensAsErrors)
            {
                _errors.AddRange(
                    unmatchedTokens.Select(token =>
                                           new ParseError(parser.Configuration.ValidationMessages.UnrecognizedCommandOrArgument(token))));
            }
        }
Example #2
0
        public EnumValue(
            ITypeCompletionContext completionContext,
            EnumValueDefinition enumValueDefinition)
        {
            if (completionContext == null)
            {
                throw new ArgumentNullException(nameof(completionContext));
            }

            if (enumValueDefinition is null)
            {
                throw new ArgumentNullException(nameof(enumValueDefinition));
            }

            if (enumValueDefinition.RuntimeValue is null)
            {
                throw new ArgumentException(
                          TypeResources.EnumValue_ValueIsNull,
                          nameof(enumValueDefinition));
            }

            SyntaxNode = enumValueDefinition.SyntaxNode;
            Name       = enumValueDefinition.Name.HasValue
                ? enumValueDefinition.Name
                : (NameString)enumValueDefinition.RuntimeValue.ToString() !;
            Description       = enumValueDefinition.Description;
            DeprecationReason = enumValueDefinition.DeprecationReason;
            IsDeprecated      = !string.IsNullOrEmpty(enumValueDefinition.DeprecationReason);
            Value             = enumValueDefinition.RuntimeValue;
            ContextData       = enumValueDefinition.GetContextData();

            _directives = DirectiveCollection
                          .CreateAndComplete(completionContext, this, enumValueDefinition !.GetDirectives());
        }
        internal ParseResult(
            Parser parser,
            CommandResult rootCommandResult,
            CommandResult commandResult,
            IDirectiveCollection directives,
            IReadOnlyList<Token> tokens,
            IReadOnlyCollection<string> unparsedTokens,
            IReadOnlyCollection<string> unmatchedTokens,
            IReadOnlyCollection<TokenizeError> tokenizeErrors,
            string rawInput)
        {
            Parser = parser;
            RootCommandResult = rootCommandResult;
            CommandResult = commandResult;
            Directives = directives;
            Tokens = tokens;
            UnparsedTokens = unparsedTokens;
            UnmatchedTokens = unmatchedTokens;

            RawInput = rawInput;

            if (tokenizeErrors?.Count > 0)
            {
                _errors.AddRange(
                    tokenizeErrors.Select(e => new ParseError(e.Message)));
            }

            AddImplicitOptionsAndCheckForErrors();
        }
        internal ParseResult(
            CommandResult rootCommandResult,
            CommandResult commandResult,
            IDirectiveCollection directives,
            IReadOnlyCollection <Token> tokens,
            IReadOnlyCollection <string> unparsedTokens,
            IReadOnlyCollection <string> unmatchedTokens,
            IReadOnlyCollection <ParseError> errors,
            string rawInput)
        {
            RootCommandResult = rootCommandResult;
            CommandResult     = commandResult;
            Directives        = directives;
            Tokens            = tokens;
            UnparsedTokens    = unparsedTokens;
            UnmatchedTokens   = unmatchedTokens;
            RawInput          = rawInput;

            if (errors != null)
            {
                _errors.AddRange(errors);
            }

            AddImplicitOptionsAndCheckForErrors();
        }
Example #5
0
 private static IEnumerable <T> OfType <T>(IDirectiveCollection directives)
 {
     foreach (IDirective directive in directives)
     {
         if (typeof(T).IsAssignableFrom(directive.Type.ClrType))
         {
             yield return(directive.ToObject <T>());
         }
     }
 }
        internal ParseResult(
            Parser parser,
            RootCommandResult rootCommandResult,
            CommandResult commandResult,
            IDirectiveCollection directives,
            TokenizeResult tokenizeResult,
            IReadOnlyList <Token>?unparsedTokens,
            IReadOnlyList <Token>?unmatchedTokens,
            List <ParseError>?errors,
            string?commandLineText = null)
        {
            Parser             = parser;
            _rootCommandResult = rootCommandResult;
            CommandResult      = commandResult;
            Directives         = directives;

            // skip the root command when populating Tokens property
            if (tokenizeResult.Tokens.Count > 1)
            {
                var tokens = new Token[tokenizeResult.Tokens.Count - 1];
                for (var i = 0; i < tokenizeResult.Tokens.Count - 1; i++)
                {
                    var token = tokenizeResult.Tokens[i + 1];
                    tokens[i] = token;
                }

                Tokens = tokens;
            }
            else
            {
                Tokens = Array.Empty <Token>();
            }

            _unparsedTokens = unparsedTokens ?? Array.Empty <Token>();
            _errors         = errors ?? new List <ParseError>();
            CommandLineText = commandLineText;

            if (unmatchedTokens is null)
            {
                _unmatchedTokens = Array.Empty <Token>();
            }
            else
            {
                _unmatchedTokens = unmatchedTokens;

                if (parser.Configuration.RootCommand.TreatUnmatchedTokensAsErrors)
                {
                    for (var i = 0; i < _unmatchedTokens.Count; i++)
                    {
                        var token = _unmatchedTokens[i];
                        _errors.Add(new ParseError(parser.Configuration.LocalizationResources.UnrecognizedCommandOrArgument(token.Value), rootCommandResult));
                    }
                }
            }
        }
		/*----------------------------------------------------------------------------------------*/
		#region Disposal
		/// <summary>
		/// Releases all resources currently held by the object.
		/// </summary>
		/// <param name="disposing"><see langword="True"/> if managed objects should be disposed, otherwise <see langword="false"/>.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && !IsDisposed)
			{
				DisposeMember(Behavior);
				DisposeMember(Directives);

				Type = null;
				Behavior = null;
				Directives = null;
			}

			base.Dispose(disposing);
		}
Example #8
0
        internal void CompleteValue(ITypeCompletionContext context)
        {
            var directives = new DirectiveCollection(
                this, _definition.Directives);

            directives.CompleteCollection(context);
            Directives = directives;

            OnCompleteValue(context, _definition);

            _contextData = new Dictionary <string, object>(
                _definition.ContextData);
            _definition = null;
        }
Example #9
0
        internal ParseResult(
            Parser parser,
            RootCommandResult rootCommandResult,
            CommandResult commandResult,
            IDirectiveCollection directives,
            TokenizeResult tokenizeResult,
            IReadOnlyList <Token> unparsedTokens,
            IReadOnlyList <Token> unmatchedTokens,
            List <ParseError>?errors = null,
            string?rawInput          = null)
        {
            Parser             = parser;
            _rootCommandResult = rootCommandResult;
            CommandResult      = commandResult;
            Directives         = directives;

            // skip the root command when populating Tokens property
            if (tokenizeResult.Tokens.Count > 1)
            {
                var tokens = new Token[tokenizeResult.Tokens.Count - 1];
                for (var i = 0; i < tokenizeResult.Tokens.Count - 1; i++)
                {
                    var token = tokenizeResult.Tokens[i + 1];
                    tokens[i] = token;
                }
                Tokens = tokens;
            }
            else
            {
                Tokens = Array.Empty <Token>();
            }

            _unparsedTokens  = unparsedTokens;
            _unmatchedTokens = unmatchedTokens;

            RawInput = rawInput;

            _errors = errors ?? (parser.Configuration.RootCommand.TreatUnmatchedTokensAsErrors
                                     ? new List <ParseError>(unmatchedTokens.Count)
                                     : new List <ParseError>());

            if (parser.Configuration.RootCommand.TreatUnmatchedTokensAsErrors)
            {
                for (var i = 0; i < unmatchedTokens.Count; i++)
                {
                    var token = unmatchedTokens[i];
                    _errors.Add(new ParseError(parser.Configuration.ValidationMessages.UnrecognizedCommandOrArgument(token.Value)));
                }
            }
        }
        /*----------------------------------------------------------------------------------------*/
        #region Disposal
        /// <summary>
        /// Releases all resources currently held by the object.
        /// </summary>
        /// <param name="disposing"><see langword="True"/> if managed objects should be disposed, otherwise <see langword="false"/>.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && !IsDisposed)
            {
                DisposeMember(Behavior);
                DisposeMember(Directives);

                Type       = null;
                Behavior   = null;
                Directives = null;
            }

            base.Dispose(disposing);
        }
Example #11
0
        protected void Initialize(
            NameString name,
            string description,
            IDirectiveCollection directives)
        {
            Name        = name;
            Description = description;
            Directives  = directives;

            if (directives is INeedsInitialization init)
            {
                RegisterForInitialization(init);
            }
        }
        public void RepeatableDirective()
        {
            // arrange
            var directiveType = new DirectiveType(
                t => t.Name("foo")
                .Repeatable()
                .Location(DirectiveLocation.Object)
                .Argument("a").Type <StringType>());

            var objectType = new ObjectType(t =>
            {
                t.Name("Bar");
                t.Directive("foo", new ArgumentNode("a", "1"));
                t.Directive("foo", new ArgumentNode("a", "2"));
                t.Field("foo").Resolver(() => "baz");
            });

            // act
            var schema = Schema.Create(t =>
            {
                t.RegisterDirective(directiveType);
                t.RegisterQueryType(objectType);
            });

            // assert
            IDirectiveCollection collection =
                schema.GetType <ObjectType>("Bar").Directives;

            Assert.Collection(collection,
                              t =>
            {
                Assert.Equal("foo", t.Name);
                Assert.Equal("1", t.GetArgument <string>("a"));
            },
                              t =>
            {
                Assert.Equal("foo", t.Name);
                Assert.Equal("2", t.GetArgument <string>("a"));
            });
        }
Example #13
0
        TryMatchRule(CommandRule rule, IEnumerable <Token> tokens, CommandResult commandResult, IDirectiveCollection directives)
        {
            var entryItems = ImmutableArray.CreateBuilder <KeyValuePair <string, string> >();

            entryItems.Add(new KeyValuePair <string, string>("verb", rule.CommandName));

            // Filter out option tokens as we query the command result for them when processing a rule.
            var tokenQueue = new Queue <Token>(tokens.Where(x => x.Type != TokenType.Option));

            Token NextToken()
            {
                return(tokenQueue.TryDequeue(out var firstToken) ? firstToken : null);
            }

            var currentToken = NextToken();

            // We have a valid rule so far.
            var passed = true;

            _directiveProcessor?.Invoke(commandResult, directives, entryItems);

            foreach (var item in rule.Items)
            {
                // Stop checking items since our rule already failed.
                if (!passed)
                {
                    break;
                }

                switch (item)
                {
                case OptionItem optItem:
                {
                    var optionValue = commandResult.Children.OfType <OptionResult>().FirstOrDefault(o => o.Option.HasAlias(optItem.Option))?.GetValueOrDefault()?.ToString();
                    if (optionValue is not null && optItem.Values.Contains(optionValue))
                    {
                        entryItems.Add(new KeyValuePair <string, string>(optItem.EntryKey, optionValue));
                    }
Example #14
0
 public static bool Any <T>(
     this IDirectiveCollection directives) =>
 Enumerable.Any(OfType <T>(directives));
 private static bool IsDelegationField(IDirectiveCollection directives)
 {
     return(directives.Contains(DirectiveNames.Delegate) ||
            directives.Contains(DirectiveNames.Computed));
 }
Example #16
0
        FilterCommand(string commandName, IEnumerable <Token> tokens, CommandResult commandResult, IDirectiveCollection directives)
        {
            if (commandName is null || tokens is null)
            {
                return(null);
            }

            return(Rules
                   .Select(rule => rule.CommandName == commandName
                    ? TryMatchRule(rule, tokens, commandResult, directives)
                    : null)
                   .FirstOrDefault(x => x is not null));
        }
 /*----------------------------------------------------------------------------------------*/
 #region Constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="StandardActivationPlan"/> class.
 /// </summary>
 /// <param name="type">The type that the plan will describe.</param>
 public StandardActivationPlan(Type type)
 {
     Type       = type;
     Directives = new DirectiveCollection();
 }
Example #18
0
 private static IReadOnlyCollection <IDirective> GetValidationDirectives(IDirectiveCollection collection)
 {
     return(collection.Where(d => d.Type is IValidationDirectiveType).ToList());
 }
 public static T SingleOrDefault <T>(this IDirectiveCollection directives) =>
 directives
 .Where(t => typeof(T).IsAssignableFrom(t.Type.RuntimeType))
 .Select(t => t.ToObject <T>()).SingleOrDefault();
Example #20
0
        TryMatchRule(CommandRule rule, IEnumerable <Token> tokens, CommandResult commandResult, IDirectiveCollection directives)
        {
            var entryItems = ImmutableArray.CreateBuilder <KeyValuePair <string, string> >();

            entryItems.Add(new KeyValuePair <string, string>("verb", rule.CommandName));

            // Filter out option tokens as we query the command result for them when processing a rule.
            var tokenQueue = new Queue <Token>(tokens.Where(x => x.Type != TokenType.Option));

            Token NextToken()
            {
                return(tokenQueue.TryDequeue(out var firstToken) ? firstToken : null);
            }

            var currentToken = NextToken();

            // We have a valid rule so far.
            var passed = true;

            _directiveProcessor?.Invoke(commandResult, directives, entryItems);

            foreach (var item in rule.Items)
            {
                // Stop checking items since our rule already failed.
                if (!passed)
                {
                    break;
                }

                switch (item)
                {
                case OptionItem optItem:
                {
                    var optionValue = commandResult.OptionResult(optItem.Option).GetValueOrDefault()?.ToString();
                    if (optionValue != null && optItem.Values.Contains(optionValue))
                    {
                        entryItems.Add(new KeyValuePair <string, string>(optItem.EntryKey, optionValue));
                    }
                    else
                    {
                        passed = false;
                    }
                    break;
                }

                case ArgumentItem argItem:
                {
                    if (argItem.TokenType == currentToken?.Type &&
                        argItem.Value == currentToken?.Value)
                    {
                        entryItems.Add(new KeyValuePair <string, string>(argItem.EntryKey, argItem.Value));
                        currentToken = NextToken();
                    }
                    else if (argItem.IsOptional)
                    {
                        currentToken = NextToken();
                    }
                    else
                    {
                        passed = false;
                    }
                    break;
                }

                case IgnoreItem ignoreItem:
                {
                    if (ignoreItem.TokenType == currentToken?.Type)
                    {
                        currentToken = NextToken();
                    }
                    else if (ignoreItem.IsOptional)
                    {
                        currentToken = NextToken();
                    }
                    else
                    {
                        passed = false;
                    }
                    break;
                }

                default:
                    passed = false;
                    break;
                }
            }

            if (passed)
            {
                return(entryItems.ToImmutable());
            }
            else
            {
                return(null);
            }
        }
Example #21
0
 public static T First <T>(
     this IDirectiveCollection directives,
     Func <T, bool> predicate) =>
 Enumerable.First(OfType <T>(directives), predicate);
Example #22
0
 public static bool Any <T>(
     this IDirectiveCollection directives,
     Func <T, bool> predicate) =>
 Enumerable.Any(OfType <T>(directives), predicate);
Example #23
0
 /*----------------------------------------------------------------------------------------*/
 #region Public Methods
 /// <summary>
 /// Copies the directives from the specified collection.
 /// </summary>
 /// <param name="directives">The collection of directives to copy from.</param>
 public void CopyFrom(IDirectiveCollection directives)
 {
     directives.GetTypes().Each(t => AddRange(t, directives.GetAll(t)));
 }
		/*----------------------------------------------------------------------------------------*/
		#region Constructors
		/// <summary>
		/// Initializes a new instance of the <see cref="StandardActivationPlan"/> class.
		/// </summary>
		/// <param name="type">The type that the plan will describe.</param>
		public StandardActivationPlan(Type type)
		{
			Type = type;
			Directives = new DirectiveCollection();
		}
Example #25
0
 public static T FirstOrDefault <T>(
     this IDirectiveCollection directives) =>
 Enumerable.FirstOrDefault(OfType <T>(directives));
Example #26
0
 public static T SingleOrDefault <T>(
     this IDirectiveCollection directives) =>
 Enumerable.SingleOrDefault(OfType <T>(directives));
Example #27
0
 public static T SingleOrDefault <T>(
     this IDirectiveCollection directives,
     Func <T, bool> predicate) =>
 Enumerable.SingleOrDefault(OfType <T>(directives), predicate);