public virtual void Parse() { Workspaces.Document item = Item; string code = item.Code; string ffn = item.FullPath; bool has_changed = item.Changed; item.Changed = false; if (!has_changed) { return; } IGrammarDescription gd = GrammarDescriptionFactory.Create(ffn); if (gd == null) { throw new Exception(); } gd.Parse(this); AllNodes = DFSVisitor.DFS(ParseTree as ParserRuleContext); Comments = gd.ExtractComments(code); Defs = new Dictionary <TerminalNodeImpl, int>(); Refs = new Dictionary <TerminalNodeImpl, int>(); Tags = new Dictionary <TerminalNodeImpl, int>(); Errors = new HashSet <IParseTree>(); Imports = new HashSet <string>(); Attributes = new Dictionary <IParseTree, IList <CombinedScopeSymbol> >(); Cleanup(); }
internal void Initialize( IBufferTagAggregatorFactoryService aggregatorFactory, IClassificationTypeRegistryService service, IClassificationFormatMapService ClassificationFormatMapService) { try { if (initialized) { return; } var ffn = _buffer.GetFFN().Result; if (ffn == null) { return; } _grammar_description = LanguageServer.GrammarDescriptionFactory.Create(ffn); if (_grammar_description == null) { return; } var document = Workspaces.Workspace.Instance.FindDocument(ffn); if (document == null) { Workspaces.Loader.LoadAsync().Wait(); var to_do = LanguageServer.Module.Compile(); document = Workspaces.Workspace.Instance.FindDocument(ffn); } _aggregator = aggregatorFactory.CreateTagAggregator <AntlrTokenTag>(_buffer); _antlrtype_to_classifiertype = new Dictionary <int, IClassificationType>(); for (int i = 0; i < _grammar_description.Map.Length; ++i) { var key = i; var val = _grammar_description.Map[i]; var identiferClassificationType = service.GetClassificationType(val); var classificationType = identiferClassificationType == null?service.CreateClassificationType(val, new IClassificationType[] { }) : identiferClassificationType; var classificationFormatMap = ClassificationFormatMapService.GetClassificationFormatMap(category: "text"); var identifierProperties = classificationFormatMap .GetExplicitTextProperties(classificationType); var color = !Themes.IsInvertedTheme() ? _grammar_description.MapColor[key] : _grammar_description.MapInvertedColor[key]; System.Windows.Media.Color newColor = System.Windows.Media.Color.FromArgb(color.A, color.R, color.G, color.B); var newProperties = identifierProperties.SetForeground(newColor); classificationFormatMap.AddExplicitTextProperties(classificationType, newProperties); } for (int i = 0; i < _grammar_description.Map.Length; ++i) { var key = i; var val = _grammar_description.Map[i]; _antlrtype_to_classifiertype[key] = service.GetClassificationType(val); } initialized = true; } catch (Exception exception) { Logger.Log.Notify(exception.StackTrace); } }
public static ParserDetails Create(Workspaces.Document item) { if (item == null) { return(null); } string ffn = item.FullPath; foreach (KeyValuePair <string, ParserDetails> pd in _per_file_parser_details) { if (pd.Key == ffn) { return(pd.Value); } } IGrammarDescription gd = GrammarDescriptionFactory.Create(ffn); if (gd == null) { return(null); } ParserDetails result = gd.CreateParserDetails(item); result.Gd = gd; _per_file_parser_details[ffn] = result; return(result); }
public virtual List <string> Candidates(int char_index) { Workspaces.Document item = Item; string ffn = item.FullPath; IGrammarDescription gd = GrammarDescriptionFactory.Create(ffn); if (gd == null) { throw new Exception(); } string code = Code.Substring(0, char_index); gd.Parse(code, out CommonTokenStream tok_stream, out Parser parser, out Lexer lexer, out IParseTree pt); LASets la_sets = new LASets(); IntervalSet int_set = la_sets.Compute(parser, tok_stream); List <string> result = new List <string>(); foreach (int r in int_set.ToList()) { string rule_name = Lexer.RuleNames[r]; result.Add(rule_name); } return(result); }
internal AntlrClassifier(ITextBuffer buffer) { try { _buffer = buffer; _buffer.Changed += new EventHandler <TextContentChangedEventArgs>(OnTextChanged); var ffn = _buffer.GetFFN().Result; if (ffn == null) { return; } _grammar_description = LanguageServer.GrammarDescriptionFactory.Create(ffn); if (_grammar_description == null) { return; } var document = Workspaces.Workspace.Instance.FindDocument(ffn); if (document == null) { Workspaces.Loader.LoadAsync().Wait(); var to_do = LanguageServer.Module.Compile(); document = Workspaces.Workspace.Instance.FindDocument(ffn); } AntlrLanguagePackage package = AntlrLanguagePackage.Instance; } catch (Exception exception) { Logger.Log.Notify(exception.ToString()); } }
public AntlrQuickInfoSource(ITextBuffer buffer, ITagAggregator <AntlrTokenTag> aggregator) { _aggregator = aggregator; _buffer = buffer; var path = buffer.GetFFN().Result; _grammar_description = LanguageServer.GrammarDescriptionFactory.Create(path); }
public virtual void GatherDefs() { Workspaces.Document item = Item; string ffn = item.FullPath; IGrammarDescription gd = GrammarDescriptionFactory.Create(ffn); if (gd == null) { throw new Exception(); } for (int classification = 0; classification < gd.IdentifyDefinition.Count; ++classification) { Func <IGrammarDescription, Dictionary <IParseTree, IList <CombinedScopeSymbol> >, IParseTree, bool> fun = gd.IdentifyDefinition[classification]; if (fun == null) { continue; } IEnumerable <IParseTree> it = AllNodes.Where(t => fun(gd, Attributes, t)); foreach (IParseTree t in it) { TerminalNodeImpl x = (t as TerminalNodeImpl); if (x == null) { continue; } if (x.Symbol == null) { continue; } try { Defs.Add(x, classification); Tags.Add(x, classification); } catch (ArgumentException) { // Duplicate } } } }
public virtual List <string> Candidates(int index) { var item = Item; var ffn = item.FullPath; IGrammarDescription gd = GrammarDescriptionFactory.Create(ffn); if (gd == null) { throw new Exception(); } string code = this.Code.Substring(0, index); gd.Parse(code, out CommonTokenStream tok_stream, out Parser parser, out Lexer lexer, out IParseTree pt); LASets la_sets = new LASets(); var result = la_sets.Compute(parser, tok_stream); return(null); }
public virtual void GatherErrors() { var item = Item; var ffn = item.FullPath; IGrammarDescription gd = GrammarDescriptionFactory.Create(ffn); if (gd == null) { throw new Exception(); } { var it = this.AllNodes.Where(t => t as Antlr4.Runtime.Tree.ErrorNodeImpl != null); foreach (var t in it) { this.Errors.Add(t); } } }
public virtual void GatherErrors() { Workspaces.Document item = Item; string ffn = item.FullPath; IGrammarDescription gd = GrammarDescriptionFactory.Create(ffn); if (gd == null) { throw new Exception(); } { IEnumerable <IParseTree> it = AllNodes.Where(t => t as Antlr4.Runtime.Tree.ErrorNodeImpl != null); foreach (IParseTree t in it) { Errors.Add(t); } } }
public HighlightTagger(ITextView view, ITextBuffer sourceBuffer, ITextSearchService textSearchService, ITextStructureNavigator textStructureNavigator, IClassifier aggregator) { _view = view; _buffer = sourceBuffer; var ffn = _buffer.GetFFN().Result; if (ffn == null) { return; } _grammar_description = LanguageServer.GrammarDescriptionFactory.Create(ffn); TextSearchService = textSearchService; TextStructureNavigator = textStructureNavigator; _aggregator = aggregator; WordSpans = new NormalizedSnapshotSpanCollection(); CurrentWord = null; _view_to_tagger[view] = this; }
public virtual void GatherDefs() { var item = Item; var ffn = item.FullPath; IGrammarDescription gd = GrammarDescriptionFactory.Create(ffn); if (gd == null) { throw new Exception(); } for (int classification = 0; classification < gd.IdentifyDefinition.Count; ++classification) { var fun = gd.IdentifyDefinition[classification]; if (fun == null) { continue; } var it = this.AllNodes.Where(t => fun(gd, this.Attributes, t)); foreach (var t in it) { var x = (t as TerminalNodeImpl); if (x == null) { continue; } if (x.Symbol == null) { continue; } try { this.Defs.Add(x, classification); this.Tags.Add(x, classification); } catch (ArgumentException) { // Duplicate } } } }
public static int GetTag(int index, Document doc) { ParserDetails pd = ParserDetailsFactory.Create(doc); if (pd.ParseTree == null) { LanguageServer.Module.Compile(); } Antlr4.Runtime.Tree.IParseTree pt = LanguageServer.Util.Find(index, doc); IGrammarDescription gd = GrammarDescriptionFactory.Create(doc.FullPath); if (pt == null) { return(-1); } Antlr4.Runtime.Tree.IParseTree p = pt; TerminalNodeImpl q = p as Antlr4.Runtime.Tree.TerminalNodeImpl; bool found = pd.Tags.TryGetValue(q, out int tag_type); if (found) { return(tag_type); } if (q.Symbol == null) { return(-1); } bool found2 = pd.Comments.TryGetValue(q.Symbol, out int tag2); if (found2) { return(tag2); } return(-1); }
public static DocumentSymbol GetDocumentSymbol(int index, Document doc) { ParserDetails pd = ParserDetailsFactory.Create(doc); if (pd.ParseTree == null) { LanguageServer.Module.Compile(); } Antlr4.Runtime.Tree.IParseTree pt = LanguageServer.Util.Find(index, doc); IGrammarDescription gd = GrammarDescriptionFactory.Create(doc.FullPath); if (pt == null) { return(default(DocumentSymbol)); } Antlr4.Runtime.Tree.IParseTree p = pt; TerminalNodeImpl q = p as Antlr4.Runtime.Tree.TerminalNodeImpl; bool found = pd.Tags.TryGetValue(q, out int tag_type); if (!found) { return(null); } if (q.Symbol == null) { return(null); } return(new DocumentSymbol() { name = q.Symbol.Text, range = new Workspaces.Range(q.Symbol.StartIndex, q.Symbol.StopIndex), kind = tag_type }); }
public static void ResetMenus() { if (GoToDefinitionCommand.Instance == null || FindAllReferencesCommand.Instance == null || RenameCommand.Instance == null || Reformat.ReformatCommand.Instance == null) { return; } IWpfTextView view = AntlrLanguagePackage.Instance.GetActiveView(); if (view == null) { return; } // First, find out what this view is, and what the file is. ITextBuffer buffer = view.TextBuffer; string path = buffer.GetFFN().Result; IGrammarDescription grammar_description = LanguageServer.GrammarDescriptionFactory.Create(path); // Whack any old values that cursor points to. GoToDefinitionCommand.Instance.Enabled = false; FindAllReferencesCommand.Instance.Enabled = false; NextSymCommand.Instance.Enabled = true; RenameCommand.Instance.Enabled = false; ReformatCommand.Instance.Enabled = false; GoToVisitorCommand.Instance.Enabled = false; AntlrLanguagePackage.Instance.Span = default(SnapshotSpan); AntlrLanguagePackage.Instance.Classification = default(string); AntlrLanguagePackage.Instance.View = view; if (grammar_description == null) { return; } var fp = view.GetFilePath().Result; if (fp != null) { var gd = LanguageServer.GrammarDescriptionFactory.Create(fp); if (gd != null && gd.CanNextRule) { NextSymCommand.Instance.Enabled = true; } if (gd != null && gd.CanReformat) { Reformat.ReformatCommand.Instance.Enabled = true; } } else { return; } // Find details of the Antlr symbol pointed to. ITextCaret car = view.Caret; CaretPosition cp = car.Position; SnapshotPoint bp = cp.BufferPosition; TextExtent extent = AntlrVSIX.Package.AntlrLanguagePackage.Instance.Navigator[view].GetExtentOfWord(bp); SnapshotSpan span = extent.Span; AntlrLanguagePackage.Instance.Span = span; HighlightTagger.Update(view, bp); // Now, check for valid classification type. ClassificationSpan[] c1 = AntlrVSIX.Package.AntlrLanguagePackage.Instance.Aggregator[view].GetClassificationSpans(span).ToArray(); foreach (ClassificationSpan classification in c1) { var name = classification.ClassificationType.Classification; if (!grammar_description.InverseMap.TryGetValue(name, out int type)) { continue; } if (grammar_description.CanFindAllRefs[type]) { FindAllReferencesCommand.Instance.Enabled = true; } if (grammar_description.CanRename[type]) { RenameCommand.Instance.Enabled = true; } if (grammar_description.CanGotodef[type]) { GoToDefinitionCommand.Instance.Enabled = true; } if (grammar_description.CanGotovisitor[type]) { GoToVisitorCommand.Instance.Enabled = true; } if (grammar_description.CanReformat) { ReformatCommand.Instance.Enabled = true; } } }
public static TextEdit[] Reformat(Document doc) { ParserDetails ref_pd = ParserDetailsFactory.Create(doc); string code = doc.Code; string corpus_location = Options.Option.GetString("CorpusLocation"); if (corpus_location == null) { TextEdit[] result = new TextEdit[] { }; return(result); } string ffn = doc.FullPath; if (ffn == null) { TextEdit[] result = new TextEdit[] { }; return(result); } IGrammarDescription grammar_description = LanguageServer.GrammarDescriptionFactory.Create(ffn); if (grammar_description == null) { TextEdit[] result = new TextEdit[] { }; return(result); } org.antlr.codebuff.Tool.unformatted_input = code; try { string result = org.antlr.codebuff.Tool.Main( new object[] { "-g", grammar_description.Name, "-lexer", grammar_description.Lexer, "-parser", grammar_description.Parser, "-rule", grammar_description.StartRule, "-files", grammar_description.FileExtension, "-corpus", corpus_location, "-inoutstring", "" }); List <TextEdit> edits = new List <TextEdit>(); diff_match_patch diff = new diff_match_patch(); List <Diff> diffs = diff.diff_main(code, result); List <Patch> patch = diff.patch_make(diffs); //patch.Reverse(); // Start edit session. int times = 0; int delta = 0; foreach (Patch p in patch) { times++; int start = p.start1 - delta; int offset = 0; foreach (Diff ed in p.diffs) { if (ed.operation == Operation.EQUAL) { //// Let's verify that. int len = ed.text.Length; //var tokenSpan = new SnapshotSpan(buffer.CurrentSnapshot, // new Span(start + offset, len)); //var tt = tokenSpan.GetText(); //if (ed.text != tt) //{ } offset = offset + len; } else if (ed.operation == Operation.DELETE) { int len = ed.text.Length; //var tokenSpan = new SnapshotSpan(buffer.CurrentSnapshot, // new Span(start + offset, len)); //var tt = tokenSpan.GetText(); //if (ed.text != tt) //{ } TextEdit edit = new TextEdit() { range = new Workspaces.Range( new Workspaces.Index(start + offset), new Workspaces.Index(start + offset + len)), NewText = "" }; offset = offset + len; edits.Add(edit); } else if (ed.operation == Operation.INSERT) { int len = ed.text.Length; TextEdit edit = new TextEdit() { range = new Workspaces.Range( new Workspaces.Index(start + offset), new Workspaces.Index(start + offset)), NewText = ed.text }; edits.Add(edit); } } delta = delta + (p.length2 - p.length1); } return(edits.ToArray()); } catch (Exception) { TextEdit[] result = new TextEdit[] { }; return(result); } }
public static List <ParserDetails> Compile() { try { Workspace ws = Workspaces.Workspace.Instance; // Get all changed files. HashSet <ParserDetails> to_do = new HashSet <ParserDetails>(); DoAgain: // Get current directory, and add all grammar files. foreach (Document document in Workspaces.DFSContainer.DFS(ws)) { string file_name = document.FullPath; if (file_name == null) { continue; } Container parent = document.Parent; IGrammarDescription gd = LanguageServer.GrammarDescriptionFactory.Create(file_name); if (gd == null) { continue; } // Get suffix of file_name. string extension = System.IO.Path.GetExtension(file_name); string directory = System.IO.Path.GetDirectoryName(file_name); foreach (string file in System.IO.Directory.GetFiles(directory)) { if (System.IO.Path.GetExtension(file) != extension) { continue; } IGrammarDescription g2 = LanguageServer.GrammarDescriptionFactory.Create(file); if (g2 == null) { continue; } Document x = Workspaces.Workspace.Instance.FindDocument(file); if (x == null) { // Add document. Container proj = parent; Document new_doc = new Workspaces.Document(file); proj.AddChild(new_doc); } ParserDetails p2 = ParserDetailsFactory.Create(document); if (!p2.Changed) { continue; } to_do.Add(p2); } } foreach (Document document in Workspaces.DFSContainer.DFS(ws)) { string file_name = document.FullPath; if (file_name == null) { continue; } IGrammarDescription gd = LanguageServer.GrammarDescriptionFactory.Create(file_name); if (gd == null) { continue; } // file_name can be a URI, so this doesn't make sense. //if (!System.IO.File.Exists(file_name)) continue; ParserDetails pd = ParserDetailsFactory.Create(document); if (!pd.Changed) { continue; } to_do.Add(pd); } Digraph <ParserDetails> g = ConstructGraph(to_do); foreach (ParserDetails v in g.Vertices) { v.Item.Changed = true; // Force. v.Parse(); } bool changed = true; for (int pass = 0; changed; pass++) { changed = false; foreach (ParserDetails v in g.Vertices) { int number_of_passes = v.Passes.Count; if (pass < number_of_passes) { bool reset = v.Pass(pass); if (reset) { goto DoAgain; } changed = true; } } } foreach (ParserDetails v in g.Vertices) { v.GatherDefs(); } foreach (ParserDetails v in g.Vertices) { v.GatherRefs(); } foreach (ParserDetails v in g.Vertices) { v.GatherErrors(); } return(g.Vertices.ToList()); } catch (Exception e) { Logger.Log.Notify(e.ToString()); } return(new List <ParserDetails>()); }
public static QuickInfo GetQuickInfo(int index, Document doc) { ParserDetails pd = ParserDetailsFactory.Create(doc); if (pd.ParseTree == null) { LanguageServer.Module.Compile(); } Antlr4.Runtime.Tree.IParseTree pt = LanguageServer.Util.Find(index, doc); IGrammarDescription gd = GrammarDescriptionFactory.Create(doc.FullPath); if (pt == null) { return(null); } Antlr4.Runtime.Tree.IParseTree p = pt; pd.Attributes.TryGetValue(p, out IList <CombinedScopeSymbol> list_value); if (list_value == null) { return(null); } TerminalNodeImpl q = p as Antlr4.Runtime.Tree.TerminalNodeImpl; Range range = new Workspaces.Range(new Workspaces.Index(q.Symbol.StartIndex), new Workspaces.Index(q.Symbol.StopIndex + 1)); bool found = pd.Tags.TryGetValue(q, out int tag_type); if (!found) { return(null); } if (list_value == null || list_value.Count == 0) { return(new QuickInfo() { Display = gd.Map[tag_type], Range = range }); } if (list_value.Count == 1) { CombinedScopeSymbol value = list_value.First(); ISymbol name = value as Symtab.ISymbol; string show = name?.Name; if (value is Symtab.Literal) { show = ((Symtab.Literal)value).Cleaned; } if (gd.PopUpDefinition[tag_type] != null) { Func <ParserDetails, IParseTree, string> fun = gd.PopUpDefinition[tag_type]; string mess = fun(pd, p); if (mess != null) { return(new QuickInfo() { Display = mess, Range = range }); } } string display = gd.Map[tag_type] + "\n" + show; return(new QuickInfo() { Display = display, Range = range }); } { string display = "Ambiguous -- "; foreach (CombinedScopeSymbol value in list_value) { ISymbol name = value as Symtab.ISymbol; string show = name?.Name; if (value is Symtab.Literal) { show = ((Symtab.Literal)value).Cleaned; } if (gd.PopUpDefinition[tag_type] != null) { Func <ParserDetails, IParseTree, string> fun = gd.PopUpDefinition[tag_type]; string mess = fun(pd, p); if (mess != null) { display = display + mess; } } else { display = display + gd.Map[tag_type] + "\n" + show; } } return(new QuickInfo() { Display = display, Range = range }); } }
public virtual void GatherRefs() { var item = Item; var ffn = item.FullPath; IGrammarDescription gd = GrammarDescriptionFactory.Create(ffn); if (gd == null) { throw new Exception(); } for (int classification = 0; classification < gd.Identify.Count; ++classification) { var fun = gd.Identify[classification]; if (fun == null) { continue; } var it = this.AllNodes.Where(t => fun(gd, this.Attributes, t)); foreach (var t in it) { var x = (t as TerminalNodeImpl); if (x == null) { continue; } if (x.Symbol == null) { continue; } try { this.Attributes.TryGetValue(x, out IList <CombinedScopeSymbol> attr_list); if (attr_list == null) { continue; } foreach (var attr in attr_list) { this.Tags.Add(x, classification); if (attr == null) { continue; } var sym = attr as Symtab.ISymbol; if (sym == null) { continue; } var def = sym.resolve(); if (def != null && def.file != null && def.file != "" && def.file != ffn) { var def_item = Workspaces.Workspace.Instance.FindDocument(def.file); var def_pd = ParserDetailsFactory.Create(def_item); def_pd.PropagateChangesTo.Add(ffn); } this.Refs.Add(x, classification); } } catch (ArgumentException) { // Duplicate } } } }
public virtual void GatherRefs() { Workspaces.Document item = Item; string ffn = item.FullPath; IGrammarDescription gd = GrammarDescriptionFactory.Create(ffn); if (gd == null) { throw new Exception(); } for (int classification = 0; classification < gd.Identify.Count; ++classification) { Func <IGrammarDescription, Dictionary <IParseTree, IList <CombinedScopeSymbol> >, IParseTree, bool> fun = gd.Identify[classification]; if (fun == null) { continue; } IEnumerable <IParseTree> it = AllNodes.Where(t => fun(gd, Attributes, t)); foreach (IParseTree t in it) { TerminalNodeImpl x = (t as TerminalNodeImpl); if (x == null) { continue; } if (x.Symbol == null) { continue; } try { Attributes.TryGetValue(x, out IList <CombinedScopeSymbol> attr_list); if (attr_list == null) { continue; } foreach (CombinedScopeSymbol attr in attr_list) { Tags.Add(x, classification); if (attr == null) { continue; } ISymbol sym = attr as Symtab.ISymbol; if (sym == null) { continue; } ISymbol def = sym.resolve(); if (def != null && def.file != null && def.file != "" && def.file != ffn) { Workspaces.Document def_item = Workspaces.Workspace.Instance.FindDocument(def.file); ParserDetails def_pd = ParserDetailsFactory.Create(def_item); def_pd.PropagateChangesTo.Add(ffn); } Refs.Add(x, classification); } } catch (ArgumentException) { // Duplicate } } } }
private void MenuItemCallback(object sender, EventArgs e, bool visitor) { try { // Return if I can't determine what application this is. DTE application = Workspaces.Help.GetApplication(); if (application == null) { return; } // Get active view and determine if it's a grammar file. var grammar_view = AntlrLanguagePackage.Instance.GetActiveView(); if (grammar_view == null) { return; } ITextCaret car = grammar_view.Caret; CaretPosition cp = car.Position; SnapshotPoint bp = cp.BufferPosition; int pos = bp.Position; ITextBuffer buffer = grammar_view.TextBuffer; var g4_file_path = buffer.GetFFN().Result; if (g4_file_path == null) { return; } IGrammarDescription grammar_description = LanguageServer.GrammarDescriptionFactory.Create(g4_file_path); if (!grammar_description.IsFileType(g4_file_path)) { return; } // Get name of base class for listener and visitor. These are generated by Antlr, // constructed from the name of the file. var grammar_name = Path.GetFileName(g4_file_path); grammar_name = Path.GetFileNameWithoutExtension(grammar_name); var listener_baseclass_name = visitor ? (grammar_name + "BaseVisitor") : (grammar_name + "BaseListener"); var listener_class_name = visitor ? ("My" + grammar_name + "Visitor") : ("My" + grammar_name + "Listener"); // In the current view, find the details of the Antlr symbol at the cursor. TextExtent extent = AntlrVSIX.Package.AntlrLanguagePackage.Instance.Navigator[grammar_view] .GetExtentOfWord(bp); SnapshotSpan span = extent.Span; AntlrLanguagePackage.Instance.Span = span; // Now, check for valid classification type. var cla = -1; bool can_gotovisitor = AntlrVSIX.Package.AntlrLanguagePackage.Instance.Aggregator[grammar_view].GetClassificationSpans(span).Where( classification => { var name = classification.ClassificationType.Classification; if (!grammar_description.InverseMap.TryGetValue(name, out int c)) { return(false); } cla = c; return(grammar_description.CanGotovisitor[cla]); }).Any(); if (!can_gotovisitor) { return; } // Find defining occurrence. List <Antlr4.Runtime.Tree.TerminalNodeImpl> where = new List <Antlr4.Runtime.Tree.TerminalNodeImpl>(); List <ParserDetails> where_details = new List <ParserDetails>(); Antlr4.Runtime.Tree.TerminalNodeImpl token = null; foreach (var kvp in ParserDetailsFactory.AllParserDetails) { string file_name = kvp.Key; ParserDetails details = kvp.Value; { var it = details.Defs.Where( (t) => t.Value == cla && t.Key.Symbol.Text == span.GetText()).Select(t => t.Key); where.AddRange(it); foreach (var i in it) { where_details.Add(details); } } } if (where.Any()) { token = where.First(); } else { System.Windows.Forms.MessageBox.Show( "Symbol '" + span.GetText() + "' definer not found."); return; } // Get the symbol name as a string. var symbol_name = token.Symbol.Text; var capitalized_symbol_name = Capitalized(symbol_name); // Parse all the C# files in the solution. Dictionary <string, SyntaxTree> trees = new Dictionary <string, SyntaxTree>(); foreach (var item in DteExtensions.SolutionFiles(application)) { string file_name = item.Name; if (file_name != null) { string prefix = file_name.TrimSuffix(".cs"); if (prefix == file_name) { continue; } try { object prop = item.Properties.Item("FullPath").Value; string ffn = (string)prop; StreamReader sr = new StreamReader(ffn); string code = sr.ReadToEnd(); SyntaxTree tree = CSharpSyntaxTree.ParseText(code); trees[ffn] = tree; } catch (Exception) { } } } // Find all occurrences of visitor class. List <ClassDeclarationSyntax> found_class = new List <ClassDeclarationSyntax>(); string class_file_path = null; try { foreach (var kvp in trees) { var file_name = kvp.Key; var tree = kvp.Value; // Look for IParseTreeListener or IParseTreeVisitor classes. var root = (CompilationUnitSyntax)tree.GetRoot(); if (root == null) { continue; } foreach (var nm in root.Members) { var namespace_member = nm as NamespaceDeclarationSyntax; if (namespace_member == null) { continue; } foreach (var cm in namespace_member.Members) { var class_member = cm as ClassDeclarationSyntax; if (class_member == null) { continue; } var bls = class_member.BaseList; if (bls == null) { continue; } var types = bls.Types; Regex reg = new Regex("[<].+[>]"); foreach (var type in types) { var s = type.ToString(); s = reg.Replace(s, ""); if (s.ToString() == listener_baseclass_name) { // Found the right class. found_class.Add(class_member); throw new Exception(); } } } } } } catch { } if (found_class.Count == 0) { if (!global::Options.POptions.GetBoolean("GenerateVisitorListener")) { return; } // Look in grammar directory for any C# files. string name_space = null; string ffn = Path.GetFullPath(g4_file_path); ffn = Path.GetDirectoryName(ffn); foreach (var i in DteExtensions.SolutionFiles(application)) { string file_name = i.Name; if (file_name != null) { string prefix = file_name.TrimSuffix(".cs"); if (prefix == file_name) { continue; } try { object prop = i.Properties.Item("FullPath").Value; string ffncs = (string)prop; // Look for namespace. var t = trees[ffncs]; if (t == null) { continue; } var root = t.GetCompilationUnitRoot(); foreach (var nm in root.Members) { var namespace_member = nm as NamespaceDeclarationSyntax; if (namespace_member == null) { continue; } name_space = namespace_member.Name.ToString(); break; } } catch (Exception) { } } } if (name_space == null) { name_space = "Generated"; } // Create class. string clazz = visitor ? $@" using System; using System.Collections.Generic; using System.Text; namespace {name_space} {{ class {listener_class_name}<Result> : {listener_baseclass_name}<Result> {{ //public override Result VisitA([NotNull] A3Parser.AContext context) //{{ // return VisitChildren(context); //}} }} }} " : $@" using System; using System.Collections.Generic; using System.Text; namespace {name_space} {{ class {listener_class_name} : {listener_baseclass_name} {{ //public override void EnterA(A3Parser.AContext context) //{{ // base.EnterA(context); //}} //public override void ExitA(A3Parser.AContext context) //{{ // base.ExitA(context); //}} }} }} "; class_file_path = ffn + Path.DirectorySeparatorChar + listener_class_name + ".cs"; System.IO.File.WriteAllText(class_file_path, clazz); var item = ProjectHelpers.GetSelectedItem(); string folder = FindFolder(item); if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) { return; } var file = new FileInfo(class_file_path); var selectedItem = Workspaces.Workspace.Instance.FindDocument(class_file_path); if (selectedItem == null) { //var selectedProject = item as Project; //Project project = selectedItem?.ContainingProject ?? selectedProject ?? null; //var projectItem = project.AddFileToProject(file); } // Redo parse. try { StreamReader sr = new StreamReader(class_file_path); string code = sr.ReadToEnd(); SyntaxTree tree = CSharpSyntaxTree.ParseText(code); trees[class_file_path] = tree; } catch (Exception) { } // Redo find class. try { var tree = trees[class_file_path]; var save = class_file_path; class_file_path = null; // Look for IParseTreeListener or IParseTreeVisitor classes. var root = (CompilationUnitSyntax)tree.GetRoot(); foreach (var nm in root.Members) { var namespace_member = nm as NamespaceDeclarationSyntax; if (namespace_member == null) { continue; } foreach (var cm in namespace_member.Members) { var class_member = cm as ClassDeclarationSyntax; if (class_member == null) { continue; } var bls = class_member.BaseList; if (bls == null) { continue; } var types = bls.Types; Regex reg = new Regex("[<].+[>]"); foreach (var type in types) { var s = type.ToString(); s = reg.Replace(s, ""); if (s.ToString() == listener_baseclass_name) { // Found the right class. found_class.Add(class_member); throw new Exception(); } } } } } catch { } } // Look for enter or exit method for symbol. MethodDeclarationSyntax found_member = null; var ctl = CtrlKeyState.GetStateForView(grammar_view).Enabled; var capitalized_member_name = ""; if (visitor) { capitalized_member_name = "Visit" + capitalized_symbol_name; } else if (ctl) { capitalized_member_name = "Exit" + capitalized_symbol_name; } else { capitalized_member_name = "Enter" + capitalized_symbol_name; } var capitalized_grammar_name = Capitalized(grammar_name); try { foreach (var fc in found_class) { foreach (var me in fc.Members) { var method_member = me as MethodDeclarationSyntax; if (method_member == null) { continue; } if (method_member.Identifier.ValueText.ToLower() == capitalized_member_name.ToLower()) { found_member = method_member; throw new Exception(); } } } } catch { } if (found_member == null) { if (!global::Options.POptions.GetBoolean("GenerateVisitorListener")) { return; } // Find point for edit. var fc = found_class.First(); var here = fc.OpenBraceToken; var spn = here.FullSpan; var end = spn.End; IVsTextView vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); if (vstv == null) { IVsTextViewExtensions.ShowFrame(class_file_path); vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); } IWpfTextView wpftv = vstv.GetIWpfTextView(); if (wpftv == null) { return; } ITextSnapshot cc = wpftv.TextBuffer.CurrentSnapshot; var res = vstv.GetBuffer(out IVsTextLines ppBuffer); var nss = new SnapshotSpan(cc, spn.End + 1, 0); var txt_span = nss.Span; int line_number; int colum_number; vstv.GetLineAndColumn(txt_span.Start, out line_number, out colum_number); res = ppBuffer.CreateEditPoint(line_number, colum_number, out object ppEditPoint); EditPoint editPoint = ppEditPoint as EditPoint; // Create class. string member = visitor ? $@" public override Result {capitalized_member_name}([NotNull] {capitalized_grammar_name}Parser.{capitalized_symbol_name}Context context) {{ return VisitChildren(context); }} " : $@" public override void {capitalized_member_name}({capitalized_grammar_name}Parser.{capitalized_symbol_name}Context context) {{ base.{capitalized_member_name}(context); }} "; editPoint.Insert(member); // Redo parse. try { vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); if (vstv == null) { IVsTextViewExtensions.ShowFrame(class_file_path); vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); } var text_buffer = vstv.GetITextBuffer(); var code = text_buffer.GetBufferText(); SyntaxTree tree = CSharpSyntaxTree.ParseText(code); trees[class_file_path] = tree; } catch (Exception) { } // Redo find class. try { var tree = trees[class_file_path]; var save = class_file_path; class_file_path = null; // Look for IParseTreeListener or IParseTreeVisitor classes. var root = (CompilationUnitSyntax)tree.GetRoot(); foreach (var nm in root.Members) { var namespace_member = nm as NamespaceDeclarationSyntax; if (namespace_member == null) { continue; } foreach (var cm in namespace_member.Members) { var class_member = cm as ClassDeclarationSyntax; if (class_member == null) { continue; } var bls = class_member.BaseList; if (bls == null) { continue; } var types = bls.Types; Regex reg = new Regex("[<].+[>]"); foreach (var type in types) { var s = type.ToString(); s = reg.Replace(s, ""); if (s.ToString() == listener_baseclass_name) { // Found the right class. found_class.Add(class_member); class_file_path = save; throw new Exception(); } } } } } catch { } try { foreach (var fcc in found_class) { foreach (var me in fcc.Members) { var method_member = me as MethodDeclarationSyntax; if (method_member == null) { continue; } if (method_member.Identifier.ValueText.ToLower() == capitalized_member_name.ToLower()) { found_member = method_member; throw new Exception(); } } } } catch { } } { // Open to this line in editor. IVsTextView vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); { IVsTextViewExtensions.ShowFrame(class_file_path); vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); } IWpfTextView wpftv = vstv.GetIWpfTextView(); if (wpftv == null) { return; } int line_number; int colum_number; var txt_span = found_member.Identifier.Span; vstv.GetLineAndColumn(txt_span.Start, out line_number, out colum_number); // Create new span in the appropriate view. ITextSnapshot cc = wpftv.TextBuffer.CurrentSnapshot; SnapshotSpan ss = new SnapshotSpan(cc, txt_span.Start, txt_span.Length); SnapshotPoint sp = ss.Start; // Put cursor on symbol. wpftv.Caret.MoveTo(sp); // This sets cursor, bot does not center. // Center on cursor. //wpftv.Caret.EnsureVisible(); // This works, sort of. It moves the scroll bar, but it does not CENTER! Does not really work! if (line_number > 0) { vstv.CenterLines(line_number - 1, 2); } else { vstv.CenterLines(line_number, 1); } return; } } catch (Exception exception) { Logger.Log.Notify(exception.StackTrace); } }