public static string GetMethodStringFromElement(CodeElement elem) { try { if (elem.Kind == vsCMElement.vsCMElementFunction) { return GetMethodStringFromElement(elem as CodeFunction); } if (elem.Kind == vsCMElement.vsCMElementProperty) { var getter = ((CodeProperty) elem).Getter; return GetMethodStringFromElement(getter); } if (elem.Kind == vsCMElement.vsCMElementVariable) { return GetFieldStringFromElement(elem); } } catch(Exception ex) { Core.DebugLog.Debug.WriteDebug("Exception getting Method String : " + ex.ToString()); return null; } return null; }
protected override void Visit(CodeElement element) { //结果已经找到,退出访问。 if (_result != null) return; base.Visit(element); }
private static void AddCommentsTo(CodeElement codeElement) { if (CodeElementsThatNeedDocComment.Contains(codeElement.Kind)) { if (string.IsNullOrWhiteSpace(codeElement.GetDocComment())) { if (codeElement.IsInherited() || codeElement.OverridesSomething()) { codeElement.SetDocComment(@"<DOC><inheritdoc/></DOC>"); } else { switch (codeElement.Kind) { case vsCMElement.vsCMElementProperty: AddDocCommentToProperty(codeElement as CodeProperty); break; case vsCMElement.vsCMElementFunction: AddDocCommentToFunction(codeElement as CodeFunction); break; case vsCMElement.vsCMElementEnum: AddGhostDogCommand(codeElement); break; case vsCMElement.vsCMElementStruct: AddGhostDogCommand(codeElement); break; case vsCMElement.vsCMElementInterface: AddDocCommentToInterface(codeElement as CodeInterface); break; case vsCMElement.vsCMElementEvent: AddGhostDogCommand(codeElement); break; case vsCMElement.vsCMElementClass: AddDocCommentToClass(codeElement as CodeClass); break; case vsCMElement.vsCMElementVariable: AddGhostDogCommand(codeElement); break; } } } } if (CodeElementsWithChildren.Contains(codeElement.Kind)) { foreach (CodeElement child in codeElement.Children) { AddCommentsTo(child); } } }
private static string GetFieldStringFromElement(CodeElement elem) { var v = (CodeVariable) elem; var typeName = GenericNameMangler.MangleTypeName(GetTypeName(v.Parent)); var oftype = GetVariableType(v); return oftype + " " + typeName + "::" + v.Name; }
/// <summary> /// /// </summary> public CodeFieldInfo(BaseInfo parent, CodeElement item, TypeInfo type) : base(parent, item as CodeElement2) { this._item = item; this.Access = CMAccess.Public; // ObjectFactory.Convert(this._item.Access); this._type = type; }
private static string ExamineCodeElement(CodeElement codeElement, vsCMElement type) { return codeElement.Kind == type ? codeElement.Name : (from CodeElement childElement in codeElement.Children select ExamineCodeElement(childElement, type)) .FirstOrDefault(result => !string.IsNullOrEmpty(result)); }
public MoveToRegionForm(CodeElement classElement) { this.classElement = classElement; InitializeComponent(); BindRegionToTreeView(); }
/// <summary> /// Selects text in the code editor. /// </summary> /// <param name="dte">A DTE2 object exposing the Visual Studio automation object model.</param> /// <param name="element">The CodeElementWrapper object containing the selection.</param> /// <param name="useTryShow">true to use TryToShow to adjust the code editor window to show the selection, otherwise false.</param> public static void GoToCodeElementHelper(DTE dte, CodeElement element, bool useTryShow) { if (element != null) { try { TextPoint start = element.StartPoint; var tx = (TextDocument)dte.ActiveDocument.Object("TextDocument"); int line = start.Line; int offset = start.LineCharOffset; if (!useTryShow) { tx.Selection.MoveToLineAndOffset(line, offset, false); } else { start.TryToShow(vsPaneShowHow.vsPaneShowCentered, start); } if (!useTryShow) { tx.Selection.SelectLine(); } } catch (COMException) { // Discard the exception that gets thrown when accessing // a non-code TextDocument, for example a Windows form. } } }
// ------------------------------------------------------ public void Process(CodeElement element) { bool visitChildren = Visit(element); if (visitChildren) Process(element.Children); }
private EnvDTE.CodeElements GetCodeElementMembers(CodeElement objCodeElement) { EnvDTE.CodeElements colCodeElements = default(EnvDTE.CodeElements); if (objCodeElement is EnvDTE.CodeNamespace) { colCodeElements = ((EnvDTE.CodeNamespace)objCodeElement).Members; } else if (objCodeElement is EnvDTE.CodeType) { colCodeElements = ((EnvDTE.CodeType)objCodeElement).Members; } else if (objCodeElement is EnvDTE.CodeFunction) { colCodeElements = ((EnvDTE.CodeFunction)objCodeElement).Parameters; } return colCodeElements; }
/// <summary> /// Rename function in scope of parentElement. /// </summary> /// <param name="element">Element to rename.</param> /// <param name="parentElement">Containing element.</param> /// <param name="elementType">Type of element.</param> /// <param name="oldName">Old name of element.</param> /// <param name="newName">New name of element.</param> public override IRenameResult RenameSymbols(CodeElement element, LuaCodeClass parentElement, vsCMElement elementType, string oldName, string newName) { renameResult = new RenameResult(oldName, newName); changedCodeElements = new List<CodeElement>(); //Function without parent element could not be renamed if (element is LuaCodeFunction && parentElement == null) { var ex = new InvalidCodeElementException(Resources.InvalidFunctionParentMessage, parentElement); Trace.WriteLine(ex); throw ex; } //Rename function, function calls or null element by its name if (element is LuaCodeFunction || element is LuaCodeElement<FunctionCall> || element == null) { renameResult = Rename(element, parentElement, oldName, newName); } else { throw new InvalidCodeElementException( Resources.InvalidFunctionElementMessage, parentElement); } //Set RenameReferences flag to indicates that rename is local or not renameResult.RenameReferences = !IsLocalDeclaration; renameResult.ChangedElements = changedCodeElements; renameResult.Success = true; return renameResult; }
public static VsClass Parse( CodeElement codeElement) { var vsClass = new VsClass(); vsClass.Name = codeElement.Name; var codeClass = (CodeClass) codeElement; var startPoint = codeClass.StartPoint.CreateEditPoint(); var endPoint = codeClass.EndPoint.CreateEditPoint(); int i = 1; while( startPoint.LessThan(endPoint)) { i++; startPoint.LineDown(1); } vsClass.Loc = i; foreach (CodeElement element in ((CodeClass)codeElement).Members) { if (element.Kind == vsCMElement.vsCMElementVariable) { vsClass.Variables.Add(VsVariable.Parse(element)); } else if (element.Kind == vsCMElement.vsCMElementFunction) { CodeFunction function = element as CodeFunction; if (function.FunctionKind == vsCMFunction.vsCMFunctionConstructor) vsClass.Constructors.Add(VsConstructors.Parse(function)); else vsClass.Methods.Add(VsMethod.Parse(function)); } } return vsClass; }
/// <summary> /// Rename element in scope of parentElement. /// </summary> /// <param name="element">Element to rename.</param> /// <param name="parentElement">Containing element.</param> /// <param name="elementType">Type of element.</param> /// <param name="oldName">Old name of element.</param> /// <param name="newName">New name of element.</param> public IRenameResult RenameSymbols(CodeElement element, LuaCodeClass parentElement, vsCMElement elementType, string oldName, string newName) { if (CodeElementRename == null) { throw new InvalidStrategyException(CodeElementRename); } return CodeElementRename.RenameSymbols(element, parentElement, elementType, oldName, newName); }
internal static CodeElementNodeFactory CreateNodeFactoryFromCodeElement(CodeElement element) { if (element is CodeNamespace) { return new CodeNamespaceNodeFactory(element as CodeNamespace); } if (element is CodeClass2) { return new CodeClassNodeFactory(element as CodeClass2); } if (element is CodeInterface2) { return new CodeInterfaceNodeFactory(element as CodeInterface2); } if (element is CodeProperty) { return new CodePropertyNodeFactory(element as CodeProperty); } if (element is CodeFunction2) { return new CodeMethodNodeFactory(element as CodeFunction2); } if (element is CodeEvent) { return new CodeEventNodeFactory(element as CodeEvent); } if (element is CodeVariable2) { return new CodeVariableNodeFactory(element as CodeVariable2); } if (element is CodeEnum) { return new CodeEnumNodeFactory(element as CodeEnum); } if (element is CodeAttribute2) { return new CodeAttributeNodeFactory(element as CodeAttribute2); } if (element is CodeDelegate2) { return new CodeDelegateNodeFactory(element as CodeDelegate2); } if (element is CodeParameter2) { return new CodeParameterNodeFactory(element as CodeParameter2); } if (element is CodeAttributeArgument) { return new CodeAttributeArgumentNodeFactory(element); } if (element is CodeStruct2) { return new CodeStructNodeFactory(element as CodeStruct2); } return new CodeElementNodeFactory(element); }
private static bool IsNamespaceImportPresent(CodeElement codeElement, string productNamespace) { if (codeElement.Kind.Equals(vsCMElement.vsCMElementImportStmt)) { CodeImport codeImport = (CodeImport)codeElement; return String.Equals(codeImport.Namespace, productNamespace, StringComparison.OrdinalIgnoreCase); } return false; }
public CodeDomCodeAttribute(DTE dte, CodeElement parent, string name) : base(dte, name) { this.parent = parent; CodeAttributeDeclaration cad = new CodeAttributeDeclaration(); // !!! name, value CodeObject = cad; }
public CodeElements getCodeElements(CodeElement ce) { if (ce is CodeNamespace) return ((CodeNamespace) ce).Members; if (ce is CodeClass) return ((CodeClass) ce).Members; if (ce is CodeType ) return ((CodeType )ce).Members; if (ce is CodeFunction ) return ((CodeFunction )ce).Parameters ; return null; }
/// <summary> /// Initializes a new instance of the <see cref="LuaCodeVariableTable"/> class. /// </summary> /// <param name="dte"></param> /// <param name="parentElement"></param> /// <param name="name"></param> /// <param name="access"></param> /// <param name="variable"></param> public LuaCodeVariableTable(DTE dte, CodeElement parentElement, string name, vsCMAccess access, TableConstructor variable) : base(dte, parentElement, name, new LuaCodeTypeRef( dte, LuaDeclaredType.Table), access, new Variable(variable.Location) {Identifier = new Identifier(variable.Location)}) { childObjects = new LuaCodeElements(dte, this); astNode = variable; parent = parentElement; }
private static bool IsImportPresentUnderNamespace(CodeElement codeElement, string productNamespace) { foreach (CodeElement codeElementChildren in codeElement.Children) { if (IsNamespaceImportPresent(codeElementChildren, productNamespace)) { return true; } } return false; }
internal Violation(Microsoft.StyleCop.Rule rule, CodeElement element, int line, string message) { this.rule = rule; this.element = element; this.line = line; this.message = message; if ((this.element != null) && (this.element.Document != null)) { this.sourceCode = this.element.Document.SourceCode; } }
internal override CodeElement BuildElement(CodeElement parent) { CodePhysicalFile file = new CodePhysicalFile(this.Name.ToLowerInvariant()); foreach (var child in Children) { var childElement = child.BuildElement(file); file.AddChild(childElement); } return file; }
public static VsInterfaces Parse(CodeElement codeElement) { var vsInterface = new VsInterfaces(); vsInterface.Name = codeElement.Name; foreach (CodeElement element in ((CodeInterface)codeElement).Members) { if (element.Kind == vsCMElement.vsCMElementFunction) { CodeFunction function = element as CodeFunction; vsInterface.Methods.Add(VsMethod.Parse(function)); } } return vsInterface; }
/// <summary> /// Initializes a new instance of the <see cref="FileNamingDialog"/>. /// </summary> /// <param name="sourceCodeFilePath"><see cref="SourceCodeFilePath"/></param> /// <param name="docCommentIncludeFileBasePath"><see cref="DocCommentIncludeFileBasePath"/></param> /// <param name="matchExpression"><see cref="MatchExpression"/></param> /// <param name="replaceExpression"><see cref="ReplaceExpression"/></param> /// <param name="genFileNameHandler"><see cref="OpenSlashDocFileCommand.GenDocFilePathFromCodeFilePathHandler"/></param> /// <param name="codeElement">The current code element being documented.</param> public FileNamingDialog(string sourceCodeFilePath, string docCommentIncludeFileBasePath, string matchExpression, string replaceExpression, CodeElement codeElement, OpenSlashDocFileCommand.GenDocFilePathFromCodeFilePathHandler genFileNameHandler) { InitializeComponent(); _genFileNameHandler = genFileNameHandler; _codeElement = codeElement; this.txtSourceCodeFilePath.Text = sourceCodeFilePath; this.txtMatchExpression.Text = matchExpression; this.txtReplaceExpression.Text = replaceExpression; this.txtDocCommentIncludeFileBasePath.Text = docCommentIncludeFileBasePath; this.txtCurrentMember.Text = codeElement.FullName; _isInitializing = false; UpdateSlashdocFilePath(); }
public UserAlertActionRequired(string message, Type codeElementType, CodeElement ce, ref DTE2 applicationObject, UnitTestCodeType codeType, object testFramework) { InitializeComponent(); ivType = codeElementType; FormCodeElement = ce; FromCodeType = codeType; FormApplicationObject = applicationObject; TestFramework = testFramework; Dictionary<Type, ApplicableAcction>.KeyCollection.Enumerator it = lstApplicableTypes.Keys.GetEnumerator(); while (it.MoveNext()) { Type itemType = it.Current; if (itemType == codeElementType) { ApplicableAcction tvApplicableAcction; lstApplicableTypes.TryGetValue(itemType, out tvApplicableAcction); if (tvApplicableAcction == ApplicableAcction.ignore) { ApplicableAcctionState = ApplicableAcction.ignore; } else if (tvApplicableAcction == ApplicableAcction.mutate) { ApplicableAcctionState = ApplicableAcction.mutate; } else if (tvApplicableAcction == ApplicableAcction.overwrite) { ApplicableAcctionState = ApplicableAcction.overwrite; } this.Close(); return; } } this.txtContent.Text += message; }
/// <summary> /// Finds the conflicts. /// </summary> /// <param name="element">The element.</param> /// <param name="newName">The new name.</param> /// <returns></returns> public override IEnumerable<CodeElement> FindConflicts(CodeElement element, string newName) { CodeConflictType = ConflictType.None; var elements = new List<CodeElement>(); var navigator = new LuaCodeDomNavigator(fileCodeModel); var results = navigator.WalkTopLevelMembers<LuaCodeFunction>(); results.ForEach(item => { if (element != item && newName == item.Name) { elements.Add(item); CodeConflictType = ConflictType.Function; } }); return elements; }
private static VsFile Parse(VsFile vsFile,CodeElement cdElement) { vsFile.Namespaces = cdElement.FullName; foreach (CodeElement codeElement in ((CodeNamespace)cdElement).Members) { if (codeElement.Kind == vsCMElement.vsCMElementClass) { vsFile.Classes.Add(VsClass.Parse(codeElement)); } else if (codeElement.Kind == vsCMElement.vsCMElementInterface) { vsFile.Interfaces.Add(VsInterfaces.Parse(codeElement)); } } return vsFile; }
void GetTopLevelTypeDecls (CodeElement elm, string nsName, Document doc, List<string> usings, List<TypeDecl> decls) { var k = elm.Kind; switch (k) { case vsCMElement.vsCMElementImportStmt: { var cs = ((CodeImport)elm).Namespace; usings.Add ("using " + cs + ";"); } break; case vsCMElement.vsCMElementNamespace: foreach (CodeElement e in elm.Children) { GetTopLevelTypeDecls (e, elm.Name, doc, usings, decls); } break; case vsCMElement.vsCMElementClass: decls.Add (new CodeTypeDecl (elm, nsName, doc, usings.ToArray ())); break; } }
private static void GetFunctionInCurrentPositionImpl(CodeElement element, List<String> functions) { if (element == null) { return; } if (element.Kind == vsCMElement.vsCMElementFunction) { functions.Add(element.FullName); } else if ( element.Kind == vsCMElement.vsCMElementNamespace || element.Kind == vsCMElement.vsCMElementClass || element.Kind == vsCMElement.vsCMElementStruct || element.Kind == vsCMElement.vsCMElementUnion ) { foreach (CodeElement child in element.Children) { GetFunctionInCurrentPositionImpl(child, functions); } } }
/// <summary> /// Find elements in members recursively. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="element">The element.</param> protected virtual void WalkMembers <T>(CodeElement element) { if (element == null) { return; } if (element is T) { if (element != rootElement || (element == rootElement && IncludeSelf)) { codeElements.Add((SimpleCodeElement)element); } } if (element.Children != null) { foreach (CodeElement childElement in element.Children) { WalkMembers <T>(childElement); } } }
/// <summary> /// Returns true if given element is decorated with [Localizable(false)] /// </summary> public static bool HasLocalizableFalseAttribute(this CodeElement element) { if (element == null) { throw new ArgumentNullException("element"); } bool set = false; try { switch (element.Kind) { case vsCMElement.vsCMElementClass: set = AttributesContainLocalizableFalse((element as CodeClass).Attributes); break; case vsCMElement.vsCMElementStruct: set = AttributesContainLocalizableFalse((element as CodeStruct).Attributes); break; case vsCMElement.vsCMElementModule: set = AttributesContainLocalizableFalse((element as CodeClass).Attributes); break; case vsCMElement.vsCMElementProperty: set = AttributesContainLocalizableFalse((element as CodeProperty).Attributes); break; case vsCMElement.vsCMElementFunction: set = AttributesContainLocalizableFalse((element as CodeFunction).Attributes); break; case vsCMElement.vsCMElementVariable: set = AttributesContainLocalizableFalse((element as CodeVariable).Attributes); break; } } catch { } return(set); }
public void AfterFindComponents() { // before finding dependencies, let's find the types that are used to implement each component foreach (Component component in _componentsFound) { foreach (CodeElement codeElement in component.CodeElements) { codeElement.Visibility = _typeRepository.FindVisibility(codeElement.Type); codeElement.Category = _typeRepository.FindCategory(codeElement.Type); } foreach (SupportingTypesStrategy strategy in _supportingTypesStrategies) { foreach (string type in strategy.FindSupportingTypes(component)) { if (ComponentFinder.Container.GetComponentOfType(type) == null) { CodeElement codeElement = component.AddSupportingType(type); codeElement.Visibility = _typeRepository.FindVisibility(type); codeElement.Category = _typeRepository.FindCategory(type); } } } } foreach (Component component in ComponentFinder.Container.Components) { if (component.Type != null) { AddEfferentDependencies(component, component.Type, new HashSet <string>()); // and repeat for the supporting types foreach (CodeElement codeElement in component.CodeElements) { AddEfferentDependencies(component, codeElement.Type, new HashSet <string>()); } } } }
private static void AddListImport(CodeElement currentElement) { if (currentElement is CodeClass currentClass) { var childElements = currentClass.GetChildElements(true); if (childElements.OfType <CodeProperty>().Any(x => x.Type?.CollectionKind == CodeType.CodeTypeCollectionKind.Complex) || childElements.OfType <CodeMethod>().Any(x => x.ReturnType?.CollectionKind == CodeType.CodeTypeCollectionKind.Complex) || childElements.OfType <CodeMethod>().Any(x => x.Parameters.Any(y => y.Type.CollectionKind == CodeType.CodeTypeCollectionKind.Complex))) { var nUsing = new CodeUsing(currentClass) { Name = "List" }; nUsing.Declaration = new CodeType(nUsing) { Name = "java.util", IsExternal = true }; currentClass.AddUsing(nUsing); } } CrawlTree(currentElement, AddListImport); }
private static async Task <CodeElement> GetContainingCodeElementAsync(OmniSharpTestHost host, string filePath, int line, int column) { var codeStructureService = host.GetRequestHandler <CodeStructureService>(OmniSharpEndpoints.V2.CodeStructure); var request = new CodeStructureRequest { FileName = filePath }; var response = await codeStructureService.Handle(request); CodeElement result = null; var elements = response.Elements; while (elements != null) { var stop = true; foreach (var element in elements) { if (element.Ranges[SymbolRangeNames.Full].Contains(line, column)) { result = element; elements = element.Children; stop = false; break; } } if (stop) { break; } } Assert.NotNull(result); return(result); }
/// <summary> /// Generates a doxygen comment block for the given code element. /// </summary> /// <param name="spaces">Indentation for the whole comment block</param> /// <param name="codeElement">The code element.</param> /// <param name="existingComment">Existing comment for the code element. Empty if not found.</param> /// <returns>Generated doxygen comment block</returns> public string GenerateComment(string spaces, CodeElement codeElement, string existingComment) { ThreadHelper.ThrowIfNotOnUIThread(); // Parse existing comment. ParsedComment parsedComment = ParseComment(existingComment); // Start writing a new one. StringBuilder sb = new StringBuilder("/*!"); // Write brief summary. WriteBriefComment(sb, spaces, codeElement, parsedComment); if (codeElement != null) { // Write comments for template parameters, if any. WriteTemplateParamComments(sb, spaces, codeElement, parsedComment); // Write comments for function parameters and return value. if (codeElement is CodeFunction) { CodeFunction function = codeElement as CodeFunction; WriteParamComments(sb, spaces, function, parsedComment); WriteReturnComment(sb, spaces, function, parsedComment); } } // Write other sections that were in the existing comments. foreach (ParsedSection section in parsedComment.TagSections) { string tagLine = m_indentString + Config.TagChar + section.TagName + " "; sb.Append("\r\n" + spaces + " *"); sb.Append("\r\n" + spaces + " * " + tagLine); AppendComments(sb, section.Comments, spaces, tagLine.Length); } sb.Append("\r\n" + spaces + " */"); return(sb.ToString()); }
public static string SetDocComment(this CodeElement codeElement, string docComment) { switch (codeElement.Kind) { case vsCMElement.vsCMElementProperty: (codeElement as CodeProperty).DocComment = docComment; break; case vsCMElement.vsCMElementFunction: (codeElement as CodeFunction).DocComment = docComment; break; case vsCMElement.vsCMElementEnum: (codeElement as CodeEnum).DocComment = docComment; break; case vsCMElement.vsCMElementStruct: (codeElement as CodeStruct).DocComment = docComment; break; case vsCMElement.vsCMElementInterface: (codeElement as CodeInterface).DocComment = docComment; break; case vsCMElement.vsCMElementEvent: (codeElement as CodeEvent).DocComment = docComment; break; case vsCMElement.vsCMElementClass: (codeElement as CodeClass).DocComment = docComment; break; case vsCMElement.vsCMElementVariable: (codeElement as CodeVariable).DocComment = docComment; break; } return(default(string)); }
private void CheckNotInTable(SymbolTable table, SymbolReference symbol, CodeElement ce) { if (symbol == null) { return; } string message = "TCRFUN_NO_PERFORM_OF_ENCLOSING_PROGRAM"; var found = table.GetSection(symbol.Name); if (found.Count > 0) { DiagnosticUtils.AddError(ce, message); } else { var paragraphFounds = table.GetParagraph(symbol.Name); if (paragraphFounds.Count > 0) { DiagnosticUtils.AddError(ce, message); } } }
public void CalcInjectionPoints(CPClassLayout cpClassLayout, CPTraceVar traceVar, bool needDeclare) { if (needDeclare) { // find all places, where this file included CodeElement theFunc = null; // find & store all constructors init points of this class foreach (CodeElement _func in ent.Functions) { if (_func.Name == ent.Name) { theFunc = _func; VCCodeFunction vcFunc = (VCCodeFunction)_func; EditPoint pnt = _func.StartPoint.CreateEditPoint(); if (pnt.FindPattern("{")) { traceVar.traceVarInitPos.Add(new FilePosPnt() { fileName = _func.ProjectItem.Name, pos = { lineNum = pnt.Line - 1, linePos = pnt.LineCharOffset } }); } } } // if no constructor found add default one if (traceVar.traceVarInitPos.Count == 0) { EditPoint pnt = ent.StartPoint.CreateEditPoint(); if (pnt.FindPattern("{")) { traceVar.injConstructorPos = new FilePosPnt() { fileName = ent.ProjectItem.Name, pos = { lineNum = pnt.Line - 1, linePos = pnt.LineCharOffset } }; } } } }
private static T SearchSingleInCodeElement <T>(CodeElement codeElement) { var objCodeNamespace = codeElement as CodeNamespace; var objCodeType = codeElement as CodeType; if (codeElement is T) { return((T)codeElement); } if (objCodeNamespace != null) { return(SearchSingleInCodeElements <T>(objCodeNamespace.Members)); } if (objCodeType != null) { return(SearchSingleInCodeElements <T>(objCodeType.Members)); } return(default(T)); }
private static CodeElements GetCodeElementMembers(CodeElement objCodeElement) { var colCodeElements = default(CodeElements); // ReSharper disable CanBeReplacedWithTryCastAndCheckForNull if (objCodeElement is CodeNamespace) { colCodeElements = ((CodeNamespace)objCodeElement).Members; } else if (objCodeElement is CodeType) { colCodeElements = ((CodeType)objCodeElement).Members; } else if (objCodeElement is CodeFunction) { colCodeElements = ((CodeFunction)objCodeElement).Parameters; } return(colCodeElements); // ReSharper restore CanBeReplacedWithTryCastAndCheckForNull }
public void OnCodeElement(CodeElement e, ParserRuleContext c) { var statement = e as MoveSimpleStatement; if (statement == null) { return; //not our job } var context = c as CodeElementsParser.MoveSimpleContext; if (statement.StorageAreaWrites != null) { for (int i = 0; i < statement.StorageAreaWrites.Count; i++) { var receiver = statement.StorageAreaWrites[i].StorageArea; if (receiver is FunctionCallResult) { DiagnosticUtils.AddError(statement, "MOVE: illegal <function call> after TO", context.storageArea1()[i]); } } } }
public static OperationBase CreateVariableOrOperation(CodeElement elem, Scope scope, DefType resultType, out bool alwaysReturnValue) { alwaysReturnValue = false; OperationBase stm; switch (elem.Name) { case WordVariableDef: stm = CreateVariableDef(elem, scope); break; case WordAssign: stm = CreateAssign(elem, scope); break; case WordIf: stm = CreateIf(elem, scope, resultType, out alwaysReturnValue); break; case WordWhile: case WordLoop: stm = CreateWhile(elem, scope, resultType); break; case WordFuncCall: stm = CreateOperationFuncCall(elem, scope); break; case WordReturn: stm = CreateReturn(elem, scope, resultType); alwaysReturnValue = true; break; default: throw new Exception(string.Format("The operation type '{0}' is not allowed, {1}", elem.Name, elem.GetLineAndColumn())); } return(stm); }
/// <summary> /// Gets the first code element. /// </summary> /// <param name="instance">The instance.</param> /// <returns>The first code element</returns> public static CodeElement GetFirstCodeElement(this ProjectItem instance) { if (instance.FileCodeModel.CodeElements.Count > 0) { CodeElement nameSpaceCodeElement = instance.FileCodeModel.CodeElements.Item(1); if (nameSpaceCodeElement.Kind == vsCMElement.vsCMElementNamespace) { CodeNamespace codeNamespace = nameSpaceCodeElement as CodeNamespace; if (codeNamespace != null) { if (nameSpaceCodeElement.Children.Count > 0) { return(nameSpaceCodeElement.Children.Item(1)); } } } } return(null); }
public void OnCodeElement(CodeElement ce, ParserRuleContext context) { var function = ce as FunctionDeclarationHeader; if (function == null) { return; //not my job } if (function.ActualType == FunctionType.Undefined) { DiagnosticUtils.AddError(ce, "Incompatible parameter clauses for " + ToString(function.UserDefinedType) + " \"" + function.Name + "\"", context); } else if ((function.ActualType == FunctionType.Function && function.UserDefinedType == FunctionType.Procedure) || (function.ActualType == FunctionType.Procedure && function.UserDefinedType == FunctionType.Function)) { var message = "Symbol \"" + function.Name + "\" is defined as " + ToString(function.UserDefinedType) + ", but parameter clauses describe a " + ToString(function.ActualType); DiagnosticUtils.AddError(ce, message, context); } }
private static void ProcessElement(CodeElement element, List<IntellisenseObject> list, HashSet<CodeClass> underProcess) { if (element.Kind == vsCMElement.vsCMElementEnum) { ProcessEnum((CodeEnum)element, list); } else if (element.Kind == vsCMElement.vsCMElementClass) { var cc = (CodeClass)element; // Don't re-generate the intellisense. if (list.Any(x => x.Name == GetClassName(cc) && x.Namespace == GetNamespace(cc))) return; // Collect inherit classes. CodeClass baseClass = null; try { // To recuse from throwing from a weird case // where user inherit class from struct and save. As such inheritance is disallowed. baseClass = cc.Bases.Cast<CodeClass>() .FirstOrDefault(c => c.FullName != "System.Object"); } catch { /* Silently continue. */ } ProcessClass(cc, baseClass, list, underProcess); var references = new HashSet<string>(); // Process Inheritence. if (baseClass != null && !underProcess.Contains(baseClass) && !HasIntellisense(baseClass.ProjectItem, Ext.TypeScript, references)) { list.Last().UpdateReferences(references); underProcess.Add(baseClass); list.AddRange(ProcessFile(baseClass.ProjectItem, underProcess)); } } }
private void CheckParameter([NotNull] ParameterDescriptionEntry parameter, CodeElement ce, ParserRuleContext context, Node node) { // TCRFUN_LEVEL_88_PARAMETERS if (parameter.LevelNumber.Value != 1) { DiagnosticUtils.AddError(ce, "Condition parameter \"" + parameter.Name + "\" must be subordinate to another parameter.", context); } if (parameter.DataConditions != null) { foreach (var condition in parameter.DataConditions) { if (condition.LevelNumber.Value != 88) { DiagnosticUtils.AddError(ce, "Condition parameter \"" + condition.Name + "\" must be level 88."); } } } var type = parameter.DataType; TypeDefinitionHelper.Check(node, type); //Check if the type exists and is not ambiguous }
public void VerfiyInitializationOfPropertyGenerator() { CodeElement[] codeElements = new CodeElement[] { new MockedCodeVariable2("variable2", vsCMAccess.vsCMAccessPrivate), new MockedCodeElement("testElement"), new MockedCodeVariable2("variable1", vsCMAccess.vsCMAccessPrivate), new MockedCodeVariable2("_variable3", vsCMAccess.vsCMAccessPrivate), new MockedCodeVariable2("m_aprefixedvariable", vsCMAccess.vsCMAccessPrivate), }; MockedCodeClass2 mockedCodeClass = new MockedCodeClass2(codeElements); PropertyGenerator propertyGenerator = new PropertyGenerator(mockedCodeClass); Assert.IsFalse(propertyGenerator.GenerateComments); Assert.AreSame(mockedCodeClass, propertyGenerator.CodeClass); Assert.AreEqual(4, propertyGenerator.Properties.Length); Assert.AreEqual("Aprefixedvariable", propertyGenerator.Properties[0].Name); Assert.AreEqual("Variable1", propertyGenerator.Properties[1].Name); Assert.AreEqual("Variable2", propertyGenerator.Properties[2].Name); Assert.AreEqual("Variable3", propertyGenerator.Properties[3].Name); }
/// <summary> /// Get TypeDescriptor defined by given element. /// </summary> /// <param name="element">Element which type will be resolved.</param> /// <returns>Result type fullname of given element.</returns> public static TypeDescriptor ResolveType(this CodeElement element) { if (element == null) { return(null); } try { CodeTypeRef typeRef; switch (element.Kind) { case vsCMElement.vsCMElementFunction: typeRef = (element as CodeFunction).Type; break; case vsCMElement.vsCMElementParameter: typeRef = (element as CodeParameter).Type; break; case vsCMElement.vsCMElementVariable: typeRef = (element as CodeVariable).Type; break; case vsCMElement.vsCMElementProperty: typeRef = (element as CodeProperty).Type; break; default: throw new NotSupportedException("This element is not supported for type resolving"); } return(resolveTypeRef(typeRef)); } catch (COMException) { return(null); } }
public static ExpressionBase BuildExp(CodeElement elem) { if (elem == null) { throw new Exception("Missing expression element"); } switch (elem.Name) { case "power": return(new Power(elem)); case "mul": return(new Multiply(elem)); case "div": return(new Divide(elem)); case "sum": return(new Sum(elem)); case "sub": return(new Minus(elem)); case "number": case "int": return(new Number(elem)); case "exp": return(BuildExp(elem.Codes().FirstOrDefault())); case "par": return(BuildExp(elem.Codes().FirstOrDefault())); default: throw new Exception(string.Format("Unknown expression element: '{0}'", elem.Name)); } }
/// <summary> /// Moves using statements to a given set of insertion points. /// </summary> /// <param name="fileCodeModel">The code model to search.</param> /// <param name="insertionPoints">The insertion points to use.</param> private void MoveUsingStatements(FileCodeModel fileCodeModel, List <EditPoint> insertionPoints) { List <string> usingStatements = new List <string>(); for (int i = 1; i <= fileCodeModel.CodeElements.Count; i++) { CodeElement element = fileCodeModel.CodeElements.Item(i); if (element.Kind == vsCMElement.vsCMElementImportStmt) { EditPoint usingStart = element.StartPoint.CreateEditPoint(); string statement = usingStart.GetText(element.EndPoint); usingStatements.Add(statement); usingStart.Delete(element.EndPoint); usingStart.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); i--; } } for (int i = 0; i < insertionPoints.Count; i++) { EditPoint origin = insertionPoints[i].CreateEditPoint(); if (usingStatements.Count > 0) { origin.Insert("\r\n"); for (int j = 0; j < usingStatements.Count; j++) { origin.Insert(usingStatements[j] + "\r\n"); } } origin.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); if (usingStatements.Count > 0) { origin.Insert("\r\n"); } } }
public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as Coding; if (dest != null) { base.CopyTo(dest); if (SystemElement != null) { dest.SystemElement = (Hl7.Fhir.Model.FhirUri)SystemElement.DeepCopy(); } if (VersionElement != null) { dest.VersionElement = (Hl7.Fhir.Model.FhirString)VersionElement.DeepCopy(); } if (CodeElement != null) { dest.CodeElement = (Hl7.Fhir.Model.Code)CodeElement.DeepCopy(); } if (DisplayElement != null) { dest.DisplayElement = (Hl7.Fhir.Model.FhirString)DisplayElement.DeepCopy(); } if (PrimaryElement != null) { dest.PrimaryElement = (Hl7.Fhir.Model.FhirBoolean)PrimaryElement.DeepCopy(); } if (ValueSet != null) { dest.ValueSet = (Hl7.Fhir.Model.ResourceReference)ValueSet.DeepCopy(); } return(dest); } else { throw new ArgumentException("Can only copy to an object of the same type", "other"); } }
private static bool IsElementCorrect(CodeElement element, int startLine, int endLine, bool isCSharp) { if (element == null) { return(false); } try { if (element.StartPoint.Line > endLine) { return(false); } } catch (Exception ex) { //element.StartPoint not implemented in VS2017 15.2 (26430.6) for expression bodied property getters (before no getter element was available) System.Diagnostics.Debug.Print("### Error: ParseForStrings({0}): element.StartPoint.Line > endLine? {1} - {2}", element.Kind, ex.GetType().Name, ex.Message); return(false); } try { if (element.EndPoint.Line < startLine) { return(false); } } catch (Exception ex) { //element.EndPoint invalid when deleting or cutting text System.Diagnostics.Debug.Print("### Error: ParseForStrings(): element.EndPoint < startLine? {0} - {1}", ex.GetType().Name, ex.Message); return(false); } return(true); }
/// <summary> /// Returns the description of the specified CodeElement. /// </summary> /// <param name="element">CodeElement instance.</param> /// <returns>Name of CodeElement.Kind.</returns> private static string GetElementTypeDescription(CodeElement element) { string name = string.Empty; string prefix = string.Empty; if (element is IDeclarationCodeElement) { vsCMAccess access = ((IDeclarationCodeElement)element).Access; prefix = access == vsCMAccess.vsCMAccessPrivate ? "local " : string.Empty; } if (element != null) { switch (element.Kind) { case vsCMElement.vsCMElementDefineStmt: case vsCMElement.vsCMElementDeclareDecl: case vsCMElement.vsCMElementLocalDeclStmt: { name = "variable"; break; } case vsCMElement.vsCMElementFunctionInvokeStmt: case vsCMElement.vsCMElementFunction: { name = "function"; break; } case vsCMElement.vsCMElementMap: { name = "table"; break; } } } return(String.Format("Rename {0}{1}", prefix, name)); }
private static void LoadCodeElement(CodeElement element, Snippet snippet) { if (element.Delimiter?.Length == 1) { snippet.Delimiter = element.Delimiter[0]; } if (element.Kind != null && ContextKinds.TryGetValue(element.Kind, out ContextKind kind)) { snippet.ContextKind = kind; } if (element.Language != null) { snippet.Language = LanguageMapper.MapTextToEnum(element.Language); } if (element.Code != null) { snippet.CodeText = element.Code; } }
// recursively examine code elements private void ExamineCodeElement(CodeElement codeElement, int tabs) { tabs++; try { Console.WriteLine(new string('\t', tabs) + "{0} {1}", codeElement.Name, codeElement.Kind.ToString()); // if this is a namespace, add a class to it. if (codeElement.Kind == vsCMElement.vsCMElementNamespace) { //AddClassToNamespace((CodeNamespace)codeElement); } foreach (CodeElement childElement in codeElement.Children) { ExamineCodeElement(childElement, tabs); } } catch { Console.WriteLine(new string('\t', tabs) + "codeElement without name: {0}", codeElement.Kind.ToString()); } }
public void DeleteElement(object parent, CodeElement element) { if (element is VCCodeClass || element is VCCodeStruct) { TreeNode node = FindNodeForTestSuite(element); if (node != null) { node.Remove(); } } else if (element is VCCodeFunction) { VCCodeFunction function = (VCCodeFunction)element; TreeNode node = FindNodeForTestCase(parent, function); if (node != null) { node.Remove(); } } }
private static List <T> SearchInCodeElement <T>(CodeElement codeElement) { List <T> list = new List <T>(); var objCodeNamespace = codeElement as CodeNamespace; var objCodeType = codeElement as CodeType; if (codeElement is T) { list.Add((T)codeElement); } if (objCodeNamespace != null) { list.AddRange(SearchInCodeElements <T>(objCodeNamespace.Members)); } if (objCodeType != null) { list.AddRange(SearchInCodeElements <T>(objCodeType.Members)); } return(list); }
private void btOk_Click(object sender, System.EventArgs e) { ListItemData data = listView.SelectedData; if (data == null) { return; } if (!(data.Datas[2] is CodeElement)) { return; } CodeElement el = (CodeElement)data.Datas[2]; TextSelection ts = VSExpertVSIX.SolutionList.DTE.ActiveDocument.Selection as TextSelection; if (ts != null) { ts.MoveToPoint(el.StartPoint, false); } }
/// internal static bool BuildRules(Parser parser, CodeDocument doc, ParserStatus status) { parser.Rules = new List <Rule>(); foreach (CodeElement ruleElement in doc.Codes(MetaParser.Rule_______)) { string debug1 = "(" + parser.Name + ")".NL() + ruleElement.ToMarkupProtected(""); List <CodeElement> ruleElements = ruleElement.Codes().ToList(); CodeElement elementId = ruleElements.First(); ruleElements.Remove(elementId); List <ParserElementBase> elements = BuildExpression(parser, ruleElements, status); Rule rule = AddRule(parser, elementId, elements.ToArray()); string debug2 = debug1 + rule.GetGrammar(); } parser.Rules[0].Comment = true; return(ApplySettingsFromGrammar(parser, doc, status) && InitializeGrammar(parser, parser.Rules, status) && ValidateGrammar(parser, status)); }
/// <summary> /// Rename LuaCodeFunction in scope of parentElement. /// </summary> /// <param name="parentElement">Containing element. (LuaCodeClass)</param> /// <param name="oldName">Old name of element.</param> /// <param name="newName">New name of element.</param> private bool RenameFunctionCalls(CodeElement parentElement, string oldName, string newName) { bool result = true; var navigator = new LuaCodeDomNavigator(parentElement); codeElements = new List <SimpleCodeElement>(navigator.WalkMembers <LuaCodeElement <FunctionCall> >()); codeElements.ForEach(funcCallElement => { if (funcCallElement.Children != null) { LuaCodeElement <Identifier> identifier = funcCallElement.Children.OfType <LuaCodeElement <Identifier> >() .FirstOrDefault(); if (identifier.Name == oldName) { identifier.RenameSymbol(newName); changedCodeElements.Add(identifier); } } funcCallElement.Name = newName; }); return(result); }
/// <summary> /// Calculates the complexity of the given element. /// </summary> /// <param name="element">The code element to examine.</param> /// <returns>The calculated complexity.</returns> internal static int CalculateComplexity(CodeElement element) { EditPoint startPoint = element.StartPoint.CreateEditPoint(); string functionText = startPoint.GetText(element.EndPoint); // Rip out single line comments. functionText = Regex.Replace(functionText, @"//.*" + Environment.NewLine, Environment.NewLine); // Rip out multi-line comments. functionText = Regex.Replace(functionText, @"/\*.*\*/", String.Empty, RegexOptions.Singleline); // Rip out strings. functionText = Regex.Replace(functionText, @"""[^""]*""", String.Empty); // Rip out characters. functionText = Regex.Replace(functionText, @"'[^']*'", String.Empty); int ifCount = Regex.Matches(functionText, @"\sif[\s\(]").Count; int elseCount = Regex.Matches(functionText, @"\selse\s").Count; int elseIfCount = Regex.Matches(functionText, @"\selse if[\s\(]").Count; int whileCount = Regex.Matches(functionText, @"\swhile[\s\(]").Count; int forCount = Regex.Matches(functionText, @"\sfor[\s\(]").Count; int forEachCount = Regex.Matches(functionText, @"\sforeach[\s\(]").Count; int switchCount = Regex.Matches(functionText, @"\sswitch[\s\(]").Count; int caseCount = Regex.Matches(functionText, @"\scase\s[^;]*;").Count; int catchCount = Regex.Matches(functionText, @"\scatch[\s\(]").Count; int tertiaryCount = Regex.Matches(functionText, @"\s\?\s").Count; int andCount = Regex.Matches(functionText, @"\&\&").Count; int orCount = Regex.Matches(functionText, @"\|\|").Count; int complexity = 1 + ifCount + elseCount - elseIfCount + // else if will have been counted twice already by 'if' and 'else' whileCount + forCount + forEachCount + switchCount + caseCount + catchCount + tertiaryCount + andCount + orCount; return complexity; }