示例#1
0
        private static void InferTypeNamesFromDeclarationWithDefaultValue(ParserRuleContext context, ImplicitAsTypeNameResolver resolver, AsTypeNamesResultsHandler resultsHandler)
        {
            var results = new Dictionary <string, List <string> >();

            var lExprContext   = context.GetChild <VBAParser.LExprContext>();
            var litExprContext = context.GetChild <VBAParser.LiteralExprContext>();

            if (lExprContext is null && litExprContext is null)
            {
                //Declarations that have a default value expression (Constants and Optional parameters)
                //must resolve to an AsTypeName. Expressions are indeterminant and result assigning the Variant type
                resultsHandler.AddIndeterminantResult();
                return;
            }

            if (lExprContext != null)
            {
                resultsHandler.AddCandidates(nameof(VBAParser.LExprContext), resolver.InferAsTypeNames(new List <VBAParser.LExprContext>()
                {
                    lExprContext
                }));
            }

            if (litExprContext != null)
            {
                resultsHandler.AddCandidates(nameof(VBAParser.LiteralExprContext), resolver.InferAsTypeNames(new List <VBAParser.LiteralExprContext>()
                {
                    litExprContext
                }));
            }
        }
        private void CreateProperty(SkryptObject target, IScopedContext ctx, ParserRuleContext propertyTree, bool isPrivate)
        {
            IToken nameToken = null;

            if (propertyTree.GetChild(0) is MemberDefinitionStatementContext assignCtx)
            {
                nameToken = assignCtx.name().NAME().Symbol;
            }
            else if (propertyTree.GetChild(0) is FunctionStatementContext fnCtx)
            {
                nameToken = fnCtx.name().NAME().Symbol;
            }
            else if (propertyTree.GetChild(0) is ModuleStatementContext moduleCtx)
            {
                nameToken = moduleCtx.name().NAME().Symbol;
            }
            else if (propertyTree.GetChild(0) is StructStatementContext structCtx)
            {
                nameToken = structCtx.name().NAME().Symbol;
            }

            var value = ctx.LexicalEnvironment.Variables[nameToken.Text].Value;

            if (value == null)
            {
                CompileErrorHandler.TolerateError(nameToken, "Field can't be set to an undefined value.");
            }

            target.CreateProperty(nameToken.Text, value, isPrivate, ctx.LexicalEnvironment.Variables[nameToken.Text].IsConstant);
        }
        private void ResolveDefault(
            ParserRuleContext expression,
            StatementResolutionContext statementContext = StatementResolutionContext.Undefined,
            bool isAssignmentTarget      = false,
            bool hasExplicitLetStatement = false,
            bool isSetAssignment         = false)
        {
            var withExpression  = GetInnerMostWithExpression();
            var boundExpression = _bindingService.ResolveDefault(
                _moduleDeclaration,
                _currentParent,
                expression,
                withExpression,
                statementContext);

            if (boundExpression.Classification == ExpressionClassification.ResolutionFailed)
            {
                var lexpression = expression as VBAParser.LExpressionContext
                                  ?? expression.GetChild <VBAParser.LExpressionContext>(0)
                                  ?? (expression as VBAParser.LExprContext
                                      ?? expression.GetChild <VBAParser.LExprContext>(0))?.lExpression();

                if (lexpression != null)
                {
                    _declarationFinder.AddUnboundContext(_currentParent, lexpression, withExpression);
                }
                else
                {
                    Logger.Warn(
                        $"Default Context: Failed to resolve {expression.GetText()}. Binding as much as we can.");
                }
            }

            IParameterizedDeclaration defaultMember = null;

            if (boundExpression.ReferencedDeclaration != null &&
                boundExpression.ReferencedDeclaration.DeclarationType != DeclarationType.Project &&
                boundExpression.ReferencedDeclaration.AsTypeDeclaration != null)
            {
                var module  = boundExpression.ReferencedDeclaration.AsTypeDeclaration;
                var members = _declarationFinder.Members(module);
                defaultMember = (IParameterizedDeclaration)members.FirstOrDefault(member =>
                                                                                  member is IParameterizedDeclaration && member.Attributes.HasDefaultMemberAttribute() &&
                                                                                  (isAssignmentTarget
                            ? member.DeclarationType.HasFlag(DeclarationType.Procedure)
                            : member.DeclarationType.HasFlag(DeclarationType.Function)));
            }

            _boundExpressionVisitor.AddIdentifierReferences(
                boundExpression,
                _qualifiedModuleName,
                _currentScope,
                _currentParent,
                isAssignmentTarget && (defaultMember == null || isSetAssignment || defaultMember.Parameters.All(param => param.IsOptional)),
                hasExplicitLetStatement,
                isSetAssignment);
        }
示例#4
0
        public virtual void EnterOperatorBitwise([NotNull] ParserRuleContext context)
        {
            if (justCompoundStatements)
            {
                return;
            }

            ParserRuleContext parent = (ParserRuleContext)context.Parent;

            if (parent.ChildCount == 3)
            {
                ParserRuleContext binOp       = (ParserRuleContext)parent.GetChild(1);
                string            binOpString = GetText(binOp);

                string lhs             = GetText(parent.GetChild(0));
                string rhs             = GetText(parent.GetChild(2));
                string replacementText = "";

                switch (binOpString)
                {
                case ">>":
                    replacementText = string.Format("bin32.arshift( {0}, {1} )", lhs, rhs);
                    break;

                case ">>>":
                    replacementText = string.Format("bin32.rshift( {0}, {1} )", lhs, rhs);
                    break;

                case "<<>":
                    replacementText = string.Format("bin32.lrotate( {0}, {1} )", lhs, rhs);
                    break;

                case ">><":
                    replacementText = string.Format("bin32.rrotate( {0}, {1} )", lhs, rhs);
                    break;
                }

                if (replacementText != "")
                {
                    //Console.WriteLine("" + parent.start.StartIndex + "-->" +parent.stop.StopIndex);
                    //Console.WriteLine("Replacing \'" + GetText(parent) + "\' with \'" + replacementText + "\'");
                    Replacements.Push(
                        new Replacement(
                            parent.start.StartIndex,
                            parent.stop.StopIndex,
                            replacementText
                            )
                        );
                }

                //Console.WriteLine(  GetText(parent.GetChild(0)) + ":" +
                //    GetText(parent.GetChild(1)) + ":" +
                //    GetText(parent.GetChild(2))
                //);
            }
        }
示例#5
0
        public virtual void EnterEveryRule(ParserRuleContext ctx)
        {
            // Find sibling lists that are children of this parent node
            ISet <Type> completed = new HashSet <Type>(); // only count sibling list for each subtree type once

            for (int i = 0; i < ctx.ChildCount; i++)
            {
                ParseTree child = ctx.GetChild(i);

                if (completed.Contains(child.GetType()))
                {
                    continue; // avoid counting repeatedly
                }
                completed.Add(child.GetType());
                if (child is TerminalNode)
                {
                    continue; // tokens are separators at most not siblings
                }

                // found subtree child
                //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
                //ORIGINAL LINE: java.util.List<? extends org.antlr.v4.runtime.ParserRuleContext> siblings = ctx.getRuleContexts(((org.antlr.v4.runtime.ParserRuleContext) child).getClass());

                var s = ctx.GetRuleContexts <ParserRuleContext>();
                IList <ParserRuleContext> siblings = s.Where((n) => n.GetType() == child.GetType()).ToList();

                //IList<ParserRuleContext> siblings = ctx.GetRuleContexts(((ParserRuleContext) child).GetType());
                if (siblings.Count > 1)
                { // we found a list
                  // check for separator by looking between first two siblings (assume all are same)
                    ParserRuleContext first    = siblings[0];
                    ParserRuleContext second   = siblings[1];
                    IList <ITree>     children = Trees.GetChildren(ctx);

                    int firstIndex  = children.IndexOf(first);
                    int secondIndex = children.IndexOf(second);

                    if (firstIndex + 1 == secondIndex)
                    {
                        continue; // nothing between first and second so no separator
                    }

                    ParseTree between = ctx.GetChild(firstIndex + 1);
                    if (between is TerminalNode)
                    { // is it a token?
                        Token separator = ((TerminalNode)between).Symbol;
                        visitNonSingletonWithSeparator(ctx, siblings, separator);
                    }
                }
            }
        }
示例#6
0
        private Expression NotNull(Expression expr, ParserRuleContext ctx)
        {
            if (expr == null)
            {
                return(null);
            }

            if (!expr.Type.Nullable)
            {
                this.AddSyntaxError($"The expression '{ctx.GetChild(1).GetText()}' is not nullable.", ctx);
                return(null);
            }

            Type clrType;

            if (expr.Type.ClrType.GetTypeInfo().IsValueType)
            {
                clrType = expr.Type.ClrType.GetGenericArguments()[0];
            }
            else
            {
                clrType = expr.Type.ClrType;
            }

            return(new UnaryConvertExpression(new DataType(clrType, false), expr, ctx));
        }
示例#7
0
        public IEnumerable <NewFolding> CreateNewFoldings(IParseTree tree)
        {
            List <NewFolding> res = new List <NewFolding>();
            ParserRuleContext rc  = tree as ParserRuleContext;

            if (rc == null)
            {
                return(res);
            }

            if (IsTreeElementToFolding(tree))
            {
                IToken tokenStart = rc.Start;
                IToken tokenEnd   = rc.Stop;
                if ((tokenStart != null) && (tokenEnd != null) && (tokenStart != tokenEnd) && (tokenEnd.StopIndex > tokenStart.StartIndex))
                {
                    NewFolding folding = new NewFolding(tokenStart.StartIndex, tokenEnd.StopIndex);
                    folding.Name = tree.GetText();
                    res.Add(folding);
                }
            }

            for (int i = 0; i < rc.ChildCount; i++)
            {
                res.AddRange(CreateNewFoldings(rc.GetChild(i)));
            }

            return(res);
        }
 /// <summary>
 /// Search <see cref="T"/> for Child direction and return first match.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="context"></param>
 /// <returns></returns>
 public static T Descendant <T>(this ParserRuleContext context) where T : ParserRuleContext
 {
     if (context == null)
     {
         throw new ArgumentNullException($"{nameof(context)} is null");
     }
     if (context is T type)
     {
         return(type);
     }
     if (context.ChildCount == 0)
     {
         return(null);
     }
     // first child's depth priority search. (not same depth search first.)
     for (var i = 0; i < context.ChildCount; i++)
     {
         var result = Descendant <T>(context.GetChild <T>(i));
         if (result != null)
         {
             return(result);
         }
     }
     return(null);
 }
示例#9
0
    public static T FindLast <T>(this ParserRuleContext tree, bool recursive = true) where T : IParseTree
    {
        if (tree == null)
        {
            return(default(T));
        }

        var find = tree.GetChild <T>(0);

        if (find != null || tree.children == null || !recursive)
        {
            return(find);
        }

        foreach (var parseTree in tree.children.Reverse())
        {
            var child = parseTree as ParserRuleContext;

            if (child == null)
            {
                continue;
            }

            find = FindLast <T>(child);
            if (find != null)
            {
                return(find);
            }
        }

        return(default(T));
    }
示例#10
0
        public override void EnterObjectCreationExpression([NotNull] CSharpParser.ObjectCreationExpressionContext context)
        {
            //context.getchild(1) la sqlcommand
            // child 2 ~> gia tri ~> bien khoi tao
            //context.GetChild(2).GetChild(1).GetText() ~> danh sach tham so
            //context.GetChild(2).GetChild(1).GetChild(0).GetText() -> string truyen vao == argumentcontext


            //Console.WriteLine(context.GetText());
            //Console.WriteLine(context.GetChild(2).GetText());
            //if (context.GetChild(2).ChildCount == 3) {
            //Console.WriteLine(context.GetChild(2).GetChild(1).GetChild(0).GetType().ToString());
            //}

            foreach (var item in listCommand)
            {
                if (context.GetChild(1).GetText().Equals(item))
                {
                    if (context.GetChild(2).ChildCount == 3)
                    {
                        listExpressLine.Add(context.Start.Line);
                        //Console.WriteLine(context.GetChild(2).GetChild(1).GetText());
                        string query = context.GetChild(2).GetChild(1).GetChild(0).GetText();
                        if (!queryVar.Contains(query))
                        {
                            queryVar.Add(query);
                        }
                    }
                    else if (context.GetChild(2).ChildCount == 2)
                    {
                        ParserRuleContext parentOfTree = (ParserRuleContext)context.Parent;
                        while (!(parentOfTree is CSharpParser.Local_variable_declaratorContext))
                        {
                            try
                            {
                                parentOfTree = (ParserRuleContext)parentOfTree.Parent;
                                if (parentOfTree == null)
                                {
                                    return;
                                }
                            }
                            catch (Exception ex)
                            {
                                // Console.WriteLine(ex.Message);
                            }
                        }
                        if (parentOfTree is CSharpParser.Local_variable_declaratorContext)
                        {
                            //Console.WriteLine(parentOfTree.GetChild(0).GetText());
                            string command = parentOfTree.GetChild(0).GetText();
                            if (!commandVar.Contains(command))
                            {
                                commandVar.Add(command);
                            }
                        }
                    }
                }
            }
        }
示例#11
0
 private void VisitChildren(ParserRuleContext context)
 {
     int count = context.ChildCount;
     for (int i = 0; i < count; i++)
     {
         Visit(context.GetChild(i));
     }
 }
示例#12
0
            private Int32 AddIntegerToLiterals(ParserRuleContext context, Byte @base, Boolean hasTwoCharPrefix)
            {
                var integerLiteral = context.GetChild(0).GetText();
                var literal        = GetInteger(integerLiteral, @base, hasTwoCharPrefix);

                Literals.Add(literal);
                return(0);
            }
        private IToken GetPropertyNameToken(ParserRuleContext propertyTree)
        {
            if (propertyTree.GetChild(0) is AssignNameStatementContext assignCtx)
            {
                return(assignCtx.name().NAME().Symbol);
            }
            else if (propertyTree.GetChild(0) is FunctionStatementContext fnCtx)
            {
                return(fnCtx.name().NAME().Symbol);
            }
            else if (propertyTree.GetChild(0) is MemberDefinitionStatementContext mdCtx)
            {
                return(mdCtx.name().NAME().Symbol);
            }

            return(null);
        }
        private void ResolveDefault(
            ParserRuleContext expression,
            StatementResolutionContext statementContext = StatementResolutionContext.Undefined,
            bool isAssignmentTarget      = false,
            bool hasExplicitLetStatement = false,
            bool isSetAssignment         = false)
        {
            var withExpression  = GetInnerMostWithExpression();
            var boundExpression = _bindingService.ResolveDefault(
                _moduleDeclaration,
                _currentParent,
                expression,
                withExpression,
                statementContext);

            if (boundExpression.Classification == ExpressionClassification.ResolutionFailed)
            {
                var lexpression = expression as VBAParser.LExpressionContext
                                  ?? expression.GetChild <VBAParser.LExpressionContext>(0)
                                  ?? (expression as VBAParser.LExprContext
                                      ?? expression.GetChild <VBAParser.LExprContext>(0))?.lExpression();

                if (lexpression != null)
                {
                    _declarationFinder.AddUnboundContext(_currentParent, lexpression, withExpression);
                }
                else
                {
                    Logger.Warn(
                        $"Default Context: Failed to resolve {expression.GetText()}. Binding as much as we can.");
                }
            }

            var hasDefaultMember = false;

            if (boundExpression.ReferencedDeclaration != null &&
                boundExpression.ReferencedDeclaration.DeclarationType != DeclarationType.Project &&
                boundExpression.ReferencedDeclaration.AsTypeDeclaration != null)
            {
                var module  = boundExpression.ReferencedDeclaration.AsTypeDeclaration;
                var members = _declarationFinder.Members(module);
                hasDefaultMember = members.Any(m => m.Attributes.Any(a => a.Name == $"{m.IdentifierName}.VB_UserMemId" && a.Values.SingleOrDefault() == "0"));
            }
            _boundExpressionVisitor.AddIdentifierReferences(boundExpression, _qualifiedModuleName, _currentScope, _currentParent, (!hasDefaultMember || isSetAssignment) && isAssignmentTarget, hasExplicitLetStatement);
        }
 /// <summary>
 /// Output child items
 /// </summary>
 /// <param name="context"></param>
 public static void DebugGetChildlen(this ParserRuleContext context, string indent = "")
 {
     for (var i = 0; i < context.ChildCount; i++)
     {
         var child = context.GetChild(i);
         var name  = child.GetText();
         Console.WriteLine(indent + name);
     }
 }
示例#16
0
        private void ProcessObj(ParserRuleContext context)
        {
            ParserRuleContext child = context.GetChild(0) as ParserRuleContext;

            if (child is PlSqlParser.Procedure_bodyContext ||
                child is PlSqlParser.Procedure_specContext ||
                child is PlSqlParser.Function_bodyContext ||
                child is PlSqlParser.Function_specContext)
            {
                var procedure = _procedureVisitor.Visit(child).SetPositionExt(child);
                _Result.Objects.Add(procedure);
            }
            else if (child is PlSqlParser.Variable_declarationContext variableContext)
            {
                var name   = variableContext.GetChild(0).GetText();
                var pltype = variableContext.GetChild(1).GetText();

                if (name == "PROCEDURE")
                {
                    var procedure = new ParsedProcedure(pltype);
                    procedure.SetPosition(variableContext);
                    _Result.Objects.Add(procedure);
                }
                else
                {
                    var variable = new ParsedVariable(name, pltype);
                    variable.SetPosition(variableContext);

                    var codePosition = new PieceOfCode();
                    codePosition.SetPosition(variableContext.GetChild(0) as ParserRuleContext);
                    variable.NameIdentifierPart = codePosition;

                    _Result.Objects.Add(variable);
                }
            }
            else if (child is PlSqlParser.Type_declarationContext typeContext)
            {
                var NameContext = typeContext.GetChild(1);
                var name        = NameContext.GetText();
                var type        = new ParsedType(name);
                type.SetPosition(typeContext);
                type.NameIdentifierPart.SetPosition(NameContext as ParserRuleContext);

                _Result.Objects.Add(type);
            }
            else if (child is PlSqlParser.Cursor_declarationContext cursorContext)
            {
                var NameContext = cursorContext.GetChild(1);
                var name        = NameContext.GetText();
                var type        = new ParsedCursor(name);
                type.SetPosition(cursorContext);
                type.NameIdentifierPart.SetPosition(NameContext as ParserRuleContext);

                _Result.Objects.Add(type);
            }
        }
        // contextオブジェクトの直下の全ての子ノードからコメントを取得する
        private Comments GetComments(ParserRuleContext context)
        {
            var ret = new Comments();

            if (context == null)
            {
                return(ret);
            }

            var start = context.Start.TokenIndex;

            for (var i = 0; i < context.ChildCount; ++i)
            {
                IParseTree child = context.GetChild(i);

                // 終端ノードの直後のコメントだけを取得する
                if (child.ChildCount > 1)
                {
                    continue;
                }
                else if (child.ChildCount == 1)
                {
                    if (child.GetType() == typeof(MiniSqlParserParser.IdentifierContext) ||
                        child.GetType() == typeof(MiniSqlParserParser.Column_aliasContext) ||
                        child.GetType() == typeof(MiniSqlParserParser.Table_aliasContext) ||
                        child.GetType() == typeof(MiniSqlParserParser.Collation_nameContext) ||
                        child.GetType() == typeof(MiniSqlParserParser.Constraint_nameContext))
                    {
                        child = child.GetChild(0);
                    }
                    else
                    {
                        continue;
                    }
                }

                var childTokenIndex = child.SourceInterval.b;
                //IList<IToken> commentTokens = _tokens.GetHiddenTokensToRight(childTokenIndex, 1);
                IList <IToken> commentTokens = this.GetHiddenTokensToRight(childTokenIndex);
                if (commentTokens == null || commentTokens.Count == 0)
                {
                    ret.Add(null);
                }
                else
                {
                    string comment = null;
                    foreach (var commentToken in commentTokens)
                    {
                        comment += commentToken.Text;
                    }
                    ret.Add(comment);
                }
            }

            return(ret);
        }
        private Ust ProcessTypeDeclaration(ParserRuleContext context,
                                           JavaParser.ClassOrInterfaceModifierContext[] modifiers)
        {
            if (context.GetChild(0) is ITerminalNode child0Terminal) // ignore ';'
            {
                return(null);
            }

            var result = Visit(context.GetChild(context.ChildCount - 1));

            if (modifiers.Any() && result is TypeDeclaration typeDeclaration)
            {
                typeDeclaration.Modifiers = modifiers
                                            .Select(m => VisitClassOrInterfaceModifier(m) as ModifierLiteral)
                                            .Where(m => m != null).ToList();
            }

            return(result);
        }
示例#19
0
 private void ProcessingNode(ParserRuleContext context)
 {
     for (int i = 0; i < context.ChildCount; i++)
     {
         var node = context.GetChild(i);
         if (node is HtmlAttributeContext node2)
         {
             List.Add(Tuple.Create(i, context));
         }
     }
 }
示例#20
0
 // Checks if the current context is an identifier, and pushes it to the expression stack.
 private void PushIfIdentifier(ParserRuleContext context)
 {
     if (context.ChildCount == 1)
     {
         var child = context.GetChild(0) as TerminalNodeImpl;
         if (child != null && child.Payload.Type == SBP.IDENTIFIER)
         {
             m_expressionData.Push(SBExpressionData.CreateIdentifier(context.GetText(), token: child.Payload as CommonToken));
         }
     }
 }
示例#21
0
 public static int indexOf(ParserRuleContext parent, ParseTree child)
 {
     for (int i = 0; i < parent.ChildCount; i++)
     {
         if (parent.GetChild(i) == child)
         {
             return(i);
         }
     }
     return(-1);
 }
示例#22
0
        private static void RemoveAsTypeDeclaration(ParserRuleContext functionContext, IModuleRewriter rewriter)
        {
            var asTypeContext = functionContext.GetChild <VBAParser.AsTypeClauseContext>();

            if (asTypeContext != null)
            {
                rewriter.Remove(asTypeContext);
                rewriter.Remove(
                    functionContext.children.ElementAt(functionContext.children.IndexOf(asTypeContext) -
                                                       1) as ParserRuleContext);
            }
        }
示例#23
0
        Program VisitStatement(ParserRuleContext context, OpCode opCode)
        {
            string           operand = "";
            string           label   = "";
            TerminalNodeImpl sourceLineContext;

            if (context.GetChild(0) is cardiasmParser.LabelContext)
            {
                label = context.GetChild(0).GetChild(0).GetText();
            }

            if (string.IsNullOrEmpty(label))
            {
                operand           = context.GetChild(1).GetText();
                sourceLineContext = context.GetChild(1) as TerminalNodeImpl;
            }
            else
            {
                operand           = context.GetChild(2).GetText();
                sourceLineContext = context.GetChild(2) as TerminalNodeImpl;
            }

            TargetProgram.EmitStatement(sourceLineContext.Payload.Line, label, opCode, operand);

            return(TargetProgram);
        }
        private static (string dataTypeName, int?dataLength, bool unsigned) ExtractColumnData(ParserRuleContext context)
        {
            var dataName     = context.GetChild <TerminalNodeImpl>(0);
            var dataTypeName = dataName.GetText();
            var unsigned     = false;

            if (context.ChildCount >= 3)
            {
                // signed / unsigned
                var signed = context.GetChild <TerminalNodeImpl>(1);
                unsigned = signed.GetText() == "UNSIGNED"; // MUST BE
            }

            int?dataLength = null;
            var lengthOne  = context.GetChild <LengthOneDimensionContext>(0);

            if (lengthOne != null)
            {
                dataLength = int.Parse(lengthOne.GetText().RemoveParenthesis());
            }

            return(dataTypeName, dataLength, unsigned);
        }
 private static ITerminalNode GetTerminalNode <Result>(this AbstractParseTreeVisitor <Result> t, ParserRuleContext node, IToken terminal)
 {
     for (int i = 0; i < node.ChildCount; i++)
     {
         ITerminalNode child = node.GetChild(i) as ITerminalNode;
         if (child != null)
         {
             if (child.Symbol == terminal)
             {
                 return(child);
             }
         }
     }
     return(null);
 }
示例#26
0
 private ITerminalNode GetTerminalNode(ParserRuleContext node, IToken terminal)
 {
     for (int i = 0; i < node.ChildCount; i++)
     {
         ITerminalNode child = node.GetChild(i) as ITerminalNode;
         if (child != null)
         {
             if (child.Symbol == terminal)
             {
                 return(child);
             }
         }
     }
     return(null);
 }
示例#27
0
        /// <summary>
        /// Extract Key Definition from context
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private static MySqlKeyDefinition ExtractKeyDefinition(ParserRuleContext context)
        {
            var indexName = context.GetChild <UidContext>().GetText();
            var indexes   = context.GetChild <IndexColumnNamesContext>();
            var indexData = Enumerable.Range(0, indexes.ChildCount)
                            .Select(x => indexes.GetChild(x) is IndexColumnNameContext columnName
                    ? columnName.GetText()
                    : "")
                            .Where(x => !string.IsNullOrEmpty(x))
                            .Select((x, i) => new MySqlKeyDetailDefinition
            {
                IndexKey = x.RemoveBackQuote(),
                Order    = i,
            })
                            .ToArray();

            var definition = new MySqlKeyDefinition()
            {
                KeyName = indexName.RemoveBackQuote(),
                Indexes = indexData,
            };

            return(definition);
        }
示例#28
0
        public override void EnterExpression([NotNull] CSharpParser.ExpressionContext context)
        {
            string pattern = @"log.*Pass";
            Regex  regex   = new Regex(pattern);

            //MatchCollection logList = regex.Matches(context.GetText());
            if (regex.IsMatch(context.GetText()))
            //if (context.GetText().Contains("log.Info"))
            {
                //Console.WriteLine(context.GetText());
                MethodInfor tmpMethod = new MethodInfor();
                tmpMethod.BaselineItem = 700;
                ParserRuleContext parrentOfTree = (ParserRuleContext)context.Parent;
                while (!(parrentOfTree is CSharpParser.Method_declarationContext))
                {
                    try
                    {
                        parrentOfTree = (ParserRuleContext)parrentOfTree.Parent;
                        if (parrentOfTree == null)
                        {
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
                if (parrentOfTree is CSharpParser.Method_declarationContext)
                {
                    tmpMethod.methodName = parrentOfTree.GetChild(0).GetText();
                    tmpMethod.startLine  = parrentOfTree.Start.Line;
                }

                if (listMethod != null)
                {
                    if (!listMethod.Any(x => x.startLine == tmpMethod.startLine))
                    {
                        listMethod.Add(tmpMethod);
                    }
                }
                else
                {
                    listMethod.Add(tmpMethod);
                }
            }
        }
示例#29
0
        public AstNode Visit(ParserRuleContext context)
        {
            var node = base.Visit(context);

            var textOutput = new StringBuilder();

            for (var i = 0; i < context.ChildCount; i++)
            {
                textOutput.AppendLine(context.GetChild(i).GetText());
            }

            var text   = textOutput.ToString();
            var line   = context.Start.Line;
            var column = context.Start.Column;

            node.SourceCode = new SourceLocation(text, line, column);
            return(node);
        }
示例#30
0
        public Node parse(ParserRuleContext context, Node parent_node = null)
        {
            Node node = new Node();

            node.rule_name = rule_names[context.RuleIndex];

            node.value = context.GetText();
            if (parent_node != null)
            {
                parent_node.children.Add(node);
            }

            for (var i = 0; i < context.ChildCount; i++)
            {
                var child = context.GetChild(i);
                parse(child, node);
            }
            return(node);
        }
示例#31
0
 private void TagRegion(ParserRuleContext context, int endChild)
 {
     var endToken = context.GetChild(endChild);
     if (endToken is LanguageService.SyntaxTree.Tree.TerminalNodeImpl)
     {
         LanguageService.SyntaxTree.IToken sym = ((LanguageService.SyntaxTree.Tree.TerminalNodeImpl)endToken).Symbol;
         var tokenSpan = new TextSpan(context.Start.StartIndex, 1);
         tags.Add(tokenSpan.ToClassificationSpan(Snapshot, xsharpRegionStartType));
         tokenSpan = new TextSpan( sym.StartIndex, sym.StopIndex - sym.StartIndex + 1);
         tags.Add(tokenSpan.ToClassificationSpan(Snapshot, xsharpRegionStopType));
     }
     else if (endToken is LanguageService.CodeAnalysis.XSharp.SyntaxParser.XSharpParser.StatementBlockContext)
     {
         XSharpParser.StatementBlockContext lastTokenInContext = endToken as LanguageService.CodeAnalysis.XSharp.SyntaxParser.XSharpParser.StatementBlockContext;
         var tokenSpan = new TextSpan(context.Start.StartIndex, 1);
         tags.Add(tokenSpan.ToClassificationSpan(Snapshot, xsharpRegionStartType));
         tokenSpan = new TextSpan(lastTokenInContext.Stop.StartIndex - 1, 1);
         tags.Add(tokenSpan.ToClassificationSpan(Snapshot, xsharpRegionStopType));
     }
 }
示例#32
0
 /// <summary>
 /// Replace any subtree siblings of root that are completely to left
 /// or right of lookahead range with a CommonToken(Token.INVALID_TYPE,"...")
 /// node.
 /// </summary>
 /// <remarks>
 /// Replace any subtree siblings of root that are completely to left
 /// or right of lookahead range with a CommonToken(Token.INVALID_TYPE,"...")
 /// node. The source interval for t is not altered to suit smaller range!
 /// WARNING: destructive to t.
 /// </remarks>
 /// <since>4.5.1</since>
 public static void StripChildrenOutOfRange(ParserRuleContext t, ParserRuleContext root, int startIndex, int stopIndex)
 {
     if (t == null)
     {
         return;
     }
     for (int i = 0; i < t.ChildCount; i++)
     {
         IParseTree child = t.GetChild(i);
         Interval range = child.SourceInterval;
         if (child is ParserRuleContext && (range.b < startIndex || range.a > stopIndex))
         {
             if (IsAncestorOf(child, root))
             {
                 // replace only if subtree doesn't have displayed root
                 CommonToken abbrev = new CommonToken(TokenConstants.InvalidType, "...");
                 t.children.Set(i, new TerminalNodeImpl(abbrev));
             }
         }
     }
 }