Пример #1
0
        public static IEnumerable <Member> GetMembers(this CodeModule module, vbext_ProcKind?procedureKind = null)
        {
            var currentLine = module.CountOfDeclarationLines + 1;

            while (currentLine < module.CountOfLines)
            {
                vbext_ProcKind kind;
                var            name = module.get_ProcOfLine(currentLine, out kind);

                if ((procedureKind ?? kind) == kind)
                {
                    var startLine = module.get_ProcStartLine(name, kind);
                    var lineCount = module.get_ProcCountLines(name, kind);

                    var body = module.Lines[startLine, lineCount].Split('\n');

                    Member member;
                    if (Member.TryParse(body, new QualifiedModuleName(module.Parent), out member))
                    {
                        yield return(member);

                        currentLine = startLine + lineCount;
                    }
                    else
                    {
                        currentLine = currentLine + 1;
                    }
                }
            }
        }
Пример #2
0
        List <CodeModule> _Items;                        // list of code module

        internal CodeModules(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p)
        {
            _Items = new List <CodeModule>();
            // Loop thru all the child nodes
            foreach (XmlNode xNodeLoop in xNode.ChildNodes)
            {
                if (xNodeLoop.NodeType != XmlNodeType.Element)
                {
                    continue;
                }
                if (xNodeLoop.Name == "CodeModule")
                {
                    CodeModule cm = new CodeModule(r, this, xNodeLoop);
                    _Items.Add(cm);
                }
                else
                {
                    // don't know this element - log it
                    OwnerReport.rl.LogError(4, "Unknown CodeModules element '" + xNodeLoop.Name + "' ignored.");
                }
            }
            if (_Items.Count == 0)
            {
                OwnerReport.rl.LogError(8, "For CodeModules at least one CodeModule is required.");
            }
            else
            {
                _Items.TrimExcess();
            }
        }
        private void RewriteCall(VBAParser.ArgsCallContext paramList, CodeModule module)
        {
            var paramNames = paramList.argCall().Select(arg => arg.GetText()).ToList();
            var lineCount  = paramList.Stop.Line - paramList.Start.Line + 1; // adjust for total line count

            var newContent = module.Lines[paramList.Start.Line, lineCount].Replace(" _" + Environment.NewLine, string.Empty).RemoveExtraSpacesLeavingIndentation();

            var parameterIndex     = 0;
            var currentStringIndex = 0;

            for (var i = 0; i < paramNames.Count && parameterIndex < _model.Parameters.Count; i++)
            {
                var parameterStringIndex = newContent.IndexOf(paramNames.ElementAt(i), currentStringIndex, StringComparison.Ordinal);

                if (parameterStringIndex <= -1)
                {
                    continue;
                }

                var oldParameterString = paramNames.ElementAt(i);
                var newParameterString = paramNames.ElementAt(_model.Parameters.ElementAt(parameterIndex).Index);
                var beginningSub       = newContent.Substring(0, parameterStringIndex);
                var replaceSub         = newContent.Substring(parameterStringIndex).Replace(oldParameterString, newParameterString);

                newContent = beginningSub + replaceSub;

                parameterIndex++;
                currentStringIndex = beginningSub.Length + newParameterString.Length;
            }

            module.ReplaceLine(paramList.Start.Line, newContent);
            module.DeleteLines(paramList.Start.Line + 1, lineCount - 1);
        }
Пример #4
0
        private void FixTypeHintUsage(string hint, CodeModule module, Selection selection, bool isDeclaration = false)
        {
            var line = module.Lines[selection.StartLine, 1];

            var asTypeClause = ' ' + Tokens.As + ' ' + TypeHints[hint];

            string fix;

            if (isDeclaration && (Context is VBAParser.FunctionStmtContext || Context is VBAParser.PropertyGetStmtContext))
            {
                var typeHint  = (ParserRuleContext)Context.children.First(c => c is VBAParser.TypeHintContext);
                var argList   = (ParserRuleContext)Context.children.First(c => c is VBAParser.ArgListContext);
                var endLine   = argList.Stop.Line;
                var endColumn = argList.Stop.Column;

                var oldLine = module.Lines[endLine, selection.LineCount];
                fix = oldLine.Insert(endColumn + 1, asTypeClause).Remove(typeHint.Start.Column, 1);  // adjust for VBA 0-based indexing

                module.ReplaceLine(endLine, fix);
            }
            else
            {
                var pattern = "\\b" + _declaration.IdentifierName + "\\" + hint;
                fix = Regex.Replace(line, pattern, _declaration.IdentifierName + (isDeclaration ? asTypeClause : string.Empty));
                module.ReplaceLine(selection.StartLine, fix);
            }
        }
        private void FixTypeHintUsage(string hint, CodeModule module, Selection selection, bool isDeclaration = false)
        {
            var line = module.Lines[selection.StartLine, 1];

            var asTypeClause = ' ' + Tokens.As + ' ' + TypeHints[hint];

            string fix;

            if (isDeclaration && (Context is VBAParser.FunctionStmtContext || Context is VBAParser.PropertyGetStmtContext))
            {
                var typeHint = (ParserRuleContext)Context.children.First(c => c is VBAParser.TypeHintContext);
                var argList = (ParserRuleContext) Context.children.First(c => c is VBAParser.ArgListContext);
                var endLine = argList.Stop.Line;
                var endColumn = argList.Stop.Column;

                var oldLine = module.Lines[endLine, selection.LineCount];
                fix = oldLine.Insert(endColumn + 1, asTypeClause).Remove(typeHint.Start.Column, 1);  // adjust for VBA 0-based indexing

                module.ReplaceLine(endLine, fix);
            }
            else
            {
                var pattern = "\\b" + _declaration.IdentifierName + "\\" + hint;
                fix = Regex.Replace(line, pattern, _declaration.IdentifierName + (isDeclaration ? asTypeClause : string.Empty));
                module.ReplaceLine(selection.StartLine, fix);
            }
        }
Пример #6
0
        /// <summary>
        /// 获取项目代码输出文件名
        /// </summary>
        public string GetCodeFileName(CodeModule module)
        {
            string fileName = OutputFileFormat.Replace("{Project.NamespacePrefix}", module.Project.NamespacePrefix)
                              .Replace("{Module.Name:Lower}", module.Name.UpperToLowerAndSplit())
                              .Replace("{Module.Name}", module.Name);

            return(fileName);
        }
Пример #7
0
        public static QualifiedSelection?GetSelection(this CodeModule module)
        {
            var selection = module.CodePane.GetSelection();

            return(selection.HasValue
                ? new QualifiedSelection(new QualifiedModuleName(module.Parent), selection.Value)
                : new QualifiedSelection?());
        }
Пример #8
0
 public CodeModuleWrapper(CodeModule codeModule)
 {
     if (codeModule == null)
     {
         throw new ArgumentNullException("CodeModule cannot be null");
     }
     this._codeModule = codeModule;
 }
Пример #9
0
        public static ModuleViewModel ToViewModel(this CodeModule module, ProjectViewModel projectModel = null)
        {
            ModuleViewModel model = IoC.Get <ModuleViewModel>();

            model         = module.MapTo(model);
            model.Project = projectModel;
            return(model);
        }
        private void RemoveCallParameter(VBAParser.ArgsCallContext paramList, CodeModule module)
        {
            var paramNames = paramList.argCall().Select(arg => arg.GetText()).ToList();
            var lineCount  = paramList.Stop.Line - paramList.Start.Line + 1; // adjust for total line count

            var newContent         = module.Lines[paramList.Start.Line, lineCount].Replace(" _", "").RemoveExtraSpaces();
            var currentStringIndex = 0;

            foreach (
                var param in
                _model.Parameters.Where(item => item.IsRemoved && item.Index < paramNames.Count)
                .Select(item => item.Declaration))
            {
                var paramIndex = _model.Parameters.FindIndex(item => item.Declaration.Context.GetText() == param.Context.GetText());
                if (paramIndex >= paramNames.Count)
                {
                    return;
                }

                do
                {
                    var paramToRemoveName = paramNames.ElementAt(0).Contains(":=")
                        ? paramNames.Find(item => item.Contains(param.IdentifierName + ":="))
                        : paramNames.ElementAt(paramIndex);

                    if (paramToRemoveName == null || !newContent.Contains(paramToRemoveName))
                    {
                        continue;
                    }

                    var valueToRemove = paramToRemoveName != paramNames.Last()
                        ? paramToRemoveName + ","
                        : paramToRemoveName;

                    var parameterStringIndex = newContent.IndexOf(valueToRemove, currentStringIndex, StringComparison.Ordinal);
                    if (parameterStringIndex <= -1)
                    {
                        continue;
                    }

                    newContent = newContent.Remove(parameterStringIndex, valueToRemove.Length);

                    currentStringIndex = parameterStringIndex;

                    if (paramToRemoveName == paramNames.Last() && newContent.LastIndexOf(',') != -1)
                    {
                        newContent = newContent.Remove(newContent.LastIndexOf(','), 1);
                    }
                } while (paramIndex >= _model.Parameters.Count - 1 && ++paramIndex < paramNames.Count &&
                         newContent.Contains(paramNames.ElementAt(paramIndex)));
            }

            module.ReplaceLine(paramList.Start.Line, newContent);
            for (var line = paramList.Start.Line + 1; line < paramList.Start.Line + lineCount; line++)
            {
                module.ReplaceLine(line, "");
            }
        }
        private void RewriteCall(VBAParser.ArgumentListContext paramList, CodeModule module)
        {
            List <string> paramNames = new List <string>();

            if (paramList.positionalOrNamedArgumentList().positionalArgumentOrMissing() != null)
            {
                paramNames.AddRange(paramList.positionalOrNamedArgumentList().positionalArgumentOrMissing().Select(p =>
                {
                    if (p is VBAParser.SpecifiedPositionalArgumentContext)
                    {
                        return(((VBAParser.SpecifiedPositionalArgumentContext)p).positionalArgument().GetText());
                    }
                    else
                    {
                        return(string.Empty);
                    }
                }).ToList());
            }
            if (paramList.positionalOrNamedArgumentList().namedArgumentList() != null)
            {
                paramNames.AddRange(paramList.positionalOrNamedArgumentList().namedArgumentList().namedArgument().Select(p => p.GetText()).ToList());
            }
            if (paramList.positionalOrNamedArgumentList().requiredPositionalArgument() != null)
            {
                paramNames.Add(paramList.positionalOrNamedArgumentList().requiredPositionalArgument().GetText());
            }

            var lineCount = paramList.Stop.Line - paramList.Start.Line + 1; // adjust for total line count

            var newContent = module.Lines[paramList.Start.Line, lineCount].Replace(" _" + Environment.NewLine, string.Empty).RemoveExtraSpacesLeavingIndentation();

            var parameterIndex     = 0;
            var currentStringIndex = 0;

            for (var i = 0; i < paramNames.Count && parameterIndex < _model.Parameters.Count; i++)
            {
                var parameterStringIndex = newContent.IndexOf(paramNames.ElementAt(i), currentStringIndex, StringComparison.Ordinal);

                if (parameterStringIndex <= -1)
                {
                    continue;
                }

                var oldParameterString = paramNames.ElementAt(i);
                var newParameterString = paramNames.ElementAt(_model.Parameters.ElementAt(parameterIndex).Index);
                var beginningSub       = newContent.Substring(0, parameterStringIndex);
                var replaceSub         = newContent.Substring(parameterStringIndex).Replace(oldParameterString, newParameterString);

                newContent = beginningSub + replaceSub;

                parameterIndex++;
                currentStringIndex = beginningSub.Length + newParameterString.Length;
            }

            module.ReplaceLine(paramList.Start.Line, newContent);
            module.DeleteLines(paramList.Start.Line + 1, lineCount - 1);
        }
Пример #12
0
        /// <summary>
        /// Returns all of the code in a Module as a string.
        /// </summary>
        public static string Lines(this CodeModule module)
        {
            if (module.CountOfLines == 0)
            {
                return(string.Empty);
            }

            return(module.Lines[1, module.CountOfLines]);
        }
        /// <summary>重写以提供要初始化的种子数据</summary>
        /// <returns></returns>
        protected override CodeEntity[] SeedData(IServiceProvider provider)
        {
            IRepository <CodeModule, Guid> repository = provider.GetRequiredService <IRepository <CodeModule, Guid> >();
            CodeModule        module   = repository.GetFirst(m => m.Name == "Identity");
            List <CodeEntity> entities = new List <CodeEntity>()
            {
                new CodeEntity()
                {
                    Name               = "User", Display = "用户", Order = 1, PrimaryKeyTypeFullName = "System.Int32", Listable = true, Addable = true,
                    Updatable          = true, Deletable = true, IsDataAuth = true, HasLocked = true, HasSoftDeleted = true, HasCreatedTime = true,
                    HasCreationAudited = true, HasUpdateAudited = true, ModuleId = module.Id
                },
                new CodeEntity()
                {
                    Name      = "Role", Display = "角色", Order = 2, PrimaryKeyTypeFullName = "System.Int32", Listable = true, Addable = true,
                    Updatable = true, Deletable = true, IsDataAuth = true, HasLocked = true, HasSoftDeleted = true, HasCreatedTime = true,
                    ModuleId  = module.Id
                },
                new CodeEntity()
                {
                    Name     = "UserRole", Display = "用户角色", Order = 3, PrimaryKeyTypeFullName = "System.Int32",
                    Listable = true, Updatable = true, ModuleId = module.Id
                },
            };

            module = repository.GetFirst(m => m.Name == "Auth");
            entities.AddRange(new List <CodeEntity>()
            {
                new CodeEntity()
                {
                    Name = "Module", Display = "模块", Order = 1, PrimaryKeyTypeFullName = "System.Int32", ModuleId = module.Id
                },
                new CodeEntity()
                {
                    Name = "Function", Display = "功能", Order = 2, PrimaryKeyTypeFullName = "System.Guid", ModuleId = module.Id
                },
                new CodeEntity()
                {
                    Name = "EntityInfo", Display = "实体", Order = 3, PrimaryKeyTypeFullName = "System.Guid", ModuleId = module.Id
                },
            });

            module = repository.GetFirst(m => m.Name == "Infos");
            entities.AddRange(new List <CodeEntity>()
            {
                new CodeEntity()
                {
                    Name = "Article", Display = "文章", Order = 1, PrimaryKeyTypeFullName = "System.Int32", ModuleId = module.Id
                },
                new CodeEntity()
                {
                    Name = "Message", Display = "站内信", Order = 2, PrimaryKeyTypeFullName = "System.Guid", ModuleId = module.Id
                }
            });

            return(entities.ToArray());
        }
Пример #14
0
        /// <summary>
        /// Creates a new <see cref="Mock{VBComponent}"/>.
        /// </summary>
        /// <param name="name">The name to return from the <see cref="VBComponent.Name"/> property.</param>
        /// <param name="codeModule">The <see cref="CodeModule"/> to return from the CodeModule property.</param>
        /// <param name="componentType">
        /// The type of component to be simulated.
        /// Use vbext_ct_StdModule for standard modules.
        /// Use vbext_ct_ClassModule for classes.
        /// vbext_ct_ActiveXDesigner is invalid for the VBE.
        /// </param>
        /// <returns></returns>
        internal static Mock <VBComponent> CreateComponentMock(string name, CodeModule codeModule, vbext_ComponentType componentType)
        {
            var component = new Mock <VBComponent>();

            component.SetupProperty(c => c.Name, name);
            component.SetupGet(c => c.CodeModule).Returns(codeModule);
            component.SetupGet(c => c.Type).Returns(componentType);
            return(component);
        }
Пример #15
0
        private void FixTypeHintUsage(string hint, CodeModule module, Selection selection, bool isDeclaration = false)
        {
            var line = module.get_Lines(selection.StartLine, 1);

            var asTypeClause = ' ' + Tokens.As + ' ' + TypeHints[hint];
            var pattern      = "\\b" + _declaration.IdentifierName + "\\" + hint;
            var fix          = Regex.Replace(line, pattern, _declaration.IdentifierName + (isDeclaration ? asTypeClause : string.Empty));

            module.ReplaceLine(selection.StartLine, fix);
        }
        private void FixTypeHintUsage(string hint, CodeModule module, Selection selection, bool isDeclaration = false)
        {
            var line = module.get_Lines(selection.StartLine, 1);

            var asTypeClause = ' ' + Tokens.As + ' ' + TypeHints[hint];
            var pattern = "\\b" + _declaration.IdentifierName + "\\" + hint;
            var fix = Regex.Replace(line, pattern, _declaration.IdentifierName + (isDeclaration ? asTypeClause : string.Empty));

            module.ReplaceLine(selection.StartLine, fix);
        }
Пример #17
0
        public static bool HasAttribute(this CodeModule code, string name)
        {
            if (code.CountOfDeclarationLines == 0)
            {
                return(false);
            }
            var moduleAttributes = MemberAttribute.GetAttributes(code.Lines[1, code.CountOfDeclarationLines].Split('\n'));

            return(moduleAttributes.Any(attribute => attribute.Name == name));
        }
Пример #18
0
        /// <summary>
        /// Creates a new <see cref="Mock{VBComponent}"/>.
        /// </summary>
        /// <param name="name">The name to return from the <see cref="VBComponent.Name"/> property.</param>
        /// <param name="codeModule">The <see cref="CodeModule"/> to return from the CodeModule property.</param>
        /// <param name="componentType">
        /// The type of component to be simulated.
        /// Use vbext_ct_StdModule for standard modules.
        /// Use vbext_ct_ClassModule for classes.
        /// vbext_ct_ActiveXDesigner is invalid for the VBE.
        /// </param>
        /// <returns></returns>
        internal static Mock <VBComponent> CreateComponentMock(string name, CodeModule codeModule, vbext_ComponentType componentType, Mock <VBE> vbe)
        {
            var component = new Mock <VBComponent>();

            component.SetupProperty(m => m.Name, name);
            component.SetupGet(m => m.CodeModule).Returns(codeModule);
            component.SetupGet(m => m.Type).Returns(componentType);
            component.SetupGet(m => m.VBE).Returns(vbe.Object);
            return(component);
        }
Пример #19
0
        public IntPtr WindowProc(IntPtr hwnd, uint msg, IntPtr WParam, IntPtr LParam)
        {
            // WM_CHAR
            if (msg == 0x102)
            {
                int chr = WParam.ToInt32();

                if (chr == '\x9')
                {
                    //MessageBox.Show("Tab", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    int x, y, w, h;
                    _vbe.ActiveCodePane.GetSelection(out x, out y, out h, out w);

                    Debug.WriteLine(String.Format("x : {0}, y : {1}, h : {2}, w : {3}", x, y, h, w));
                    CodeModule cm   = _vbe.ActiveCodePane.CodeModule;
                    string     line = cm.Lines[x, 1];
                    Debug.WriteLine("the code :" + line);

                    line = line.TrimEnd();

                    string token = findTokenReverse(line);

                    if (token == "if")
                    {
                        // paste if stat
                        line = line.Substring(0, line.Length - 2);
                        String[] strs = new String[3];
                        var      l    = line.Length;

                        strs[0] = line + "If    Then";
                        strs[1] = "";
                        strs[2] = new String(' ', line.Length) + "End If";

                        cm.DeleteLines(x);
                        cm.InsertLines(x, String.Join("\r\n", strs));

                        // set pos
                        _vbe.ActiveCodePane.SetSelection(x, y, h, w);
                    }
                }

                Debug.WriteLine("the chr : " + Convert.ToChar(chr));
            }

            if (msg == 0x14)
            {
                Debug.WriteLine("EraseBackgroud");
            }

            if (msg == 0x85)
            {
                Debug.WriteLine("NC PAINT");
            }
            return(NativeMethods.CallWindowProc(oldProc, hwnd, msg, WParam, LParam));
        }
        public override void Fix()
        {
            dynamic functionContext    = Context as VBAParser.FunctionStmtContext;
            dynamic propertyGetContext = Context as VBAParser.PropertyGetStmtContext;

            var context = functionContext ?? propertyGetContext;

            if (context == null)
            {
                throw new InvalidOperationException(string.Format(InspectionsUI.InvalidContextTypeInspectionFix, Context.GetType(), GetType()));
            }


            VBAParser.FunctionNameContext functionName = null;
            if (Context is VBAParser.FunctionStmtContext)
            {
                functionName = ((VBAParser.FunctionStmtContext)Context).functionName();
            }
            else
            {
                functionName = ((VBAParser.PropertyGetStmtContext)Context).functionName();
            }

            string token = functionContext != null
                ? Tokens.Function
                : Tokens.Property + ' ' + Tokens.Get;
            string endToken = token == Tokens.Function
                ? token
                : Tokens.Property;

            string visibility  = context.visibility() == null ? string.Empty : context.visibility().GetText() + ' ';
            string name        = ' ' + Identifier.GetName(functionName.identifier());
            bool   hasTypeHint = Identifier.GetTypeHintValue(functionName.identifier()) != null;

            string args   = context.argList().GetText();
            string asType = context.asTypeClause() == null ? string.Empty : ' ' + context.asTypeClause().GetText();

            string oldSignature = visibility + token + name + (hasTypeHint ? Identifier.GetTypeHintValue(functionName.identifier()) : string.Empty) + args + asType;
            string newSignature = visibility + Tokens.Sub + name + args;

            string procedure          = Context.GetText();
            string noReturnStatements = procedure;

            _returnStatements.ToList().ForEach(returnStatement =>
                                               noReturnStatements = Regex.Replace(noReturnStatements, @"[ \t\f]*" + returnStatement + @"[ \t\f]*\r?\n?", ""));
            string result = noReturnStatements.Replace(oldSignature, newSignature)
                            .Replace(Tokens.End + ' ' + endToken, Tokens.End + ' ' + Tokens.Sub)
                            .Replace(Tokens.Exit + ' ' + endToken, Tokens.Exit + ' ' + Tokens.Sub);

            CodeModule module    = Selection.QualifiedName.Component.CodeModule;
            Selection  selection = Context.GetSelection();

            module.DeleteLines(selection.StartLine, selection.LineCount);
            module.InsertLines(selection.StartLine, result);
        }
Пример #21
0
        /// <summary>
        /// Gets an array of strings where each element is a line of code in the Module.
        /// </summary>
        public static string[] Code(this CodeModule module)
        {
            var lines = module.CountOfLines;

            if (lines == 0)
            {
                return(new string[] { });
            }

            return(module.get_Lines(1, lines).Replace("\r", string.Empty).Split('\n'));
        }
Пример #22
0
        private static bool HasCode(CodeModule module)
        {
            for (var i = 0; i < module.CountOfLines; i++)
            {
                if (!string.IsNullOrWhiteSpace(module.Lines[i, 1]))
                {
                    return(true);
                }
            }

            return(false);
        }
        private void RewriteCall(VBAParser.ArgumentListContext paramList, CodeModule module)
        {
            var argValues = new List <string>();

            if (paramList.positionalOrNamedArgumentList().positionalArgumentOrMissing() != null)
            {
                argValues.AddRange(paramList.positionalOrNamedArgumentList().positionalArgumentOrMissing().Select(p =>
                {
                    if (p is VBAParser.SpecifiedPositionalArgumentContext)
                    {
                        return(((VBAParser.SpecifiedPositionalArgumentContext)p).positionalArgument().GetText());
                    }

                    return(string.Empty);
                }).ToList());
            }
            if (paramList.positionalOrNamedArgumentList().namedArgumentList() != null)
            {
                argValues.AddRange(paramList.positionalOrNamedArgumentList().namedArgumentList().namedArgument().Select(p => p.GetText()).ToList());
            }
            if (paramList.positionalOrNamedArgumentList().requiredPositionalArgument() != null)
            {
                argValues.Add(paramList.positionalOrNamedArgumentList().requiredPositionalArgument().GetText());
            }

            var lineCount = paramList.Stop.Line - paramList.Start.Line + 1; // adjust for total line count

            var newContent = module.Lines[paramList.Start.Line, lineCount];

            newContent = newContent.Remove(paramList.Start.Column, paramList.GetText().Length);

            var reorderedArgValues = new List <string>();

            foreach (var param in _model.Parameters)
            {
                var argAtIndex = argValues.ElementAtOrDefault(param.Index);
                if (argAtIndex != null)
                {
                    reorderedArgValues.Add(argAtIndex);
                }
            }

            // property let/set and paramarrays
            for (var index = reorderedArgValues.Count; index < argValues.Count; index++)
            {
                reorderedArgValues.Add(argValues[index]);
            }

            newContent = newContent.Insert(paramList.Start.Column, string.Join(", ", reorderedArgValues));

            module.ReplaceLine(paramList.Start.Line, newContent.Replace(" _" + Environment.NewLine, string.Empty));
            module.DeleteLines(paramList.Start.Line + 1, lineCount - 1);
        }
Пример #24
0
        /// <summary>
        /// Gets an array of strings where each element is a line of code in the Module,
        /// with line numbers stripped and any other pre-processing that needs to be done.
        /// </summary>
        public static string[] GetSanitizedCode(this CodeModule module)
        {
            var lines = module.CountOfLines;

            if (lines == 0)
            {
                return(new string[] { });
            }

            var code = module.get_Lines(1, lines).Replace("\r", string.Empty).Split('\n');

            StripLineNumbers(code);
            return(code);
        }
Пример #25
0
        /// <summary>
        /// 更新代码实体信息信息
        /// </summary>
        /// <param name="dtos">包含更新信息的代码实体信息DTO信息</param>
        /// <returns>业务操作结果</returns>
        public async Task <OperationResult> UpdateCodeEntities(params CodeEntityInputDto[] dtos)
        {
            List <string> names = new List <string>();

            UnitOfWork.EnableTransaction();
            foreach (var dto in dtos)
            {
                dto.Validate();
                CodeModule module = await ModuleRepository.GetAsync(dto.ModuleId);

                if (module == null)
                {
                    return(new OperationResult(OperationResultType.Error, $"编号为“{dto.ModuleId}”的模块信息不存在"));
                }

                if (await CheckCodeEntityExists(m => m.Name == dto.Name && m.ModuleId == dto.ModuleId, dto.Id))
                {
                    return(new OperationResult(OperationResultType.Error, $"模块“{module.Name}”中名称为“{dto.Name}”的实体信息已存在"));
                }

                if (dto.Order == 0)
                {
                    dto.Order = EntityRepository.Query(m => m.ModuleId == module.Id).Count() + 1;
                }
                int count;
                if (dto.Id == default)
                {
                    CodeEntity entity = dto.MapTo <CodeEntity>();
                    count = await EntityRepository.InsertAsync(entity);
                }
                else
                {
                    CodeEntity entity = await EntityRepository.GetAsync(dto.Id);

                    entity = dto.MapTo(entity);
                    count  = await EntityRepository.UpdateAsync(entity);
                }

                if (count > 0)
                {
                    names.Add(dto.Name);
                }
            }

            await UnitOfWork.CommitAsync();

            return(names.Count > 0
                ? new OperationResult(OperationResultType.Success, $"实体“{names.ExpandAndToString()}”保存成功")
                : OperationResult.NoChanged);
        }
Пример #26
0
        public static string GetSelectedProcedureScope(this CodeModule module, Selection selection)
        {
            var moduleName  = module.Name;
            var projectName = module.Parent.Collection.Parent.Name;
            var parentScope = projectName + '.' + moduleName;

            vbext_ProcKind kind;
            var            procStart = module.get_ProcOfLine(selection.StartLine, out kind);
            var            procEnd   = module.get_ProcOfLine(selection.EndLine, out kind);

            return(procStart == procEnd
                ? parentScope + '.' + procStart
                : null);
        }
Пример #27
0
        private IEnumerable<RegexSearchResult> GetResultsFromModule(CodeModule module, string searchPattern)
        {
            var results = new List<RegexSearchResult>();

            // VBA uses 1-based indexing
            for (var i = 1; i <= module.CountOfLines; i++)
            {
                var matches =
                    Regex.Matches(module.Lines[i, 1], searchPattern)
                        .OfType<Match>()
                        .Select(m => new RegexSearchResult(m, module, i));

                results.AddRange(matches);
            }
            return results;
        }
Пример #28
0
        private IEnumerable <RegexSearchResult> GetResultsFromModule(CodeModule module, string searchPattern)
        {
            var results = new List <RegexSearchResult>();

            // VBA uses 1-based indexing
            for (var i = 1; i <= module.CountOfLines; i++)
            {
                var matches =
                    Regex.Matches(module.Lines[i, 1], searchPattern)
                    .OfType <Match>()
                    .Select(m => new RegexSearchResult(m, module, i));

                results.AddRange(matches);
            }
            return(results);
        }
Пример #29
0
        private bool IsValidSelection(CodeModule module, Selection selection)
        {
            if (selection.LineCount > 1)
            {
                vbext_ProcKind kindStart;
                var            startProc = module.get_ProcOfLine(selection.StartLine, out kindStart);

                vbext_ProcKind kindEnd;
                var            endProc = module.get_ProcOfLine(selection.EndLine, out kindEnd);

                if (startProc != endProc || kindStart != kindEnd)
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #30
0
        public void Refactor(CodeModule module)
        {
            var codePane  = module.CodePane;
            var selection = codePane.GetSelection();
            var scope     = codePane.SelectedProcedure(selection);

            if (!IsValidSelection(module, selection))
            {
                return;
            }

            /* find all referenced identifiers in selection.
             * find all referenced identifiers in containing procedure.
             * if all identifiers referenced in selection are only used in selection, extract selection into a [Private Sub].
             * if idenfitiers referenced in selection are also used after selection, we need a [ByRef parameter] for each.
             * ...but if there's only one, we make a [Private Function] instead, and return the value.
             *
             */
        }
Пример #31
0
        public static Type CreateProxyType(Type contractInterface, ContractDescription cd, bool duplex)
        {
            string modname = "dummy";
            Type   crtype  =
#if !NET_2_1
                duplex ? typeof(DuplexClientRuntimeChannel) :
#endif
                typeof(ClientRuntimeChannel);

            // public class __clientproxy_MyContract : ClientRuntimeChannel, [ContractType]
            CodeClass c = new CodeModule(modname).CreateClass(
                "__clientproxy_" + cd.Name,
                crtype,
                new Type [] { contractInterface });

            //
            // public __clientproxy_MyContract (
            //	ServiceEndpoint arg1, ChannelFactory arg2, EndpointAddress arg3, Uri arg4)
            //	: base (arg1, arg2, arg3, arg4)
            // {
            // }
            //
            Type []    ctorargs = new Type [] { typeof(ServiceEndpoint), typeof(ChannelFactory), typeof(EndpointAddress), typeof(Uri) };
            CodeMethod ctor     = c.CreateConstructor(
                MethodAttributes.Public, ctorargs);
            CodeBuilder b        = ctor.CodeBuilder;
            MethodBase  baseCtor = crtype.GetConstructors(
                BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) [0];

            if (baseCtor == null)
            {
                throw new Exception("INTERNAL ERROR: ClientRuntimeChannel.ctor() was not found.");
            }
            b.Call(
                ctor.GetThis(),
                baseCtor,
                new CodeArgumentReference(typeof(ServiceEndpoint), 1, "arg0"),
                new CodeArgumentReference(typeof(ChannelFactory), 2, "arg1"),
                new CodeArgumentReference(typeof(EndpointAddress), 3, "arg2"),
                new CodeArgumentReference(typeof(Uri), 4, "arg3"));
            return(CreateProxyTypeOperations(crtype, c, cd));
        }
Пример #32
0
        public static Type CreateCallbackProxyType(DispatchRuntime dispatchRuntime, Type callbackType)
        {
            var  ed = dispatchRuntime.EndpointDispatcher;
            var  channelDispatcher = ed.ChannelDispatcher;
            Type contractType      = channelDispatcher != null?channelDispatcher.Host.ImplementedContracts.Values.First(hcd => hcd.Name == ed.ContractName && hcd.Namespace == ed.ContractNamespace).ContractType : dispatchRuntime.Type;

            var    cd      = ContractDescriptionGenerator.GetCallbackContract(contractType, callbackType);
            string modname = "dummy";
            Type   crtype  = typeof(DuplexServiceRuntimeChannel);

            // public class __clientproxy_MyContract : ClientRuntimeChannel, [ContractType]
            CodeClass c = new CodeModule(modname).CreateClass(
                "__callbackproxy_" + cd.Name,
                crtype,
                new Type [] { callbackType });

            //
            // public __callbackproxy_MyContract (
            //	IChannel channel, DispatchRuntime runtime)
            //	: base (channel, runtime)
            // {
            // }
            //
            Type []    ctorargs = new Type [] { typeof(IChannel), typeof(DispatchRuntime) };
            CodeMethod ctor     = c.CreateConstructor(
                MethodAttributes.Public, ctorargs);
            CodeBuilder b        = ctor.CodeBuilder;
            MethodBase  baseCtor = crtype.GetConstructors(
                BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) [0];

            if (baseCtor == null)
            {
                throw new Exception("INTERNAL ERROR: DuplexServiceRuntimeChannel.ctor() was not found.");
            }
            b.Call(
                ctor.GetThis(),
                baseCtor,
                new CodeArgumentReference(typeof(IChannel), 1, "arg0"),
                new CodeArgumentReference(typeof(DispatchRuntime), 2, "arg1"));

            return(CreateProxyTypeOperations(crtype, c, cd));
        }
Пример #33
0
        private static async Task <CodeModule> GetOrAddModule(IDataContract contract, Guid projectId, CodeModule mod)
        {
            CodeModule module = contract.CodeModules.FirstOrDefault(m => m.ProjectId == projectId && m.Name == mod.Name && m.Display == mod.Display);

            if (module != null)
            {
                return(module);
            }

            CodeModuleInputDto dto = new CodeModuleInputDto()
            {
                Name      = mod.Name,
                Display   = mod.Display ?? mod.Name,
                Icon      = mod.Icon,
                ProjectId = projectId
            };
            await contract.UpdateCodeModules(dto);

            module = contract.CodeModules.First(m => m.ProjectId == projectId && m.Name == mod.Name && m.Display == mod.Display);

            return(module);
        }
        private void SetFieldToPrivate(CodeModule module)
        {
            if (_model.TargetDeclaration.Accessibility == Accessibility.Private)
            {
                return;
            }

            RemoveField(_model.TargetDeclaration);

            var newField = "Private " + _model.TargetDeclaration.IdentifierName + " As " +
                           _model.TargetDeclaration.AsTypeName;

            module.InsertLines(module.CountOfDeclarationLines + 1, newField);

            _editor.SetSelection(_model.TargetDeclaration.QualifiedSelection);
            for (var index = 1; index <= module.CountOfDeclarationLines; index++)
            {
                if (module.Lines[index, 1].Trim() == string.Empty)
                {
                    _editor.DeleteLines(new Selection(index, 0, index, 0));
                }
            }
        }
Пример #35
0
        private ISyntaxTreeNode ParseFileHeader(string fileName, string[] content, ref int currentLine)
        {
            ISyntaxTreeNode result;

            var firstLine = content[0].Trim();
            if (firstLine == "VERSION 1.0 CLASS")
            {
                var multiUse = content[2].Trim();
                var persistable = content[3].Trim();
                var dataBindingBehavior = content[4].Trim();
                var dataSourceBehavior = content[5].Trim();
                var mtsTransactionMode = content[6].Trim();

                var regex = new Regex(@"\=\s\-?(?<IntValue>\d+)\s");
                result = new ClassModule(fileName)
                                {
                                    DataBindingBehavior = int.Parse(regex.Match(dataBindingBehavior).Groups["IntValue"].Value),
                                    DataSourceBehavior = int.Parse(regex.Match(dataSourceBehavior).Groups["IntValue"].Value),
                                    MTSTransactionMode = int.Parse(regex.Match(mtsTransactionMode).Groups["IntValue"].Value),
                                    MultiUse = int.Parse(regex.Match(multiUse).Groups["IntValue"].Value),
                                    Persistable = int.Parse(regex.Match(persistable).Groups["IntValue"].Value)
                                };

                result.Nodes.Add(AttributeNode.Parse(content[8].Trim()));
                result.Nodes.Add(AttributeNode.Parse(content[9].Trim()));
                result.Nodes.Add(AttributeNode.Parse(content[10].Trim()));
                result.Nodes.Add(AttributeNode.Parse(content[11].Trim()));
                result.Nodes.Add(AttributeNode.Parse(content[12].Trim()));

                currentLine = 13;
            }
            else
            {
                result = new CodeModule(fileName);
                result.Nodes.Add(AttributeNode.Parse(content[0].Trim()));

                currentLine = 1;
            }

            return result;
        }
Пример #36
0
 public CodeModuleSelection(CodeModule codeModule, Selection selection)
 {
     _codeModule = codeModule;
     _selection = selection;
 }
        private void RewriteCall(VBAParser.ArgsCallContext paramList, CodeModule module)
        {
            var paramNames = paramList.argCall().Select(arg => arg.GetText()).ToList();
            var lineCount = paramList.Stop.Line - paramList.Start.Line + 1; // adjust for total line count

            var newContent = module.Lines[paramList.Start.Line, lineCount].Replace(" _" + Environment.NewLine, string.Empty).RemoveExtraSpacesLeavingIndentation();

            var parameterIndex = 0;
            var currentStringIndex = 0;

            for (var i = 0; i < paramNames.Count && parameterIndex < _model.Parameters.Count; i++)
            {
                var parameterStringIndex = newContent.IndexOf(paramNames.ElementAt(i), currentStringIndex, StringComparison.Ordinal);

                if (parameterStringIndex <= -1) { continue; }

                var oldParameterString = paramNames.ElementAt(i);
                var newParameterString = paramNames.ElementAt(_model.Parameters.ElementAt(parameterIndex).Index);
                var beginningSub = newContent.Substring(0, parameterStringIndex);
                var replaceSub = newContent.Substring(parameterStringIndex).Replace(oldParameterString, newParameterString);

                newContent = beginningSub + replaceSub;

                parameterIndex++;
                currentStringIndex = beginningSub.Length + newParameterString.Length;
            }

            module.ReplaceLine(paramList.Start.Line, newContent);
            module.DeleteLines(paramList.Start.Line + 1, lineCount - 1);
        }
        private void RewriteSignature(Declaration target, VBAParser.ArgListContext paramList, CodeModule module)
        {
            var argList = paramList.arg();

            var newContent = GetOldSignature(target);
            var lineNum = paramList.GetSelection().LineCount;

            var parameterIndex = 0;
            var currentStringIndex = 0;

            for (var i = parameterIndex; i < _model.Parameters.Count; i++)
            {
                var oldParam = argList.ElementAt(parameterIndex).GetText();
                var newParam = argList.ElementAt(_model.Parameters.ElementAt(parameterIndex).Index).GetText();
                var parameterStringIndex = newContent.IndexOf(oldParam, currentStringIndex, StringComparison.Ordinal);

                if (parameterStringIndex > -1)
                {
                    var beginningSub = newContent.Substring(0, parameterStringIndex);
                    var replaceSub = newContent.Substring(parameterStringIndex).Replace(oldParam, newParam);

                    newContent = beginningSub + replaceSub;

                    parameterIndex++;
                    currentStringIndex = beginningSub.Length + newParam.Length;
                }
            }

            module.ReplaceLine(paramList.Start.Line, newContent.Replace(" _" + Environment.NewLine, string.Empty));
            module.DeleteLines(paramList.Start.Line + 1, lineNum - 1);
        }
Пример #39
0
 public RegexSearchResult(Match match, CodeModule module, int line)
 {
     Match = match;
     Module = module;
     Selection = new Selection(line, match.Index + 1, line, match.Index + match.Length + 1); // adjust columns for VBE 1-based indexing
 }
Пример #40
0
        private static bool HasCode(CodeModule module)
        {
            for (var i = 0; i < module.CountOfLines; i++)
            {
                if (!string.IsNullOrWhiteSpace(module.Lines[i, 1]))
                {
                    return true;
                }
            }

            return false;
        }
        private void RemoveCallParameter(VBAParser.ArgsCallContext paramList, CodeModule module)
        {
            var paramNames = paramList.argCall().Select(arg => arg.GetText()).ToList();
            var lineCount = paramList.Stop.Line - paramList.Start.Line + 1; // adjust for total line count

            var newContent = module.Lines[paramList.Start.Line, lineCount].Replace(" _", "").RemoveExtraSpaces();
            var currentStringIndex = 0;

            foreach (
                var param in
                    _model.Parameters.Where(item => item.IsRemoved && item.Index < paramNames.Count)
                        .Select(item => item.Declaration))
            {
                var paramIndex = _model.Parameters.FindIndex(item => item.Declaration.Context.GetText() == param.Context.GetText()); 
                if (paramIndex >= paramNames.Count) { return; }

                do
                {
                    var paramToRemoveName = paramNames.ElementAt(0).Contains(":=")
                        ? paramNames.Find(item => item.Contains(param.IdentifierName + ":="))
                        : paramNames.ElementAt(paramIndex);

                    if (paramToRemoveName == null || !newContent.Contains(paramToRemoveName))
                    {
                        continue;
                    }

                    var valueToRemove = paramToRemoveName != paramNames.Last()
                        ? paramToRemoveName + ","
                        : paramToRemoveName;

                    var parameterStringIndex = newContent.IndexOf(valueToRemove, currentStringIndex, StringComparison.Ordinal);
                    if (parameterStringIndex <= -1) { continue; }

                    newContent = newContent.Remove(parameterStringIndex, valueToRemove.Length);

                    currentStringIndex = parameterStringIndex;

                    if (paramToRemoveName == paramNames.Last() && newContent.LastIndexOf(',') != -1)
                    {
                        newContent = newContent.Remove(newContent.LastIndexOf(','), 1);
                    }
                } while (paramIndex >= _model.Parameters.Count - 1 && ++paramIndex < paramNames.Count &&
                         newContent.Contains(paramNames.ElementAt(paramIndex)));
            }

            module.ReplaceLine(paramList.Start.Line, newContent);
            for (var line = paramList.Start.Line + 1; line < paramList.Start.Line + lineCount; line++)
            {
                module.ReplaceLine(line, "");
            }
        }
        private void RemoveSignatureParameters(Declaration target, VBAParser.ArgListContext paramList, CodeModule module)
        {
            var paramNames = paramList.arg();

            var paramsRemoved = _model.Parameters.Where(item => item.IsRemoved).ToList();
            var signature = GetOldSignature(target);

            foreach (var param in paramsRemoved)
            {
                try
                {
                    signature = ReplaceCommas(signature.Replace(paramNames.ElementAt(param.Index).GetText(), ""), _model.Parameters.FindIndex(item => item == param) - paramsRemoved.FindIndex(item => item == param));
                }
                catch (ArgumentOutOfRangeException)
                {
                }
            }
            var lineNum = paramList.GetSelection().LineCount;

            module.ReplaceLine(paramList.Start.Line, signature);
            for (var line = paramList.Start.Line + 1; line < paramList.Start.Line + lineNum; line++)
            {
                module.ReplaceLine(line, "");
            }
        }
Пример #43
0
 /// <summary>
 /// Creates a new <see cref="Mock{VBComponent}"/>.
 /// </summary>
 /// <param name="name">The name to return from the <see cref="VBComponent.Name"/> property.</param>
 /// <param name="codeModule">The <see cref="CodeModule"/> to return from the CodeModule property.</param>
 /// <param name="componentType">
 /// The type of component to be simulated.
 /// Use vbext_ct_StdModule for standard modules.
 /// Use vbext_ct_ClassModule for classes.
 /// vbext_ct_ActiveXDesigner is invalid for the VBE.
 /// </param>
 /// <returns></returns>
 internal static Mock<VBComponent> CreateComponentMock(string name, CodeModule codeModule, vbext_ComponentType componentType, Mock<VBE> vbe)
 {
     var component = new Mock<VBComponent>();
     component.SetupProperty(m => m.Name, name);
     component.SetupGet(m => m.CodeModule).Returns(codeModule);
     component.SetupGet(m => m.Type).Returns(componentType);
     component.SetupGet(m => m.VBE).Returns(vbe.Object);
     return component;
 }
Пример #44
0
        private string GetReplacementLine(CodeModule module, Declaration target, string newName)
        {
            var content = module.Lines[target.Selection.StartLine, 1];

            if (target.DeclarationType == DeclarationType.Parameter)
            {
                var argContext = (VBAParser.ArgContext)target.Context;
                var rewriter = _model.ParseResult.GetRewriter(target.QualifiedName.QualifiedModuleName.Component);
                rewriter.Replace(argContext.ambiguousIdentifier().Start.TokenIndex, _model.NewName);

                // Target.Context is an ArgContext, its parent is an ArgsListContext;
                // the ArgsListContext's parent is the procedure context and it includes the body.
                var context = (ParserRuleContext)target.Context.Parent.Parent;
                var firstTokenIndex = context.Start.TokenIndex;
                var lastTokenIndex = -1; // will blow up if this code runs for any context other than below

                var subStmtContext = context as VBAParser.SubStmtContext;
                if (subStmtContext != null)
                {
                    lastTokenIndex = subStmtContext.argList().RPAREN().Symbol.TokenIndex;
                }

                var functionStmtContext = context as VBAParser.FunctionStmtContext;
                if (functionStmtContext != null)
                {
                    lastTokenIndex = functionStmtContext.asTypeClause() != null
                        ? functionStmtContext.asTypeClause().Stop.TokenIndex
                        : functionStmtContext.argList().RPAREN().Symbol.TokenIndex;
                }

                var propertyGetStmtContext = context as VBAParser.PropertyGetStmtContext;
                if (propertyGetStmtContext != null)
                {
                    lastTokenIndex = propertyGetStmtContext.asTypeClause() != null
                        ? propertyGetStmtContext.asTypeClause().Stop.TokenIndex
                        : propertyGetStmtContext.argList().RPAREN().Symbol.TokenIndex;
                }

                var propertyLetStmtContext = context as VBAParser.PropertyLetStmtContext;
                if (propertyLetStmtContext != null)
                {
                    lastTokenIndex = propertyLetStmtContext.argList().RPAREN().Symbol.TokenIndex;
                }

                var propertySetStmtContext = context as VBAParser.PropertySetStmtContext;
                if (propertySetStmtContext != null)
                {
                    lastTokenIndex = propertySetStmtContext.argList().RPAREN().Symbol.TokenIndex;
                }

                var declareStmtContext = context as VBAParser.DeclareStmtContext;
                if (declareStmtContext != null)
                {
                    lastTokenIndex = declareStmtContext.STRINGLITERAL().Last().Symbol.TokenIndex;
                    if (declareStmtContext.argList() != null)
                    {
                        lastTokenIndex = declareStmtContext.argList().RPAREN().Symbol.TokenIndex;
                    }
                    if (declareStmtContext.asTypeClause() != null)
                    {
                        lastTokenIndex = declareStmtContext.asTypeClause().Stop.TokenIndex;
                    }
                }

                var eventStmtContext = context as VBAParser.EventStmtContext;
                if (eventStmtContext != null)
                {
                    lastTokenIndex = eventStmtContext.argList().RPAREN().Symbol.TokenIndex;
                }

                return rewriter.GetText(new Interval(firstTokenIndex, lastTokenIndex));
            }
            return GetReplacementLine(content, newName, target.Selection);
        }
Пример #45
0
 /// <summary>
 /// Creates a new <see cref="Mock{VBComponent}"/>.
 /// </summary>
 /// <param name="name">The name to return from the <see cref="VBComponent.Name"/> property.</param>
 /// <param name="codeModule">The <see cref="CodeModule"/> to return from the CodeModule property.</param>
 /// <param name="componentType">
 /// The type of component to be simulated.
 /// Use vbext_ct_StdModule for standard modules.
 /// Use vbext_ct_ClassModule for classes.
 /// vbext_ct_ActiveXDesigner is invalid for the VBE.
 /// </param>
 /// <returns></returns>
 internal static Mock<VBComponent> CreateComponentMock(string name, CodeModule codeModule, vbext_ComponentType componentType)
 {
     var component = new Mock<VBComponent>();
     component.SetupProperty(c => c.Name, name);
     component.SetupGet(c => c.CodeModule).Returns(codeModule);
     component.SetupGet(c => c.Type).Returns(componentType);
     return component;
 }