Exemple #1
0
		private void Manager_OnMouseHover(ScintillaControl sci, Int32 position)
		{
			DebuggerManager debugManager = PluginMain.debugManager;
			FlashInterface flashInterface = debugManager.FlashInterface;
			if (!PluginBase.MainForm.EditorMenu.Visible && flashInterface != null && flashInterface.isDebuggerStarted && flashInterface.isDebuggerSuspended)
			{
				if (debugManager.CurrentLocation != null && debugManager.CurrentLocation.File != null)
				{
					String localPath = debugManager.GetLocalPath(debugManager.CurrentLocation.File);
					if (localPath == null || localPath != PluginBase.MainForm.CurrentDocument.FileName)
					{
						return;
					}
				}
				else return;
				Point dataTipPoint = Control.MousePosition;
				Rectangle rect = new Rectangle(m_ToolTip.Location, m_ToolTip.Size);
				if (m_ToolTip.Visible && rect.Contains(dataTipPoint))
				{
					return;
				}
				position = sci.WordEndPosition(position, true);
				String leftword = GetWordAtPosition(sci, position);
				if (leftword != String.Empty)
				{
					try
					{
						ASTBuilder builder = new ASTBuilder(true);
						ValueExp exp = builder.parse(new System.IO.StringReader(leftword));
						ExpressionContext context = new ExpressionContext(flashInterface.Session);
						context.Depth = debugManager.CurrentFrame;
						Object obj = exp.evaluate(context);
						Show(dataTipPoint, (Variable)obj);
					}
					catch (Exception){}
				}
			}
		}
        private static StatementReturnType GetStatementReturnType(ScintillaControl sci, ClassModel inClass, string line, int startPos)
        {
            Regex target = new Regex(@"[;\s\n\r]*", RegexOptions.RightToLeft);
            Match m = target.Match(line);
            if (!m.Success)
            {
                return null;
            }
            line = line.Substring(0, m.Index);

            if (line.Length == 0)
            {
                return null;
            }

            line = ReplaceAllStringContents(line);

            ASResult resolve = null;
            int pos = -1; 
            string word = null;
            ClassModel type = null;

            if (line[line.Length - 1] == ')')
            {
                pos = -1;
                int lastIndex = 0;
                int bracesBalance = 0;
                while (true)
                {
                    int pos1 = line.IndexOf('(', lastIndex);
                    int pos2 = line.IndexOf(')', lastIndex);
                    if (pos1 != -1 && pos2 != -1)
                    {
                        lastIndex = Math.Min(pos1, pos2);
                    }
                    else if (pos1 != -1 || pos2 != -1)
                    {
                        lastIndex = Math.Max(pos1, pos2);
                    }
                    else
                    {
                        break;
                    }
                    if (lastIndex == pos1)
                    {
                        bracesBalance++;
                        if (bracesBalance == 1)
                        {
                            pos = lastIndex;
                        }
                    }
                    else if (lastIndex == pos2)
                    {
                        bracesBalance--;
                    }
                    lastIndex++;
                }
            }
            else
            {
                pos = line.Length;
            }
            if (pos != -1)
            {
                line = line.Substring(0, pos);
                pos += startPos;
                pos -= line.Length - line.TrimEnd().Length + 1;
                pos = sci.WordEndPosition(pos, true);
                resolve = ASComplete.GetExpressionType(sci, pos);
                if (resolve.IsNull()) resolve = null;
                word = sci.GetWordFromPosition(pos);
            }

            IASContext ctx = inClass.InFile.Context;
            m = Regex.Match(line, "new\\s+([\\w\\d.<>,_$-]+)+(<[^]]+>)|(<[^]]+>)", RegexOptions.IgnoreCase);

            if (m.Success)
            {
                string m1 = m.Groups[1].Value;
                string m2 = m.Groups[2].Value;

                string cname;
                if (string.IsNullOrEmpty(m1) && string.IsNullOrEmpty(m2))
                    cname = m.Groups[0].Value;
                else
                    cname = String.Concat(m1, m2);

                if (cname.StartsWith('<'))
                    cname = "Vector." + cname; // literal vector

                type = ctx.ResolveType(cname, inClass.InFile);
                if (!type.IsVoid()) resolve = null;
            }
            else
            {
                char c = (char)sci.CharAt(pos);
                if (c == '"' || c == '\'')
                {
                    type = ctx.ResolveType(ctx.Features.stringKey, inClass.InFile);
                }
                else if (c == '}')
                {
                    type = ctx.ResolveType(ctx.Features.objectKey, inClass.InFile);
                }
                else if (c == '>')
                {
                    type = ctx.ResolveType("XML", inClass.InFile);
                }
                else if (c == ']')
                {
                    resolve = ASComplete.GetExpressionType(sci, pos + 1);
                    if (resolve.Type != null) type = resolve.Type;
                    else type = ctx.ResolveType(ctx.Features.arrayKey, inClass.InFile);
                    resolve = null;
                }
                else if (word != null && Char.IsDigit(word[0]))
                {
                    type = ctx.ResolveType(ctx.Features.numberKey, inClass.InFile);
                }
                else if (word == "true" || word == "false")
                {
                    type = ctx.ResolveType(ctx.Features.booleanKey, inClass.InFile);
                }
                if (type != null && type.IsVoid()) type = null;
            }
            if (resolve == null) resolve = new ASResult();
            if (resolve.Type == null) resolve.Type = type;
            return new StatementReturnType(resolve, pos, word);
        }
        private static void GenerateClass(ScintillaControl sci, String className, ClassModel inClass)
        {
            AddLookupPosition(); // remember last cursor position for Shift+F4

            List<FunctionParameter> parameters = ParseFunctionParameters(sci, sci.WordEndPosition(sci.CurrentPos, true));
            List<MemberModel> constructorArgs = new List<MemberModel>();
            List<String> constructorArgTypes = new List<String>();
            MemberModel paramMember = new MemberModel();
            for (int i = 0; i < parameters.Count; i++)
            {
                FunctionParameter p = parameters[i];
                constructorArgs.Add(new MemberModel(p.paramName, p.paramType, FlagType.ParameterVar, 0));
                constructorArgTypes.Add(CleanType(GetQualifiedType(p.paramQualType, inClass)));
            }
            
            paramMember.Parameters = constructorArgs;

            IProject project = PluginBase.CurrentProject;
            if (String.IsNullOrEmpty(className)) className = "Class";
            string projFilesDir = Path.Combine(PathHelper.TemplateDir, "ProjectFiles");
            string projTemplateDir = Path.Combine(projFilesDir, project.GetType().Name);
            string paramsString = TemplateUtils.ParametersString(paramMember, true);
            Hashtable info = new Hashtable();
            info["className"] = className;
            if (project.Language.StartsWithOrdinal("as")) info["templatePath"] = Path.Combine(projTemplateDir, "Class.as.fdt");
            else if (project.Language.StartsWithOrdinal("haxe")) info["templatePath"] = Path.Combine(projTemplateDir, "Class.hx.fdt");
            else if (project.Language.StartsWithOrdinal("loom")) info["templatePath"] = Path.Combine(projTemplateDir, "Class.ls.fdt");
            info["inDirectory"] = Path.GetDirectoryName(inClass.InFile.FileName);
            info["constructorArgs"] = paramsString.Length > 0 ? paramsString : null;
            info["constructorArgTypes"] = constructorArgTypes;
            DataEvent de = new DataEvent(EventType.Command, "ProjectManager.CreateNewFile", info);
            EventManager.DispatchEvent(null, de);
            if (de.Handled) return;
        }
        private static void GenerateFunctionJob(GeneratorJobType job, ScintillaControl sci, MemberModel member,
            bool detach, ClassModel inClass)
        {
            int position = 0;
            MemberModel latest = null;
            bool isOtherClass = false;

            Visibility funcVisi = job.Equals(GeneratorJobType.FunctionPublic) ? Visibility.Public : GetDefaultVisibility(inClass);
            int wordPos = sci.WordEndPosition(sci.CurrentPos, true);
            List<FunctionParameter> functionParameters = ParseFunctionParameters(sci, wordPos);

            // evaluate, if the function should be generated in other class
            ASResult funcResult = ASComplete.GetExpressionType(sci, sci.WordEndPosition(sci.CurrentPos, true));

            int contextOwnerPos = GetContextOwnerEndPos(sci, sci.WordStartPosition(sci.CurrentPos, true));
            MemberModel isStatic = new MemberModel();
            if (contextOwnerPos != -1)
            {
                ASResult contextOwnerResult = ASComplete.GetExpressionType(sci, contextOwnerPos);
                if (contextOwnerResult != null)
                {
                    if (contextOwnerResult.Member == null && contextOwnerResult.Type != null)
                    {
                        isStatic.Flags |= FlagType.Static;
                    }
                }
            }
            else if (member != null && (member.Flags & FlagType.Static) > 0)
            {
                isStatic.Flags |= FlagType.Static;
            }


            if (funcResult.RelClass != null && !funcResult.RelClass.IsVoid() && !funcResult.RelClass.Equals(inClass))
            {
                AddLookupPosition();
                lookupPosition = -1;

                ASContext.MainForm.OpenEditableDocument(funcResult.RelClass.InFile.FileName, true);
                sci = ASContext.CurSciControl;
                isOtherClass = true;

                FileModel fileModel = new FileModel();
                fileModel.Context = ASContext.Context;
                ASFileParser parser = new ASFileParser();
                parser.ParseSrc(fileModel, sci.Text);

                foreach (ClassModel cm in fileModel.Classes)
                {
                    if (cm.QualifiedName.Equals(funcResult.RelClass.QualifiedName))
                    {
                        funcResult.RelClass = cm;
                        break;
                    }
                }
                inClass = funcResult.RelClass;

                ASContext.Context.UpdateContext(inClass.LineFrom);
            }

            string blockTmpl = null;
            if ((isStatic.Flags & FlagType.Static) > 0)
            {
                blockTmpl = TemplateUtils.GetBoundary("StaticMethods");
            }
            else if ((funcVisi & Visibility.Public) > 0)
            {
                blockTmpl = TemplateUtils.GetBoundary("PublicMethods");
            }
            else
            {
                blockTmpl = TemplateUtils.GetBoundary("PrivateMethods");
            }
            latest = TemplateUtils.GetTemplateBlockMember(sci, blockTmpl);
            if (latest == null || (!isOtherClass && member == null))
            {
                latest = GetLatestMemberForFunction(inClass, funcVisi, isStatic);

                // if we generate function in current class..
                if (!isOtherClass)
                {
                    MethodsGenerationLocations location = ASContext.CommonSettings.MethodsGenerationLocations;
                    if (member == null)
                    {
                        detach = false;
                        lookupPosition = -1;
                        position = sci.WordStartPosition(sci.CurrentPos, true);
                        sci.SetSel(position, sci.WordEndPosition(position, true));
                    }
                    else if (latest != null && location == MethodsGenerationLocations.AfterSimilarAccessorMethod)
                    {
                        position = sci.PositionFromLine(latest.LineTo + 1) - ((sci.EOLMode == 0) ? 2 : 1);
                        sci.SetSel(position, position);
                    }
                    else
                    {
                        position = sci.PositionFromLine(member.LineTo + 1) - ((sci.EOLMode == 0) ? 2 : 1);
                        sci.SetSel(position, position);
                    }
                }
                else // if we generate function in another class..
                {
                    if (latest != null)
                    {
                        position = sci.PositionFromLine(latest.LineTo + 1) - ((sci.EOLMode == 0) ? 2 : 1);
                    }
                    else
                    {
                        position = GetBodyStart(inClass.LineFrom, inClass.LineTo, sci);
                        detach = false;
                    }
                    sci.SetSel(position, position);
                }
            }
            else
            {
                position = sci.PositionFromLine(latest.LineTo + 1) - ((sci.EOLMode == 0) ? 2 : 1);
                sci.SetSel(position, position);
            }

            // add imports to function argument types
            if (functionParameters.Count > 0)
            {
                List<string> l = new List<string>();
                foreach (FunctionParameter fp in functionParameters)
                {
                    try
                    {
                        l.Add(fp.paramQualType);
                    }
                    catch (Exception) { }
                }
                int o = AddImportsByName(l, sci.LineFromPosition(position));
                position += o;
                if (latest == null)
                    sci.SetSel(position, sci.WordEndPosition(position, true));
                else
                    sci.SetSel(position, position);
            }
            
            List<MemberModel> parameters = new List<MemberModel>();
            for (int i = 0; i < functionParameters.Count; i++)
            {
                string name = functionParameters[i].paramName;
                string type = functionParameters[i].paramType;
                parameters.Add(new MemberModel(name, type, FlagType.ParameterVar, 0));
            }
            MemberModel newMember = NewMember(contextToken, isStatic, FlagType.Function, funcVisi);
            newMember.Parameters = parameters;
            GenerateFunction(newMember, position, detach, inClass);
        }
        private static void GenerateVariableJob(GeneratorJobType job, ScintillaControl sci, MemberModel member,
            bool detach, ClassModel inClass)
        {
            int position = 0;
            MemberModel latest = null;
            bool isOtherClass = false;

            Visibility varVisi = job.Equals(GeneratorJobType.Variable) ? GetDefaultVisibility(inClass) : Visibility.Public;
            FlagType ft = job.Equals(GeneratorJobType.Constant) ? FlagType.Constant : FlagType.Variable;

            // evaluate, if the variable (or constant) should be generated in other class
            ASResult varResult = ASComplete.GetExpressionType(sci, sci.WordEndPosition(sci.CurrentPos, true));

            int contextOwnerPos = GetContextOwnerEndPos(sci, sci.WordStartPosition(sci.CurrentPos, true));
            MemberModel isStatic = new MemberModel();
            if (contextOwnerPos != -1)
            {
                ASResult contextOwnerResult = ASComplete.GetExpressionType(sci, contextOwnerPos);
                if (contextOwnerResult != null)
                {
                    if (contextOwnerResult.Member == null && contextOwnerResult.Type != null)
                    {
                        isStatic.Flags |= FlagType.Static;
                    }
                }
            }
            else if (member != null && (member.Flags & FlagType.Static) > 0)
            {
                isStatic.Flags |= FlagType.Static;
            }

            ASResult returnType = null;
            int lineNum = sci.CurrentLine;
            string line = sci.GetLine(lineNum);
            
            Match m = Regex.Match(line, "\\b" + Regex.Escape(contextToken) + "\\(");
            if (m.Success)
            {
                returnType = new ASResult();
                returnType.Type = ASContext.Context.ResolveType("Function", null);
            }
            else
            {
                m = Regex.Match(line, @"=\s*[^;\n\r}}]+");
                if (m.Success)
                {
                    int posLineStart = sci.PositionFromLine(lineNum);
                    if (posLineStart + m.Index >= sci.CurrentPos)
                    {
                        line = line.Substring(m.Index);
                        StatementReturnType rType = GetStatementReturnType(sci, inClass, line, posLineStart + m.Index);
                        if (rType != null)
                        {
                            returnType = rType.resolve;
                        }
                    }
                }
            }

            if (varResult.RelClass != null && !varResult.RelClass.IsVoid() && !varResult.RelClass.Equals(inClass))
            {
                AddLookupPosition();
                lookupPosition = -1;

                ASContext.MainForm.OpenEditableDocument(varResult.RelClass.InFile.FileName, false);
                sci = ASContext.CurSciControl;
                isOtherClass = true;

                FileModel fileModel = new FileModel();
                fileModel.Context = ASContext.Context;
                ASFileParser parser = new ASFileParser();
                parser.ParseSrc(fileModel, sci.Text);

                foreach (ClassModel cm in fileModel.Classes)
                {
                    if (cm.QualifiedName.Equals(varResult.RelClass.QualifiedName))
                    {
                        varResult.RelClass = cm;
                        break;
                    }
                }
                inClass = varResult.RelClass;

                ASContext.Context.UpdateContext(inClass.LineFrom);
            }

            latest = GetLatestMemberForVariable(job, inClass, varVisi, isStatic);
            
            // if we generate variable in current class..
            if (!isOtherClass && member == null)
            {
                detach = false;
                lookupPosition = -1;
                position = sci.WordStartPosition(sci.CurrentPos, true);
                sci.SetSel(position, sci.WordEndPosition(position, true));
            }
            else // if we generate variable in another class
            {
                if (latest != null)
                {
                    position = FindNewVarPosition(sci, inClass, latest);
                }
                else
                {
                    position = GetBodyStart(inClass.LineFrom, inClass.LineTo, sci);
                    detach = false;
                }
                if (position <= 0) return;
                sci.SetSel(position, position);
            }

            // if this is a constant, we assign a value to constant
            string returnTypeStr = null;
            string eventValue = null;
            if (job == GeneratorJobType.Constant && returnType == null)
            {
                isStatic.Flags |= FlagType.Static;
                eventValue = "String = \"" + Camelize(contextToken) + "\"";
            }
            else if (returnType != null)
            {
                ClassModel inClassForImport = null;
                if (returnType.InClass != null)
                {
                    inClassForImport = returnType.InClass;
                }
                else if (returnType.RelClass != null)
                {
                    inClassForImport = returnType.RelClass;
                }
                else
                {
                    inClassForImport = inClass;
                }
                List<String> imports = new List<string>();
                if (returnType.Member != null)
                {
                    if (returnType.Member.Type != ASContext.Context.Features.voidKey)
                    {
                        returnTypeStr = FormatType(GetShortType(returnType.Member.Type));
                        imports.Add(GetQualifiedType(returnType.Member.Type, inClassForImport));
                    }
                }
                else if (returnType != null && returnType.Type != null)
                {
                    returnTypeStr = FormatType(GetShortType(returnType.Type.QualifiedName));
                    imports.Add(GetQualifiedType(returnType.Type.QualifiedName, inClassForImport));
                }
                if (imports.Count > 0)
                {
                    position += AddImportsByName(imports, sci.LineFromPosition(position));
                    sci.SetSel(position, position);
                }
            }
            MemberModel newMember = NewMember(contextToken, isStatic, ft, varVisi);
            if (returnTypeStr != null)
            {
                newMember.Type = returnTypeStr;
            }
            else if (eventValue != null)
            {
                newMember.Type = eventValue;
            }
            GenerateVariable(newMember, position, detach);
        }
        private static void ChangeConstructorDecl(ScintillaControl sci, MemberModel member, ClassModel inClass)
        {
            int wordPos = sci.WordEndPosition(sci.CurrentPos, true);
            List<FunctionParameter> functionParameters = ParseFunctionParameters(sci, wordPos);
            ASResult funcResult = ASComplete.GetExpressionType(sci, sci.WordEndPosition(sci.CurrentPos, true));

            if (funcResult == null || funcResult.Type == null) return;
            if (funcResult.Type != null && !funcResult.Type.Equals(inClass))
            {
                AddLookupPosition();
                lookupPosition = -1;

                ASContext.MainForm.OpenEditableDocument(funcResult.Type.InFile.FileName, true);
                sci = ASContext.CurSciControl;

                FileModel fileModel = new FileModel(funcResult.Type.InFile.FileName);
                fileModel.Context = ASContext.Context;
                ASFileParser parser = new ASFileParser();
                parser.ParseSrc(fileModel, sci.Text);

                foreach (ClassModel cm in fileModel.Classes)
                {
                    if (cm.QualifiedName.Equals(funcResult.Type.QualifiedName))
                    {
                        funcResult.Type = cm;
                        break;
                    }
                }

                inClass = funcResult.Type;
                ASContext.Context.UpdateContext(inClass.LineFrom);
            }

            foreach (MemberModel m in inClass.Members)
            {
                if ((m.Flags & FlagType.Constructor) > 0)
                {
                    funcResult.Member = m;
                    break;
                }
            }

            if (funcResult.Member == null) return;
            if (IsHaxe) funcResult.Member.Name = "new";

            ChangeDecl(sci, funcResult.Member, functionParameters);
        }
        private static void ChangeMethodDecl(ScintillaControl Sci, MemberModel member, ClassModel inClass)
        {
            int wordPos = Sci.WordEndPosition(Sci.CurrentPos, true);
            List<FunctionParameter> functionParameters = ParseFunctionParameters(Sci, wordPos);

            ASResult funcResult = ASComplete.GetExpressionType(Sci, Sci.WordEndPosition(Sci.CurrentPos, true));
            if (funcResult == null || funcResult.Member == null) return;
            if (funcResult.InClass != null && !funcResult.InClass.Equals(inClass))
            {
                AddLookupPosition();
                lookupPosition = -1;

                ASContext.MainForm.OpenEditableDocument(funcResult.InClass.InFile.FileName, true);
                Sci = ASContext.CurSciControl;

                FileModel fileModel = new FileModel();
                fileModel.Context = ASContext.Context;
                ASFileParser parser = new ASFileParser();
                parser.ParseSrc(fileModel, Sci.Text);

                foreach (ClassModel cm in fileModel.Classes)
                {
                    if (cm.QualifiedName.Equals(funcResult.InClass.QualifiedName))
                    {
                        funcResult.InClass = cm;
                        break;
                    }
                }
                inClass = funcResult.InClass;

                ASContext.Context.UpdateContext(inClass.LineFrom);
            }

            MemberList members = inClass.Members;
            foreach (MemberModel m in members)
            {
                if (m.Equals(funcResult.Member))
                {
                    funcResult.Member = m;
                    break;
                }
            }

            ChangeDecl(Sci, funcResult.Member, functionParameters);
        }
        public static void ContextualGenerator(ScintillaControl Sci, List<ICompletionListItem> options)
        {
            if (ASContext.Context is ASContext) (ASContext.Context as ASContext).UpdateCurrentFile(false); // update model
            if ((ASContext.Context.CurrentClass.Flags & (FlagType.Enum | FlagType.TypeDef)) > 0) return;

            lookupPosition = -1;
            int position = Sci.CurrentPos;
            int style = Sci.BaseStyleAt(position);
            if (style == 19) // on keyword
                return;

            bool isNotInterface = (ASContext.Context.CurrentClass.Flags & FlagType.Interface) == 0;
            int line = Sci.LineFromPosition(position);
            contextToken = Sci.GetWordFromPosition(position);
            contextMatch = null;

            FoundDeclaration found = GetDeclarationAtLine(Sci, line);
            string text = Sci.GetLine(line);
            bool suggestItemDeclaration = false;

            if (isNotInterface && ASComplete.IsLiteralStyle(style))
            {
                ShowConvertToConst(found, options);
                return;
            }

            ASResult resolve = ASComplete.GetExpressionType(Sci, Sci.WordEndPosition(position, true));
            contextResolved = resolve;
            
            // ignore automatic vars (MovieClip members)
            if (isNotInterface
                && resolve.Member != null
                && (((resolve.Member.Flags & FlagType.AutomaticVar) > 0) || (resolve.InClass != null && resolve.InClass.QualifiedName == "Object")))
            {
                resolve.Member = null;
                resolve.Type = null;
            }

            if (isNotInterface && found.inClass != ClassModel.VoidClass && contextToken != null)
            {
                if (resolve.Member == null && resolve.Type != null
                    && (resolve.Type.Flags & FlagType.Interface) > 0) // implement interface
                {
                    contextParam = resolve.Type.Type;
                    ShowImplementInterface(found, options);
                    return;
                }

                if (resolve.Member != null && !ASContext.Context.CurrentClass.IsVoid()
                    && (resolve.Member.Flags & FlagType.LocalVar) > 0) // promote to class var
                {
                    contextMember = resolve.Member;
                    ShowPromoteLocalAndAddParameter(found, options);
                    return;
                }
            }
            
            if (contextToken != null && resolve.Member == null) // import declaration
            {
                if ((resolve.Type == null || resolve.Type.IsVoid() || !ASContext.Context.IsImported(resolve.Type, line)) && CheckAutoImport(found, options)) return;
                if (resolve.Type == null)
                {
                    suggestItemDeclaration = ASComplete.IsTextStyle(Sci.BaseStyleAt(position - 1));
                }
            }

            if (isNotInterface && found.member != null)
            {
                // private var -> property
                if ((found.member.Flags & FlagType.Variable) > 0 && (found.member.Flags & FlagType.LocalVar) == 0)
                {
                    // maybe we just want to import the member's non-imported type
                    Match m = Regex.Match(text, String.Format(patternVarDecl, found.member.Name, contextToken));
                    if (m.Success)
                    {
                        contextMatch = m;
                        ClassModel type = ASContext.Context.ResolveType(contextToken, ASContext.Context.CurrentModel);
                        if (type.IsVoid() && CheckAutoImport(found, options))
                            return;
                    }
                    ShowGetSetList(found, options);
                    return;
                }
                // inside a function
                else if ((found.member.Flags & (FlagType.Function | FlagType.Getter | FlagType.Setter)) > 0
                    && resolve.Member == null && resolve.Type == null)
                {
                    if (contextToken != null)
                    {
                        // "generate event handlers" suggestion
                        string re = String.Format(patternEvent, contextToken);
                        Match m = Regex.Match(text, re, RegexOptions.IgnoreCase);
                        if (m.Success)
                        {
                            contextMatch = m;
                            contextParam = CheckEventType(m.Groups["event"].Value);
                            ShowEventList(found, options);
                            return;
                        }
                        m = Regex.Match(text, String.Format(patternAS2Delegate, contextToken), RegexOptions.IgnoreCase);
                        if (m.Success)
                        {
                            contextMatch = m;
                            ShowDelegateList(found, options);
                            return;
                        }
                        // suggest delegate
                        if (ASContext.Context.Features.hasDelegates)
                        {
                            m = Regex.Match(text, @"([a-z0-9_.]+)\s*\+=\s*" + contextToken, RegexOptions.IgnoreCase);
                            if (m.Success)
                            {
                                int offset = Sci.PositionFromLine(Sci.LineFromPosition(position))
                                    + m.Groups[1].Index + m.Groups[1].Length;
                                resolve = ASComplete.GetExpressionType(Sci, offset);
                                if (resolve.Member != null)
                                    contextMember = ResolveDelegate(resolve.Member.Type, resolve.InFile);
                                contextMatch = m;
                                ShowDelegateList(found, options);
                                return;
                            }
                        }
                    }
                    else
                    {
                        // insert a default handler name, then "generate event handlers" suggestion
                        Match m = Regex.Match(text, String.Format(patternEvent, ""), RegexOptions.IgnoreCase);
                        if (m.Success)
                        {
                            int regexIndex = m.Index + Sci.PositionFromLine(Sci.CurrentLine);
                            GenerateDefaultHandlerName(Sci, position, regexIndex, m.Groups["event"].Value, true);
                            resolve = ASComplete.GetExpressionType(Sci, Sci.CurrentPos);
                            if (resolve.Member == null || (resolve.Member.Flags & FlagType.AutomaticVar) > 0)
                            {
                                contextMatch = m;
                                contextParam = CheckEventType(m.Groups["event"].Value);
                                ShowEventList(found, options);
                            }
                            return;
                        }

                        // insert default delegate name, then "generate delegate" suggestion
                        if (ASContext.Context.Features.hasDelegates)
                        {
                            m = Regex.Match(text, @"([a-z0-9_.]+)\s*\+=\s*", RegexOptions.IgnoreCase);
                            if (m.Success)
                            {
                                int offset = Sci.PositionFromLine(Sci.LineFromPosition(position))
                                        + m.Groups[1].Index + m.Groups[1].Length;
                                resolve = ASComplete.GetExpressionType(Sci, offset);
                                if (resolve.Member != null)
                                {
                                    contextMember = ResolveDelegate(resolve.Member.Type, resolve.InFile);
                                    string delegateName = resolve.Member.Name;
                                    if (delegateName.StartsWithOrdinal("on")) delegateName = delegateName.Substring(2);
                                    GenerateDefaultHandlerName(Sci, position, offset, delegateName, false);
                                    resolve = ASComplete.GetExpressionType(Sci, Sci.CurrentPos);
                                    if (resolve.Member == null || (resolve.Member.Flags & FlagType.AutomaticVar) > 0)
                                    {
                                        contextMatch = m;
                                        ShowDelegateList(found, options);
                                    }
                                    return;
                                }
                            }
                        }
                    }
                }

                // "Generate fields from parameters" suggestion
                if (found.member != null
                    && (found.member.Flags & FlagType.Function) > 0
                    && found.member.Parameters != null && (found.member.Parameters.Count > 0)
                    && resolve.Member != null && (resolve.Member.Flags & FlagType.ParameterVar) > 0)
                {
                    contextMember = resolve.Member;
                    ShowFieldFromParameter(found, options);
                    return;
                }

                // "add to interface" suggestion
                if (resolve.Member != null
                    && resolve.Member.Name == found.member.Name
                    && line == found.member.LineFrom
                    && ((found.member.Flags & FlagType.Function) > 0 
                            || (found.member.Flags & FlagType.Getter) > 0
                            || (found.member.Flags & FlagType.Setter) > 0)
                    && found.inClass != ClassModel.VoidClass
                    && found.inClass.Implements != null
                    && found.inClass.Implements.Count > 0)
                {
                    string funcName = found.member.Name;
                    FlagType flags = found.member.Flags & ~FlagType.Access;
                    
                    List<string> interfaces = new List<string>();
                    foreach (string interf in found.inClass.Implements)
                    {
                        bool skip = false;
                        ClassModel cm = ASContext.Context.ResolveType(interf, ASContext.Context.CurrentModel);
                        foreach (MemberModel m in cm.Members)
                        {
                            if (m.Name.Equals(funcName) && m.Flags.Equals(flags))
                            {
                                skip = true;
                                break;
                            }
                        }
                        if (!skip)
                        {
                            interfaces.Add(interf);
                        }
                    }
                    if (interfaces.Count > 0)
                    {
                        ShowAddInterfaceDefList(found, interfaces, options);
                        return;
                    }
                }

                // "assign var to statement" suggestion
                int curLine = Sci.CurrentLine;
                string ln = Sci.GetLine(curLine).TrimEnd();
                if (ln.Length > 0 && ln.IndexOf('=') == -1 
                    && ln.Length <= Sci.CurrentPos - Sci.PositionFromLine(curLine)) // cursor at end of line
                {
                    ShowAssignStatementToVarList(found, options);
                    return;
                }
            }
            
            // suggest generate constructor / toString
            if (isNotInterface && found.member == null && found.inClass != ClassModel.VoidClass && contextToken == null)
            {
                bool hasConstructor = false;
                bool hasToString = false;
                foreach (MemberModel m in ASContext.Context.CurrentClass.Members)
                {
                    if (!hasConstructor && (m.Flags & FlagType.Constructor) > 0)
                        hasConstructor = true;

                    if (!hasToString && (m.Flags & FlagType.Function) > 0 && m.Name.Equals("toString"))
                        hasToString = true;
                }

                if (!hasConstructor || !hasToString)
                {
                    ShowConstructorAndToStringList(found, hasConstructor, hasToString, options);
                    return;
                }
            }

            if (isNotInterface 
                && resolve.Member != null
                && resolve.Type != null
                && resolve.Type.QualifiedName == ASContext.Context.Features.stringKey
                && found.inClass != ClassModel.VoidClass)
            {
                int lineStartPos = Sci.PositionFromLine(Sci.CurrentLine);
                string lineStart = text.Substring(0, Sci.CurrentPos - lineStartPos);
                Match m = Regex.Match(lineStart, String.Format(@"new\s+(?<event>\w+)\s*\(\s*\w+", lineStart));
                if (m.Success)
                {
                    Group g = m.Groups["event"];
                    ASResult eventResolve = ASComplete.GetExpressionType(Sci, lineStartPos + g.Index + g.Length);
                    if (eventResolve != null && eventResolve.Type != null)
                    {
                        ClassModel aType = eventResolve.Type;
                        aType.ResolveExtends();
                        while (!aType.IsVoid() && aType.QualifiedName != "Object")
                        {
                            if (aType.QualifiedName == "flash.events.Event")
                            {
                                contextParam = eventResolve.Type.QualifiedName;
                                ShowEventMetatagList(found, options);
                                return;
                            }
                            aType = aType.Extends;
                        }
                    }
                }
            }
            
            // suggest declaration
            if (contextToken != null)
            {
                if (suggestItemDeclaration)
                {
                    Match m = Regex.Match(text, String.Format(patternClass, contextToken));
                    if (m.Success)
                    {
                        contextMatch = m;
                        ShowNewClassList(found, options);
                    }
                    else if (!found.inClass.IsVoid())
                    {
                        m = Regex.Match(text, String.Format(patternMethod, contextToken));
                        if (m.Success)
                        {
                            contextMatch = m;
                            ShowNewMethodList(found, options);
                        }
                        else ShowNewVarList(found, options);
                    }
                }
                else
                {
                    if (resolve != null
                        && resolve.InClass != null
                        && resolve.InClass.InFile != null
                        && resolve.Member != null
                        && (resolve.Member.Flags & FlagType.Function) > 0
                        && File.Exists(resolve.InClass.InFile.FileName)
                        && !resolve.InClass.InFile.FileName.StartsWithOrdinal(PathHelper.AppDir))
                    {
                        Match m = Regex.Match(text, String.Format(patternMethodDecl, contextToken));
                        Match m2 = Regex.Match(text, String.Format(patternMethod, contextToken));
                        if (!m.Success && m2.Success)
                        {
                            contextMatch = m;
                            ShowChangeMethodDeclList(found, options);
                        }
                    }
                    else if (resolve != null
                        && resolve.Type != null
                        && resolve.Type.InFile != null
                        && resolve.RelClass != null
                        && File.Exists(resolve.Type.InFile.FileName)
                        && !resolve.Type.InFile.FileName.StartsWithOrdinal(PathHelper.AppDir))
                    {
                        Match m = Regex.Match(text, String.Format(patternClass, contextToken));
                        if (m.Success)
                        {
                            contextMatch = m;
                            ShowChangeConstructorDeclList(found, options);
                        }
                    }
                }
            }
            // TODO: Empty line, show generators list? yep
        }
Exemple #9
0
        public PositionInfos(ScintillaControl sci, Int32 position, String argString)
        {
            // Variables
            String[] vars = argString.Split('¤');
            this.ArgCurWord = vars[0];
            this.ArgPackageName = vars[1];
            this.ArgClassName = vars[2];
            this.ArgClassType = vars[3];
            this.ArgMemberName = vars[4];
            this.ArgMemberType = vars[5];

            // Selection
            Int32 ss = sci.SelectionStart;
            Int32 se = sci.SelectionEnd;
            if (se != ss)
            {
                this.SelectionStart = ss;
                this.SelectionEnd = se;
                this.HasSelection = true;
                if (sci.LineFromPosition(ss) != sci.LineFromPosition(se))
                    this.SelectionIsMultiline = true;
                else SelectedText = sci.SelText;
            }

            // Current
            this.CurrentPosition = position;
            this.CurrentCharCode = sci.CharAt(position);
            this.CurrentIsWhiteChar = (HelpTools.IsWhiteChar(this.CurrentCharCode));
            this.CurrentIsDotChar = (this.CurrentCharCode == 46);
            this.CurrentIsActionScriptChar = HelpTools.IsActionScriptChar(this.CurrentCharCode);
            this.CurrentIsWordChar = HelpTools.IsWordChar((byte)this.CurrentCharCode);
            Int32 s = sci.StyleAt(position);
            this.CurrentIsInsideComment = (s == 1 || s == 2 || s == 3 || s == 17);

            // Next
            Int32 np = sci.PositionAfter(position);
            if (np != position)
                this.NextPosition = np;
            else
                this.CaretIsAtEndOfDocument = true;

            // Word
            this.CodePage = sci.CodePage; // (UTF-8|Big Endian|Little Endian : 65001) (8 Bits|UTF-7 : 0)
            
            if (this.CurrentIsInsideComment == false && this.SelectionIsMultiline == false)
            {
                Int32 wsp = sci.WordStartPosition(position, true);
                // Attention (WordEndPosition n'est pas estimé comme par defaut)
                Int32 wep = sci.PositionBefore(sci.WordEndPosition(position, true));

                if (this.CodePage != 65001)
                {
                    wsp = HelpTools.GetWordStartPositionByWordChar(sci, position);
                    // Attention (WordEndPosition n'est pas estimé comme par defaut)
                    wep = sci.PositionBefore(HelpTools.GetWordEndPositionByWordChar(sci, position));
                }

                this.WordStartPosition = wsp;
                this.WordEndPosition = wep;

                if (this.CodePage == 65001)
                    this.WordFromPosition = this.ArgCurWord;
                else
                    this.WordFromPosition = HelpTools.GetText(sci, wsp, sci.PositionAfter(wep));

                if (position > wep)
                    this.CaretIsAfterLastLetter = true;
            }
            
            // Previous
            if (this.CurrentPosition > 0)
            {
                this.PreviousPosition = sci.PositionBefore(position);
                this.PreviousCharCode = sci.CharAt(this.PreviousPosition);
                this.PreviousIsWhiteChar = HelpTools.IsWhiteChar(this.PreviousCharCode);
                this.PreviousIsDotChar = (this.PreviousCharCode == 46);
                this.PreviousIsActionScriptChar = HelpTools.IsActionScriptChar(this.PreviousCharCode);
            }

            // Line
            this.CurrentLineIdx = sci.LineFromPosition(position);
            if (this.CurrentPosition > 0)
                this.PreviousLineIdx = sci.LineFromPosition(this.PreviousPosition);

            this.LineIdxMax = sci.LineCount - 1;
            this.LineStartPosition = HelpTools.LineStartPosition(sci, this.CurrentLineIdx);
            this.LineEndPosition = sci.LineEndPosition(this.CurrentLineIdx);
            this.NewLineMarker = LineEndDetector.GetNewLineMarker(sci.EOLMode);

            // Previous / Next
            if (this.WordStartPosition != -1)
            {
                this.PreviousNonWhiteCharPosition = HelpTools.PreviousNonWhiteCharPosition(sci, this.WordStartPosition);
                this.PreviousWordIsFunction = (sci.GetWordFromPosition(this.PreviousNonWhiteCharPosition) == "function");
                this.NextNonWhiteCharPosition = HelpTools.NextNonWhiteCharPosition(sci, this.WordEndPosition);
            }

            // Function
            if (this.PreviousWordIsFunction)
            {
                Int32 nobp = HelpTools.NextCharPosition(sci, position, "(");
                Int32 ncbp = HelpTools.NextCharPosition(sci, position, ")");
                Int32 nlbp = HelpTools.NextCharPosition(sci, position, "{");
                if ((nobp < ncbp) && (ncbp < nlbp))
                {
                    this.NextOpenBracketPosition = nobp;
                    this.NextCloseBracketPosition = ncbp;
                    this.NextLeftBracePosition = nlbp;
                }

                // Arguments
                String args = HelpTools.GetText(sci, sci.PositionAfter(this.NextOpenBracketPosition), this.NextCloseBracketPosition).Trim();
                if (args.Length > 0)
                {
                    this.HasArguments = true;
                    this.Arguments = HelpTools.ExtractArguments(sci, args);
                }
            }
        }
 /// <summary>
 /// 
 /// </summary>
 private void UpdateHighlightUnderCursor(ScintillaControl sci)
 {
     string file = PluginBase.MainForm.CurrentDocument.FileName;
     if (!IsValidFile(file)) return;
     int currentPos = sci.CurrentPos;
     string newToken = sci.GetWordFromPosition(currentPos);
     if (!string.IsNullOrEmpty(newToken)) newToken = newToken.Trim();
     if (!string.IsNullOrEmpty(newToken))
     {
         if (prevResult == null && prevToken == newToken) return;
         ASResult result = IsValidFile(file) ? ASComplete.GetExpressionType(sci, sci.WordEndPosition(currentPos, true)) : null;
         if (result != null && !result.IsNull())
         {
             if (prevResult != null && (result.Member != prevResult.Member || result.Type != prevResult.Type || result.Path != prevResult.Path)) return;
             RemoveHighlights(sci);
             prevToken = newToken;
             prevResult = result;
             List<SearchMatch> matches = FilterResults(GetResults(sci, prevToken), result, sci);
             if (matches == null || matches.Count == 0) return;
             highlightUnderCursorTimer.Stop();
             AddHighlights(sci, matches);
         }
         else RemoveHighlights(sci);
     }
     else RemoveHighlights(sci);
 }
 /// <summary>
 /// TODO slavara: IMPLEMENT ME
 /// </summary>
 /// <param name="matches"></param>
 /// <param name="exprType"></param>
 /// <param name="sci"></param>
 /// <returns></returns>
 private List<SearchMatch> FilterResults(List<SearchMatch> matches, ASResult exprType, ScintillaControl sci)
 {
     if (matches == null || matches.Count == 0) return null;
     MemberModel contextMember = null;
     int lineFrom = 0;
     int lineTo = sci.LineCount;
     FlagType localVarMask = FlagType.LocalVar | FlagType.ParameterVar;
     bool isLocalVar = false;
     if (exprType.Member != null)
     {
         if ((exprType.Member.Flags & localVarMask) > 0)
         {
             contextMember = exprType.Context.ContextFunction;
             lineFrom = contextMember.LineFrom;
             lineTo = contextMember.LineTo;
             isLocalVar = true;
         }
     }
     List<SearchMatch> newMatches = new List<SearchMatch>();
     foreach (SearchMatch m in matches)
     {
         if (m.Line < lineFrom || m.Line > lineTo) continue;
         int pos = sci.MBSafePosition(m.Index);
         exprType = ASComplete.GetExpressionType(sci, sci.WordEndPosition(pos, true));
         if (exprType != null)
         {
             MemberModel member = exprType.Member;
             if (!isLocalVar)
             {
                 if ((exprType.Type != null && member == null) || (member != null && (member.Flags & localVarMask) == 0)) newMatches.Add(m);
             }
             else if (member != null && (member.Flags & localVarMask) > 0) newMatches.Add(m);
         }
     }
     return newMatches;
 }
Exemple #12
0
        private static void GenerateFunctionJob(GeneratorJobType job, ScintillaControl sci, MemberModel member, bool detach, ClassModel inClass)
        {
            var position = 0;
            bool isOtherClass = false;
            Visibility visibility = job.Equals(GeneratorJobType.FunctionPublic) ? Visibility.Public : GetDefaultVisibility(inClass);
            int wordPos = sci.WordEndPosition(sci.CurrentPos, true);
            List<FunctionParameter> functionParameters = ParseFunctionParameters(sci, wordPos);
            // evaluate, if the function should be generated in other class
            ASResult funcResult = ASComplete.GetExpressionType(sci, sci.WordEndPosition(sci.CurrentPos, true));
            var memberIsStatic = member != null && (member.Flags & FlagType.Static) > 0;
            var dot = ASContext.Context.Features.dot;
            if (ASContext.CommonSettings.GenerateScope && !funcResult.Context.Value.Contains(dot))
            {
                position = sci.CurrentPos;
                var start = sci.WordStartPosition(position, true);
                var length = sci.MBSafeTextLength(contextToken);
                sci.SetSel(start, start + length);
                var scope = memberIsStatic ? inClass.QualifiedName : "this";
                var text = scope + dot + contextToken;
                sci.ReplaceSel(text);
                UpdateLookupPosition(position, text.Length - length);
            }
            int contextOwnerPos = GetContextOwnerEndPos(sci, sci.WordStartPosition(sci.CurrentPos, true));
            MemberModel isStatic = new MemberModel();
            if (contextOwnerPos != -1)
            {
                ASResult contextOwnerResult = ASComplete.GetExpressionType(sci, contextOwnerPos);
                if (contextOwnerResult != null
                    && (contextOwnerResult.Member == null || (contextOwnerResult.Member.Flags & FlagType.Constructor) > 0)
                    && contextOwnerResult.Type != null)
                {
                    isStatic.Flags |= FlagType.Static;
                }
            }
            else if (memberIsStatic)
            {
                isStatic.Flags |= FlagType.Static;
            }
            if (funcResult.RelClass != null && !funcResult.RelClass.IsVoid() && !funcResult.RelClass.Equals(inClass))
            {
                AddLookupPosition();
                lookupPosition = -1;

                ASContext.MainForm.OpenEditableDocument(funcResult.RelClass.InFile.FileName, true);
                sci = ASContext.CurSciControl;
                isOtherClass = true;

                FileModel fileModel = new FileModel();
                fileModel.Context = ASContext.Context;
                ASFileParser parser = new ASFileParser();
                parser.ParseSrc(fileModel, sci.Text);

                foreach (ClassModel cm in fileModel.Classes)
                {
                    if (cm.QualifiedName.Equals(funcResult.RelClass.QualifiedName))
                    {
                        funcResult.RelClass = cm;
                        break;
                    }
                }
                inClass = funcResult.RelClass;

                ASContext.Context.UpdateContext(inClass.LineFrom);
            }

            string blockTmpl;
            if ((isStatic.Flags & FlagType.Static) > 0)
            {
                blockTmpl = TemplateUtils.GetBoundary("StaticMethods");
            }
            else if ((visibility & Visibility.Public) > 0)
            {
                blockTmpl = TemplateUtils.GetBoundary("PublicMethods");
            }
            else
            {
                blockTmpl = TemplateUtils.GetBoundary("PrivateMethods");
            }
            var latest = TemplateUtils.GetTemplateBlockMember(sci, blockTmpl);
            if (latest == null || (!isOtherClass && member == null))
            {
                latest = GetLatestMemberForFunction(inClass, visibility, isStatic);
                // if we generate function in current class..
                if (!isOtherClass)
                {
                    MethodsGenerationLocations location = ASContext.CommonSettings.MethodsGenerationLocations;
                    if (member == null)
                    {
                        detach = false;
                        lookupPosition = -1;
                        position = sci.WordStartPosition(sci.CurrentPos, true);
                        sci.SetSel(position, sci.WordEndPosition(position, true));
                    }
                    else if (latest != null && location == MethodsGenerationLocations.AfterSimilarAccessorMethod)
                    {
                        position = sci.PositionFromLine(latest.LineTo + 1) - (sci.EOLMode == 0 ? 2 : 1);
                        sci.SetSel(position, position);
                    }
                    else
                    {
                        position = sci.PositionFromLine(member.LineTo + 1) - (sci.EOLMode == 0 ? 2 : 1);
                        sci.SetSel(position, position);
                    }
                }
                else // if we generate function in another class..
                {
                    if (latest != null)
                    {
                        position = sci.PositionFromLine(latest.LineTo + 1) - (sci.EOLMode == 0 ? 2 : 1);
                    }
                    else
                    {
                        position = GetBodyStart(inClass.LineFrom, inClass.LineTo, sci);
                        detach = false;
                    }
                    sci.SetSel(position, position);
                }
            }
            else
            {
                position = sci.PositionFromLine(latest.LineTo + 1) - (sci.EOLMode == 0 ? 2 : 1);
                sci.SetSel(position, position);
            }

            // add imports to function argument types
            if (functionParameters.Count > 0)
            {
                List<string> typesUsed = new List<string>();
                foreach (FunctionParameter parameter in functionParameters)
                {
                    try
                    {
                        typesUsed.Add(parameter.paramQualType);
                    }
                    catch (Exception) { }
                }
                int o = AddImportsByName(typesUsed, sci.LineFromPosition(position));
                position += o;
                if (latest == null)
                    sci.SetSel(position, sci.WordEndPosition(position, true));
                else
                    sci.SetSel(position, position);
            }
            List<MemberModel> parameters = new List<MemberModel>();
            foreach (FunctionParameter parameter in functionParameters)
            {
                parameters.Add(new MemberModel(parameter.paramName, parameter.paramType, FlagType.ParameterVar, 0));
            }
            var newMember = NewMember(contextToken, isStatic, FlagType.Function, visibility);
            newMember.Parameters = parameters;
            GenerateFunction(newMember, position, detach, inClass);
        }
        /// <summary>
        /// Gets a word from the specified position
        /// </summary>
        public static string GetWordFromPosition(ScintillaControl sci,int position, ref int start, ref int end)
        {
            try
            {
                //startPosition = sci.MBSafeCharPosition(sci.WordStartPosition(position, true));
                //endPosition = sci.MBSafeCharPosition(sci.WordEndPosition(position, true));
                //string keyword = sci.Text.Substring(startPosition, endPosition - startPosition);

                start = sci.WordStartPosition(position, true);
                end = sci.WordEndPosition(position, true);
                int startPosition = sci.MBSafeCharPosition(start);
                int endPosition = sci.MBSafeCharPosition(end);

                string keyword = sci.Text.Substring(startPosition, endPosition - startPosition);

                if (keyword.Length==0 || keyword.Equals(" "))  return null;

                //startPosition = sci.WordStartPosition(position, true);
                //endPosition = sci.WordEndPosition(position, true);
                return keyword.Trim();
            }
            catch
            {
                return null;
            }
        }
Exemple #14
0
        public static void GenerateDelegateMethods(ScintillaControl Sci, MemberModel member,
            Dictionary<MemberModel, ClassModel> selectedMembers, ClassModel classModel, ClassModel inClass)
        {
            Sci.BeginUndoAction();
            try
            {
                string result = TemplateUtils.ReplaceTemplateVariable(
                    TemplateUtils.GetTemplate("DelegateMethodsHeader"), 
                    "Class", 
                    classModel.Type);

                int position = -1;
                ClassModel type;
                List<string> importsList = new List<string>();
                bool isStaticMember = false;

                if ((member.Flags & FlagType.Static) > 0)
                    isStaticMember = true;

                inClass.ResolveExtends();
                
                Dictionary<MemberModel, ClassModel>.KeyCollection selectedMemberKeys = selectedMembers.Keys;
                foreach (MemberModel m in selectedMemberKeys)
                {
                    MemberModel mCopy = (MemberModel) m.Clone();

                    string methodTemplate = NewLine;

                    bool overrideFound = false;
                    ClassModel baseClassType = inClass;
                    while (baseClassType != null && !baseClassType.IsVoid())
                    {
                        MemberList inClassMembers = baseClassType.Members;
                        foreach (MemberModel inClassMember in inClassMembers)
                        {
                            if ((inClassMember.Flags & FlagType.Function) > 0
                               && m.Name.Equals(inClassMember.Name))
                            {
                                mCopy.Flags |= FlagType.Override;
                                overrideFound = true;
                                break;
                            }
                        }

                        if (overrideFound)
                            break;

                        baseClassType = baseClassType.Extends;
                    }

                    if (isStaticMember && (m.Flags & FlagType.Static) == 0)
                        mCopy.Flags |= FlagType.Static;

                    if ((m.Flags & FlagType.Setter) > 0)
                    {
                        methodTemplate += TemplateUtils.GetTemplate("Setter");
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Modifiers", 
                            (TemplateUtils.GetStaticExternOverride(m) + TemplateUtils.GetModifiers(m)).Trim());
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Name", m.Name);
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "EntryPoint", "");
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Type", m.Parameters[0].Type);
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Member", member.Name + "." + m.Name);
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Void", ASContext.Context.Features.voidKey ?? "void");
                    }
                    else if ((m.Flags & FlagType.Getter) > 0)
                    {
                        methodTemplate += TemplateUtils.GetTemplate("Getter");
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Modifiers",
                            (TemplateUtils.GetStaticExternOverride(m) + TemplateUtils.GetModifiers(m)).Trim());
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Name", m.Name);
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "EntryPoint", "");
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Type", FormatType(m.Type));
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Member", member.Name + "." + m.Name);
                    }
                    else
                    {
                        methodTemplate += TemplateUtils.GetTemplate("Function");
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Body", "<<$(Return) >>$(Body)");
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "EntryPoint", null);
                        methodTemplate = TemplateUtils.ToDeclarationWithModifiersString(mCopy, methodTemplate);
                        if (m.Type != null && m.Type.ToLower() != "void")
                            methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Return", "return");
                        else
                            methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Return", null);

                        // check for varargs
                        bool isVararg = false;
                        if (m.Parameters != null && m.Parameters.Count > 0)
                        {
                            MemberModel mm = m.Parameters[m.Parameters.Count - 1];
                            if (mm.Name.StartsWithOrdinal("..."))
                                isVararg = true;
                        }

                        string callMethodTemplate = TemplateUtils.GetTemplate("CallFunction");
                        if (!isVararg)
                        {
                            callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Name", member.Name + "." + m.Name);
                            callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Arguments", 
                                TemplateUtils.CallParametersString(m));
                            callMethodTemplate += ";";
                        }
                        else 
                        {
                            List<MemberModel> pseudoParamsList = new List<MemberModel>();
                            pseudoParamsList.Add(new MemberModel("null", null, FlagType.ParameterVar, 0));
                            pseudoParamsList.Add(new MemberModel("[$(Subarguments)].concat($(Lastsubargument))", null, FlagType.ParameterVar, 0));
                            MemberModel pseudoParamsOwner = new MemberModel();
                            pseudoParamsOwner.Parameters = pseudoParamsList;

                            callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Name",
                                member.Name + "." + m.Name + ".apply");
                            callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Arguments",
                                TemplateUtils.CallParametersString(pseudoParamsOwner));
                            callMethodTemplate += ";";

                            List<MemberModel> arrayParamsList = new List<MemberModel>();
                            for (int i = 0; i < m.Parameters.Count - 1; i++)
                            {
                                MemberModel param = m.Parameters[i];
                                arrayParamsList.Add(param);
                            }

                            pseudoParamsOwner.Parameters = arrayParamsList;

                            callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Subarguments",
                                TemplateUtils.CallParametersString(pseudoParamsOwner));

                            callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Lastsubargument", 
                                m.Parameters[m.Parameters.Count - 1].Name.TrimStart(new char[] { '.', ' '}));
                        }

                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Body", callMethodTemplate);
                    }
                    methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "BlankLine", NewLine);
                    result += methodTemplate;

                    if (m.Parameters != null)
                    {
                        for (int i = 0; i < m.Parameters.Count; i++)
                        {
                            MemberModel param = m.Parameters[i];
                            if (param.Type != null)
                            {
                                type = ASContext.Context.ResolveType(param.Type, selectedMembers[m].InFile);
                                importsList.Add(type.QualifiedName);
                            }
                        }
                    }

                    if (position < 0)
                    {
                        MemberModel latest = GetLatestMemberForFunction(inClass, mCopy.Access, mCopy);
                        if (latest == null)
                        {
                            position = Sci.WordStartPosition(Sci.CurrentPos, true);
                            Sci.SetSel(position, Sci.WordEndPosition(position, true));
                        }
                        else
                        {
                            position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1);
                            Sci.SetSel(position, position);
                        }
                    }
                    else
                    {
                        position = Sci.CurrentPos;
                    }

                    if (m.Type != null)
                    {
                        type = ASContext.Context.ResolveType(m.Type, selectedMembers[m].InFile);
                        importsList.Add(type.QualifiedName);
                    }
                }

                if (importsList.Count > 0 && position > -1)
                {
                    int o = AddImportsByName(importsList, Sci.LineFromPosition(position));
                    position += o;
                    Sci.SetSel(position, position);
                }

                InsertCode(position, result, Sci);
            }
            finally { Sci.EndUndoAction(); }
        }
Exemple #15
0
        private static void EventMetatag(ClassModel inClass, ScintillaControl sci, MemberModel member)
        {
            ASResult resolve = ASComplete.GetExpressionType(sci, sci.WordEndPosition(sci.CurrentPos, true));
            string line = sci.GetLine(inClass.LineFrom);
            int position = sci.PositionFromLine(inClass.LineFrom) + (line.Length - line.TrimStart().Length);

            string value = resolve.Member.Value;
            if (value != null)
            {
                if (value.StartsWith('\"'))
                {
                    value = value.Trim(new char[] { '"' });
                }
                else if (value.StartsWith('\''))
                {
                    value = value.Trim(new char[] { '\'' });
                }
            }
            else value = resolve.Member.Type;

            if (string.IsNullOrEmpty(value))
                return;

            Regex re1 = new Regex("'(?:[^'\\\\]|(?:\\\\\\\\)|(?:\\\\\\\\)*\\\\.{1})*'");
            Regex re2 = new Regex("\"(?:[^\"\\\\]|(?:\\\\\\\\)|(?:\\\\\\\\)*\\\\.{1})*\"");
            Match m1 = re1.Match(value);
            Match m2 = re2.Match(value);

            if (m1.Success || m2.Success)
            {
                Match m = null;
                if (m1.Success && m2.Success) m = m1.Index > m2.Index ? m2 : m1;
                else if (m1.Success) m = m1;
                else m = m2;
                value = value.Substring(m.Index + 1, m.Length - 2);
            }

            string template = TemplateUtils.GetTemplate("EventMetatag");
            template = TemplateUtils.ReplaceTemplateVariable(template, "Name", value);
            template = TemplateUtils.ReplaceTemplateVariable(template, "Type", contextParam);
            template += "\n$(Boundary)";

            AddLookupPosition();

            sci.CurrentPos = position;
            sci.SetSel(position, position);
            InsertCode(position, template, sci);
        }
Exemple #16
0
        private static void GenerateDefaultHandlerName(ScintillaControl sci, int position, int targetPos, string eventName, bool closeBrace)
        {
            string target = null;
            int contextOwnerPos = GetContextOwnerEndPos(sci, sci.WordStartPosition(targetPos, true));
            if (contextOwnerPos != -1)
            {
                ASResult contextOwnerResult = ASComplete.GetExpressionType(sci, contextOwnerPos);
                if (contextOwnerResult != null && !contextOwnerResult.IsNull()
                    && contextOwnerResult.Member != null)
                {
                    if (contextOwnerResult.Member.Name == "contentLoaderInfo" && sci.CharAt(contextOwnerPos) == '.')
                    {
                        // we want to name the event from the loader var and not from the contentLoaderInfo parameter
                        contextOwnerPos = GetContextOwnerEndPos(sci, sci.WordStartPosition(contextOwnerPos - 1, true));
                        if (contextOwnerPos != -1)
                        {
                            contextOwnerResult = ASComplete.GetExpressionType(sci, contextOwnerPos);
                            if (contextOwnerResult != null && !contextOwnerResult.IsNull()
                                && contextOwnerResult.Member != null)
                            {
                                target = contextOwnerResult.Member.Name;
                            }
                        }
                    }
                    else
                    {
                        target = contextOwnerResult.Member.Name;
                    }
                }
            }
            
            eventName = Camelize(eventName.Substring(eventName.LastIndexOf('.') + 1));
            if (target != null) target = target.TrimStart(new char[] { '_' });

            switch (ASContext.CommonSettings.HandlerNamingConvention)
            {
                case HandlerNamingConventions.handleTargetEventName:
                    if (target == null) contextToken = "handle" + Capitalize(eventName);
                    else contextToken = "handle" + Capitalize(target) + Capitalize(eventName);
                    break;
                case HandlerNamingConventions.onTargetEventName:
                    if (target == null) contextToken = "on" + Capitalize(eventName);
                    else contextToken = "on" + Capitalize(target) + Capitalize(eventName);
                    break;
                case HandlerNamingConventions.target_eventNameHandler:
                    if (target == null) contextToken = eventName + "Handler";
                    else contextToken = target + "_" + eventName + "Handler";
                    break;
                default: //HandlerNamingConventions.target_eventName
                    if (target == null) contextToken = eventName;
                    else contextToken = target + "_" + eventName;
                    break;
            }

            char c = (char)sci.CharAt(position - 1);
            if (c == ',') InsertCode(position, "$(Boundary) " + contextToken + "$(Boundary)", sci);
            else InsertCode(position, contextToken, sci);

            position = sci.WordEndPosition(position + 1, true);
            sci.SetSel(position, position);
            c = (char)sci.CharAt(position);
            if (c <= 32) if (closeBrace) sci.ReplaceSel(");"); else sci.ReplaceSel(";");

            sci.SetSel(position, position);
        }
Exemple #17
0
        private static void ConvertToConst(ClassModel inClass, ScintillaControl sci, MemberModel member, bool detach)
        {
            String suggestion = "NEW_CONST";
            String label = TextHelper.GetString("ASCompletion.Label.ConstName");
            String title = TextHelper.GetString("ASCompletion.Title.ConvertToConst");

            Hashtable info = new Hashtable();
            info["suggestion"] = suggestion;
            info["label"] = label;
            info["title"] = title;
            DataEvent de = new DataEvent(EventType.Command, "ProjectManager.LineEntryDialog", info);
            EventManager.DispatchEvent(null, de);
            if (!de.Handled)
                return;
            
            suggestion = (string)info["suggestion"];

            int position = sci.CurrentPos;
            int style = sci.BaseStyleAt(position);
            MemberModel latest = null;

            int wordPosEnd = position + 1;
            int wordPosStart = position;

            while (sci.BaseStyleAt(wordPosEnd) == style) wordPosEnd++;
            while (sci.BaseStyleAt(wordPosStart - 1) == style) wordPosStart--;
            
            sci.SetSel(wordPosStart, wordPosEnd);
            string word = sci.SelText;
            sci.ReplaceSel(suggestion);
            
            if (member == null)
            {
                detach = false;
                lookupPosition = -1;
                position = sci.WordStartPosition(sci.CurrentPos, true);
                sci.SetSel(position, sci.WordEndPosition(position, true));
            }
            else
            {
                latest = GetLatestMemberForVariable(GeneratorJobType.Constant, inClass, 
                    Visibility.Private, new MemberModel("", "", FlagType.Static, 0));
                if (latest != null)
                {
                    position = FindNewVarPosition(sci, inClass, latest);
                }
                else
                {
                    position = GetBodyStart(inClass.LineFrom, inClass.LineTo, sci);
                    detach = false;
                }
                if (position <= 0) return;
                sci.SetSel(position, position);
            }

            MemberModel m = NewMember(suggestion, member, FlagType.Variable | FlagType.Constant | FlagType.Static, GetDefaultVisibility(inClass));

            var features = ASContext.Context.Features;

            switch (style)
            {
                case 4:
                    m.Type = features.numberKey;
                    break;
                case 6:
                case 7:
                    m.Type = features.stringKey;
                    break;
            }

            m.Value = word;
            GenerateVariable(m, position, detach);
        }
Exemple #18
0
        private void OnMouseHover(ScintillaControl sci, int position)
        {
            if (!ASContext.Context.IsFileValid)
                return;

            lastHoverPosition = position;

            // get word at mouse position
            int style = sci.BaseStyleAt(position);
            if (!ASComplete.IsTextStyle(style))
                return;
            position = sci.WordEndPosition(position, true);
            ASResult result = ASComplete.GetExpressionType(sci, position);

            // set tooltip
            if (!result.IsNull())
            {
                string text = ASComplete.GetToolTipText(result);
                if (text == null) return;
                // show tooltip
                UITools.Tip.ShowAtMouseLocation(text);
            }
        }
        private static void ConvertToConst(ClassModel inClass, ScintillaControl Sci, MemberModel member, bool detach)
        {
            String suggestion = "NEW_CONST";
            String label = TextHelper.GetString("ASCompletion.Label.ConstName");
            String title = TextHelper.GetString("ASCompletion.Title.ConvertToConst");

            Hashtable info = new Hashtable();
            info["suggestion"] = suggestion;
            info["label"] = label;
            info["title"] = title;
            DataEvent de = new DataEvent(EventType.Command, "ProjectManager.LineEntryDialog", info);
            EventManager.DispatchEvent(null, de);
            if (!de.Handled)
                return;
            
            suggestion = (string)info["suggestion"];

            int position = Sci.CurrentPos;
            MemberModel latest = null;

            int wordPosEnd = Sci.WordEndPosition(position, true);
            int wordPosStart = Sci.WordStartPosition(position, true);
            char cr = (char)Sci.CharAt(wordPosEnd);
            if (cr == '.')
            {
                wordPosEnd = Sci.WordEndPosition(wordPosEnd + 1, true);
            }
            else
            {
                cr = (char)Sci.CharAt(wordPosStart - 1);
                if (cr == '.')
                {
                    wordPosStart = Sci.WordStartPosition(wordPosStart - 1, true);
                }
            }
            Sci.SetSel(wordPosStart, wordPosEnd);
            string word = Sci.SelText;
            Sci.ReplaceSel(suggestion);
            
            if (member == null)
            {
                detach = false;
                lookupPosition = -1;
                position = Sci.WordStartPosition(Sci.CurrentPos, true);
                Sci.SetSel(position, Sci.WordEndPosition(position, true));
            }
            else
            {
                latest = GetLatestMemberForVariable(GeneratorJobType.Constant, inClass, 
                    Visibility.Private, new MemberModel("", "", FlagType.Static, 0));
                if (latest != null)
                {
                    position = FindNewVarPosition(Sci, inClass, latest);
                }
                else
                {
                    position = GetBodyStart(inClass.LineFrom, inClass.LineTo, Sci);
                    detach = false;
                }
                if (position <= 0) return;
                Sci.SetSel(position, position);
            }

            MemberModel m = NewMember(suggestion, member, FlagType.Variable | FlagType.Constant | FlagType.Static);
            m.Type = ASContext.Context.Features.numberKey;
            m.Value = word;
            GenerateVariable(m, position, detach);
        }