public void InvalidXmlLiteral() { // ensure we don't crash on this invalid VB code SnippetParser parser = new SnippetParser(SupportedLanguage.VBNet); INode node = parser.Parse("<Cell StyleID=<%= print_title %>>"); Assert.IsTrue(parser.Errors.Count > 0); }
public JsFile GetJsFileFromCodeSnippet(string codeSnippet, SupportedLanguage language) { var file = new JsFile(); var snippetParser = new SnippetParser(language); var jsFile = new JsFile { FullPath = string.Empty }; var parsedNode = snippetParser.Parse(codeSnippet); if (parsedNode.Children.Count > 0) { var visitor = new AstVisitor { Model = jsFile }; parsedNode.AcceptVisitor(visitor, null); file = visitor.Model; return(file); } return(null); }
public void InvalidExpressionSyntax() { // SD2-1584: ensure we don't crash on this invalid VB code SnippetParser parser = new SnippetParser(); INode node = parser.Parse("i == 5"); Assert.IsTrue(parser.Errors.Count > 0); }
public void Snippet_Can_Parse_When_Language_Service_Is_Null() { var snippet = SnippetParser.Parse(null, 1, 1, 1, "${type=int} ${ClassName}::get_${property=Property}()\n{\n\treturn ${ToFieldName(property)};\n}\n\nvoid ${ClassName}::set_${property}(${type} value)\n{\t${ToFieldName(property)} = value;${Caret}\n}"); Assert.Equal(18, snippet.Elements.Count); AssertSnippetTextElement <SnippetReplaceableTextElement>(snippet.Elements[0], "int"); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[1], " "); AssertSnippetTextElement <SnippetReplaceableTextElement>(snippet.Elements[2], "ClassName"); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[3], "::get_"); AssertSnippetTextElement <SnippetReplaceableTextElement>(snippet.Elements[4], "Property"); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[5], "()\n{\n\treturn "); AssertSnippetTextElement <SnippetReplaceableTextElement>(snippet.Elements[6], "_ToFieldName"); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[7], ";\n}\n\nvoid "); AssertBoundSnippetElement(snippet.Elements[8], snippet.Elements[2]); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[9], "::set_"); AssertBoundSnippetElement(snippet.Elements[10], snippet.Elements[4]); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[11], "("); AssertBoundSnippetElement(snippet.Elements[12], snippet.Elements[0]); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[13], " value)\n{\t"); AssertBoundSnippetElement(snippet.Elements[14], snippet.Elements[6]); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[15], " = value;"); Assert.IsType <SnippetCaretElement>(snippet.Elements[16]); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[17], "\n}"); }
public void Snippet_Correctly_Falls_Back_When_Language_Service_Doesnt_Contain_Function() { var languageService = new TestLanguageService(); languageService.SnippetDynamicVariables.Add("ClassName", (offset, line, column) => $"Ls_ClassName{offset}_{line}_{column}"); var snippet = SnippetParser.Parse(languageService, 8213, 101, 32, "${type=int} ${ClassName}::get_${property=Property}()\n{\n\treturn ${ToFieldName(property)};\n}\n\nvoid ${ClassName}::set_${property}(${type} value)\n{\t${ToFieldName(property)} = value;${Caret}\n}"); Assert.Equal(18, snippet.Elements.Count); AssertSnippetTextElement <SnippetReplaceableTextElement>(snippet.Elements[0], "int"); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[1], " "); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[2], "Ls_ClassName8213_101_32"); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[3], "::get_"); AssertSnippetTextElement <SnippetReplaceableTextElement>(snippet.Elements[4], "Property"); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[5], "()\n{\n\treturn "); AssertSnippetTextElement <SnippetReplaceableTextElement>(snippet.Elements[6], "_ToFieldName"); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[7], ";\n}\n\nvoid "); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[8], "Ls_ClassName8213_101_32"); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[9], "::set_"); AssertBoundSnippetElement(snippet.Elements[10], snippet.Elements[4]); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[11], "("); AssertBoundSnippetElement(snippet.Elements[12], snippet.Elements[0]); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[13], " value)\n{\t"); AssertBoundSnippetElement(snippet.Elements[14], snippet.Elements[6]); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[15], " = value;"); Assert.IsType <SnippetCaretElement>(snippet.Elements[16]); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[17], "\n}"); }
public void SimpleXmlDocument() { SnippetParser parser = new SnippetParser(SupportedLanguage.VBNet); INode node = parser.Parse("Dim doc = <test><%= test %></test>"); Assert.IsTrue(parser.Errors.Count == 0); }
void VB2CS(string input, string expectedOutput) { SnippetParser parser = new SnippetParser(SupportedLanguage.VBNet); INode node = parser.Parse(input); // parser.Errors.ErrorOutput contains syntax errors, if any Assert.IsNotNull(node); Assert.AreEqual("", parser.Errors.ErrorOutput); // parser.Specials is the list of comments, preprocessor directives etc. PreprocessingDirective.VBToCSharp(parser.Specials); // Convert VB.NET constructs to C#: node.AcceptVisitor(new VBNetConstructsConvertVisitor(), null); node.AcceptVisitor(new ToCSharpConvertVisitor(), null); CSharpOutputVisitor output = new CSharpOutputVisitor(); using (SpecialNodesInserter.Install(parser.Specials, output)) { node.AcceptVisitor(output, null); } // output.Errors.ErrorOutput contains conversion errors/warnings, if any // output.Text contains the converted code Assert.AreEqual("", output.Errors.ErrorOutput); Assert.AreEqual(expectedOutput, output.Text); }
public static string ast_CSharp_CreateCompilableClass(this string codeSnippet) { var snippetParser = new SnippetParser(SupportedLanguage.CSharp); var iNode = snippetParser.Parse(codeSnippet); return(iNode.cast <BlockStatement>() .ast_CSharp_CreateCompilableClass(snippetParser, codeSnippet)); }
public static string errors(this SnippetParser snippetParser) { if (snippetParser.Errors.Count > 0) { return(snippetParser.Errors.ErrorOutput); } return(""); }
public void InvalidExpressionSyntax() { // SD2-1584: ensure we don't crash on this invalid VB code SnippetParser parser = new SnippetParser(SupportedLanguage.VBNet); INode node = parser.Parse("i == 5"); Assert.IsTrue(parser.Errors.Count > 0); }
public static INode snippetParser_Parse(this string code) { if (code.notValid()) { return(null); } var snippetParser = new SnippetParser(SupportedLanguage.CSharp); return(snippetParser.Parse(code)); }
public static string ConvertVBNET2CS(string vbcode) { var snippetParser = new SnippetParser(SupportedLanguage.VBNet); var node = snippetParser.Parse(vbcode); node.AcceptVisitor(new ToVBNetConvertVisitor(), null); var csharpOutputVisitor = new CSharpOutputVisitor(); using (SpecialNodesInserter.Install(snippetParser.Specials, csharpOutputVisitor)) node.AcceptVisitor(csharpOutputVisitor, null); return(csharpOutputVisitor.Text); }
public static string ConvertCS2VBNET(string cscode) { var snippetParser = new SnippetParser(SupportedLanguage.CSharp); var node = snippetParser.Parse(cscode); node.AcceptVisitor(new ToVBNetConvertVisitor(), null); var netOutputVisitor = new VBNetOutputVisitor(); using (SpecialNodesInserter.Install(snippetParser.Specials, netOutputVisitor)) node.AcceptVisitor(netOutputVisitor, null); return(netOutputVisitor.Text); }
public static INode Parse(string code, SupportedLanguage language) { SnippetParser parser = new SnippetParser(language); INode astRoot = parser.Parse(code); if (parser.Errors.Count > 0) { throw new GetValueException(parser.Errors.ErrorOutput); } if (parser.SnippetType != SnippetType.Expression && parser.SnippetType != SnippetType.Statements) { throw new GetValueException("Code must be expression or statement"); } return astRoot; }
public void Snippet_FallBack_When_LanguageService_Contains_Variable_But_Reports_Null() { var languageService = new TestLanguageService(); languageService.SnippetCodeGenerators.Add("ToFieldName", (propertyName) => { if (string.IsNullOrEmpty(propertyName)) { return(propertyName); } string newName = Char.ToLower(propertyName[0]) + propertyName.Substring(1); if (newName == propertyName) { return("_" + newName); } else { return(newName); } }); languageService.SnippetDynamicVariables.Add("ClassName", (offset, line, column) => null); var snippet = SnippetParser.Parse(languageService, 1, 1, 1, "${type=int} ${ClassName}::get_${property=Property}()\n{\n\treturn ${ToFieldName(property)};\n}\n\nvoid ${ClassName}::set_${property}(${type} value)\n{\t${ToFieldName(property)} = value;${Caret}\n}"); Assert.Equal(18, snippet.Elements.Count); AssertSnippetTextElement <SnippetReplaceableTextElement>(snippet.Elements[0], "int"); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[1], " "); AssertSnippetTextElement <SnippetReplaceableTextElement>(snippet.Elements[2], "ClassName"); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[3], "::get_"); AssertSnippetTextElement <SnippetReplaceableTextElement>(snippet.Elements[4], "Property"); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[5], "()\n{\n\treturn "); AssertFunctionBoundSnippetElement(snippet.Elements[6], snippet.Elements[4], "PropertyName", "propertyName"); AssertFunctionBoundSnippetElement(snippet.Elements[6], snippet.Elements[4], "propertyName", "_propertyName"); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[7], ";\n}\n\nvoid "); AssertBoundSnippetElement(snippet.Elements[8], snippet.Elements[2]); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[9], "::set_"); AssertBoundSnippetElement(snippet.Elements[10], snippet.Elements[4]); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[11], "("); AssertBoundSnippetElement(snippet.Elements[12], snippet.Elements[0]); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[13], " value)\n{\t"); AssertFunctionBoundSnippetElement(snippet.Elements[14], snippet.Elements[4], "PropertyName", "propertyName"); AssertFunctionBoundSnippetElement(snippet.Elements[14], snippet.Elements[4], "propertyName", "_propertyName"); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[15], " = value;"); Assert.IsType <SnippetCaretElement>(snippet.Elements[16]); AssertSnippetTextElement <SnippetTextElement>(snippet.Elements[17], "\n}"); }
/// <returns> Returned value or null for statements </returns> public static Value Evaluate(string code, SupportedLanguage language, StackFrame context) { SnippetParser parser = new SnippetParser(language); INode astRoot = parser.Parse(code); if (parser.SnippetType == SnippetType.Expression || parser.SnippetType == SnippetType.Statements) { if (parser.Errors.Count > 0) { throw new GetValueException(parser.Errors.ErrorOutput); } try { EvaluateAstVisitor visitor = new EvaluateAstVisitor(context); return(astRoot.AcceptVisitor(visitor, null) as Value); } catch (NotImplementedException e) { throw new GetValueException("Language feature not implemented: " + e.Message); } } throw new GetValueException("Code must be expression or statement"); }
public CodeEditor() : base(new TextArea(), null) { TextArea.IndentationStrategy = null; _shell = IoC.Get <IShell>(); _snippetManager = IoC.Get <SnippetManager>(); _lineNumberMargin = new LineNumberMargin(this); _breakpointMargin = new BreakPointMargin(this, IoC.Get <IDebugManager2>()?.Breakpoints); _selectedLineBackgroundRenderer = new SelectedLineBackgroundRenderer(this); _bracketMatchingBackgroundRenderer = new BracketMatchingBackgroundRenderer(this); _selectedWordBackgroundRenderer = new SelectedWordBackgroundRenderer(); _columnLimitBackgroundRenderer = new ColumnLimitBackgroundRenderer(); _selectedDebugLineBackgroundRenderer = new SelectedDebugLineBackgroundRenderer(); TextArea.TextView.Margin = new Thickness(10, 0, 0, 0); TextArea.TextView.BackgroundRenderers.Add(_selectedDebugLineBackgroundRenderer); TextArea.TextView.LineTransformers.Add(_selectedDebugLineBackgroundRenderer); TextArea.TextView.BackgroundRenderers.Add(_bracketMatchingBackgroundRenderer); TextArea.SelectionBrush = Brush.Parse("#AA569CD6"); TextArea.SelectionCornerRadius = 0; void tunneledKeyUpHandler(object send, KeyEventArgs ee) { if (CaretOffset > 0) { _intellisenseManager?.OnKeyUp(ee, CaretOffset, TextArea.Caret.Line, TextArea.Caret.Column); } } void tunneledKeyDownHandler(object send, KeyEventArgs ee) { if (CaretOffset > 0) { _intellisenseManager?.OnKeyDown(ee, CaretOffset, TextArea.Caret.Line, TextArea.Caret.Column); if (ee.Key == Key.Tab && _currentSnippetContext == null && Editor is ICodeEditor codeEditor && codeEditor.LanguageService != null) { var wordStart = Document.FindPrevWordStart(CaretOffset); if (wordStart > 0) { string word = Document.GetText(wordStart, CaretOffset - wordStart); var codeSnippet = _snippetManager.GetSnippet(codeEditor.LanguageService, Editor.SourceFile.Project?.Solution, Editor.SourceFile.Project, word); if (codeSnippet != null) { var snippet = SnippetParser.Parse(codeEditor.LanguageService, CaretOffset, TextArea.Caret.Line, TextArea.Caret.Column, codeSnippet.Snippet); _intellisenseManager.CloseIntellisense(); using (Document.RunUpdate()) { Document.Remove(wordStart, CaretOffset - wordStart); _intellisenseManager.IncludeSnippets = false; _currentSnippetContext = snippet.Insert(TextArea); } if (_currentSnippetContext.ActiveElements.Count() > 0) { IDisposable disposable = null; disposable = Observable.FromEventPattern <SnippetEventArgs>(_currentSnippetContext, nameof(_currentSnippetContext.Deactivated)).Take(1).Subscribe(o => { _currentSnippetContext = null; _intellisenseManager.IncludeSnippets = true; disposable.Dispose(); }); } else { _currentSnippetContext = null; _intellisenseManager.IncludeSnippets = true; } } } } } } _disposables = new CompositeDisposable { this.GetObservable(LineNumbersVisibleProperty).Subscribe(s => { if (s) { TextArea.LeftMargins.Add(_lineNumberMargin); } else { TextArea.LeftMargins.Remove(_lineNumberMargin); } }), this.GetObservable(ShowBreakpointsProperty).Subscribe(s => { if (s) { TextArea.LeftMargins.Insert(0, _breakpointMargin); } else { TextArea.LeftMargins.Remove(_breakpointMargin); } }), this.GetObservable(HighlightSelectedWordProperty).Subscribe(s => { if (s) { TextArea.TextView.BackgroundRenderers.Add(_selectedWordBackgroundRenderer); } else { TextArea.TextView.BackgroundRenderers.Remove(_selectedWordBackgroundRenderer); } }), this.GetObservable(HighlightSelectedLineProperty).Subscribe(s => { if (s) { TextArea.TextView.BackgroundRenderers.Insert(0, _selectedLineBackgroundRenderer); } else { TextArea.TextView.BackgroundRenderers.Remove(_selectedLineBackgroundRenderer); } }), this.GetObservable(ShowColumnLimitProperty).Subscribe(s => { if (s) { TextArea.TextView.BackgroundRenderers.Add(_columnLimitBackgroundRenderer); } else { TextArea.TextView.BackgroundRenderers.Remove(_columnLimitBackgroundRenderer); } }), this.GetObservable(ColumnLimitProperty).Subscribe(limit => { _columnLimitBackgroundRenderer.Column = limit; this.TextArea.TextView.InvalidateLayer(KnownLayer.Background); }), this.GetObservable(ContextActionsIconProperty).Subscribe(icon => { if (_contextActionsRenderer != null) { _contextActionsRenderer.IconImage = icon; } }), this.GetObservable(ColorSchemeProperty).Subscribe(colorScheme => { if (colorScheme != null) { Background = colorScheme.Background; Foreground = colorScheme.Text; _lineNumberMargin.Background = colorScheme.Background; if (_diagnosticMarkersRenderer != null) { _diagnosticMarkersRenderer.ColorScheme = colorScheme; } _textColorizer?.RecalculateBrushes(); TextArea.TextView.InvalidateLayer(KnownLayer.Background); TextArea.TextView.Redraw(); } }), this.GetObservable(EditorCaretOffsetProperty).Subscribe(s => { if (Document?.TextLength >= s) { CaretOffset = s; TextArea.Caret.BringCaretToView(); } }), BackgroundRenderersProperty.Changed.Subscribe(s => { if (s.Sender == this) { if (s.OldValue != null) { foreach (var renderer in (ObservableCollection <IBackgroundRenderer>)s.OldValue) { TextArea.TextView.BackgroundRenderers.Remove(renderer); } } if (s.NewValue != null) { foreach (var renderer in (ObservableCollection <IBackgroundRenderer>)s.NewValue) { TextArea.TextView.BackgroundRenderers.Add(renderer); } } } }), DocumentLineTransformersProperty.Changed.Subscribe(s => { if (s.Sender == this) { if (s.OldValue != null) { foreach (var renderer in (ObservableCollection <IVisualLineTransformer>)s.OldValue) { TextArea.TextView.LineTransformers.Remove(renderer); } } if (s.NewValue != null) { foreach (var renderer in (ObservableCollection <IVisualLineTransformer>)s.NewValue) { TextArea.TextView.LineTransformers.Add(renderer); } } } }), Observable.FromEventPattern(TextArea.Caret, nameof(TextArea.Caret.PositionChanged)).Subscribe(e => { if (_isLoaded && Document != null) { _lastLine = TextArea.Caret.Line; Line = TextArea.Caret.Line; Column = TextArea.Caret.Column; EditorCaretOffset = TextArea.Caret.Offset; var location = new TextViewPosition(Document.GetLocation(CaretOffset)); var visualLocation = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineBottom); var visualLocationTop = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineTop); var position = visualLocation - TextArea.TextView.ScrollOffset; position = position.Transform(TextArea.TextView.TransformToVisual(TextArea).Value); _intellisenseControl.SetLocation(position); } }), Observable.FromEventPattern(TextArea.Caret, nameof(TextArea.Caret.PositionChanged)).Throttle(TimeSpan.FromMilliseconds(100)).ObserveOn(AvaloniaScheduler.Instance).Subscribe(e => { if (Document != null) { var location = new TextViewPosition(Document.GetLocation(CaretOffset)); if (_intellisenseManager != null && !_textEntering) { if (TextArea.Selection.IsEmpty) { _intellisenseManager.SetCursor(CaretOffset, location.Line, location.Column, UnsavedFiles.ToList()); } else if (_currentSnippetContext != null) { var offset = Document.GetOffset(TextArea.Selection.StartPosition.Location); _intellisenseManager.SetCursor(offset, TextArea.Selection.StartPosition.Line, TextArea.Selection.StartPosition.Column, UnsavedFiles.ToList()); } } _selectedWordBackgroundRenderer.SelectedWord = GetWordAtOffset(CaretOffset); TextArea.TextView.InvalidateLayer(KnownLayer.Background); } }), this.WhenAnyValue(x => x.DebugHighlight).Where(loc => loc != null).Subscribe(location => { if (location.Line != -1) { SetDebugHighlight(location.Line, location.StartColumn, location.EndColumn); } else { ClearDebugHighlight(); } }), this.GetObservable(EditorProperty).Subscribe(editor => { if (editor != null) { if (editor.SourceFile.Project?.Solution != null) { _snippetManager.InitialiseSnippetsForSolution(editor.SourceFile.Project.Solution); } if (editor.SourceFile.Project != null) { _snippetManager.InitialiseSnippetsForProject(editor.SourceFile.Project); } SyntaxHighlighting = CustomHighlightingManager.Instance.GetDefinition(editor.SourceFile.ContentType); if (editor.Document is AvalonStudioTextDocument td && Document != td.Document) { Document = td.Document; if (editor.Offset <= Document.TextLength) { CaretOffset = editor.Offset; } _textColorizer = new TextColoringTransformer(Document); _scopeLineBackgroundRenderer = new ScopeLineBackgroundRenderer(Document); TextArea.TextView.BackgroundRenderers.Add(_scopeLineBackgroundRenderer); TextArea.TextView.LineTransformers.Insert(0, _textColorizer); _diagnosticMarkersRenderer = new TextMarkerService(Document); _contextActionsRenderer = new ContextActionsRenderer(this, _diagnosticMarkersRenderer); TextArea.LeftMargins.Add(_contextActionsRenderer); TextArea.TextView.BackgroundRenderers.Add(_diagnosticMarkersRenderer); } if (editor is ICodeEditor codeEditor) { if (codeEditor.Highlights != null) { _disposables.Add( Observable.FromEventPattern <NotifyCollectionChangedEventArgs>(codeEditor.Highlights, nameof(codeEditor.Highlights.CollectionChanged)) .Subscribe(observer => { var e = observer.EventArgs; switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (var(tag, highlightList) in e.NewItems.Cast <(object tag, SyntaxHighlightDataList highlightList)>()) { _textColorizer.SetTransformations(tag, highlightList); } break; case NotifyCollectionChangedAction.Remove: foreach (var(tag, highlightList) in e.OldItems.Cast <(object tag, SyntaxHighlightDataList highlightList)>()) { _textColorizer.RemoveAll(i => i.Tag == tag); } break; case NotifyCollectionChangedAction.Reset: foreach (var(tag, highlightList) in e.OldItems.Cast <(object tag, SyntaxHighlightDataList highlightList)>()) { _textColorizer.RemoveAll(i => true); } break; default: throw new NotSupportedException(); } TextArea.TextView.Redraw(); })); _disposables.Add( Observable.FromEventPattern <NotifyCollectionChangedEventArgs>(codeEditor.Diagnostics, nameof(codeEditor.Diagnostics.CollectionChanged)) .Subscribe(observer => { var e = observer.EventArgs; switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (var(tag, diagnostics) in e.NewItems.Cast <(object tag, IEnumerable <Diagnostic> diagnostics)>()) { _diagnosticMarkersRenderer.SetDiagnostics(tag, diagnostics); } break; case NotifyCollectionChangedAction.Remove: foreach (var(tag, diagnostics) in e.OldItems.Cast <(object tag, IEnumerable <Diagnostic> diagnostics)>()) { _diagnosticMarkersRenderer.RemoveAll(x => x.Tag == tag); } break; case NotifyCollectionChangedAction.Reset: foreach (var(tag, diagnostics) in e.OldItems.Cast <(object tag, IEnumerable <Diagnostic> diagnostics)>()) { _diagnosticMarkersRenderer.RemoveAll(i => true); } break; default: throw new NotSupportedException(); } TextArea.TextView.Redraw(); _contextActionsRenderer.OnDiagnosticsUpdated(); })); _disposables.Add(codeEditor.WhenAnyValue(x => x.CodeIndex).Subscribe(codeIndex => { _scopeLineBackgroundRenderer.ApplyIndex(codeIndex); })); _scopeLineBackgroundRenderer.ApplyIndex(codeEditor.CodeIndex); foreach (var(tag, diagnostics) in codeEditor.Diagnostics) { _diagnosticMarkersRenderer.SetDiagnostics(tag, diagnostics); } foreach (var(tag, highlights) in codeEditor.Highlights) { _textColorizer.SetTransformations(tag, highlights); } TextArea.TextView.Redraw(); } _intellisenseManager = new IntellisenseManager(editor, Intellisense, _completionAssistant, codeEditor.LanguageService, editor.SourceFile, offset => { var location = new TextViewPosition(Document.GetLocation(offset)); var visualLocation = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineBottom); var visualLocationTop = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineTop); var position = visualLocation - TextArea.TextView.ScrollOffset; position = position.Transform(TextArea.TextView.TransformToVisual(TextArea).Value); _completionAssistantControl.SetLocation(position); }); _disposables.Add(_intellisenseManager); foreach (var contextActionProvider in codeEditor.LanguageService.GetContextActionProviders()) { _contextActionsRenderer.Providers.Add(contextActionProvider); } } Dispatcher.UIThread.Post(() => { TextArea.ScrollToLine(Line); Focus(); }); } else { if (Document != null) { Document = null; } } }), this.GetObservable(RenameOpenProperty).Subscribe(open => { if (_isLoaded && Editor != null) { var token = Editor.Document.GetToken(CaretOffset); var location = new TextViewPosition(Document.GetLocation(token.Offset)); var visualLocation = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineBottom); var visualLocationTop = TextArea.TextView.GetVisualPosition(location, VisualYPosition.LineTop); var position = visualLocation - TextArea.TextView.ScrollOffset; position = position.Transform(TextArea.TextView.TransformToVisual(TextArea).Value); _renameControl.SetLocation(position); _renameControl.Open(this, Editor.Document.GetText(token)); } }), AddHandler(KeyDownEvent, tunneledKeyDownHandler, RoutingStrategies.Tunnel), AddHandler(KeyUpEvent, tunneledKeyUpHandler, RoutingStrategies.Tunnel) }; Options = new AvaloniaEdit.TextEditorOptions { ConvertTabsToSpaces = true, IndentationSize = 4, EnableHyperlinks = false, EnableEmailHyperlinks = false, }; //BackgroundRenderersProperty.Changed.Subscribe(s => //{ // if (s.Sender == this) // { // if (s.OldValue != null) // { // foreach (var renderer in (ObservableCollection<IBackgroundRenderer>)s.OldValue) // { // TextArea.TextView.BackgroundRenderers.Remove(renderer); // } // } // if (s.NewValue != null) // { // foreach (var renderer in (ObservableCollection<IBackgroundRenderer>)s.NewValue) // { // TextArea.TextView.BackgroundRenderers.Add(renderer); // } // } // } //}); //DocumentLineTransformersProperty.Changed.Subscribe(s => //{ // if (s.Sender == this) // { // if (s.OldValue != null) // { // foreach (var renderer in (ObservableCollection<IVisualLineTransformer>)s.OldValue) // { // TextArea.TextView.LineTransformers.Remove(renderer); // } // } // if (s.NewValue != null) // { // foreach (var renderer in (ObservableCollection<IVisualLineTransformer>)s.NewValue) // { // TextArea.TextView.LineTransformers.Add(renderer); // } // } // } //}); /*_analysisTriggerEvents.Select(_ => Observable.Timer(TimeSpan.FromMilliseconds(300)).ObserveOn(AvaloniaScheduler.Instance) * .SelectMany(o => DoCodeAnalysisAsync())).Switch().Subscribe(_ => { });*/ Intellisense = new IntellisenseViewModel(); _completionAssistant = new CompletionAssistantViewModel(Intellisense); TextArea.TextEntering += TextArea_TextEntering; TextArea.TextEntered += TextArea_TextEntered; } ~CodeEditor() { }
public static string ast_CSharp_CreateCompilableClass(this BlockStatement blockStatement, SnippetParser snippetParser, string codeSnippet, CSharp_FastCompiler_CompilerOptions compilerOptions, CSharp_FastCompiler_CompilerArtifacts compilerArtifacts, CSharp_FastCompiler_ExecutionOptions executionOptions) { if (blockStatement.isNull() || compilerOptions.isNull()) { return(null); } var compilationUnit = compilerArtifacts.CompilationUnit = new CompilationUnit(); compilationUnit.add_Type(compilerOptions.default_TypeName) .add_Method(compilerOptions.default_MethodName, executionOptions.InvocationParameters, compilerOptions.ResolveInvocationParametersType, blockStatement); // remove comments from parsed code var astCSharp = compilerArtifacts.AstCSharp = new Ast_CSharp(compilerArtifacts.CompilationUnit, snippetParser.Specials); // add references included in the original source code file compilerArtifacts.AstCSharp.mapCodeO2References(compilerOptions); astCSharp.mapAstDetails(); astCSharp.ExtraSpecials.Clear(); var method = compilationUnit.method(compilerOptions.default_MethodName); var returntype = method.returnType(); var type = compilationUnit.type(compilerOptions.default_TypeName); type.Children.Clear(); var tempBlockStatement = new BlockStatement(); tempBlockStatement.add_Variable("a", 0); method.Body = tempBlockStatement; var newMethod = type.add_Method(compilerOptions.default_MethodName, executionOptions.InvocationParameters, compilerOptions.ResolveInvocationParametersType, tempBlockStatement); newMethod.TypeReference = returntype; if (blockStatement.returnStatements().size() > 1) { astCSharp.methodDeclarations().first().remove_LastReturnStatement(); } astCSharp.mapAstDetails(); var codeToReplace = "Int32 a = 0;"; var csharpCode = astCSharp.AstDetails.CSharpCode .replace("\t\t{0}".format(codeToReplace), codeToReplace) // remove tabs .replace("Int32 a = 0;", codeSnippet); // put the actual code (this should be done via AST, but it was affectting code complete) return(csharpCode); }
//this code needs to be completely rewritten public string tryToCreateCSharpCodeWith_Class_Method_WithMethodText(string code) { if (code.empty()) { return(null); } code = code.line(); // make sure there is an empty line at the end try { //handle special incudes in source code var lines = code.fix_CRLF().lines(); foreach (var originalLine in lines) { string line = originalLine; originalLine.starts("//O2Include:", (includeText) => { var file = includeText; var baseFile = SourceCodeFile ?? PublicDI.CurrentScript; var parentFolder = baseFile.parentFolder(); if (parentFolder.notValid()) { "[CSharpFastCompiled] in O2Include mapping, could not get parent folder of current script".error(); } var resolvedFile = CompileEngine.findFileOnLocalScriptFolder(file, parentFolder); if (resolvedFile.fileExists()) { var fileContents = resolvedFile.contents(); code = code.Replace(line, line.line().add(fileContents).line()); } else { "[CSharpFastCompiled] in O2Include mapping, could not a mapping for: {0}".error(includeText); } }); } var snippetParser = new SnippetParser(SupportedLanguage.CSharp); var parsedCode = snippetParser.Parse(code); AstErrors = snippetParser.errors(); CompilationUnit = new CompilationUnit(); if (parsedCode is BlockStatement || parsedCode is CompilationUnit) { Ast_CSharp astCSharp; if (parsedCode is BlockStatement) { // map parsedCode into a new type and method var blockStatement = (BlockStatement)parsedCode; CompilationUnit.add_Type(default_TypeName) .add_Method(default_MethodName, InvocationParameters, this.ResolveInvocationParametersType, blockStatement); // remove comments from parsed code astCSharp = new Ast_CSharp(CompilationUnit, snippetParser.Specials); // add references included in the original source code file mapCodeO2References(astCSharp); astCSharp.mapAstDetails(); astCSharp.ExtraSpecials.Clear(); var method = CompilationUnit.method(default_MethodName); var returntype = method.returnType(); var type = CompilationUnit.type(default_TypeName); type.Children.Clear(); var tempBlockStatement = new BlockStatement(); tempBlockStatement.add_Variable("a", 0); method.Body = tempBlockStatement; var newMethod = type.add_Method(default_MethodName, InvocationParameters, this.ResolveInvocationParametersType, tempBlockStatement); newMethod.TypeReference = returntype; astCSharp.mapAstDetails(); var csharpCode = astCSharp.AstDetails.CSharpCode .replace("Int32 a = 0;", code); AstDetails = new Ast_CSharp(csharpCode).AstDetails; CreatedFromSnipptet = true; DebugMode.ifDebug("Ast parsing was OK"); SourceCode = csharpCode; onAstOK.invoke(); return(csharpCode); } CompilationUnit = (CompilationUnit)parsedCode; if (CompilationUnit.Children.Count == 0) { return(null); } astCSharp = new Ast_CSharp(CompilationUnit, snippetParser.Specials); // add the comments from the original code mapCodeO2References(astCSharp); CreatedFromSnipptet = false; // create sourceCode using Ast_CSharp & AstDetails if (CompilationUnit.Children.Count > 0) { // reset the astCSharp.AstDetails object astCSharp.mapAstDetails(); // add the comments from the original code astCSharp.ExtraSpecials.AddRange(snippetParser.Specials); SourceCode = astCSharp.AstDetails.CSharpCode; //once we have the created SourceCode we need to create a new AST with it var tempAstDetails = new Ast_CSharp(SourceCode).AstDetails; //note we should try to add back the specials here (so that comments make it to the generated code AstDetails = tempAstDetails; DebugMode.ifDebug("Ast parsing was OK"); onAstOK.invoke(); return(SourceCode); } } } catch (Exception ex) { DebugMode.ifError("in createCSharpCodeWith_Class_Method_WithMethodText:{0}", ex.Message); } return(null); }
/// /// <summary> /// Returns a compilable C# file from and Snippet /// /// Dev Note:this code needs to be refactored (since it is too big and complex) /// </summary> /// <param name="code"></param> /// <returns></returns> public string tryToCreateCSharpCodeWith_Class_Method_WithMethodText(string code) { if (code.empty()) { return(null); } code = code.line(); // make sure there is an empty line at the end try { //handle special incudes in source code var lines = code.fix_CRLF().lines(); foreach (var originalLine in lines) { var line = originalLine; if (originalLine.starts("//O2Include:")) { var includeText = line.subString_After("//O2Include:"); var file = includeText; var baseFile = CompilerOptions.SourceCodeFile ?? PublicDI.CurrentScript; var parentFolder = baseFile.parentFolder(); if (parentFolder.notValid()) { "[CSharpFastCompiled] in O2Include mapping, could not get parent folder of current script".error(); } var resolvedFile = CompileEngine.findFileOnLocalScriptFolder(file, parentFolder); if (resolvedFile.fileExists()) { var fileContents = resolvedFile.contents(); code = code.Replace(line, line.line().add(fileContents).line()); } else { "[CSharpFastCompiled] in O2Include mapping, could not a mapping for: {0}".error(includeText); } } ; } var snippetParser = new SnippetParser(SupportedLanguage.CSharp); var parsedCode = snippetParser.Parse(code); this.astErrors(snippetParser.errors()); this.compilationUnit(new CompilationUnit()); if (parsedCode is BlockStatement || parsedCode is CompilationUnit) { Ast_CSharp astCSharp; if (parsedCode is BlockStatement) { // map parsedCode into a new type and method var blockStatement = (BlockStatement)parsedCode; var csharpCode = blockStatement.ast_CSharp_CreateCompilableClass(snippetParser, code, CompilerOptions, CompilerArtifacts, ExecutionOptions); this.astDetails(new Ast_CSharp(csharpCode).AstDetails); this.createdFromSnippet(true); DebugMode.ifDebug("Ast parsing was OK"); this.sourceCode(csharpCode); this.raise_OnAstOK(); return(csharpCode); } this.compilationUnit((CompilationUnit)parsedCode); if (this.compilationUnit().Children.Count == 0) { return(null); } astCSharp = new Ast_CSharp(this.compilationUnit(), snippetParser.Specials); // add the comments from the original code astCSharp.mapCodeO2References(CompilerOptions); this.createdFromSnippet(false); // create sourceCode using Ast_CSharp & AstDetails if (this.compilationUnit().Children.Count > 0) { // reset the astCSharp.AstDetails object astCSharp.mapAstDetails(); // add the comments from the original code astCSharp.ExtraSpecials.AddRange(snippetParser.Specials); this.sourceCode(astCSharp.AstDetails.CSharpCode); //once we have the created SourceCode we need to create a new AST with it var tempAstDetails = new Ast_CSharp(this.sourceCode()).AstDetails; //note we should try to add back the specials here (so that comments make it to the generated code this.astDetails(tempAstDetails); DebugMode.ifDebug("Ast parsing was OK"); this.raise_OnAstOK(); return(this.sourceCode()); } } } catch (Exception ex) { DebugMode.ifError("in createCSharpCodeWith_Class_Method_WithMethodText:{0}", ex.Message); } return(null); }
public virtual CompilerResults CompileModuleFromDomBatch(CompilerParameters options, CodeCompileUnit[] compilationUnits, ErrorNodeList errorNodes){ if (options == null){Debug.Assert(false); return null;} int n = compilationUnits == null ? 0 : compilationUnits.Length; if (options.OutputAssembly == null || options.OutputAssembly.Length == 0){ for (int i = 0; i < n; i++){ CodeSnippetCompileUnit csu = compilationUnits[i] as CodeSnippetCompileUnit; if (csu == null || csu.LinePragma == null || csu.LinePragma.FileName == null) continue; this.SetOutputFileName(options, csu.LinePragma.FileName); break; } } CompilerResults results = new CompilerResults(options.TempFiles); Module module = this.CreateModule(options, errorNodes); Compilation compilation = this.CreateCompilation(module, new CompilationUnitList(n), options, this.GetGlobalScope(module)); CodeDomTranslator cdt = new CodeDomTranslator(); SnippetParser sp = new SnippetParser(this, module, errorNodes, options); for (int i = 0; i < n; i++){ CompilationUnit cu = cdt.Translate(this, compilationUnits[i], module, errorNodes); sp.Visit(cu); compilation.CompilationUnits.Add(cu); cu.Compilation = compilation; } this.CompileParseTree(compilation, errorNodes); this.ProcessErrors(options, results, errorNodes); this.SaveCompilation(compilation, module, options, results); return results; }
public virtual CompilerResults CompileModuleFromFileBatch(CompilerParameters options, string[] fileNames, ErrorNodeList errorNodes, bool canUseMemoryMap){ if (options == null){Debug.Assert(false); return null;} int n = fileNames.Length; if (options.OutputAssembly == null || options.OutputAssembly.Length == 0){ for (int i = 0; i < n; i++){ if (fileNames[i] == null) continue; this.SetOutputFileName(options, fileNames[i]); break; } } CompilerResults results = new CompilerResults(options.TempFiles); Module module = this.CreateModule(options, errorNodes); Compilation compilation = this.CreateCompilation(module, new CompilationUnitList(n), options, this.GetGlobalScope(module)); SnippetParser sp = new SnippetParser(this, module, errorNodes, options); for (int i = 0; i < n; i++){ string fileName = fileNames[i]; if (fileName == null) continue; DocumentText text = this.CreateDocumentText(fileName, results, options, errorNodes, canUseMemoryMap); CompilationUnitSnippet cu = this.CreateCompilationUnitSnippet(fileName, 1, text, compilation); sp.Visit(cu); compilation.CompilationUnits.Add(cu); cu.Compilation = compilation; } this.CompileParseTree(compilation, errorNodes); this.ProcessErrors(options, results, errorNodes); this.SaveCompilation(compilation, module, options, results); return results; }
public string tryToCreateCSharpCodeWith_Class_Method_WithMethodText(string code) { if (code.empty()) { return(null); } code = code.line(); // make sure there is an empty line at the end try { // handle special incudes in source code foreach (var originalLine in code.lines()) { originalLine.starts("//include", (includeText) => { if (includeText.fileExists()) { code = code.Replace(originalLine, originalLine.line().add(includeText.contents())); } }); } var snippetParser = new SnippetParser(SupportedLanguage.CSharp); var parsedCode = snippetParser.Parse(code); AstErrors = snippetParser.errors(); CompilationUnit = new CompilationUnit(); if (parsedCode is BlockStatement || parsedCode is CompilationUnit) { Ast_CSharp astCSharp; if (parsedCode is BlockStatement) { // map parsedCode into a new type and method var blockStatement = (BlockStatement)parsedCode; CompilationUnit.add_Type(default_TypeName) .add_Method(default_MethodName, InvocationParameters, blockStatement); astCSharp = new Ast_CSharp(CompilationUnit, snippetParser.Specials); //astCSharp.AstDetails.mapSpecials(); // add references included in the original source code file mapCodeO2References(astCSharp); CreatedFromSnipptet = true; } else { CompilationUnit = (CompilationUnit)parsedCode; if (CompilationUnit.Children.Count == 0) { return(null); } astCSharp = new Ast_CSharp(CompilationUnit, snippetParser.Specials); // add the comments from the original code mapCodeO2References(astCSharp); CreatedFromSnipptet = false; } // create sourceCode using Ast_CSharp & AstDetails if (CompilationUnit.Children.Count > 0) { // reset the astCSharp.AstDetails object astCSharp.mapAstDetails(); // add the comments from the original code astCSharp.ExtraSpecials.AddRange(snippetParser.Specials); SourceCode = astCSharp.AstDetails.CSharpCode; //once we have the created SourceCode we need to create a new AST with it var tempAstDetails = new Ast_CSharp(SourceCode).AstDetails; //note we should try to add back the specials here (so that comments make it to the generated code AstDetails = tempAstDetails; DebugMode.ifDebug("Ast parsing was OK"); this.invoke(onAstOK); return(SourceCode); } } } catch (Exception ex) { DebugMode.ifError("in createCSharpCodeWith_Class_Method_WithMethodText:{0}", ex.Message); } return(null); }
public static string ast_CSharp_CreateCompilableClass(this BlockStatement blockStatement, SnippetParser snippetParser, string codeSnippet) { if (blockStatement.isNull() || snippetParser.isNull() || codeSnippet.notValid()) { return(null); } var compilerOptions = new CSharp_FastCompiler_CompilerOptions(); var compilerArtifacts = new CSharp_FastCompiler_CompilerArtifacts(); var executionOptions = new CSharp_FastCompiler_ExecutionOptions(); var csharpCode = blockStatement.ast_CSharp_CreateCompilableClass(snippetParser, codeSnippet, compilerOptions, compilerArtifacts, executionOptions); return(csharpCode); }
INode Parse(SupportedLanguage sourceLanguage, string sourceCode, out string error) { project = new DefaultProjectContent(); project.ReferencedContents.AddRange(ReferencedContents); if (sourceLanguage == SupportedLanguage.VBNet) { project.Language = LanguageProperties.VBNet; project.DefaultImports = new DefaultUsing(project); project.DefaultImports.Usings.AddRange(DefaultImportsToAdd); } else { project.Language = LanguageProperties.CSharp; } SnippetParser parser = new SnippetParser(sourceLanguage); INode result = parser.Parse(sourceCode); error = parser.Errors.ErrorOutput; specials = parser.Specials; if (parser.Errors.Count != 0) { return(null); } wasExpression = parser.SnippetType == SnippetType.Expression; if (wasExpression) { // Special case 'Expression': expressions may be replaced with other statements in the AST by the ConvertVisitor, // but we need to return a 'stable' node so that the correct transformed AST is returned. // Thus, we wrap any expressions into a statement block. result = MakeBlockFromExpression((Expression)result); } // now create a dummy compilation unit around the snippet result switch (parser.SnippetType) { case SnippetType.CompilationUnit: compilationUnit = (CompilationUnit)result; break; case SnippetType.Expression: case SnippetType.Statements: compilationUnit = MakeCompilationUnitFromTypeMembers( MakeMethodFromBlock( (BlockStatement)result )); break; case SnippetType.TypeMembers: compilationUnit = MakeCompilationUnitFromTypeMembers(result.Children); break; default: throw new NotSupportedException("Unknown snippet type: " + parser.SnippetType); } // convert NRefactory CU in DOM CU NRefactoryASTConvertVisitor visitor = new NRefactoryASTConvertVisitor(project); visitor.VisitCompilationUnit(compilationUnit, null); visitor.Cu.FileName = sourceLanguage == SupportedLanguage.CSharp ? "a.cs" : "a.vb"; // and register the compilation unit in the DOM foreach (IClass c in visitor.Cu.Classes) { project.AddClassToNamespaceList(c); } parseInfo = new ParseInformation(); parseInfo.SetCompilationUnit(visitor.Cu); return(result); }
public CodeEditor() { _codeAnalysisRunner = new JobRunner(1); _shell = IoC.Get <IShell>(); _snippetManager = IoC.Get <SnippetManager>(); _lineNumberMargin = new LineNumberMargin(this); _breakpointMargin = new BreakPointMargin(this, IoC.Get <IDebugManager2>().Breakpoints); _selectedLineBackgroundRenderer = new SelectedLineBackgroundRenderer(this); _selectedWordBackgroundRenderer = new SelectedWordBackgroundRenderer(); _columnLimitBackgroundRenderer = new ColumnLimitBackgroundRenderer(); _selectedDebugLineBackgroundRenderer = new SelectedDebugLineBackgroundRenderer(); TextArea.TextView.Margin = new Thickness(10, 0, 0, 0); TextArea.TextView.BackgroundRenderers.Add(_selectedDebugLineBackgroundRenderer); TextArea.TextView.LineTransformers.Add(_selectedDebugLineBackgroundRenderer); TextArea.SelectionBrush = Brush.Parse("#AA569CD6"); TextArea.SelectionCornerRadius = 0; this.GetObservable(LineNumbersVisibleProperty).Subscribe(s => { if (s) { TextArea.LeftMargins.Add(_lineNumberMargin); } else { TextArea.LeftMargins.Remove(_lineNumberMargin); } }); this.GetObservable(ShowBreakpointsProperty).Subscribe(s => { if (s) { TextArea.LeftMargins.Insert(0, _breakpointMargin); } else { TextArea.LeftMargins.Remove(_breakpointMargin); } }); this.GetObservable(HighlightSelectedWordProperty).Subscribe(s => { if (s) { TextArea.TextView.BackgroundRenderers.Add(_selectedWordBackgroundRenderer); } else { TextArea.TextView.BackgroundRenderers.Remove(_selectedWordBackgroundRenderer); } }); this.GetObservable(HighlightSelectedLineProperty).Subscribe(s => { if (s) { TextArea.TextView.BackgroundRenderers.Insert(0, _selectedLineBackgroundRenderer); } else { TextArea.TextView.BackgroundRenderers.Remove(_selectedLineBackgroundRenderer); } }); this.GetObservable(ShowColumnLimitProperty).Subscribe(s => { if (s) { TextArea.TextView.BackgroundRenderers.Add(_columnLimitBackgroundRenderer); } else { TextArea.TextView.BackgroundRenderers.Remove(_columnLimitBackgroundRenderer); } }); Options = new AvaloniaEdit.TextEditorOptions { ConvertTabsToSpaces = true, IndentationSize = 4 }; BackgroundRenderersProperty.Changed.Subscribe(s => { if (s.Sender == this) { if (s.OldValue != null) { foreach (var renderer in (ObservableCollection <IBackgroundRenderer>)s.OldValue) { TextArea.TextView.BackgroundRenderers.Remove(renderer); } } if (s.NewValue != null) { foreach (var renderer in (ObservableCollection <IBackgroundRenderer>)s.NewValue) { TextArea.TextView.BackgroundRenderers.Add(renderer); } } } }); DocumentLineTransformersProperty.Changed.Subscribe(s => { if (s.Sender == this) { if (s.OldValue != null) { foreach (var renderer in (ObservableCollection <IVisualLineTransformer>)s.OldValue) { TextArea.TextView.LineTransformers.Remove(renderer); } } if (s.NewValue != null) { foreach (var renderer in (ObservableCollection <IVisualLineTransformer>)s.NewValue) { TextArea.TextView.LineTransformers.Add(renderer); } } } }); this.GetObservable(CaretOffsetProperty).Subscribe(s => { if (Document?.TextLength > s) { CaretOffset = s; } }); /*_analysisTriggerEvents.Select(_ => Observable.Timer(TimeSpan.FromMilliseconds(300)).ObserveOn(AvaloniaScheduler.Instance) * .SelectMany(o => DoCodeAnalysisAsync())).Switch().Subscribe(_ => { });*/ _analysisTriggerEvents.Throttle(TimeSpan.FromMilliseconds(300)).ObserveOn(AvaloniaScheduler.Instance).Subscribe(async _ => { await DoCodeAnalysisAsync(); }); this.GetObservableWithHistory(SourceFileProperty).Subscribe((file) => { if (file.Item1 != file.Item2) { if (System.IO.File.Exists(file.Item2.Location)) { using (var fs = System.IO.File.OpenText(file.Item2.Location)) { Document = new TextDocument(fs.ReadToEnd()) { FileName = file.Item2.Location }; } } _isLoaded = true; RegisterLanguageService(file.Item2); TextArea.TextView.Redraw(); } }); TextArea.TextEntering += (sender, e) => { _textEntering = true; }; TextArea.Caret.PositionChanged += (sender, e) => { if (_intellisenseManager != null && !_textEntering) { if (TextArea.Selection.IsEmpty) { var location = Document.GetLocation(CaretOffset); _intellisenseManager.SetCursor(CaretOffset, location.Line, location.Column, UnsavedFiles.ToList()); } else { var offset = Document.GetOffset(TextArea.Selection.StartPosition.Location); _intellisenseManager.SetCursor(offset, TextArea.Selection.StartPosition.Line, TextArea.Selection.StartPosition.Column, UnsavedFiles.ToList()); } } if (CaretOffset > 0) { var prevLocation = new TextViewPosition(Document.GetLocation(CaretOffset - 1)); var visualLocation = TextArea.TextView.GetVisualPosition(prevLocation, VisualYPosition.LineBottom); var visualLocationTop = TextArea.TextView.GetVisualPosition(prevLocation, VisualYPosition.LineTop); var position = visualLocation - TextArea.TextView.ScrollOffset; position = position.Transform(TextArea.TextView.TransformToVisual(TextArea).Value); _intellisenseControl.SetLocation(position); _completionAssistantControl.SetLocation(position); _selectedWordBackgroundRenderer.SelectedWord = GetWordAtOffset(CaretOffset); Line = TextArea.Caret.Line; Column = TextArea.Caret.Column; EditorCaretOffset = TextArea.Caret.Offset; } }; TextArea.TextEntered += (sender, e) => { _intellisenseManager?.OnTextInput(e, CaretOffset, TextArea.Caret.Line, TextArea.Caret.Column); _textEntering = false; }; _intellisense = new IntellisenseViewModel(); _completionAssistant = new CompletionAssistantViewModel(_intellisense); EventHandler <KeyEventArgs> tunneledKeyUpHandler = (send, ee) => { if (CaretOffset > 0) { _intellisenseManager?.OnKeyUp(ee, CaretOffset, TextArea.Caret.Line, TextArea.Caret.Column); } }; EventHandler <KeyEventArgs> tunneledKeyDownHandler = (send, ee) => { if (CaretOffset > 0) { _intellisenseManager?.OnKeyDown(ee, CaretOffset, TextArea.Caret.Line, TextArea.Caret.Column); if (ee.Key == Key.Tab && _currentSnippetContext == null && LanguageService != null) { var wordStart = Document.FindPrevWordStart(CaretOffset); if (wordStart > 0) { string word = Document.GetText(wordStart, CaretOffset - wordStart); var codeSnippet = _snippetManager.GetSnippet(LanguageService, SourceFile.Project?.Solution, SourceFile.Project, word); if (codeSnippet != null) { var snippet = SnippetParser.Parse(LanguageService, CaretOffset, TextArea.Caret.Line, TextArea.Caret.Column, codeSnippet.Snippet); _intellisenseManager.CloseIntellisense(); using (Document.RunUpdate()) { Document.Remove(wordStart, CaretOffset - wordStart); _intellisenseManager.IncludeSnippets = false; _currentSnippetContext = snippet.Insert(TextArea); } if (_currentSnippetContext.ActiveElements.Count() > 0) { IDisposable disposable = null; disposable = Observable.FromEventPattern <SnippetEventArgs>(_currentSnippetContext, nameof(_currentSnippetContext.Deactivated)).Take(1).Subscribe(o => { _currentSnippetContext = null; _intellisenseManager.IncludeSnippets = true; disposable.Dispose(); }); } else { _currentSnippetContext = null; _intellisenseManager.IncludeSnippets = true; } } } } } }; EventHandler <TextInputEventArgs> tunneledTextInputHandler = (send, ee) => { if (CaretOffset > 0) { _intellisenseManager?.OnTextInput(ee, CaretOffset, TextArea.Caret.Line, TextArea.Caret.Column); } }; AddHandler(KeyDownEvent, tunneledKeyDownHandler, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, tunneledKeyUpHandler, RoutingStrategies.Tunnel); }
/// <summary> /// Parses string representation of an expression (eg. "a.b[10] + 2") into NRefactory Expression tree. /// </summary> public static Expression ParseExpression(string code, SupportedLanguage language) { SnippetParser parser = new SnippetParser(language); INode astRoot = parser.Parse(code); if (parser.Errors.Count > 0) { throw new GetValueException(parser.Errors.ErrorOutput); } Expression astExpression = astRoot as Expression; if (astExpression == null) { throw new GetValueException("Code must be expression"); } return astExpression; }
INode Parse(SupportedLanguage sourceLanguage, string sourceCode, out string error) { project = new DefaultProjectContent(); project.ReferencedContents.AddRange(ReferencedContents); if (sourceLanguage == SupportedLanguage.VBNet) { project.DefaultImports = new DefaultUsing(project); project.DefaultImports.Usings.AddRange(DefaultImportsToAdd); } SnippetParser parser = new SnippetParser(sourceLanguage); INode result = parser.Parse(sourceCode); error = parser.Errors.ErrorOutput; specials = parser.Specials; if (parser.Errors.Count != 0) { return(null); } // now create a dummy compilation unit around the snippet result switch (parser.SnippetType) { case SnippetType.CompilationUnit: compilationUnit = (CompilationUnit)result; break; case SnippetType.Expression: compilationUnit = MakeCompilationUnitFromTypeMembers( MakeMethodFromBlock( MakeBlockFromExpression( (Expression)result ))); break; case SnippetType.Statements: compilationUnit = MakeCompilationUnitFromTypeMembers( MakeMethodFromBlock( (BlockStatement)result )); break; case SnippetType.TypeMembers: compilationUnit = MakeCompilationUnitFromTypeMembers(result.Children); break; default: throw new NotSupportedException("Unknown snippet type: " + parser.SnippetType); } // convert NRefactory CU in DOM CU NRefactoryASTConvertVisitor visitor = new NRefactoryASTConvertVisitor(project); visitor.VisitCompilationUnit(compilationUnit, null); visitor.Cu.FileName = sourceLanguage == SupportedLanguage.CSharp ? "a.cs" : "a.vb"; // and register the compilation unit in the DOM foreach (IClass c in visitor.Cu.Classes) { project.AddClassToNamespaceList(c); } parseInfo = new ParseInformation(); parseInfo.SetCompilationUnit(visitor.Cu); return(result); }