Example #1
0
        public static IUnaryOperator Parse(ISyntaxNode parent, ref string Input, IRightValue firstOperand)
        {
            string temp = Input;

            Pattern regExPattern =
                "^\\s*" +
                new Group("def", "(\\+|-|!|~|\\*|&)");//|\\("+Provider.type+"\\)

            System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(regExPattern);
            System.Text.RegularExpressions.Match match = regEx.Match(Input);

            if (!match.Success)
            {
                Input = temp;
                return null;
            }

            Input = Input.Remove(0, match.Index + match.Length);

            string Operator = match.Groups["def"].Value;

            switch (Operator)
            {

                default:
                    Input = temp;
                    throw new NotImplementedException();
            }
        }
Example #2
0
        public Brackets(ISyntaxNode parent, ref string Input)
            : base(parent)
        {
            Pattern regExPattern =
                   "^\\s*" +
                   new Group("def", "\\(");

            System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(regExPattern);
            System.Text.RegularExpressions.Match match = regEx.Match(Input);

            if (!match.Success)
                throw new ParseException();

            Input = Input.Remove(0, match.Index + match.Length);

            this.Operand = IRightValue.Parse(this, ref Input);

            Pattern regExClosePattern =	"^\\s*\\)";

            regEx = new System.Text.RegularExpressions.Regex(regExClosePattern);
            match = regEx.Match(Input);

            if (!match.Success)
                throw new ParseException();
            Input = Input.Remove(0, match.Index + match.Length);
            regExClosePattern = "^\\s*\\)";
        }
Example #3
0
        public IBinaryOperator(ISyntaxNode parent, IRightValue firstOperand, IRightValue secondOperand)
            : base(parent)
        {
            this.FirstOperand = firstOperand;
            this.SecondOperand = secondOperand;

            this.FirstOperand.Parent = this;
            this.SecondOperand.Parent = this;
        }
Example #4
0
 private static void Print(ISyntaxNode node, int level)
 {
     Console.Write(new string(' ', 2 * level));
     Console.WriteLine(node);
     foreach (var child in node.GetChildren())
     {
         Print(child, level + 1);
     }
 }
Example #5
0
        public VariableDeclaration(ISyntaxNode parent, ref string Input, bool allowAssignment)
            : base(parent)
        {
            //	string regExPattern = "(?<def>(?<signdness>signed|unsigned)?\\s*(?<type>(void|char|short|int|long|float|double))(?<pointer>[\\s\\*]+)(?<identifier>[a-zA-Z_][a-zA-Z_0-9]*)\\s*(=\\s*(?<assignment>.*))?);(?<rest>.*)";

            Pattern regExPattern =
                "^\\s*" +
                new Group("def",
                    "(" +
                        new Group("signedness", "signed|unsigned") +
                        "\\s+" +
                    ")?" +
                    new Group("type", Provider.type) +
                    new Group("pointer", "[\\s\\*]+") +
                    new Group("identifier", Provider.identifier) +
                    "\\s*(" +
                        "=\\s*" +
                        new Group("assignment", ".*") +
                    ")?") +
                ";";

            System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(regExPattern);
            System.Text.RegularExpressions.Match match = regEx.Match(Input);

            if (!match.Success)
                throw new ParseException();
            //	if (match.Index != 0)
            //		throw new ParseException();
            Input = Input.Remove(0, match.Index + match.Length); // Also removes all starting spaces etc...

            // Load signedness
            if (match.Groups["signedness"].Success)
                this.Signedness = (Signedness)Enum.Parse(typeof(Signedness), match.Groups["signedness"].Value, true);
            else
                this.Signedness = this.DefaultSignedness;

            // Load type
            Type = ITypeSpecifier.Parse(this, match.Groups["type"].Value);
            if (Type == null)
                throw new SyntaxException("Error parsing variable: Expected type, got \"" + match.Groups["type"].Value + "\".");

            // Load identifier
            Identifier = match.Groups["identifier"].Value;
            if ((match.Groups["identifier"].Success) && ((Identifier == null) || (Identifier == "")))
                throw new SyntaxException("Error parsing variable: Expected identifier, got \"" + match.Groups["identifier"].Value + "\".");

            // And last but not least possible assignments
            if (allowAssignment)
            {
                Assignment = match.Groups["assignment"].Value;
                if ((match.Groups["assignment"].Success) && ((Assignment == null) || (Assignment == "")))
                    throw new SyntaxException("Error parsing variable: Expected assignment, got \"" + match.Groups["assignment"].Value + "\".");
            }
            else if (match.Groups["assignment"].Success)
                throw new SyntaxException("Error parsing variable: Assignment is not allowed here.");
        }
Example #6
0
        public FunctionCall(ISyntaxNode parent, ref string Input)
            : base(parent)
        {
            Pattern regExPattern =
                "^\\s*" +
                new Group("def",
                    new Group("identifier", Provider.identifier) +
                    "\\s*\\(" +
                    new Group("params", "[a-zA-Z_0-9*\\+/!&|%()=,\\s]*") +
                    "\\)");

            System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(regExPattern);
            System.Text.RegularExpressions.Match match = regEx.Match(Input);

            if (!match.Success)
                throw new ParseException();
            //if (match.Index != 0)
            //	throw new ParseException();
            Input = Input.Remove(0, match.Index+match.Length); // Also removes all starting spaces etc...

            Identifier = match.Groups["identifier"].Value;

            //System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("\\s*,\\s*" + new Group("", ""));
            if (!parent.IsFunctionDeclared(Identifier))
                throw new SyntaxException("Syntax error: Call of undeclared function \"" + Identifier + "\".");

            String param = match.Groups["params"].Value;
            List<IRightValue> parameters = new List<IRightValue>();

            System.Text.RegularExpressions.Regex endRegEx = new System.Text.RegularExpressions.Regex("^\\s*$");
            System.Text.RegularExpressions.Regex commaRegEx = new System.Text.RegularExpressions.Regex("^\\s*,\\s*");

            while (!endRegEx.IsMatch(param))
            {
                IRightValue val = IRightValue.Parse(this, ref param);
                if (val == null)
                    throw new SyntaxException ("syntax error: Can't parse rvalue at function call.");

                parameters.Add(val);

                if (endRegEx.IsMatch(param))
                    break;

                System.Text.RegularExpressions.Match comma = commaRegEx.Match(param);
                if (!comma.Success)
                    throw new SyntaxException("syntax error: Function arguments must be separated by a comma.");

                param = param.Remove(0, comma.Index + comma.Length); // Also removes all starting spaces etc...
            }

            this.Parameters = parameters.ToArray(); ;
        }
Example #7
0
 private void FindSymbolsRecursively(ISyntaxNode node, ref int localVariableIndex)
 {
     if (node is BlockStatementNode)
     {
         var block = (BlockStatementNode) node;
         _scopeStack.PushAnonymousScope();
         var declaredIdentifiers = block.Declarations.SelectMany(d => d.Variables).ToList();
         EnterIdentifiers(declaredIdentifiers, SymbolTableEntryType.Variable, ref localVariableIndex);
         foreach (var statement in block.Statements)
         {
             FindSymbolsRecursively(statement, ref localVariableIndex);
         }
         _scopeStack.PopScope();
     }
     else if (node is VariableReferenceNode)
     {
         var reference = (VariableReferenceNode) node;
         var symbolTableEntry = FindDeclaration(reference.Variable.Name);
         if (symbolTableEntry == null)
             throw new Exception(string.Format("Variable {0} is not declared", reference.Variable.Name));
         reference.SymbolTableEntry = symbolTableEntry;
     }
     else if (node is AssignmentStatementNode)
     {
         var assign = (AssignmentStatementNode) node;
         var symbolTableEntry = FindDeclaration(assign.Variable.Name);
         if (symbolTableEntry == null)
             throw new Exception(string.Format("Variable {0} is not declared", assign.Variable.Name));
         assign.SymbolTableEntry = symbolTableEntry;
         FindSymbolsRecursively(assign.Expression, ref localVariableIndex);
     }
     else if (node is FunctionCallNode)
     {
         var call = (FunctionCallNode) node;
         var symbolTableEntry = FindDeclaration(call.Name.Name);
         if (symbolTableEntry == null)
             throw new Exception(string.Format("Function {0} is not declared", call.Name.Name));
         call.SymbolTableEntry = symbolTableEntry;
         foreach (var argument in call.Arguments)
         {
             FindSymbolsRecursively(argument, ref localVariableIndex);
         }
     }
     else
     {
         foreach (var child in node.GetChildren())
         {
             FindSymbolsRecursively(child, ref localVariableIndex);
         }
     }
 }
Example #8
0
        public VisitorAction Enter(
            FragmentDefinitionNode node,
            ISyntaxNode parent,
            IReadOnlyList <object> path,
            IReadOnlyList <ISyntaxNode> ancestors)
        {
            if (_schema.TryGetType(
                    node.TypeCondition.Name.Value,
                    out INamedType type))
            {
                _touchedFragments.Add(node.Name.Value);
                _type.Push(type);
                _action.Push(VisitorAction.Continue);
                return(VisitorAction.Continue);
            }

            _action.Push(VisitorAction.Skip);
            return(VisitorAction.Skip);
        }
Example #9
0
        public static ISyntaxNode CreateConcept(Type conceptType, ISyntaxNode parent, string propertyName)
        {
            ISyntaxNode concept = (ISyntaxNode)Activator.CreateInstance(conceptType);

            concept.Parent = parent;

            PropertyInfo property = parent.GetPropertyInfo(propertyName);

            if (property.IsOptional())
            {
                IOptional optional = (IOptional)property.GetValue(parent);
                optional.Value = concept;
            }
            else
            {
                property.SetValue(parent, concept);
            }
            return(concept);
        }
Example #10
0
        public VisitorAction Enter(
            ObjectFieldNode node,
            ISyntaxNode parent,
            IReadOnlyList <object> path,
            IReadOnlyList <ISyntaxNode> ancestors)
        {
            if (_type.Peek().NamedType() is InputObjectType inputObject &&
                inputObject.Fields.TryGetField(
                    node.Name.Value,
                    out IInputField? field))
            {
                _type.Push(field.Type);
                _action.Push(VisitorAction.Continue);
                return(VisitorAction.Continue);
            }

            _action.Push(VisitorAction.Skip);
            return(VisitorAction.Skip);
        }
Example #11
0
        public VisitorAction Enter(
            FieldNode node,
            ISyntaxNode parent,
            IReadOnlyList <object> path,
            IReadOnlyList <ISyntaxNode> ancestors)
        {
            if (_type.Peek().NamedType() is IComplexOutputType complexType &&
                complexType.Fields.TryGetField(
                    node.Name.Value, out IOutputField? field))
            {
                _field.Push(field);
                _type.Push(field.Type);
                _action.Push(VisitorAction.Continue);
                return(VisitorAction.Continue);
            }

            _action.Push(VisitorAction.Skip);
            return(VisitorAction.Skip);
        }
        public override IEnumerable <AnalyzerMessageBase> AnalyzeSyntaxNode(ISyntaxNode syntaxNode, ISemanticModel semanticModel)
        {
            if (syntaxNode == null)
            {
                throw new ArgumentNullException(nameof(syntaxNode));
            }
            if (semanticModel == null)
            {
                throw new ArgumentNullException(nameof(semanticModel));
            }

            lock (_configRefreshLock)
            {
                return(AnalyzeCore(
                           () => GetIllegalTypeDependencies(
                               () => _typeDependencyEnumerator.GetTypeDependencies(syntaxNode, semanticModel)),
                           isProjectScope: false));
            }
        }
        public override VisitorAction Enter(
            ObjectFieldNode node,
            ISyntaxNode parent,
            IReadOnlyList <object> path,
            IReadOnlyList <ISyntaxNode> ancestors)
        {
            base.Enter(node, parent, path, ancestors);

            if (Operations.Peek() is FilterOperationField field)
            {
                for (var i = _fieldHandlers.Count - 1; i >= 0; i--)
                {
                    if (_fieldHandlers[i].Enter(
                            field,
                            node,
                            parent,
                            path,
                            ancestors,
                            Closures,
                            _inMemory,
                            out VisitorAction action))
                    {
                        return(action);
                    }
                }
                for (var i = _opHandlers.Count - 1; i >= 0; i--)
                {
                    if (_opHandlers[i].TryHandle(
                            field.Operation,
                            field.Type,
                            node.Value,
                            Closures.Peek().Instance.Peek(),
                            _converter,
                            out Expression expression))
                    {
                        Closures.Peek().Level.Peek().Enqueue(expression);
                        break;
                    }
                }
                return(VisitorAction.Skip);
            }
            return(VisitorAction.Continue);
        }
Example #14
0
        protected SyntaxNode(int line,
                             string file,
                             int abstraction,
                             ISyntaxNode parent,
                             ParserRuleContext context)
        {
            Parent      = parent;
            Root        = Parent.Root;
            AllParents  = GetAllParents();
            Abstraction = abstraction;
            File        = file;
            Line        = line;

            var a        = context.Start.StartIndex;
            var b        = context.Stop.StopIndex;
            var interval = new Interval(a, b);

            OriginalText = context.Start.InputStream.GetText(interval);
        }
Example #15
0
 public override VisitorAction Leave(
     ObjectFieldNode node,
     ISyntaxNode parent,
     IReadOnlyList <object> path,
     IReadOnlyList <ISyntaxNode> ancestors)
 {
     if (Operations.Peek() is FilterOperationField field &&
         field.Operation.Kind == FilterOperationKind.Object)
     {
         // Deque last expression to prefix with nullcheck
         var condition = Level.Peek().Dequeue();
         var nullCheck = Expression.NotEqual(
             Instance.Peek(),
             Expression.Constant(null, typeof(object)));
         Level.Peek().Enqueue(Expression.AndAlso(nullCheck, condition));
         Instance.Pop();
     }
     return(base.Leave(node, parent, path, ancestors));
 }
Example #16
0
        public VisitorAction Enter(
            InlineFragmentNode node,
            ISyntaxNode parent,
            IReadOnlyList <object> path,
            IReadOnlyList <ISyntaxNode> ancestors)
        {
            if (node.TypeCondition is not null &&
                _schema.TryGetType(
                    node.TypeCondition.Name.Value,
                    out INamedType? type))
            {
                _type.Push(type);
                _action.Push(VisitorAction.Continue);
                return(VisitorAction.Continue);
            }

            _action.Push(VisitorAction.Skip);
            return(VisitorAction.Skip);
        }
Example #17
0
        private ISyntaxNode <IN> RemoveByPassNodes(ISyntaxNode <IN> tree)
        {
            ISyntaxNode <IN> result = null;


            if (tree is SyntaxNode <IN> node && node.IsByPassNode)
            {
                result = RemoveByPassNodes(node.Children[0]);
            }
            else
            {
                if (tree is SyntaxLeaf <IN> leaf)
                {
                    result = leaf;
                }
                if (tree is SyntaxNode <IN> innernode)
                {
                    var newChildren = new List <ISyntaxNode <IN> >();
                    foreach (var child in innernode.Children)
                    {
                        newChildren.Add(RemoveByPassNodes(child));
                    }
                    innernode.Children.Clear();
                    innernode.Children.AddRange(newChildren);
                    result = innernode;
                }

                if (tree is ManySyntaxNode <IN> many)
                {
                    var newChildren = new List <ISyntaxNode <IN> >();
                    foreach (var child in many.Children)
                    {
                        newChildren.Add(RemoveByPassNodes(child));
                    }
                    many.Children.Clear();
                    many.Children.AddRange(newChildren);
                    result = many;
                }
            }

            return(result);
        }
        public override VisitorAction Enter(
            ObjectFieldNode node,
            ISyntaxNode parent,
            IReadOnlyList <object> path,
            IReadOnlyList <ISyntaxNode> ancestors)
        {
            base.Enter(node, parent, path, ancestors);

            if (Operations.Peek() is SortOperationField sortField)
            {
                Closure.EnqueueProperty(sortField.Operation.Property);
                if (!sortField.Operation.IsObject)
                {
                    var kind = (SortOperationKind)sortField.Type.Deserialize(node.Value.Value);
                    SortOperations.Enqueue(CreateSortOperation(kind));
                }
            }

            return(VisitorAction.Continue);
        }
Example #19
0
        public static FunArgumentExpressionNode CreateWith(ISyntaxNode node)
        {
            switch (node)
            {
            case NamedIdSyntaxNode varNode:
                return(new FunArgumentExpressionNode(
                           name:     varNode.Id,
                           type:     node.OutputType,
                           interval: node.Interval));

            case TypedVarDefSyntaxNode typeVarNode:
                return(new FunArgumentExpressionNode(
                           name:     typeVarNode.Id,
                           type:     typeVarNode.FunnyType,
                           interval: node.Interval));

            default:
                throw ErrorFactory.InvalidArgTypeDefinition(node);
            }
        }
Example #20
0
 private int CompareOperations(ISyntaxNode a, ISyntaxNode b, int aCountBracket, int bCountBracket)
 {
     if (aCountBracket < bCountBracket)
     {
         return(1);
     }
     if (aCountBracket > bCountBracket)
     {
         return(-1);
     }
     if (listOperations.IndexOf(a.ToStringValue()) < listOperations.IndexOf(b.ToStringValue()))
     {
         return(1);
     }
     if (listOperations.IndexOf(a.ToStringValue()) > listOperations.IndexOf(b.ToStringValue()))
     {
         return(-1);
     }
     return(0);
 }
        public static IStatementSyntax Create(ISyntaxNode parent, JurParser.StatementContext context)
        {
            if (context is JurParser.BlockStatementContext blockContext)
            {
                return(new BlockStatement(parent, blockContext));
            }
            if (context is JurParser.IfStatementContext ifContext)
            {
                return(new IfStatementSyntax(parent, ifContext));
            }
            if (context is JurParser.ForStatementContext forContext)
            {
                return(new ForStatementSyntax(parent, forContext));
            }
            if (context is JurParser.ReturnStatementContext returnContext)
            {
                return(new ReturnStatementSyntax(parent, returnContext));
            }
            if (context is JurParser.InferedVariableDeclarationStatementContext inferredContext)
            {
                return(new InferredVariableDeclarationSyntax(parent, inferredContext.inferedVariableDeclaration()));
            }
            if (context is JurParser.InitializedVariableDeclarationStatementContext initializedContext)
            {
                return(new InitializedVariableDeclarationSyntax(parent, initializedContext.initializedVariableDeclaration()));
            }
            if (context is JurParser.UninitializedVarDeclarationStatementContext uninitializedContext)
            {
                return(new UninitializedVariableDeclarationSyntax(parent, uninitializedContext.uninitializedVarDeclaration(), UninitializedVariableType.Local));
            }
            if (context is JurParser.AssignmentStatementContext assignmentContext)
            {
                return(new AssignmentStatementSyntax(parent, assignmentContext));
            }
            if (context is JurParser.ExpressionStatementContext expressionContext)
            {
                return(new ExpressionStatementSyntax(parent, expressionContext));
            }

            throw new Exception("WTF");
        }
Example #22
0
        private static (object, FunnyType) ParseSyntaxNode(ISyntaxNode syntaxNode)
        {
            if (syntaxNode == null)
            {
                throw new ArgumentException();
            }
            if (syntaxNode is ConstantSyntaxNode constant)
            {
                return(ParseConstant(constant));
            }
            if (syntaxNode is GenericIntSyntaxNode intGeneric)
            {
                return(ParseGenericIntConstant(intGeneric));
            }
            if (syntaxNode is ArraySyntaxNode array)
            {
                var       items       = new List <object>(array.Expressions.Count);
                FunnyType?unifiedType = null;
                foreach (var child in array.Expressions)
                {
                    var(value, childVarType) = ParseSyntaxNode(child);
                    if (!unifiedType.HasValue)
                    {
                        unifiedType = childVarType;
                    }
                    else if (unifiedType != childVarType)
                    {
                        unifiedType = FunnyType.Anything;
                    }

                    items.Add(value);
                }

                if (!items.Any())
                {
                    return(new object[0], FunnyType.ArrayOf(FunnyType.Anything));
                }
                return(items.ToArray(), FunnyType.ArrayOf(unifiedType.Value));
            }
            throw new NotSupportedException($"syntax node {syntaxNode.GetType().Name} is not supported");
        }
Example #23
0
        protected override ISyntaxVisitorAction Enter(
            VariableNode node,
            IDocumentValidatorContext context)
        {
            ISyntaxNode parent = context.Path.Peek();
            IValueNode? defaultValue;

            switch (parent.Kind)
            {
            case NodeKind.Argument:
            case NodeKind.ObjectField:
                defaultValue = context.InputFields.Peek().DefaultValue;
                break;

            default:
                defaultValue = null;
                break;
            }

            if (context.Variables.TryGetValue(
                    node.Name.Value,
                    out VariableDefinitionNode? variableDefinition) &&
                !IsVariableUsageAllowed(variableDefinition, context.Types.Peek(), defaultValue))
            {
                string variableName = variableDefinition.Variable.Name.Value;

                context.Errors.Add(
                    ErrorBuilder.New()
                    .SetMessage(
                        $"The variable `{variableName}` is not compatible " +
                        "with the type of the current location.")
                    .AddLocation(node)
                    .SetPath(context.CreateErrorPath())
                    .SetExtension("variable", variableName)
                    .SetExtension("variableType", variableDefinition.Type.ToString())
                    .SetExtension("locationType", context.Types.Peek().Visualize())
                    .SpecifiedBy("sec-All-Variable-Usages-are-Allowed")
                    .Build());
            }
            return(Skip);
        }
Example #24
0
 public override VisitorAction Leave(
     ObjectFieldNode node,
     ISyntaxNode parent,
     IReadOnlyList <object> path,
     IReadOnlyList <ISyntaxNode> ancestors)
 {
     if (Operations.Peek() is FilterOperationField field)
     {
         for (var i = _fieldHandlers.Count - 1; i >= 0; i--)
         {
             _fieldHandlers[i].Leave(
                 field,
                 node,
                 parent,
                 path,
                 ancestors,
                 Closures);
         }
     }
     return(base.Leave(node, parent, path, ancestors));
 }
Example #25
0
        public void Leave(
            FilterOperationField field,
            ObjectFieldNode node,
            ISyntaxNode parent,
            IReadOnlyList <object> path,
            IReadOnlyList <ISyntaxNode> ancestors,
            Stack <QueryableClosure> closures)
        {
            if (field.Operation.Kind == FilterOperationKind.Object)
            {
                // Deque last expression to prefix with nullcheck
                Expression condition = closures.Peek().Level.Peek().Dequeue();
                Expression property  = closures.Peek().Instance.Peek();

                // wrap last expression
                closures.Peek().Level.Peek().Enqueue(
                    FilterExpressionBuilder.NotNullAndAlso(
                        property, condition));
                closures.Peek().Instance.Pop();
            }
        }
Example #26
0
        public static ISyntaxNode FindVarDefinitionOrNull(this ISyntaxNode root, string nodeName)
        {
            if (root is TypedVarDefSyntaxNode v && v.Id == nodeName)
            {
                return(root);
            }
            if (root is VarDefinitionSyntaxNode vd && vd.Id == nodeName)
            {
                return(root);
            }

            foreach (var child in root.Children)
            {
                var result = FindVarDefinitionOrNull(child, nodeName);
                if (result != null)
                {
                    return(result);
                }
            }
            return(null);
        }
Example #27
0
        public static string Print(this ISyntaxNode node, bool indented)
        {
            StringSyntaxWriter writer = StringSyntaxWriter.Rent();

            try
            {
                if (indented)
                {
                    _serializer.Serialize(node, writer);
                }
                else
                {
                    _serializerNoIndent.Serialize(node, writer);
                }
                return(writer.ToString());
            }
            finally
            {
                StringSyntaxWriter.Return(writer);
            }
        }
Example #28
0
 public bool Enter(
     FilterOperationField field,
     ObjectFieldNode node,
     ISyntaxNode parent,
     IReadOnlyList <object> path,
     IReadOnlyList <ISyntaxNode> ancestors,
     Stack <QueryableClosure> closures,
     out VisitorAction action)
 {
     if (field.Operation.Kind == FilterOperationKind.Object)
     {
         var nestedProperty = Expression.Property(
             closures.Peek().Instance.Peek(),
             field.Operation.Property);
         closures.Peek().Instance.Push(nestedProperty);
         action = VisitorAction.Continue;
         return(true);
     }
     action = VisitorAction.Default;
     return(false);
 }
Example #29
0
        public ForStatementSyntax(ISyntaxNode parent, JurParser.ForStatementContext context) : base(parent, context)
        {
            Iterator = context.initializedVariableDeclaration() != null ? new InitializedVariableDeclarationSyntax(this, context.initializedVariableDeclaration())
                                   : context.inferedVariableDeclaration() != null   ? new InferredVariableDeclarationSyntax(this, context.inferedVariableDeclaration())
                                                                                      : (IVariableDeclarationSyntax?)null;

            Condition    = ToExpression(context.expression(0));
            Modification = context.expression().Length == 2 ? ToExpression(context.expression(1)) : null;
            Body         = StatementSyntaxFactory.Create(this, context.statement());

            ForLoopType = Iterator != null && Modification != null ? ForLoopType.Classic
                                      : Iterator != null                       ? ForLoopType.WhileIterator
                                      : Modification != null                   ? ForLoopType.WhileModify
                                                                                 : ForLoopType.While;

            ImmediateChildren = ImmutableArray.Create <ITreeNode>()
                                .AddIfNotNull(Iterator)
                                .Add(Condition)
                                .AddIfNotNull(Modification)
                                .Add(Body);
        }
Example #30
0
        protected override ISyntaxVisitorAction Enter(
            ISyntaxNode node,
            IDocumentValidatorContext context)
        {
            switch (node.Kind)
            {
            case NodeKind.Field:
            case NodeKind.SelectionSet:
            case NodeKind.InlineFragment:
            case NodeKind.FragmentSpread:
            case NodeKind.FragmentDefinition:
            case NodeKind.Directive:
            case NodeKind.VariableDefinition:
            case NodeKind.OperationDefinition:
            case NodeKind.Document:
                return(base.Enter(node, context));

            default:
                return(Skip);
            }
        }
        private void InitializeRepeatableViewModel(ISyntaxNodeViewModel repeatableNode)
        {
            ISyntaxNodeViewModel parentNode = repeatableNode.Owner;
            ISyntaxNode          concept    = parentNode.SyntaxNode;
            string propertyBinding          = repeatableNode.PropertyBinding;

            IList        conceptChildren;
            PropertyInfo property = concept.GetPropertyInfo(propertyBinding);

            if (property.IsOptional())
            {
                IOptional optional = (IOptional)property.GetValue(concept);
                if (optional == null || !optional.HasValue)
                {
                    return;
                }
                conceptChildren = (IList)optional.Value;
            }
            else
            {
                conceptChildren = (IList)property.GetValue(concept);
            }
            if (conceptChildren == null || conceptChildren.Count == 0)
            {
                return;
            }
            foreach (var child in conceptChildren)
            {
                if (!(child is SyntaxNode))
                {
                    continue;
                }
                ConceptNodeViewModel conceptViewModel = CreateSyntaxNode(repeatableNode, (ISyntaxNode)child);
                if (conceptViewModel == null)
                {
                    continue;
                }
                repeatableNode.Add(conceptViewModel);
            }
        }
Example #32
0
        public static IErrorBuilder AddLocation(
            this IErrorBuilder builder,
            ISyntaxNode syntaxNode)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (syntaxNode == null)
            {
                throw new ArgumentNullException(nameof(syntaxNode));
            }

            if (syntaxNode.Location != null)
            {
                return(builder.AddLocation(
                           syntaxNode.Location.Line,
                           syntaxNode.Location.Column));
            }
            return(builder);
        }
Example #33
0
        public virtual ISyntaxNode Rewrite(ISyntaxNode node, TContext context)
        {
            if (node == null)
            {
                throw new ArgumentNullException(nameof(node));
            }

            switch (node)
            {
            case DocumentNode document:
                return(RewriteDocument(document, context));

            case ITypeSystemExtensionNode extension:
                return(RewriteTypeExtensionDefinition(extension, context));

            case ITypeSystemDefinitionNode definition:
                return(RewriteTypeDefinition(definition, context));

            default:
                throw new NotSupportedException();
            }
        }
Example #34
0
        private ISyntaxNode <IN> SetAssociativity(ISyntaxNode <IN> tree)
        {
            ISyntaxNode <IN> result = null;


            if (tree is ManySyntaxNode <IN> many)
            {
                var newChildren = new List <ISyntaxNode <IN> >();
                foreach (var child in many.Children)
                {
                    newChildren.Add(SetAssociativity(child));
                }
                many.Children.Clear();
                many.Children.AddRange(newChildren);
                result = many;
            }
            else if (tree is SyntaxLeaf <IN> leaf)
            {
                result = leaf;
            }
            else if (tree is SyntaxNode <IN> node)
            {
                if (NeedLeftAssociativity(node))
                {
                    node = ProcessLeftAssociativity(node);
                }
                var newChildren = new List <ISyntaxNode <IN> >();
                foreach (var child in node.Children)
                {
                    newChildren.Add(SetAssociativity(child));
                }
                node.Children.Clear();
                node.Children.AddRange(newChildren);
                result = node;
            }

            return(result);
        }
Example #35
0
        protected override IDocumentValidatorContext OnBeforeEnter(
            ISyntaxNode node,
            ISyntaxNode?parent,
            IReadOnlyList <ISyntaxNode> ancestors,
            IDocumentValidatorContext context)
        {
            INamedOutputType?namedOutputType;
            IOutputField?    outputField;
            IInputField?     inputField;
            DirectiveType?   directiveType;
            IType?           type;

            switch (node.Kind)
            {
            case NodeKind.OperationDefinition:
                var operation = (OperationDefinitionNode)node;
                context.Types.Push(GetOperationType(context.Schema, operation.Operation));
                break;

            case NodeKind.VariableDefinition:
                var variable = (VariableDefinitionNode)node;
                context.Variables[variable.Variable.Name.Value] = variable;
                break;

            case NodeKind.Field:
                var field = ((FieldNode)node);
                if (context.Types.TryPeek(out type) &&
                    type.NamedType() is IComplexOutputType ot &&
                    ot.Fields.TryGetField(field.Name.Value, out IOutputField of))
                {
                    context.OutputFields.Push(of);
                }
                else
                {
                    context.Types.Push(context.Types.Peek());
                    context.IsInError = true;
                }
                break;
Example #36
0
        // find operator with minimum priority
        private ISyntaxNode FindMinPrioritiOperation(List <ISyntaxNode> listNode, out int position)
        {
            ISyntaxNode min = null;
            int         countMinOperationBrachet = 0;
            int         countBracketOpening      = 0;
            int         countBracketClosing      = 0;

            position = 0;
            for (int i = 0; i < listNode.Count; i++)
            {
                if (listNode[i].ToStringValue() == "(")
                {
                    countBracketOpening++;
                }
                if (listNode[i].ToStringValue() == ")")
                {
                    countBracketClosing++;
                }
                if (listOperations.IndexOf(listNode[i].ToStringValue()) != -1)
                {
                    if (min == null)
                    {
                        min      = listNode[i];
                        position = i;
                        countMinOperationBrachet = countBracketOpening - countBracketClosing;
                        continue;
                    }

                    if (CompareOperations(min, listNode[i], countMinOperationBrachet, countBracketOpening - countBracketClosing) == -1)
                    {
                        min      = listNode[i];
                        position = i;
                        countMinOperationBrachet = countBracketOpening - countBracketClosing;
                    }
                }
            }
            return(min);
        }
Example #37
0
        public override VisitorAction Enter(
            ObjectFieldNode node,
            ISyntaxNode parent,
            IReadOnlyList <object> path,
            IReadOnlyList <ISyntaxNode> ancestors)
        {
            base.Enter(node, parent, path, ancestors);

            if (Operations.Peek() is FilterOperationField field)
            {
                if (field.Operation.Kind == FilterOperationKind.Object)
                {
                    Instance.Push(Expression.Property(
                                      Instance.Peek(),
                                      field.Operation.Property));
                    return(VisitorAction.Continue);
                }
                else
                {
                    for (var i = _opHandlers.Count - 1; i >= 0; i--)
                    {
                        if (_opHandlers[i].TryHandle(
                                field.Operation,
                                field.Type,
                                node.Value,
                                Instance.Peek(),
                                _converter,
                                out Expression expression))
                        {
                            Level.Peek().Enqueue(expression);
                            break;
                        }
                    }
                    return(VisitorAction.Skip);
                }
            }
            return(VisitorAction.Continue);
        }
Example #38
0
        public FloatingConstant(ISyntaxNode parent, ref string Input)
            : base(parent)
        {
            Pattern regExPattern =
                "^\\s*" +
                new Group("def",
                    new Group("signess", "[+-]") +
                    "?" +
                    new Group("nums",
                        new Group("pre_comma", "\\d+") +
                        "(\\." +
                        new Group("post_comma", "\\d+") +
                        ")?([eE]" +
                        new Group("exp", "-?\\d+") +
                        ")?"));

            System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(regExPattern);
            System.Text.RegularExpressions.Match match = regEx.Match(Input);

            if (!match.Success)
                throw new ParseException();
            //if (match.Index != 0)
            //	throw new ParseException();
            Input = Input.Remove(0, match.Index + match.Length);

            string value = match.Groups["nums"].Value;
            try
            {
                Value = Convert.ToDouble(value);

                I_Type = AtomicTypeSpecifier.Double(this);
            }
            catch (OverflowException)
            {
                throw new SyntaxException("syntax error: value \"" + value + "\" is too large for a floating value.");
            }
        }
Example #39
0
 public IOperator(ISyntaxNode parent)
     : base(parent)
 {
 }
Example #40
0
 public VariableDeclaration(ISyntaxNode parent, ref string Input)
     : this(parent, ref Input, true)
 {
 }
Example #41
0
 void printRec(ISyntaxNode node, string prefix)
 {
 }
Example #42
0
        public IntegerConstant(ISyntaxNode parent, ref string Input)
            : base(parent)
        {
            Pattern regExPattern =
                "^\\s*" +
                new Group("def",
                    new Group ("signess", "[+-]") +
                    "?" +
                    new Group("base", "0[xbo]") +
                    "?" +
                    new Group("nums", "\\d+"));

            System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(regExPattern);
            System.Text.RegularExpressions.Match match = regEx.Match(Input);

            if (!match.Success)
                throw new ParseException();
            //if (match.Index != 0)
            //	throw new ParseException();
            Input = Input.Remove(0, match.Index + match.Length);

            string value = match.Groups["nums"].Value;
            int numBase = 10;
            switch (match.Groups["base"].Value)
            {
                case "":
                    numBase = 10;
                    break;
                case "0x":
                case "0X":
                    numBase = 16;
                    break;
                case "0o":
                case "oO":
                    numBase = 8;
                    break;
                case "0b":
                case "0B":
                    numBase = 2;
                    break;
            }

            try
            {
                Value = Convert.ToInt32(value, numBase);
                if (match.Groups["signess"].Value == "-")
                    Value = (Int32)Value * -1;
                I_Type = AtomicTypeSpecifier.Int(this);
            }
            catch (OverflowException)
            {
                try
                {
                    Value = Convert.ToInt64(value, numBase);
                    if (match.Groups["signess"].Value == "-")
                        Value = (Int64)Value * -1;

                    I_Type = AtomicTypeSpecifier.Long(this);
                }
                catch (OverflowException)
                {
                    try
                    {
                        Value = Convert.ToUInt64(value);

                        if (match.Groups["signess"].Value == "-")
                            throw new SyntaxException("syntax error: value \"" + value + "\" is too large for a signed integer value.");

                        I_Type = AtomicTypeSpecifier.ULong(this);
                    }
                    catch (OverflowException)
                    {
                        throw new SyntaxException("syntax error: value \"" + value + "\" is too large for a integer value.");
                    }
                }
            }
        }
Example #43
0
 public static AtomicTypeSpecifier UInt(ISyntaxNode parent)
 {
     return new AtomicTypeSpecifier(parent, "Int", true);
 }
Example #44
0
 public AtomicTypeSpecifier(ISyntaxNode parent,  String type, bool unsigned)
     : base(parent)
 {
     this.TypeName = type.ToLower();
     Unsigned = unsigned;
 }
Example #45
0
 public void SetRootElement(ISyntaxNode node)
 {
     RootElement = node;
 }
Example #46
0
 public IUnaryOperator(ISyntaxNode parent, IRightValue operand)
     : base(parent)
 {
     this.Operand = operand;
     this.Operand.Parent = this;
 }
Example #47
0
        public static IBinaryOperator Parse(ISyntaxNode parent, ref string Input, IRightValue firstOperand)
        {
            string temp = Input;

            Pattern regExPattern =
                "^\\s*" +
                new Group("def", "(\\+|\\*|-|/|==|!=|>=|<=|<|>|\\||\\|\\||&|&&|\\^|%|<<|>>)");

            System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(regExPattern);
            System.Text.RegularExpressions.Match match = regEx.Match(Input);

            if (!match.Groups["def"].Success)
            {
                Input = temp;
                return null;
            }

            Input = Input.Remove(0, match.Index + match.Length);

            string Operator = match.Groups["def"].Value;

            IRightValue secondOperand = IRightValue.Parse(parent, ref Input);

            switch (Operator)
            {
                case "+":
                    return new AdditionOperator(parent, firstOperand, secondOperand);
                case "-":
                    return new SubtractionOperator(parent, firstOperand, secondOperand);
                case "*":
                    return new MultiplicationOperator(parent, firstOperand, secondOperand);
                case "/":
                    return new DivisionOperator(parent, firstOperand, secondOperand);
                case "==":
                    return new EqualOperator(parent, firstOperand, secondOperand);
                case "!=":
                    return new UnequalOperator(parent, firstOperand, secondOperand);
                case ">=":
                    return new GreaterEqualOperator(parent, firstOperand, secondOperand);
                case "<=":
                    return new LessEqualOperator(parent, firstOperand, secondOperand);
                case ">":
                    return new GreaterOperator(parent, firstOperand, secondOperand);
                case "<":
                    return new LessOperator(parent, firstOperand, secondOperand);

                default:
                    Input = temp;
                    throw new NotImplementedException();
            }
        }
Example #48
0
 /// <summary>
 /// Visit sub nodes of node
 /// </summary>
 /// <param name="node">Node to visit children from</param>
 private void VisitSubNodes(ISyntaxNode node)
 {
     foreach(ISyntaxNode subNode in node.GetSubNodes())
     {
         subNode.AcceptVisitor(this);
     }
 }
Example #49
0
        public static IRightValue Parse(ISyntaxNode parent, ref string Input)
        {
            string temp = Input;

            System.Text.RegularExpressions.Regex endRegEx = new System.Text.RegularExpressions.Regex("^\\s*$");
            System.Text.RegularExpressions.Regex bracketsRegEx = new System.Text.RegularExpressions.Regex("^\\s*\\)\\s*");
            System.Text.RegularExpressions.Regex commaRegEx = new System.Text.RegularExpressions.Regex("^\\s*,\\s*");

            IRightValue highestNode = null;
            while ((!endRegEx.IsMatch(Input)) && (!bracketsRegEx.IsMatch(Input)) && (!commaRegEx.IsMatch(Input)))
            {

                IntegerConstant iconst = TryParse<IntegerConstant>(parent, ref Input);
                if (iconst != null)
                {
                    if (highestNode != null) // Function calls can only be the first one.
                        throw new SyntaxException("Syntax error: Invalid rvalue before integer constant.");
                    highestNode = iconst;
                    continue;
                }

                FloatingConstant fconst = TryParse<FloatingConstant>(parent, ref Input);
                if (fconst != null)
                {
                    if (highestNode != null) // Function calls can only be the first one.
                        throw new SyntaxException("Syntax error: Invalid rvalue before floating constant.");
                    highestNode = fconst;
                    continue;
                }

                FunctionCall fcall = TryParse<FunctionCall>(parent, ref Input);
                if (fcall != null)
                {
                    if (highestNode != null) // Function calls can only be the first one.
                        throw new SyntaxException("Syntax error: Invalid rvalue before function call.");
                    highestNode = fcall;
                    continue;
                }

                //string tmp = Input;
                IBinaryOperator binop = IBinaryOperator.Parse(parent, ref Input, highestNode);
                if (binop != null)
                {
                //	Input = tmp;

                    if (highestNode == null) // Function calls can only be the first one.
                        throw new SyntaxException("Syntax error: Missing first operand for binary operator.");
                    highestNode = binop;
                    continue;
                }

                IUnaryOperator unop = IUnaryOperator.Parse(parent, ref Input, highestNode);
                if (unop != null)
                {
                    if ((unop.Position == OperatorPosition.Postfix) && (highestNode == null)) // Function calls can only be the first one.
                        throw new SyntaxException("Syntax error: Missing first operand for unary operator.");
                    highestNode = unop;
                    continue;
                }

                Brackets backets = TryParse<Brackets>(parent, ref Input);
                if (backets != null)
                {
                    if (highestNode != null) // Function calls can only be the first one.
                        throw new SyntaxException("Syntax error: Invalid rvalue before brackets.");
                    highestNode = backets;
                    continue;
                }

            //	InfixOperator iopp = TryParse<InfixOperator>(ref Input, delegate(ref string i) { return new InfixOperator(parent, ref i, highestNode); });
            //	if (iopp != null)
            //		highestNode = fcall;

                // Well, if nothing got parsed, then it's a invalid expression
                throw new SyntaxException("Syntax error: Invalid token \"" + Input + "\"");

            }

            if ((highestNode is IOperator)
                && ((highestNode as IOperator).SecondaryOperand is IOperator)
                && (highestNode.Priority < (highestNode as IOperator).SecondaryOperand.Priority))
            {
                IOperator higher = (highestNode as IOperator);
                IOperator lower = (IOperator)higher.SecondaryOperand;

                higher.SecondaryOperand = lower.PrimaryOperand;
                lower.PrimaryOperand = higher;
                higher = lower;

                highestNode = higher;
            }

            return highestNode;
        }
Example #50
0
 public static AtomicTypeSpecifier UChar(ISyntaxNode parent)
 {
     return new AtomicTypeSpecifier(parent, "Char", true);
 }
Example #51
0
 public static AtomicTypeSpecifier Short(ISyntaxNode parent)
 {
     return new AtomicTypeSpecifier(parent, "Short", false);
 }
Example #52
0
 public IRightValue(ISyntaxNode parent)
     : base(parent)
 {
 }
Example #53
0
 public GreaterOperator(ISyntaxNode parent, IRightValue firstOperand, IRightValue secondOperand)
     : base(parent, firstOperand, secondOperand)
 {
 }
Example #54
0
 public AdditionOperator(ISyntaxNode parent, IRightValue firstOperand, IRightValue secondOperand)
     : base(parent, firstOperand, secondOperand)
 {
 }
Example #55
0
 public override ITypeSpecifier Clone(ISyntaxNode parent)
 {
     return new AtomicTypeSpecifier(parent, this.TypeName, this.Unsigned);
 }
Example #56
0
 /*
  * Static "Enum" members
  */
 public static AtomicTypeSpecifier Void(ISyntaxNode parent)
 {
     return new AtomicTypeSpecifier(parent, "Void", false);
 }
Example #57
0
 public IConstantValue(ISyntaxNode parent)
     : base(parent)
 {
 }
Example #58
0
 public static AtomicTypeSpecifier Double(ISyntaxNode parent)
 {
     return new AtomicTypeSpecifier(parent, "Double", false);
 }
Example #59
0
 public static AtomicTypeSpecifier Long(ISyntaxNode parent)
 {
     return new AtomicTypeSpecifier(parent, "Long", false);
 }
Example #60
0
 public LessEqualOperator(ISyntaxNode parent, IRightValue firstOperand, IRightValue secondOperand)
     : base(parent, firstOperand, secondOperand)
 {
 }