private static FieldDefinitionNode SerializeObjectField(
        IOutputField field,
        ReferencedTypes referenced)
    {
        var arguments = field.Arguments
                        .Select(
            t => SerializeInputField(
                t,
                referenced))
                        .ToList();

        var directives = field.Directives
                         .Select(
            t => SerializeDirective(
                t,
                referenced))
                         .ToList();

        return(new FieldDefinitionNode(
                   null,
                   new NameNode(field.Name),
                   SerializeDescription(field.Description),
                   arguments,
                   SerializeType(
                       field.Type,
                       referenced),
                   directives));
    }
        protected virtual ISelectionVisitorAction VisitChildren(
            IOutputField field,
            TContext context)
        {
            IOutputType      type         = field.Type;
            SelectionSetNode?selectionSet =
                context.SelectionSetNodes.Peek();

            if (TryGetObjectType(type, out ObjectType? objectType) &&
                selectionSet is not null)
            {
                IReadOnlyList <IFieldSelection> selections = context.Context.GetSelections(
                    objectType,
                    selectionSet,
                    true);

                for (var i = 0; i < selections.Count; i++)
                {
                    if (selections[i] is ISelection selection)
                    {
                        if (Visit(selection, context).Kind == SelectionVisitorActionKind.Break)
                        {
                            return(Break);
                        }
                    }
                }
            }

            return(DefaultAction);
        }
示例#3
0
        public static ISchemaError ArgumentNotImplemented(
            IOutputField field,
            IOutputField implementedField,
            IInputField missingArgument)
        {
            bool isInterface = field.DeclaringType.Kind == TypeKind.Interface;

            return(SchemaErrorBuilder.New()
                   .SetMessage(
                       "The argument `{0}` of the implemented field `{1}` must be defined. " +
                       "The field `{2}` must include an argument of the same name for " +
                       "every argument defined on the implemented field " +
                       "of the interface type `{3}`.",
                       missingArgument.Name,
                       field.Name,
                       field.Name,
                       implementedField.DeclaringType.Print())
                   .SetType(field.DeclaringType)
                   .SetField(field)
                   .SetImplementedField(implementedField)
                   .AddSyntaxNode(missingArgument.SyntaxNode)
                   .SetExtension("missingArgument", missingArgument)
                   .SetSpecifiedBy(isInterface)
                   .Build());
        }
        protected override ISelectionVisitorAction VisitObjectType(
            IOutputField field,
            ObjectType objectType,
            SelectionSetNode?selectionSet,
            QueryableProjectionContext context)
        {
            var isAbstractType = field.Type.NamedType().IsAbstractType();

            if (isAbstractType && context.TryGetQueryableScope(out QueryableProjectionScope? scope))
            {
                context.PushInstance(
                    Expression.Convert(context.GetInstance(), objectType.RuntimeType));
                scope.Level.Push(new Queue <MemberAssignment>());

                ISelectionVisitorAction res =
                    base.VisitObjectType(field, objectType, selectionSet, context);

                context.PopInstance();
                scope.AddAbstractType(objectType.RuntimeType, scope.Level.Pop());

                return(res);
            }

            return(base.VisitObjectType(field, objectType, selectionSet, context));
        }
示例#5
0
    public static void EnsureFieldNamesAreValid(
        IComplexOutputType type,
        ICollection <ISchemaError> errors)
    {
        for (var i = 0; i < type.Fields.Count; i++)
        {
            IOutputField field = type.Fields[i];

            if (!field.IsIntrospectionField)
            {
                if (field.Name.Value.StartsWith(_twoUnderscores))
                {
                    errors.Add(TwoUnderscoresNotAllowedField(type, field));
                }

                for (var j = 0; j < field.Arguments.Count; j++)
                {
                    IInputField argument = field.Arguments[j];

                    if (argument.Name.Value.StartsWith(_twoUnderscores))
                    {
                        errors.Add(TwoUnderscoresNotAllowedOnArgument(
                                       type, field, argument));
                    }
                }
            }
        }
    }
        protected virtual ISelectionVisitorAction VisitObjectType(
            IOutputField field,
            ObjectType objectType,
            SelectionSetNode?selectionSet,
            TContext context)
        {
            context.ResolvedType.Push(field.Type.NamedType().IsAbstractType() ? objectType : null);

            try
            {
                IReadOnlyList <IFieldSelection> selections =
                    context.Context.GetSelections(objectType, selectionSet, true);

                for (var i = 0; i < selections.Count; i++)
                {
                    if (selections[i] is ISelection selection)
                    {
                        if (Visit(selection, context).Kind == SelectionVisitorActionKind.Break)
                        {
                            return(Break);
                        }
                    }
                }
            }
            finally
            {
                context.ResolvedType.Pop();
            }

            return(DefaultAction);
        }
        protected virtual ISelectionVisitorAction Visit(
            IOutputField field,
            TContext context)
        {
            var localContext = OnBeforeEnter(field, context);
            var result       = Enter(field, localContext);

            localContext = OnAfterEnter(field, localContext, result);

            if (result.Kind == SelectionVisitorActionKind.Continue)
            {
                if (VisitChildren(field, context).Kind == SelectionVisitorActionKind.Break)
                {
                    return(Break);
                }
            }

            if (result.Kind == SelectionVisitorActionKind.Continue ||
                result.Kind == SelectionVisitorActionKind.SkipAndLeave)
            {
                localContext = OnBeforeLeave(field, localContext);
                result       = Leave(field, localContext);
                OnAfterLeave(field, localContext, result);
            }

            return(result);
        }
        protected virtual ISelectionVisitorAction VisitChildren(
            IOutputField field,
            TContext context)
        {
            IOutputType      type         = field.Type;
            SelectionSetNode?selectionSet =
                context.SelectionSetNodes.Peek();

            INamedType namedType = type.NamedType();

            if (namedType.IsAbstractType())
            {
                IReadOnlyList <ObjectType> possibleTypes =
                    context.Context.Schema.GetPossibleTypes(field.Type.NamedType());

                foreach (var possibleType in possibleTypes)
                {
                    ISelectionVisitorAction result =
                        VisitObjectType(field, possibleType, selectionSet, context);

                    if (result != Continue)
                    {
                        return(result);
                    }
                }
            }
            else if (namedType is ObjectType a)
            {
                return(VisitObjectType(field, a, selectionSet, context));
            }

            return(DefaultAction);
        }
示例#9
0
        private static void ResolveScopedVariableArguments(
            IResolverContext context,
            SelectionPathComponent component,
            IOutputField field,
            ICollection <VariableValue> variables)
        {
            foreach (ArgumentNode argument in component.Arguments)
            {
                if (!field.Arguments.TryGetField(argument.Name.Value,
                                                 out IInputField arg))
                {
                    throw new QueryException(new Error
                    {
                        Message = string.Format(
                            CultureInfo.InvariantCulture,
                            StitchingResources
                            .DelegationMiddleware_ArgumentNotFound,
                            argument.Name.Value)
                    });
                }

                if (argument.Value is ScopedVariableNode sv)
                {
                    variables.Add(_resolvers.Resolve(
                                      context, sv, arg.Type.ToTypeNode()));
                }
            }
        }
        private static void ResolveScopedVariableArguments(
            IResolverContext context,
            NameString schemaName,
            SelectionPathComponent component,
            IOutputField field,
            ICollection <Delegation.VariableValue> variables,
            ExtractFieldQuerySyntaxRewriter rewriter)
        {
            foreach (ArgumentNode argument in component.Arguments)
            {
                if (!field.Arguments.TryGetField(argument.Name.Value, out IInputField arg))
                {
                    throw new QueryException(
                              ErrorBuilder.New()
                              .SetMessage(
                                  StitchingResources.DelegationMiddleware_ArgumentNotFound,
                                  argument.Name.Value)
                              .SetExtension("argument", argument.Name.Value)
                              .SetCode(ErrorCodes.ArgumentNotFound)
                              .Build());
                }

                if (argument.Value is ScopedVariableNode sv)
                {
                    Delegation.VariableValue variable =
                        _resolvers.Resolve(context, sv, arg.Type);
                    IValueNode value = rewriter.RewriteValueNode(
                        schemaName, arg.Type, variable.Value);
                    variables.Add(variable.WithValue(value));
                }
            }
        }
示例#11
0
        private static FieldDefinitionNode SerializeObjectField(
            IOutputField field,
            ReferencedTypes referenced)
        {
            var arguments = field.Arguments
                            .Select(t => SerializeInputField(t, referenced))
                            .ToList();

            var directives = field.Directives
                             .Select(t => SerializeDirective(t, referenced))
                             .ToList();

            if (field.IsDeprecated)
            {
                directives.Add(new DirectiveNode(
                                   WellKnownDirectives.Deprecated,
                                   new ArgumentNode(
                                       WellKnownDirectives.DeprecationReasonArgument,
                                       field.DeprecationReason)));
            }

            return(new FieldDefinitionNode
                   (
                       null,
                       new NameNode(field.Name),
                       SerializeDescription(field.Description),
                       arguments,
                       SerializeType(field.Type, referenced),
                       directives
                   ));
        }
示例#12
0
        public static int DefaultCalculation(
            IOutputField field,
            FieldNode selection,
            CostDirective?cost,
            int fieldDepth,
            int nodeDepth,
            Func <string, object?> getVariable,
            IMaxComplexityOptionsAccessor options)
        {
            if (cost is null)
            {
                return(options.DefaultComplexity);
            }

            if (options.UseComplexityMultipliers)
            {
                if (cost.Multipliers.Count == 0)
                {
                    return(cost.Complexity);
                }

                int complexity = 0;

                for (int i = 0; i < cost.Multipliers.Count; i++)
                {
                    MultiplierPathString multiplier = cost.Multipliers[i];
                    ArgumentNode         argument   = selection.Arguments.FirstOrDefault(t =>
                                                                                         t.Name.Value.Equals(multiplier.Value));

                    if (argument is { } && argument.Value is { })
        private static void CollectComputeDependencies(
            Context context,
            IComplexOutputType type,
            IOutputField field)
        {
            IDirective directive = field.Directives[DirectiveNames.Computed]
                                   .FirstOrDefault();

            if (directive != null)
            {
                NameString[] dependantOn = directive
                                           .ToObject <ComputedDirective>()
                                           .DependantOn;

                if (dependantOn != null)
                {
                    foreach (string fieldName in dependantOn)
                    {
                        if (type.Fields.TryGetField(
                                fieldName,
                                out IOutputField dependency))
                        {
                            context.Dependencies.Add(new FieldDependency(
                                                         type.Name, dependency.Name));
                        }
                    }
                }
            }
        }
示例#14
0
        public override MaxComplexityVisitorContext AddField(
            IOutputField fieldDefinition,
            FieldNode fieldSelection)
        {
            IDirective directive = fieldDefinition.Directives
                                   .FirstOrDefault(t => t.Type is CostDirectiveType);
            int complexity;

            CostDirective cost = directive == null
                ? DefaultCost
                : directive.ToObject <CostDirective>();

            complexity = Complexity + CalculateComplexity(
                new ComplexityContext(
                    fieldDefinition, fieldSelection,
                    FieldPath, _variables, cost));

            if (complexity > MaxComplexity)
            {
                MaxComplexity = complexity;
            }

            return(new MaxComplexityWithMultipliersVisitorContext(
                       FragmentPath,
                       FieldPath.Add(fieldDefinition),
                       this));
        }
示例#15
0
    private static void ValidateArguments(
        IOutputField field,
        IOutputField implementedField,
        ICollection <ISchemaError> errors)
    {
        var implArgs = implementedField.Arguments.ToDictionary(t => t.Name);

        foreach (IInputField?argument in field.Arguments)
        {
            if (implArgs.TryGetValue(argument.Name, out IInputField? implementedArgument))
            {
                implArgs.Remove(argument.Name);
                if (!argument.Type.IsEqualTo(implementedArgument.Type))
                {
                    errors.Add(InvalidArgumentType(
                                   field, implementedField,
                                   argument, implementedArgument));
                }
            }
            else if (argument.Type.IsNonNullType())
            {
                errors.Add(AdditionalArgumentNotNullable(
                               field, implementedField,
                               argument));
            }
        }

        foreach (IInputField?missingArgument in implArgs.Values)
        {
            errors.Add(ArgumentNotImplemented(
                           field, implementedField, missingArgument));
        }
    }
        protected override ISelectionVisitorAction Visit(IOutputField field, TContext context)
        {
            if (context.SelectionSetNodes.Count > 1 && field.HasProjectionMiddleware())
            {
                return(Skip);
            }

            if (field.Type is IPageType and ObjectType pageType &&
                context.SelectionSetNodes.Peek() is {} pagingFieldSelection)
            {
                IReadOnlyList <IFieldSelection> selections =
                    context.Context.GetSelections(pageType, pagingFieldSelection, true);

                foreach (var selection in selections)
                {
                    if ((selection.Field.Name.Value is "nodes" ||
                         selection.Field.Name.Value is "items") &&
                        selection.SyntaxNode.SelectionSet is not null)
                    {
                        context.SelectionSetNodes.Push(
                            selection.SyntaxNode.SelectionSet);

                        return(base.Visit(selection.Field, context));
                    }
                }

                return(Skip);
            }

            return(base.Visit(field, context));
        }
        private FieldNode RewriteFieldSelectionSet(
            FieldNode node,
            IOutputField field,
            Context context)
        {
            FieldNode current = node;

            if (current.SelectionSet != null &&
                field.Type.NamedType() is INamedOutputType n)
            {
                Context cloned = context.Clone();
                cloned.TypeContext = n;

                current = Rewrite
                          (
                    current,
                    current.SelectionSet,
                    cloned,
                    RewriteSelectionSet,
                    current.WithSelectionSet
                          );
            }

            return(current);
        }
 /// <summary>
 /// This method will be called after the stitching layer
 /// has rewritten a field and allows to add custom rewriter logic.
 /// </summary>
 /// <param name="targetSchemaName">
 /// The name of the schema to which the query shall be delegated.
 /// </param>
 /// <param name="outputType">
 /// The current output type on which the selection set is declared.
 /// </param>
 /// <param name="outputField">
 /// The current output field on which this selection set is declared.
 /// </param>
 /// <param name="selectionSet">
 /// The list of selections that shall be added to the delegation query.
 /// </param>
 public virtual FieldNode OnRewriteField(
     NameString targetSchemaName,
     IOutputType outputType,
     IOutputField outputField,
     FieldNode field)
 {
     return(field);
 }
示例#19
0
 public override FieldNode OnRewriteField(
     NameString targetSchemaName,
     IOutputType outputType,
     IOutputField outputField,
     FieldNode field)
 {
     return(field.WithAlias(new NameNode("foo_bar")));
 }
 /// <summary>
 /// This method will be called after the stitching layer
 /// has rewritten a selection set and allows to add custom
 /// rewriter logic.
 /// </summary>
 /// <param name="targetSchemaName">
 /// The name of the schema to which the query shall be delegated.
 /// </param>
 /// <param name="outputType">
 /// The current output type on which the selection set is declared.
 /// </param>
 /// <param name="outputField">
 /// The current output field on which this selection set is declared.
 /// </param>
 /// <param name="selectionSet">
 /// The list of selections that shall be added to the delegation query.
 /// </param>
 public virtual SelectionSetNode OnRewriteSelectionSet(
     NameString targetSchemaName,
     IOutputType outputType,
     IOutputField outputField,
     SelectionSetNode selectionSet)
 {
     return(selectionSet);
 }
示例#21
0
        public FieldSelection(IOutputField field, FieldNode selection, Path path)
        {
            Field     = field ?? throw new ArgumentNullException(nameof(field));
            Selection = selection ?? throw new ArgumentNullException(nameof(selection));
            Path      = path ?? throw new ArgumentNullException(nameof(path));
            NameNode responseName = selection.Alias ?? selection.Name;

            ResponseName = responseName.Value;
        }
 private static object DeserializeResult(
     IOutputField field,
     object obj)
 {
     if (field.Type.IsLeafType() &&
         field.Type.NamedType() is ISerializableType t &&
         t.TryDeserialize(obj, out object value))
     {
         return(value);
     }
示例#23
0
 /// <summary>
 /// Add a field and allow it to be specified as an "ideal output field".
 /// An "ideal" field is the expected output that the neural network is
 /// training towards.
 /// </summary>
 /// <param name="outputField">The output field.</param>
 /// <param name="ideal">True if this is an ideal field.</param>
 public void AddOutputField(IOutputField outputField,
                            bool ideal)
 {
     _outputFields.Add(outputField);
     outputField.Ideal = ideal;
     if (outputField is OutputFieldGrouped)
     {
         var ofg = (OutputFieldGrouped)outputField;
         _groups.Add(ofg.Group);
     }
 }
示例#24
0
 /// <summary>
 /// Add a field and allow it to be specified as an "ideal output field".
 /// An "ideal" field is the expected output that the neural network is
 /// training towards.
 /// </summary>
 /// <param name="outputField">The output field.</param>
 /// <param name="ideal">True if this is an ideal field.</param>
 public void AddOutputField(IOutputField outputField,
                            bool ideal)
 {
     this.outputFields.Add(outputField);
     outputField.Ideal = ideal;
     if (outputField is OutputFieldGrouped)
     {
         OutputFieldGrouped ofg = (OutputFieldGrouped)outputField;
         this.groups.Add(ofg.Group);
     }
 }
示例#25
0
 public FieldSelection(
     IOutputField field,
     FieldNode syntaxNode,
     Path path,
     bool isConditional = true)
 {
     ResponseName  = syntaxNode.Alias?.Value ?? syntaxNode.Name.Value;
     Field         = field;
     SyntaxNode    = syntaxNode;
     IsConditional = isConditional;
     Path          = path;
 }
 private Expression CreateFieldComplexityExpression(
     IDocumentValidatorContext context,
     IOutputField field,
     FieldNode selection,
     List <Expression> children)
 {
     return(children.Count switch
     {
         0 => CreateCalculateExpression(context, field, selection, _zero),
         1 => CreateCalculateExpression(context, field, selection, children[0]),
         _ => CreateCalculateExpression(context, field, selection, Combine(children))
     });
示例#27
0
        private IReadOnlyList <Tensor2D> ComputeSmoothedNodalTensors(Vector solution, bool extrapolateFromGPs,
                                                                     IOutputField field)
        {
            var tensorsFromAllElements = new Dictionary <XNode, List <Tensor2D> >();

            foreach (var node in model.Nodes)
            {
                tensorsFromAllElements[node] = new List <Tensor2D>();
            }
            Vector constrainedDisplacements = model.CalculateConstrainedDisplacements(dofOrderer);

            foreach (var element in model.Elements)
            {
                IReadOnlyList <Tensor2D> elementTensors;
                if (extrapolateFromGPs)
                {
                    elementTensors =
                        ElementNodalTensorsExtrapolation(element, solution, constrainedDisplacements, field);
                }
                else
                {
                    elementTensors = ElementNodalTensorsDirectly(element, solution, constrainedDisplacements, field);
                }

                for (int nodeIdx = 0; nodeIdx < element.Nodes.Count; ++nodeIdx)
                {
                    tensorsFromAllElements[element.Nodes[nodeIdx]].Add(elementTensors[nodeIdx]);
                }
            }

            // Average with equal weights for all elements. TODO: perhaps vary the weights depending on the element type/area
            var nodalTensors = new Tensor2D[model.Nodes.Count];

            for (int i = 0; i < model.Nodes.Count; ++i)
            {
                XNode  node = model.Nodes[i];
                double tensorXX = 0.0, tensorYY = 0.0, tensorXY = 0.0;
                foreach (var tensor in tensorsFromAllElements[node])
                {
                    tensorXX += tensor.XX;
                    tensorYY += tensor.YY;
                    tensorXY += tensor.XY;
                }
                int contributingElementsCount = tensorsFromAllElements[node].Count;
                tensorXX       /= contributingElementsCount;
                tensorYY       /= contributingElementsCount;
                tensorXY       /= contributingElementsCount;
                nodalTensors[i] = new Tensor2D(tensorXX, tensorYY, tensorXY);
            }

            return(nodalTensors);
        }
示例#28
0
 internal ComplexityContext(
     IOutputField fieldDefinition,
     FieldNode fieldSelection,
     ICollection <IOutputField> path,
     IVariableValueCollection variables,
     CostDirective cost)
 {
     FieldDefinition = fieldDefinition;
     FieldSelection  = fieldSelection;
     Path            = path;
     Variables       = variables;
     Cost            = cost;
 }
示例#29
0
 private void ValidateLeafField(
     FieldNode fieldSelection,
     IOutputField field)
 {
     if (fieldSelection.SelectionSet != null)
     {
         string type = field.Type.IsScalarType() ? "a scalar" : "an enum";
         Errors.Add(new ValidationError(
                        $"`{field.Name}` is {type} field. Selections on scalars " +
                        "or enums are never allowed, because they are the leaf " +
                        "nodes of any GraphQL query.", fieldSelection));
     }
 }
示例#30
0
 private void ValidateNodeField(
     FieldNode fieldSelection,
     IOutputField field)
 {
     if (fieldSelection.SelectionSet == null)
     {
         Errors.Add(new ValidationError(
                        $"`{field.Name}` is an object, interface or union type " +
                        "field. Leaf selections on objects, interfaces, and " +
                        "unions without subfields are disallowed.",
                        fieldSelection));
     }
 }
示例#31
0
 /// <summary>
 /// Add a field and allow it to be specified as an "ideal output field".
 /// An "ideal" field is the expected output that the neural network is
 /// training towards.
 /// </summary>
 /// <param name="outputField">The output field.</param>
 /// <param name="ideal">True if this is an ideal field.</param>
 public void AddOutputField(IOutputField outputField,
                            bool ideal)
 {
     _outputFields.Add(outputField);
     outputField.Ideal = ideal;
     if (outputField is OutputFieldGrouped)
     {
         var ofg = (OutputFieldGrouped)outputField;
         _groups.Add(ofg.Group);
     }
 }
示例#32
0
 /// <summary>
 ///  Add an output field.  This output field will be added as a 
 /// "neural network input field", not an "ideal output field".
 /// </summary>
 /// <param name="outputField">The output field to add.</param>
 public void AddOutputField(IOutputField outputField)
 {
     AddOutputField(outputField, false);
 }
 public void Remove(IOutputField outputField)
 {
     mOutputField.Remove(outputField);
 }
 public void Add(IOutputField outputField)
 {
     mOutputField.Add(outputField);
 }
示例#35
0
 public void AddOutputField(IOutputField outputField, bool ideal)
 {
     this._outputFields.Add(outputField);
     outputField.Ideal = ideal;
     if (outputField is OutputFieldGrouped)
     {
         OutputFieldGrouped grouped = (OutputFieldGrouped) outputField;
         this._groups.Add(grouped.Group);
     }
 }
 /// <summary>
 /// Add a field and allow it to be specified as an "ideal output field".
 /// An "ideal" field is the expected output that the neural network is
 /// training towards.
 /// </summary>
 /// <param name="outputField">The output field.</param>
 /// <param name="ideal">True if this is an ideal field.</param>
 public void AddOutputField(IOutputField outputField,
          bool ideal)
 {
     this.outputFields.Add(outputField);
     outputField.Ideal = ideal;
     if (outputField is OutputFieldGrouped)
     {
         OutputFieldGrouped ofg = (OutputFieldGrouped)outputField;
         this.groups.Add(ofg.Group);
     }
 }