示例#1
0
        protected override void Run()
        {
            MonoDevelop.Ide.Gui.Document doc    = IdeApp.Workbench.ActiveDocument;
            PlayScriptParser             parser = new PlayScriptParser();
            var unit = parser.Parse(doc.Editor);

            if (unit == null)
            {
                return;
            }
            var node = unit.GetNodeAt(doc.Editor.Caret.Location);

            if (node == null)
            {
                return;
            }

            if (doc.Editor.IsSomethingSelected)
            {
                while (node != null && doc.Editor.MainSelection.IsSelected(node.StartLocation, node.EndLocation))
                {
                    node = node.Parent;
                }
            }

            if (node != null)
            {
                doc.Editor.SetSelection(node.StartLocation, node.EndLocation);
            }
        }
示例#2
0
        public static object Parse(SeekableStreamReader reader, SourceFile sourceFile, ModuleContainer module, ParserSession session, Report report, int lineModifier = 0, int colModifier = 0)
        {
            var file = new CompilationSourceFile(module, sourceFile);

            module.AddTypeContainer(file);

            object parser = null;

            if (sourceFile.FileType == SourceFileType.CSharp)
            {
                CSharpParser csParser = new CSharpParser(reader, file, report, session);
                csParser.Lexer.Line   += lineModifier;
                csParser.Lexer.Column += colModifier;
                csParser.Lexer.sbag    = new SpecialsBag();
                csParser.parse();
                parser = csParser;
            }
            else
            {
                PlayScriptParser psParser = new PlayScriptParser(reader, file, report, session);
                psParser.parsing_playscript = sourceFile.PsExtended;
                psParser.Lexer.Line        += lineModifier;
                psParser.Lexer.Column      += colModifier;
                psParser.Lexer.sbag         = new SpecialsBag();
                psParser.parse();
                parser = psParser;
            }

            return(parser);
        }
		public override IEntity ResolveCref(string cref)
		{
			if (cref.Length > 2 && cref[1] == ':') {
				// resolve ID string
				return base.ResolveCref(cref);
			}
			var documentationReference = new PlayScriptParser().ParseDocumentationReference(cref);
			var csharpContext = context as CSharpTypeResolveContext;
			CSharpResolver resolver;
			if (csharpContext != null) {
				resolver = new CSharpResolver(csharpContext);
			} else {
				resolver = new CSharpResolver(context.Compilation);
			}
			var astResolver = new CSharpAstResolver(resolver, documentationReference);
			var rr = astResolver.Resolve(documentationReference);
			
			MemberResolveResult mrr = rr as MemberResolveResult;
			if (mrr != null)
				return mrr.Member;
			TypeResolveResult trr = rr as TypeResolveResult;
			if (trr != null)
				return trr.Type.GetDefinition();
			return null;
		}
            void ScanPreProcessorElseIf(ref int i)
            {
                DocumentLine line      = doc.GetLineByOffset(i);
                int          length    = line.Offset + line.Length - i;
                string       parameter = doc.GetTextAt(i + 5, length - 5);
                AstNode      expr      = new PlayScriptParser().ParseExpression(parameter);
                bool         result;

                if (expr != null && !expr.IsNull)
                {
                    var visitResult = expr.AcceptVisitor(new ConditinalExpressionEvaluator(doc, Defines), null);
                    result = visitResult != null ? (bool)visitResult : false;
                }
                else
                {
                    result = false;
                }

                IfBlockSpan containingIf = null;

                if (result)
                {
                    bool previousResult = false;
                    foreach (Span span in spanStack)
                    {
                        if (span is IfBlockSpan)
                        {
                            containingIf   = (IfBlockSpan)span;
                            previousResult = ((IfBlockSpan)span).IsValid;
                            break;
                        }
                        if (span is ElseIfBlockSpan)
                        {
                            previousResult |= ((ElseIfBlockSpan)span).IsValid;
                        }
                    }

                    result = !previousResult;
                }

                var elseIfBlockSpan = new ElseIfBlockSpan(result);

                if (containingIf != null)
                {
                    elseIfBlockSpan.Disabled = containingIf.Disabled;
                }

                FoundSpanBegin(elseIfBlockSpan, i, 0);

                // put pre processor eol span on stack, so that '#elif' gets the correct highlight
                var preprocessorSpan = CreatePreprocessorSpan();

                FoundSpanBegin(preprocessorSpan, i, 0);
            }
示例#5
0
        protected override void Run()
        {
            MonoDevelop.Ide.Gui.Document doc    = IdeApp.Workbench.ActiveDocument;
            PlayScriptParser             parser = new PlayScriptParser();
            var unit = parser.Parse(doc.Editor);

            if (unit == null)
            {
                return;
            }
            var node = unit.GetNodeAt(doc.Editor.Caret.Line, doc.Editor.Caret.Column);

            if (node == null)
            {
                return;
            }
            Stack <AstNode> nodeStack = new Stack <AstNode> ();

            nodeStack.Push(node);
            if (doc.Editor.IsSomethingSelected)
            {
                while (node != null && doc.Editor.MainSelection.IsSelected(node.StartLocation, node.EndLocation))
                {
                    node = node.Parent;
                    if (node != null)
                    {
                        if (nodeStack.Count > 0 && nodeStack.Peek().StartLocation == node.StartLocation && nodeStack.Peek().EndLocation == node.EndLocation)
                        {
                            nodeStack.Pop();
                        }
                        nodeStack.Push(node);
                    }
                }
            }

            if (nodeStack.Count > 2)
            {
                nodeStack.Pop();                  // parent
                nodeStack.Pop();                  // current node
                node = nodeStack.Pop();           // next children in which the caret is
                doc.Editor.SetSelection(node.StartLocation, node.EndLocation);
            }
            else
            {
                doc.Editor.ClearSelection();
            }
        }
示例#6
0
        public static void Parse(SeekableStreamReader reader, SourceFile sourceFile, ModuleContainer module, ParserSession session, Report report)
        {
            var file = new CompilationSourceFile(module, sourceFile);

            module.AddTypeContainer(file);

            if (sourceFile.FileType == SourceFileType.CSharp)
            {
                CSharpParser parser = new CSharpParser(reader, file, session);
                parser.parse();
            }
            else
            {
                PlayScriptParser parser = new PlayScriptParser(reader, file, session);
                parser.parsing_playscript = sourceFile.PsExtended;
                parser.parse();
            }
        }
        protected SyntaxTree ParseStub(string continuation, bool appendSemicolon = true, string afterContinuation = null)
        {
            var mt = GetMemberTextToCaret();

            if (mt == null)
            {
                return(null);
            }

            string memberText      = mt.Item1;
            var    memberLocation  = mt.Item2;
            int    closingBrackets = 0;
            int    generatedLines  = 0;
            var    wrapper         = new StringBuilder();
            bool   wrapInClass     = memberLocation != new TextLocation(1, 1);

            if (wrapInClass)
            {
                wrapper.Append("package { class Stub {");
                wrapper.AppendLine();
                closingBrackets += 2;
                generatedLines++;
            }
            wrapper.Append(memberText);
            wrapper.Append(continuation);
            AppendMissingClosingBrackets(wrapper, memberText, appendSemicolon);
            wrapper.Append(afterContinuation);
            if (closingBrackets > 0)
            {
                wrapper.Append(new string('}', closingBrackets));
            }
            var parser = new PlayScriptParser();

            foreach (var sym in CompletionContextProvider.ConditionalSymbols)
            {
                parser.CompilerSettings.ConditionalSymbols.Add(sym);
            }
            parser.InitialLocation = new TextLocation(memberLocation.Line - generatedLines, 1);
            var result = parser.Parse(wrapper.ToString());

            return(result);
        }
示例#8
0
        public override IEntity ResolveCref(string cref)
        {
            if (cref.Length > 2 && cref[1] == ':')
            {
                // resolve ID string
                return(base.ResolveCref(cref));
            }
            var            documentationReference = new PlayScriptParser().ParseDocumentationReference(cref);
            var            csharpContext          = context as CSharpTypeResolveContext;
            CSharpResolver resolver;

            if (csharpContext != null)
            {
                resolver = new CSharpResolver(csharpContext);
            }
            else
            {
                resolver = new CSharpResolver(context.Compilation);
            }
            var astResolver = new CSharpAstResolver(resolver, documentationReference);
            var rr          = astResolver.Resolve(documentationReference);

            MemberResolveResult mrr = rr as MemberResolveResult;

            if (mrr != null)
            {
                return(mrr.Member);
            }
            TypeResolveResult trr = rr as TypeResolveResult;

            if (trr != null)
            {
                return(trr.Type.GetDefinition());
            }
            return(null);
        }
            void ScanPreProcessorIf(int textOffset, ref int i)
            {
                var end = CurText.Length;
                int idx = 0;

                while ((idx = CurText.IndexOf('/', idx)) >= 0 && idx + 1 < CurText.Length)
                {
                    var next = CurText [idx + 1];
                    if (next == '/')
                    {
                        end = idx - 1;
                        break;
                    }
                    idx++;
                }

                int     length    = end - textOffset;
                string  parameter = CurText.Substring(textOffset + 3, length - 3);
                AstNode expr      = new PlayScriptParser().ParseExpression(parameter);
                bool    result    = false;

                if (expr != null && !expr.IsNull)
                {
                    object o = expr.AcceptVisitor(new ConditinalExpressionEvaluator(doc, Defines), null);
                    if (o is bool)
                    {
                        result = (bool)o;
                    }
                }

                foreach (Span span in spanStack)
                {
                    if (span is ElseBlockSpan)
                    {
                        result &= ((ElseBlockSpan)span).IsValid;
                        break;
                    }
                    if (span is IfBlockSpan)
                    {
                        result &= ((IfBlockSpan)span).IsValid;
                        break;
                    }
                    if (span is ElseIfBlockSpan)
                    {
                        result &= ((ElseIfBlockSpan)span).IsValid;
                        break;
                    }
                }

                var ifBlockSpan = new IfBlockSpan(result);

                foreach (Span span in spanStack)
                {
                    if (span is AbstractBlockSpan)
                    {
                        var parentBlock = (AbstractBlockSpan)span;
                        ifBlockSpan.Disabled = parentBlock.Disabled || !parentBlock.IsValid;
                        break;
                    }
                }

                FoundSpanBegin(ifBlockSpan, i, length);
                i += length - 1;
            }
		ExpressionResult GetNewExpressionAt(int offset)
		{
			var parser = new PlayScriptParser();
			string text = this.document.GetText(0, this.offset); 
			var sb = new StringBuilder(text);
			sb.Append("a ();");
			AppendMissingClosingBrackets(sb, text, false);
			
			var completionUnit = parser.Parse(sb.ToString());
			var loc = document.GetLocation(offset);
			
			var expr = completionUnit.GetNodeAt(loc, n => n is Expression);
			if (expr == null) {
				// try without ";"
				sb = new StringBuilder(text);
				sb.Append("a ()");
				AppendMissingClosingBrackets(sb, text, false);
				completionUnit = parser.Parse(sb.ToString());
				loc = document.GetLocation(offset);
				
				expr = completionUnit.GetNodeAt(loc, n => n is Expression);
				if (expr == null) {
					return null;
				}
			}
			return new ExpressionResult(expr, completionUnit);
		}
		ExpressionResult GetExpressionAt(int offset)
		{
			var parser = new PlayScriptParser();
			string text = this.document.GetText(0, this.offset); 
			var sb = new StringBuilder(text);
			sb.Append("a;");
			AppendMissingClosingBrackets(sb, text, false);
			var completionUnit = parser.Parse(sb.ToString());
			var loc = document.GetLocation(offset);
			
			var expr = completionUnit.GetNodeAt(
				loc,
				n => n is Expression || n is VariableDeclarationStatement
				);
			if (expr == null) {
				return null;
			}
			return new ExpressionResult(expr, completionUnit);
		}
示例#12
0
        public string FormatText(PlayScriptFormattingPolicy policy, TextStylePolicy textPolicy, string mimeType, string input, int startOffset, int endOffset)
        {
            var data = new TextEditorData();

            data.Document.SuppressHighlightUpdate = true;
            data.Document.MimeType = mimeType;
            data.Document.FileName = "toformat.cs";
            if (textPolicy != null)
            {
                data.Options.TabsToSpaces    = textPolicy.TabsToSpaces;
                data.Options.TabSize         = textPolicy.TabWidth;
                data.Options.IndentationSize = textPolicy.IndentWidth;
                data.Options.IndentStyle     = textPolicy.RemoveTrailingWhitespace ? IndentStyle.Virtual : IndentStyle.Smart;
            }
            data.Text = input;

            // System.Console.WriteLine ("-----");
            // System.Console.WriteLine (data.Text.Replace (" ", ".").Replace ("\t", "->"));
            // System.Console.WriteLine ("-----");

            var  parser          = new PlayScriptParser();
            var  compilationUnit = parser.Parse(data);
            bool hadErrors       = parser.HasErrors;

            if (hadErrors)
            {
                //				foreach (var e in parser.ErrorReportPrinter.Errors)
                //					Console.WriteLine (e.Message);
                return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset)));
            }

            var originalVersion = data.Document.Version;

            var textEditorOptions = data.CreateNRefactoryTextEditorOptions();
            var formattingVisitor = new ICSharpCode.NRefactory.PlayScript.CSharpFormatter(
                policy.CreateOptions(),
                textEditorOptions
                )
            {
                FormattingMode = FormattingMode.Intrusive
            };

            var changes = formattingVisitor.AnalyzeFormatting(data.Document, compilationUnit);

            try {
                changes.ApplyChanges(startOffset, endOffset - startOffset);
            } catch (Exception e) {
                LoggingService.LogError("Error in code formatter", e);
                return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset)));
            }

            // check if the formatter has produced errors
            parser = new PlayScriptParser();
            parser.Parse(data);
            if (parser.HasErrors)
            {
                LoggingService.LogError("C# formatter produced source code errors. See console for output.");
                return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset)));
            }

            var currentVersion = data.Document.Version;

            string result = data.GetTextBetween(startOffset, originalVersion.MoveOffsetTo(currentVersion, endOffset, ICSharpCode.NRefactory.Editor.AnchorMovementType.Default));

            data.Dispose();
            return(result);
        }
        public override IEnumerable <MemberReference> FindReferences(Project project, IProjectContent content, IEnumerable <FilePath> possibleFiles, IProgressMonitor monitor, IEnumerable <object> members)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content", "Project content not set.");
            }
            SetPossibleFiles(possibleFiles);
            SetSearchedMembers(members);

            var scopes      = searchedMembers.Select(e => e is IEntity ? refFinder.GetSearchScopes((IEntity)e) : refFinder.GetSearchScopes((INamespace)e));
            var compilation = project != null?TypeSystemService.GetCompilation(project) : content.CreateCompilation();

            List <MemberReference> refs = new List <MemberReference> ();

            foreach (var opendoc in openDocuments)
            {
                foreach (var newRef in FindInDocument(opendoc.Item2))
                {
                    if (newRef == null || refs.Any(r => r.FileName == newRef.FileName && r.Region == newRef.Region))
                    {
                        continue;
                    }
                    refs.Add(newRef);
                }
            }
            foreach (var file in files)
            {
                if (monitor != null)
                {
                    monitor.Step(1);
                }
                string text = Mono.TextEditor.Utils.TextFileUtility.ReadAllText(file);
                if (memberName != null && text.IndexOf(memberName, StringComparison.Ordinal) < 0 &&
                    (keywordName == null || text.IndexOf(keywordName, StringComparison.Ordinal) < 0))
                {
                    continue;
                }
                using (var editor = TextEditorData.CreateImmutable(text)) {
                    editor.Document.FileName = file;
                    var unit = new PlayScriptParser().Parse(editor);
                    if (unit == null)
                    {
                        continue;
                    }

                    var storedFile = content.GetFile(file);
                    var parsedFile = storedFile as CSharpUnresolvedFile;

                    if (parsedFile == null && storedFile is ParsedDocumentDecorator)
                    {
                        parsedFile = ((ParsedDocumentDecorator)storedFile).ParsedFile as CSharpUnresolvedFile;
                    }

                    if (parsedFile == null)
                    {
                        // for fallback purposes - should never happen.
                        parsedFile  = unit.ToTypeSystem();
                        content     = content.AddOrUpdateFiles(parsedFile);
                        compilation = content.CreateCompilation();
                    }
                    foreach (var scope in scopes)
                    {
                        refFinder.FindReferencesInFile(
                            scope,
                            parsedFile,
                            unit,
                            compilation,
                            (astNode, result) => {
                            var newRef = GetReference(project, result, astNode, unit, file, editor);
                            if (newRef == null || refs.Any(r => r.FileName == newRef.FileName && r.Region == newRef.Region))
                            {
                                return;
                            }
                            refs.Add(newRef);
                        },
                            CancellationToken.None
                            );
                    }
                }
            }
            return(refs);
        }
		protected SyntaxTree ParseStub(string continuation, bool appendSemicolon = true, string afterContinuation = null)
		{
			var mt = GetMemberTextToCaret();
			if (mt == null) {
				return null;
			}

			string memberText = mt.Item1;
			var memberLocation = mt.Item2;
			int closingBrackets = 0;
			int generatedLines = 0;
			var wrapper = new StringBuilder();
			bool wrapInClass = memberLocation != new TextLocation(1, 1);
			if (wrapInClass) {
				wrapper.Append("package { class Stub {");
				wrapper.AppendLine();
				closingBrackets += 2;
				generatedLines++;
			}
			wrapper.Append(memberText);
			wrapper.Append(continuation);
			AppendMissingClosingBrackets(wrapper, memberText, appendSemicolon);
			wrapper.Append(afterContinuation);
			if (closingBrackets > 0) { 
				wrapper.Append(new string('}', closingBrackets));
			}
			var parser = new PlayScriptParser ();
			foreach (var sym in CompletionContextProvider.ConditionalSymbols)
				parser.CompilerSettings.ConditionalSymbols.Add (sym);
			parser.InitialLocation = new TextLocation(memberLocation.Line - generatedLines, 1);
			var result = parser.Parse(wrapper.ToString ());
			return result;
		}
        public static SyntaxTree Parse(ITextSource textSource, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var parser = new PlayScriptParser(settings);

            return(parser.Parse(textSource, fileName));
        }