Beispiel #1
0
        void InitializeClasspaths()
        {
            IASContext context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language);

            if (context == null)
            {
                return;
            }
            string projectDir = Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath);

            foreach (PathModel classpath in context.Classpath)
            {
                if (classpath.IsVirtual)
                {
                    continue;
                }
                string path     = classpath.Path;
                string fullPath = path;
                if (!Path.IsPathRooted(path))
                {
                    fullPath = Path.GetFullPath(path);
                }
                if (fullPath.StartsWith(projectDir))
                {
                    projectClasspaths.AddRange(GetClasspaths(path, projectDir));
                }
                else
                {
                    externalClasspaths.AddRange(GetClasspaths(path));
                }
            }
        }
Beispiel #2
0
        internal HashSet <ClassModel> ResolveInterfaces(ClassModel cls)
        {
            if (cls == null || cls.IsVoid())
            {
                return(new HashSet <ClassModel>());
            }
            if (cls.Implements == null)
            {
                return(ResolveInterfaces(cls.Extends));
            }

            var context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language);

            return(cls.Implements
                   .Select(impl => context.ResolveType(impl, cls.InFile))
                   .Where(interf => interf != null && !interf.IsVoid())
                   .SelectMany(interf => //take the interfaces we found already and add all interfaces they extend
            {
                interf.ResolveExtends();
                var set = ResolveExtends(interf);
                set.Add(interf);
                return set;
            })
                   .Union(ResolveInterfaces(cls.Extends)).ToHashSet());
        }
Beispiel #3
0
        /// <summary>
        /// Checks if files is related to the project
        /// TODO support SWCs -> refactor test as IProject method
        /// </summary>
        public static Boolean IsProjectRelatedFile(IProject project, String file)
        {
            if (project == null)
            {
                return(false);
            }
            IASContext context = ASContext.GetLanguageContext(project.Language);

            if (context == null)
            {
                return(false);
            }
            foreach (PathModel pathModel in context.Classpath)
            {
                string absolute = project.GetAbsolutePath(pathModel.Path);
                if (file.StartsWith(absolute))
                {
                    return(true);
                }
            }
            // If no source paths are defined, is it under the project?
            if (project.SourcePaths.Length == 0)
            {
                String projRoot = Path.GetDirectoryName(project.ProjectPath);
                if (file.StartsWith(projRoot))
                {
                    return(true);
                }
            }
            return(false);
        }
        /// <summary>
        /// Gets all files related to the project
        /// </summary>
        private static List <String> GetAllProjectRelatedFiles(IProject project)
        {
            List <String> files  = new List <String>();
            string        filter = GetSearchPatternFromLang(project.Language.ToLower());

            if (string.IsNullOrEmpty(filter))
            {
                return(files);
            }
            IASContext context = ASContext.GetLanguageContext(project.Language);

            if (context == null)
            {
                return(files);
            }
            foreach (PathModel pathModel in context.Classpath)
            {
                string path     = pathModel.Path;
                String absolute = project.GetAbsolutePath(path);
                if (Directory.Exists(path))
                {
                    files.AddRange(Directory.GetFiles(absolute, filter, SearchOption.AllDirectories));
                }
            }
            // If no source paths are defined, get files directly from project path
            if (project.SourcePaths.Length == 0)
            {
                String projRoot = Path.GetDirectoryName(project.ProjectPath);
                files.AddRange(Directory.GetFiles(projRoot, filter, SearchOption.AllDirectories));
            }
            return(files);
        }
Beispiel #5
0
        public void LintAsync(string[] files, LintCallback callback)
        {
            var context = ASContext.GetLanguageContext("haxe") as Context;

            if (context == null || !CanContinue(context))
            {
                return;
            }

            var total = files.Length;
            var list  = new List <LintingResult>();

            foreach (var file in files)
            {
                ITabbedDocument document;
                if (!File.Exists(file) || (document = DocumentManager.FindDocument(file)) != null && document.IsUntitled)
                {
                    total--;
                    continue;
                }

                var sciCreated = false;
                var sci        = document?.SciControl;
                if (sci == null)
                {
                    sci        = GetStubSci(file);
                    sciCreated = true;
                }

                var hc = context.GetHaxeComplete(sci, new ASExpr {
                    Position = 0
                }, true, HaxeCompilerService.DIAGNOSTICS);

                fileQueue.Run(finished =>
                {
                    hc.GetDiagnostics((complete, results, status) =>
                    {
                        total--;

                        if (sciCreated)
                        {
                            sci.Dispose();
                        }

                        AddDiagnosticsResults(list, status, results, hc);

                        if (total == 0)
                        {
                            callback(list);
                        }

                        finished();
                    });
                });
            }
        }
Beispiel #6
0
        static ClassModel GetClassModel(MemberModel cls)
        {
            var pos     = cls.Type.LastIndexOf('.');
            var package = pos == -1 ? "" : cls.Type.Substring(0, pos);
            var name    = cls.Type.Substring(pos + 1);

            var context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language);

            return(context.GetModel(package, name, ""));
        }
        void CreateItemsList()
        {
            closedTypes.Clear();
            openedTypes.Clear();
            TypeToClassModel.Clear();
            var context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language);

            if (context == null)
            {
                return;
            }
            var projectFolder    = Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath);
            var onlyProjectTypes = !searchingInExternalClasspaths.Checked;

            foreach (var classpath in context.Classpath)
            {
                if (onlyProjectTypes)
                {
                    var path = classpath.Path;
                    if (!Path.IsPathRooted(classpath.Path))
                    {
                        path = Path.GetFullPath(Path.Combine(projectFolder, classpath.Path));
                    }
                    if (!path.StartsWith(projectFolder))
                    {
                        continue;
                    }
                }
                classpath.ForeachFile(model =>
                {
                    foreach (var aClass in model.Classes)
                    {
                        var type = aClass.Type;
                        if (TypeToClassModel.ContainsKey(type))
                        {
                            continue;
                        }
                        if (FormHelper.IsFileOpened(aClass.InFile.FileName))
                        {
                            openedTypes.Add(type);
                        }
                        else
                        {
                            closedTypes.Add(type);
                        }
                        TypeToClassModel.Add(type, aClass);
                    }
                    return(true);
                });
            }
        }
Beispiel #8
0
        /// <summary>
        /// Checks if the class extends / implements something that does not exist (yet).
        /// </summary>
        /// <returns>True if nothing is found, false if there are non-existing parents</returns>
        /// <param name="cls"></param>
        bool IsCompletelyResolvable(ClassModel cls)
        {
            if (cls == null || cls.IsVoid())
            {
                return(true);
            }

            var context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language);

            var missingExtends    = cls.ExtendsType != "Dynamic" && cls.ExtendsType != "Void" && cls.ExtendsType != null && cls.Extends.IsVoid(); //Dynamic means the class extends nothing
            var missingInterfaces = cls.Implements != null && cls.Implements.Any(i => GetCachedModel(context.ResolveType(i, cls.InFile)) == null);

            //also check parent interfaces and extends
            return(!missingInterfaces && !missingExtends && (cls.Implements == null || ResolveInterfaces(cls).All(IsCompletelyResolvable)) && IsCompletelyResolvable(cls.Extends));
        }
        public void LintAsync(IEnumerable <string> files, LintCallback callback)
        {
            var context = ASContext.GetLanguageContext("haxe") as Context;

            if (context == null || !(PluginBase.CurrentProject is ProjectManager.Projects.Haxe.HaxeProject) || !CanContinue(context))
            {
                return;
            }

            var total = files.Count();
            var list  = new List <LintingResult>();

            String untitledFileStart = TextHelper.GetString("FlashDevelop.Info.UntitledFileStart");

            foreach (var file in files)
            {
                if (!File.Exists(file) || file.StartsWithOrdinal(untitledFileStart))
                {
                    total--;
                    continue;
                }

                var sci = GetStubSci(file);

                var hc = context.GetHaxeComplete(sci, new ASExpr {
                    Position = 0
                }, true, HaxeCompilerService.DIAGNOSTICS);

                fileQueue.Run(finished =>
                {
                    hc.GetDiagnostics((complete, results, status) =>
                    {
                        total--;

                        sci.Dispose();

                        AddDiagnosticsResults(list, status, results, hc);

                        if (total == 0)
                        {
                            callback(list);
                        }

                        finished();
                    });
                });
            }
        }
        public override Command CreateFindAllReferencesCommand(ASResult target, bool output, bool ignoreDeclarations, bool onlySourceFiles)
        {
            var context  = (Context)ASContext.GetLanguageContext("haxe");
            var settings = (HaXeSettings)context.Settings;

            if ((settings.EnabledFeatures & CompletionFeatures.EnableForFindAllReferences) == CompletionFeatures.EnableForFindAllReferences &&
                settings.CompletionMode != HaxeCompletionModeEnum.FlashDevelop &&
                target.Member != null && ((target.Member.Flags & FlagType.LocalVar) > 0 || (target.Member.Flags & FlagType.ParameterVar) > 0) &&
                context.GetCurrentSDKVersion() >= "3.2.0")
            {
                return(new Commands.HaxeFindAllReferences(target, output, ignoreDeclarations)
                {
                    OnlySourceFiles = onlySourceFiles
                });
            }
            return(base.CreateFindAllReferencesCommand(target, output, ignoreDeclarations, onlySourceFiles));
        }
Beispiel #11
0
        private void CreateItemsList()
        {
            projectTypes.Clear();
            openedTypes.Clear();
            dictionary.Clear();

            IASContext context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language);

            if (context == null)
            {
                return;
            }
            foreach (PathModel path in context.Classpath)
            {
                path.ForeachFile(FileModelDelegate);
            }
        }
Beispiel #12
0
        private void baseBrowse_Click(object sender, EventArgs e)
        {
            ClassBrowser browser = new ClassBrowser();
            IASContext   context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language);

            try
            {
                browser.ClassList = context.GetAllProjectClasses();
            }
            catch { }
            browser.ExcludeFlag = FlagType.Interface;
            browser.IncludeFlag = FlagType.Class;
            if (browser.ShowDialog(this) == DialogResult.OK)
            {
                this.baseBox.Text = browser.SelectedClass;
            }
            this.okButton.Focus();
        }
        void OnTimerTick(object sender, EventArgs e)
        {
            var context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language);

            if (context == null || SelectedNode != null || context.Classpath.Count == openedTypes.Count + closedTypes.Count)
            {
                return;
            }
            var filesCount = context.Classpath.Sum(it => it.FilesCount);

            if (filesCount == this.filesCount)
            {
                return;
            }
            this.filesCount = filesCount;
            CreateItemsList();
            RefreshTree();
        }
Beispiel #14
0
        /// <summary>
        /// Update the cache for the whole project
        /// </summary>
        public void UpdateCompleteCache()
        {
            var action = new Action(() =>
            {
                try
                {
                    var context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language);
                    if (context == null || context.Classpath == null || PathExplorer.IsWorking)
                    {
                        if (FinishedUpdate != null)
                        {
                            PluginBase.RunAsync(new MethodInvoker(FinishedUpdate));
                        }
                        return;
                    }

                    var c = new Dictionary <ClassModel, CachedClassModel>(cache.Comparer);

                    foreach (MemberModel memberModel in context.GetAllProjectClasses())
                    {
                        if (PluginBase.MainForm.ClosingEntirely)
                        {
                            return; //make sure we leave if the form is closing, so we do not block it
                        }
                        var cls = GetClassModel(memberModel);
                        UpdateClass(cls, c);
                    }

                    lock (cache)
                        cache = c;

                    if (FinishedUpdate != null)
                    {
                        PluginBase.RunAsync(new MethodInvoker(FinishedUpdate));
                    }
                }
                catch (Exception)
                {
                }
            });

            action.BeginInvoke(null, null);
        }
Beispiel #15
0
        void ShowTypeExplorer()
        {
            if (PluginBase.CurrentProject == null)
            {
                return;
            }
            var form     = new TypeExplorerForm((Settings)Settings);
            var features = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language).Features;

            if (features.hasClasses)
            {
                form.AddFilter(QuickFilterMenuItem.ShowOnlyClasses);
            }
            if (features.hasInterfaces)
            {
                form.AddFilter(QuickFilterMenuItem.ShowOnlyInterfaces);
            }
            if (features.hasTypeDefs)
            {
                form.AddFilter(QuickFilterMenuItem.ShowOnlyTypeDefs);
            }
            if (features.hasEnums)
            {
                form.AddFilter(QuickFilterMenuItem.ShowOnlyEnums);
            }
            form.KeyUp   += OnFormKeyUp;
            form.Shown   += OnFormShown;
            form.Closing += OnFormClosing;
            if (form.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            var node = form.SelectedNode;

            if (node != null)
            {
                FormHelper.Navigate(node);
            }
        }
Beispiel #16
0
        /// <summary>
        /// Added interface
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void implementBrowse_Click(object sender, EventArgs e)
        {
            ClassBrowser browser = new ClassBrowser();
            MemberList   known   = null;

            browser.IncludeFlag = FlagType.Interface;
            IASContext context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language);

            try
            {
                known = context.GetAllProjectClasses();
                known.Merge(ASContext.Context.GetVisibleExternalElements(true));
            }
            catch (Exception error)
            {
                Debug.WriteLine(error.StackTrace);
            }

            browser.ClassList = known;

            if (browser.ShowDialog(this) == DialogResult.OK)
            {
                if (browser.SelectedClass != null)
                {
                    foreach (string item in this.implementList.Items)
                    {
                        if (item == browser.SelectedClass)
                        {
                            return;
                        }
                    }
                    this.implementList.Items.Add(browser.SelectedClass);
                }
            }
            this.implementRemove.Enabled     = this.implementList.Items.Count > 0;
            this.implementList.SelectedIndex = this.implementList.Items.Count - 1;
            this.superCheck.Enabled          = this.implementList.Items.Count > 0;
            ValidateClass();
        }
Beispiel #17
0
        public void LintProjectAsync(IProject project, LintCallback callback)
        {
            var context = ASContext.GetLanguageContext("haxe") as Context;

            if (context == null || !CanContinue(context))
            {
                return;
            }

            var list = new List <LintingResult>();
            var sci  = GetStubSci();
            var hc   = context.GetHaxeComplete(sci, new ASExpr {
                Position = 0
            }, true, HaxeCompilerService.GLOBAL_DIAGNOSTICS);

            hc.GetDiagnostics((complete, results, status) =>
            {
                sci.Dispose();

                AddDiagnosticsResults(list, status, results, hc);

                callback(list);
            });
        }
Beispiel #18
0
        private string ProcessFileTemplate(string args)
        {
            Int32         eolMode          = (Int32)MainForm.Settings.EOLMode;
            String        lineBreak        = LineEndDetector.GetNewLineMarker(eolMode);
            List <String> imports          = new List <string>();
            string        extends          = "";
            string        implements       = "";
            string        access           = "";
            string        inheritedMethods = "";
            string        paramString      = "";
            string        superConstructor = "";
            string        classMetadata    = "";
            int           index;

            // resolve imports
            if (lastFileOptions.interfaces != null && lastFileOptions.interfaces.Count > 0)
            {
                string implementContinuation;
                implements = " implements ";
                index      = 0;

                if (lastFileOptions.Language == "haxe")
                {
                    bool isHaxe2 = PluginBase.CurrentSDK != null && PluginBase.CurrentSDK.Name.ToLower().Contains("haxe 2");
                    implementContinuation = isHaxe2 ? ", implements " : " implements ";
                }
                else
                {
                    implementContinuation = ", ";
                }

                foreach (string item in lastFileOptions.interfaces)
                {
                    if (item.Contains('.'))
                    {
                        imports.Add(item);
                    }
                    implements += (index > 0 ? implementContinuation : "") + item.Split('.').Last();
                    if (lastFileOptions.createInheritedMethods)
                    {
                        processOnSwitch = lastFileFromTemplate;
                        // let ASCompletion generate the implementations when file is opened
                    }
                    index++;
                }
            }
            if (lastFileOptions.superClass != "")
            {
                var superClassFullName = lastFileOptions.superClass;
                if (superClassFullName.Contains("."))
                {
                    imports.Add(superClassFullName);
                }
                var superClassShortName = superClassFullName.Split('.').Last();
                var fileName            = Path.GetFileNameWithoutExtension(lastFileFromTemplate);
                extends        = fileName == superClassShortName ? $" extends {superClassFullName}" : $" extends {superClassShortName}";
                processContext = ASContext.GetLanguageContext(lastFileOptions.Language);
                if (lastFileOptions.createConstructor && processContext != null && constructorArgs == null)
                {
                    var lastDotIndex = superClassFullName.LastIndexOf('.');
                    var cmodel       = processContext.GetModel(lastDotIndex < 0 ? "" : superClassFullName.Substring(0, lastDotIndex), superClassShortName, "");
                    if (!cmodel.IsVoid())
                    {
                        if ((cmodel.Flags & FlagType.TypeDef) != 0)
                        {
                            var tmp = cmodel;
                            while (!tmp.IsVoid())
                            {
                                if (!string.IsNullOrEmpty(tmp.Constructor))
                                {
                                    cmodel = tmp;
                                    break;
                                }
                                tmp.ResolveExtends();
                                tmp = tmp.Extends;
                            }
                        }
                        foreach (MemberModel member in cmodel.Members)
                        {
                            if (member.Name == cmodel.Constructor)
                            {
                                paramString = member.ParametersString();
                                AddImports(imports, member, cmodel);
                                superConstructor = "super(";
                                index            = 0;
                                if (member.Parameters != null)
                                {
                                    foreach (MemberModel param in member.Parameters)
                                    {
                                        if (param.Name.StartsWith('.'))
                                        {
                                            break;
                                        }
                                        var pname = TemplateUtils.GetParamName(param);
                                        superConstructor += (index > 0 ? ", " : "") + pname;
                                        index++;
                                    }
                                }
                                superConstructor += ");\n" + (lastFileOptions.Language == "as3" ? "\t\t\t" : "\t\t");
                                break;
                            }
                        }
                    }
                }
                processContext = null;
            }
            if (constructorArgs != null)
            {
                paramString = constructorArgs;
                foreach (String type in constructorArgTypes)
                {
                    if (!imports.Contains(type))
                    {
                        imports.Add(type);
                    }
                }
            }
            if (lastFileOptions.Language == "as3")
            {
                access  = lastFileOptions.isPublic ? "public " : "internal ";
                access += lastFileOptions.isDynamic ? "dynamic " : "";
                access += lastFileOptions.isFinal ? "final " : "";
            }
            else if (lastFileOptions.Language == "haxe")
            {
                access  = lastFileOptions.isPublic ? "public " : "private ";
                access += lastFileOptions.isDynamic ? "dynamic " : "";
                if (lastFileOptions.isFinal)
                {
                    classMetadata += "@:final\n";
                }
            }
            else
            {
                access = lastFileOptions.isDynamic ? "dynamic " : "";
            }
            string importsSrc = "";
            string prevImport = null;

            imports.Sort();
            foreach (string import in imports)
            {
                if (prevImport != import)
                {
                    prevImport = import;
                    if (import.LastIndexOf('.') == -1)
                    {
                        continue;
                    }
                    if (import.Substring(0, import.LastIndexOf('.')) == lastFileOptions.Package)
                    {
                        continue;
                    }
                    importsSrc += (lastFileOptions.Language == "as3" ? "\t" : "") + "import " + import + ";" + lineBreak;
                }
            }
            if (importsSrc.Length > 0)
            {
                importsSrc += (lastFileOptions.Language == "as3" ? "\t" : "") + lineBreak;
            }
            args = args.Replace("$(Import)", importsSrc);
            args = args.Replace("$(Extends)", extends);
            args = args.Replace("$(Implements)", implements);
            args = args.Replace("$(Access)", access);
            args = args.Replace("$(InheritedMethods)", inheritedMethods);
            args = args.Replace("$(ConstructorArguments)", paramString);
            args = args.Replace("$(Super)", superConstructor);
            args = args.Replace("$(ClassMetadata)", classMetadata);
            return(args);
        }
Beispiel #19
0
        private static List <String> GetAllProjectRelatedFiles(IProject project, bool onlySourceFiles, Boolean ignoreSdkFiles)
        {
            List <String> files  = new List <String>();
            string        filter = project.DefaultSearchFilter;

            if (string.IsNullOrEmpty(filter))
            {
                return(files);
            }
            string[] filters = project.DefaultSearchFilter.Split(';');
            if (!onlySourceFiles)
            {
                IASContext context = ASContext.GetLanguageContext(project.Language);
                if (context == null)
                {
                    return(files);
                }
                foreach (PathModel pathModel in context.Classpath)
                {
                    string absolute = project.GetAbsolutePath(pathModel.Path);
                    if (Directory.Exists(absolute))
                    {
                        if (ignoreSdkFiles && IsUnderSDKPath(absolute))
                        {
                            continue;
                        }
                        foreach (string filterMask in filters)
                        {
                            files.AddRange(Directory.GetFiles(absolute, filterMask, SearchOption.AllDirectories));
                        }
                    }
                }
            }
            else
            {
                var lookupPaths = project.SourcePaths.
                                  Concat(ProjectManager.PluginMain.Settings.GetGlobalClasspaths(project.Language)).
                                  Select(project.GetAbsolutePath).Distinct();
                foreach (string path in lookupPaths)
                {
                    if (Directory.Exists(path))
                    {
                        if (ignoreSdkFiles && IsUnderSDKPath(path))
                        {
                            continue;
                        }
                        foreach (string filterMask in filters)
                        {
                            files.AddRange(Directory.GetFiles(path, filterMask, SearchOption.AllDirectories));
                        }
                    }
                }
            }
            // If no source paths are defined, get files directly from project path
            if (project.SourcePaths.Length == 0)
            {
                String projRoot = Path.GetDirectoryName(project.ProjectPath);
                foreach (string filterMask in filters)
                {
                    files.AddRange(Directory.GetFiles(projRoot, filterMask, SearchOption.AllDirectories));
                }
            }
            return(files);
        }
Beispiel #20
0
        public void LintAsync(string[] files, LintCallback callback)
        {
            var context = ASContext.GetLanguageContext("haxe") as Context;

            if (context == null)
            {
                return;
            }
            var completionMode = ((HaXeSettings)context.Settings).CompletionMode;

            if (completionMode == HaxeCompletionModeEnum.FlashDevelop)
            {
                return;
            }
            var haxeVersion = context.GetCurrentSDKVersion();

            if (haxeVersion < "3.3.0")
            {
                return;
            }

            var list     = new List <LintingResult>();
            int progress = 0;
            int total    = files.Length;

            for (var i = 0; i < files.Length; i++)
            {
                var             file = files[i];
                ITabbedDocument document;
                if (!File.Exists(file) || (document = DocumentManager.FindDocument(file)) != null && document.IsUntitled)
                {
                    total--;
                    continue;
                }
                bool sciCreated = false;
                var  sci        = document?.SciControl;
                if (sci == null)
                {
                    sci = new ScintillaControl
                    {
                        FileName = file,
                        ConfigurationLanguage = "haxe"
                    };
                    sciCreated = true;
                }

                var hc = context.GetHaxeComplete(sci, new ASExpr {
                    Position = 0
                }, true, HaxeCompilerService.DIAGNOSTICS);
                hc.GetDiagnostics((complete, results, status) =>
                {
                    progress++;
                    if (sciCreated)
                    {
                        sci.Dispose();
                    }

                    if (status == HaxeCompleteStatus.DIAGNOSTICS && results != null)
                    {
                        foreach (var res in results)
                        {
                            var result = new LintingResult
                            {
                                File      = res.Range.Path,
                                FirstChar = res.Range.CharacterStart,
                                Length    = res.Range.CharacterEnd - res.Range.CharacterStart,
                                Line      = res.Range.LineStart + 1,
                            };

                            switch (res.Severity)
                            {
                            case HaxeDiagnosticsSeverity.INFO:
                                result.Severity = LintingSeverity.Info;
                                break;

                            case HaxeDiagnosticsSeverity.ERROR:
                                result.Severity = LintingSeverity.Error;
                                break;

                            case HaxeDiagnosticsSeverity.WARNING:
                                result.Severity = LintingSeverity.Warning;
                                break;

                            default:
                                continue;
                            }

                            switch (res.Kind)
                            {
                            case HaxeDiagnosticsKind.UnusedImport:
                                result.Description = TextHelper.GetString("Info.UnusedImport");
                                break;

                            case HaxeDiagnosticsKind.UnresolvedIdentifier:
                                result.Description = TextHelper.GetString("Info.UnresolvedIdentifier");
                                break;

                            case HaxeDiagnosticsKind.CompilerError:
                            case HaxeDiagnosticsKind.RemovableCode:
                                result.Description = res.Args.Description;
                                break;

                            default:     //in case new kinds are added in new compiler versions
                                continue;
                            }

                            list.Add(result);
                        }
                    }
                    else if (status == HaxeCompleteStatus.ERROR)
                    {
                        PluginBase.RunAsync(() =>
                        {
                            TraceManager.Add(hc.Errors, (int)TraceType.Error);
                        });
                    }

                    if (progress == total)
                    {
                        callback(list);
                    }
                });
            }
        }
Beispiel #21
0
        public void RunMxmlc(string cmd, string flexPath)
        {
            if (running)
            {
                return;
            }
            string basePath = null;

            if (PluginBase.CurrentProject != null)
            {
                basePath = Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath);
            }
            flexPath = PathHelper.ResolvePath(flexPath, basePath);

            if (flexPath != null && Directory.Exists(flexPath))
            {
                if (flexPath.EndsWith("bin", StringComparison.OrdinalIgnoreCase))
                {
                    flexPath = Path.GetDirectoryName(flexPath);
                }
                mxmlcPath = Path.Combine(Path.Combine(flexPath, "lib"), "mxmlc.jar");
            }
            if (mxmlcPath == null || !File.Exists(mxmlcPath))
            {
                DialogResult result = MessageBox.Show(TextHelper.GetString("Info.OpenCompilerSettings"), TextHelper.GetString("Title.ConfigurationRequired"), MessageBoxButtons.OKCancel);
                if (result == DialogResult.OK)
                {
                    IASContext context = ASContext.GetLanguageContext("as3");
                    if (context == null)
                    {
                        return;
                    }
                    PluginBase.MainForm.ShowSettingsDialog("AS3Context", "SDK");
                }
                return;
            }

            flexShellsPath = CheckResource("FlexShells.jar", flexShellsJar);
            if (!File.Exists(flexShellsPath))
            {
                ErrorManager.ShowInfo(TextHelper.GetString("Info.ResourceError"));
                return;
            }

            jvmConfig = JvmConfigHelper.ReadConfig(Path.Combine(flexPath, "bin\\jvm.config"));

            try
            {
                running = true;
                EventManager.DispatchEvent(this, new NotifyEvent(EventType.ProcessStart));

                if (mxmlcRunner == null || !mxmlcRunner.IsRunning)
                {
                    StartMxmlcRunner(flexPath);
                }

                //cmd = mainForm.ProcessArgString(cmd);
                //TraceManager.Add("MxmlcShell command: "+cmd, -1);

                ASContext.SetStatusText(TextHelper.GetString("Info.MxmlcRunning"));
                notificationSent = false;
                mxmlcRunner.HostedProcess.StandardInput.WriteLine(cmd);
            }
            catch (Exception ex)
            {
                ErrorManager.ShowError(ex);
            }
        }
Beispiel #22
0
        public void CheckAS3(string filename, string flexPath, string src)
        {
            if (running || filename.EndsWith(".mxml"))
            {
                return;
            }
            string basePath = null;

            if (PluginBase.CurrentProject != null)
            {
                basePath = Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath);
            }
            flexPath = PathHelper.ResolvePath(flexPath, basePath);
            // asc.jar in Flex2SDK
            if (flexPath != null && Directory.Exists(flexPath))
            {
                if (flexPath.EndsWith("bin", StringComparison.OrdinalIgnoreCase))
                {
                    flexPath = Path.GetDirectoryName(flexPath);
                }
                ascPath = Path.Combine(flexPath, "lib\\asc.jar");
            }
            // asc_authoring.jar in Flash CS3
            if (ascPath == null)
            {
                ascPath = FindAscAuthoring();
            }

            if (ascPath == null)
            {
                if (src != null)
                {
                    return;              // silent checking
                }
                DialogResult result = MessageBox.Show(TextHelper.GetString("Info.SetFlex2OrCS3Path"), TextHelper.GetString("Title.ConfigurationRequired"), MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Yes)
                {
                    IASContext context = ASContext.GetLanguageContext("as3");
                    if (context == null)
                    {
                        return;
                    }
                    PluginBase.MainForm.ShowSettingsDialog("AS3Context", "SDK");
                }
                else if (result == DialogResult.No)
                {
                    PluginBase.MainForm.ShowSettingsDialog("ASCompletion", "Flash");
                }
                return;
            }

            flexShellsPath = CheckResource("FlexShells.jar", flexShellsJar);
            if (!File.Exists(flexShellsPath))
            {
                if (src != null)
                {
                    return;              // silent checking
                }
                ErrorManager.ShowInfo(TextHelper.GetString("Info.ResourceError"));
                return;
            }

            jvmConfig = JvmConfigHelper.ReadConfig(Path.Combine(flexPath ?? "", "bin\\jvm.config"));

            try
            {
                running = true;
                if (src == null)
                {
                    EventManager.DispatchEvent(this, new NotifyEvent(EventType.ProcessStart));
                }
                if (ascRunner == null || !ascRunner.IsRunning)
                {
                    StartAscRunner();
                }

                notificationSent = false;
                if (src == null)
                {
                    silentChecking = false;
                    //TraceManager.Add("Checking: " + filename, -1);
                    ASContext.SetStatusText(TextHelper.GetString("Info.AscRunning"));
                    ascRunner.HostedProcess.StandardInput.WriteLine(filename);
                }
                else
                {
                    silentChecking = true;
                    ascRunner.HostedProcess.StandardInput.WriteLine(filename + "$raw$");
                    ascRunner.HostedProcess.StandardInput.WriteLine(src);
                    ascRunner.HostedProcess.StandardInput.WriteLine(filename + "$raw$");
                }
            }
            catch (Exception ex)
            {
                ErrorManager.ShowError(TextHelper.GetString("Info.CheckError"), ex);
            }
        }
Beispiel #23
0
        private string ProcessFileTemplate(string args)
        {
            Int32         eolMode   = (Int32)MainForm.Settings.EOLMode;
            String        lineBreak = LineEndDetector.GetNewLineMarker(eolMode);
            ClassModel    cmodel;
            List <String> imports          = new List <string>();
            string        extends          = "";
            string        implements       = "";
            string        access           = "";
            string        inheritedMethods = "";
            string        paramString      = "";
            string        superConstructor = "";
            int           index;

            // resolve imports
            if (lastFileOptions.interfaces != null && lastFileOptions.interfaces.Count > 0)
            {
                bool isHaxe2 = PluginBase.CurrentSDK != null && PluginBase.CurrentSDK.Name.ToLower().Contains("haxe 2");
                implements = " implements ";
                string[] _implements;
                index = 0;
                foreach (string item in lastFileOptions.interfaces)
                {
                    if (item.Split('.').Length > 1)
                    {
                        imports.Add(item);
                    }
                    _implements = item.Split('.');
                    implements += (index > 0 ? (isHaxe2 ? ", implements " : ", ") : "") + _implements[_implements.Length - 1];
                    if (lastFileOptions.createInheritedMethods)
                    {
                        processOnSwitch = lastFileFromTemplate;
                        // let ASCompletion generate the implementations when file is opened
                    }
                    index++;
                }
            }
            if (lastFileOptions.superClass != "")
            {
                String super = lastFileOptions.superClass;
                if (lastFileOptions.superClass.Split('.').Length > 1)
                {
                    imports.Add(super);
                }
                string[] _extends = super.Split('.');
                extends        = " extends " + _extends[_extends.Length - 1];
                processContext = ASContext.GetLanguageContext(lastFileOptions.Language);
                if (lastFileOptions.createConstructor && processContext != null && constructorArgs == null)
                {
                    cmodel = processContext.GetModel(super.LastIndexOf('.') < 0 ? "" : super.Substring(0, super.LastIndexOf('.')), _extends[_extends.Length - 1], "");
                    if (!cmodel.IsVoid())
                    {
                        foreach (MemberModel member in cmodel.Members)
                        {
                            if (member.Name == cmodel.Constructor)
                            {
                                paramString = member.ParametersString();
                                AddImports(imports, member, cmodel);
                                superConstructor = "super(";
                                index            = 0;
                                if (member.Parameters != null)
                                {
                                    foreach (MemberModel param in member.Parameters)
                                    {
                                        if (param.Name.StartsWith("."))
                                        {
                                            break;
                                        }
                                        superConstructor += (index > 0 ? ", " : "") + param.Name;
                                        index++;
                                    }
                                }
                                superConstructor += ");\n" + (lastFileOptions.Language == "as3" ? "\t\t\t" : "\t\t");
                                break;
                            }
                        }
                    }
                }
                processContext = null;
            }
            if (constructorArgs != null)
            {
                paramString = constructorArgs;
                foreach (String type in constructorArgTypes)
                {
                    if (!imports.Contains(type))
                    {
                        imports.Add(type);
                    }
                }
            }
            if (lastFileOptions.Language == "as3")
            {
                access  = lastFileOptions.isPublic ? "public " : "internal ";
                access += lastFileOptions.isDynamic ? "dynamic " : "";
                access += lastFileOptions.isFinal ? "final " : "";
            }
            else if (lastFileOptions.Language == "haxe")
            {
                access  = lastFileOptions.isPublic ? "public " : "private ";
                access += lastFileOptions.isDynamic ? "dynamic " : "";
            }
            else
            {
                access = lastFileOptions.isDynamic ? "dynamic " : "";
            }
            string importsSrc = "";
            string prevImport = null;

            imports.Sort();
            foreach (string import in imports)
            {
                if (prevImport != import)
                {
                    prevImport = import;
                    if (import.LastIndexOf('.') == -1)
                    {
                        continue;
                    }
                    if (import.Substring(0, import.LastIndexOf('.')) == lastFileOptions.Package)
                    {
                        continue;
                    }
                    importsSrc += (lastFileOptions.Language == "as3" ? "\t" : "") + "import " + import + ";" + lineBreak;
                }
            }
            if (importsSrc.Length > 0)
            {
                importsSrc += (lastFileOptions.Language == "as3" ? "\t" : "") + lineBreak;
            }
            args = args.Replace("$(Import)", importsSrc);
            args = args.Replace("$(Extends)", extends);
            args = args.Replace("$(Implements)", implements);
            args = args.Replace("$(Access)", access);
            args = args.Replace("$(InheritedMethods)", inheritedMethods);
            args = args.Replace("$(ConstructorArguments)", paramString);
            args = args.Replace("$(Super)", superConstructor);
            return(args);
        }
        /// <summary>
        /// Gets all files related to the project
        /// </summary>
        private static List <String> GetAllProjectRelatedFiles(IProject project, bool onlySourceFiles)
        {
            List <String> files  = new List <String>();
            string        filter = project.DefaultSearchFilter;

            if (string.IsNullOrEmpty(filter))
            {
                return(files);
            }
            string[] filters = project.DefaultSearchFilter.Split(';');
            if (!onlySourceFiles)
            {
                IASContext context = ASContext.GetLanguageContext(project.Language);
                if (context == null)
                {
                    return(files);
                }
                foreach (PathModel pathModel in context.Classpath)
                {
                    string absolute = project.GetAbsolutePath(pathModel.Path);
                    if (Directory.Exists(absolute))
                    {
                        foreach (string filterMask in filters)
                        {
                            files.AddRange(Directory.GetFiles(absolute, filterMask, SearchOption.AllDirectories));
                        }
                    }
                }
            }
            else
            {
                // NOTE: Could be simplified in .NET 3.5 with LINQ .Concat.Select.Distinct
                var visited = new Dictionary <string, byte>();
                foreach (string path in project.SourcePaths)
                {
                    string absolute = project.GetAbsolutePath(path);
                    if (visited.ContainsKey(absolute))
                    {
                        continue;
                    }
                    visited[absolute] = 1;
                    if (Directory.Exists(absolute))
                    {
                        foreach (string filterMask in filters)
                        {
                            files.AddRange(Directory.GetFiles(absolute, filterMask, SearchOption.AllDirectories));
                        }
                    }
                }
                foreach (string path in ProjectManager.PluginMain.Settings.GetGlobalClasspaths(project.Language))
                {
                    string absolute = project.GetAbsolutePath(path);
                    if (visited.ContainsKey(absolute))
                    {
                        continue;
                    }
                    visited[absolute] = 1;
                    if (Directory.Exists(absolute))
                    {
                        foreach (string filterMask in filters)
                        {
                            files.AddRange(Directory.GetFiles(absolute, filterMask, SearchOption.AllDirectories));
                        }
                    }
                }
            }
            // If no source paths are defined, get files directly from project path
            if (project.SourcePaths.Length == 0)
            {
                String projRoot = Path.GetDirectoryName(project.ProjectPath);
                foreach (string filterMask in filters)
                {
                    files.AddRange(Directory.GetFiles(projRoot, filterMask, SearchOption.AllDirectories));
                }
            }
            return(files);
        }
Beispiel #25
0
        public void CheckAS3(string filename, string flexPath, string src)
        {
            if (running)
            {
                return;
            }

            // let other plugins preprocess source/handle checking
            Hashtable data = new Hashtable();

            data["filename"] = filename;
            data["src"]      = src;
            data["ext"]      = Path.GetExtension(filename);
            DataEvent de = new DataEvent(EventType.Command, "AS3Context.CheckSyntax", data);

            EventManager.DispatchEvent(this, de);
            if (de.Handled)
            {
                return;
            }

            src      = (string)data["src"];
            filename = (string)data["filename"];
            if (".mxml" == (string)data["ext"]) // MXML not supported by ASC without preprocessing
            {
                return;
            }

            string basePath = null;

            if (PluginBase.CurrentProject != null)
            {
                basePath = Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath);
            }
            flexPath = PathHelper.ResolvePath(flexPath, basePath);
            // asc.jar in FlexSDK
            if (flexPath != null && Directory.Exists(Path.Combine(flexPath, "lib")))
            {
                ascPath = Path.Combine(flexPath, "lib\\asc.jar");
            }
            // included asc.jar
            if (ascPath == null || !File.Exists(ascPath))
            {
                ascPath = PathHelper.ResolvePath(Path.Combine(PathHelper.ToolDir, "flexlibs/lib/asc.jar"));
            }

            if (ascPath == null)
            {
                if (src != null)
                {
                    return;              // silent checking
                }
                DialogResult result = MessageBox.Show(TextHelper.GetString("Info.SetFlex2OrCS3Path"), TextHelper.GetString("Title.ConfigurationRequired"), MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Yes)
                {
                    IASContext context = ASContext.GetLanguageContext("as3");
                    if (context == null)
                    {
                        return;
                    }
                    PluginBase.MainForm.ShowSettingsDialog("AS3Context", "SDK");
                }
                else if (result == DialogResult.No)
                {
                    PluginBase.MainForm.ShowSettingsDialog("ASCompletion", "Flash");
                }
                return;
            }

            flexShellsPath = CheckResource("FlexShells.jar", flexShellsJar);
            if (!File.Exists(flexShellsPath))
            {
                if (src != null)
                {
                    return;              // silent checking
                }
                ErrorManager.ShowInfo(TextHelper.GetString("Info.ResourceError"));
                return;
            }

            jvmConfig = JvmConfigHelper.ReadConfig(flexPath);

            try
            {
                running = true;
                if (src == null)
                {
                    EventManager.DispatchEvent(this, new NotifyEvent(EventType.ProcessStart));
                }
                if (ascRunner == null || !ascRunner.IsRunning || currentSDK != flexPath)
                {
                    StartAscRunner(flexPath);
                }

                notificationSent = false;
                if (src == null)
                {
                    silentChecking = false;
                    //TraceManager.Add("Checking: " + filename, -1);
                    ASContext.SetStatusText(TextHelper.GetString("Info.AscRunning"));
                    ascRunner.HostedProcess.StandardInput.WriteLine(filename);
                }
                else
                {
                    silentChecking = true;
                    ascRunner.HostedProcess.StandardInput.WriteLine(filename + "$raw$");
                    ascRunner.HostedProcess.StandardInput.WriteLine(src);
                    ascRunner.HostedProcess.StandardInput.WriteLine(filename + "$raw$");
                }
            }
            catch (Exception ex)
            {
                ErrorManager.AddToLog(TextHelper.GetString("Info.CheckError"), ex);
                TraceManager.AddAsync(TextHelper.GetString("Info.CheckError") + "\n" + ex.Message);
            }
        }
Beispiel #26
0
        public void UpdateOutdatedModels()
        {
            var action = new Action(() =>
            {
                var context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language);
                if (context == null || context.Classpath == null)
                {
                    return;
                }

                List <ClassModel> outdated;
                lock (outdatedModels)
                {
                    outdated = new List <ClassModel>(outdatedModels);
                    outdatedModels.Clear();
                }

                foreach (var cls in outdated)
                {
                    cls.ResolveExtends();

                    lock (cache)
                    {
                        //get the old CachedClassModel
                        var cachedClassModel = GetCachedModel(cls);
                        var connectedClasses = cachedClassModel?.ConnectedClassModels;

                        //remove old cls
                        Remove(cls);

                        UpdateClass(cls, cache);

                        //also update all classes / interfaces that are connected to cls
                        if (connectedClasses != null)
                        {
                            foreach (var connection in connectedClasses)
                            {
                                if (GetCachedModel(connection) != null) //only update existing connections, so a removed class is not reintroduced
                                {
                                    UpdateClass(connection, cache);
                                }
                            }
                        }
                    }
                }

                var newModels = outdated.Any(m => GetCachedModel(m) == null);
                //for new ClassModels, we need to update everything in the list of classes that extend / implement something that does not exist
                if (newModels)
                {
                    HashSet <ClassModel> toUpdate;
                    lock (unfinishedModels)
                        toUpdate = new HashSet <ClassModel>(unfinishedModels);

                    foreach (var model in toUpdate)
                    {
                        lock (unfinishedModels)
                            unfinishedModels.Remove(model); //will be added back by UpdateClass if needed

                        lock (cache)
                            UpdateClass(model, cache);
                    }
                }

                if (FinishedUpdate != null)
                {
                    PluginBase.RunAsync(new MethodInvoker(FinishedUpdate));
                }
            });

            action.BeginInvoke(null, null);
        }
Beispiel #27
0
        /// <summary>
        /// Updates the given ClassModel in cache. This assumes that all existing references to cls in the cache are still correct.
        /// However they do not have to be complete, this function will add missing connections based on cls.
        /// </summary>
        void UpdateClass(ClassModel cls, Dictionary <ClassModel, CachedClassModel> cache)
        {
            var context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language);

            if (context.ResolveType(cls.Name, cls.InFile).IsVoid() || cls.QualifiedName == "Dynamic") //do not update no longer existing classes (or Dynamic)
            {
                Remove(cls);
                return;
            }
            cls.ResolveExtends();
            var cachedClassModel = GetOrCreate(cache, cls);

            //look for functions / variables in cls that originate from interfaces of cls
            var interfaces = ResolveInterfaces(cls);

            foreach (var interf in interfaces)
            {
                var cachedInterf = GetOrCreate(cache, interf);
                cachedClassModel.ConnectedClassModels.Add(interf); //cachedClassModel is connected to interf.Key
                cachedInterf.ConnectedClassModels.Add(cls);        //the inverse is also true

                cachedInterf.ImplementorClassModels.Add(cls);      //cls implements interf
            }

            if (interfaces.Count > 0)
            {
                //look at each member and see if one of them is defined in an interface of cls
                foreach (MemberModel member in cls.Members)
                {
                    var implementing = GetDefiningInterfaces(member, interfaces);

                    if (implementing.Count == 0)
                    {
                        continue;
                    }

                    cachedClassModel.Implementing.AddUnion(member, implementing.Keys);
                    //now that we know member is implementing the interfaces in implementing, we can add cls as implementor for them
                    foreach (var interf in implementing)
                    {
                        var cachedModel = GetOrCreate(cache, interf.Key);
                        var set         = CacheHelper.GetOrCreateSet(cachedModel.Implementors, interf.Value);
                        set.Add(cls);
                    }
                }
            }

            if (cls.Extends != null && !cls.Extends.IsVoid())
            {
                var currentParent = cls.Extends;
                while (currentParent != null && !currentParent.IsVoid())
                {
                    var cachedParent = GetOrCreate(cache, currentParent);
                    cachedClassModel.ConnectedClassModels.Add(currentParent); //cachedClassModel is connected to currentParent
                    cachedParent.ConnectedClassModels.Add(cls);               //the inverse is also true

                    cachedParent.ChildClassModels.Add(cls);                   //cls implements interf
                    currentParent = currentParent.Extends;
                }
                //look for functions in cls that originate from a super-class
                foreach (MemberModel member in cls.Members)
                {
                    if ((member.Flags & (FlagType.Function | FlagType.Override)) > 0)
                    {
                        var overridden = GetOverriddenClasses(cls, member);

                        if (overridden == null || overridden.Count <= 0)
                        {
                            continue;
                        }

                        cachedClassModel.Overriding.AddUnion(member, overridden.Keys);
                        //now that we know member is overriding the classes in overridden, we can add cls as overrider for them
                        foreach (var over in overridden)
                        {
                            var cachedModel = GetOrCreate(cache, over.Key);
                            var set         = CacheHelper.GetOrCreateSet(cachedModel.Overriders, over.Value);
                            set.Add(cls);
                        }
                    }
                }
            }

            if (!IsCompletelyResolvable(cls))
            {
                lock (unfinishedModels)
                    unfinishedModels.Add(cls);
            }
        }