예제 #1
0
        public GenerationResults Generate(IPsiFile file)
        {
            myFile = file;
            myGeneratedMethodBody = new GenerationResults(CSharpLanguage.Instance, "", GeneratedRangeMapFactory.CreateGeneratedRangeMap(myFile));
            myGeneratedFile       = new GenerationResults(CSharpLanguage.Instance, "", GeneratedRangeMapFactory.CreateGeneratedRangeMap(myFile));

            AddOptions(myFile);

            if (myPackage != null)
            {
                foreach (var info in myClassesWithShortNamespace)
                {
                    AddClassesOption(info.Definition, info.EndOffset, info.StartOffset, myPackage + "." + info.Text, myPackage.Length + 1);
                }

                foreach (var info in myShortNamespaces)
                {
                    string name = info.Text;
                    if ((name.Length >= myPackage.Length) && (name.Substring(0, myPackage.Length).Equals(myPackage)))
                    {
                        AddNamespaceOption(info.EndOffset, info.StartOffset, info.Text);
                    }
                    else
                    {
                        AddNamespaceOption(info.EndOffset, info.StartOffset, myPackage + "." + info.Text, myPackage.Length + 1);
                    }
                }
            }

            myGeneratedFile.Append(new GenerationResults(CSharpLanguage.Instance, "class ZZZ_Generated_Class{\n void foo(){\n", GeneratedRangeMapFactory.CreateGeneratedRangeMap(myFile)));
            myGeneratedFile.Append(myGeneratedMethodBody);
            myGeneratedFile.Append(new GenerationResults(CSharpLanguage.Instance, "}\n }\n", GeneratedRangeMapFactory.CreateGeneratedRangeMap(myFile)));

            return(myGeneratedFile);
        }
    public GenerationResults Generate(IPsiFile file)
    {
      myFile = file;
      myGeneratedMethodBody = new GenerationResults(CSharpLanguage.Instance, "", GeneratedRangeMapFactory.CreateGeneratedRangeMap(myFile));
      myGeneratedFile = new GenerationResults(CSharpLanguage.Instance, "", GeneratedRangeMapFactory.CreateGeneratedRangeMap(myFile));

      AddOptions(myFile);

      if (myPackage != null)
      {
        foreach (var info in myClassesWithShortNamespace)
        {
          AddClassesOption(info.Definition, info.EndOffset, info.StartOffset, myPackage + "." + info.Text, myPackage.Length + 1);
        }

        foreach (var info in myShortNamespaces)
        {
          string name = info.Text;
          if((name.Length >= myPackage.Length) && (name.Substring(0,myPackage.Length).Equals(myPackage)))
          {
            AddNamespaceOption(info.EndOffset, info.StartOffset, info.Text);
          } else
          {
            AddNamespaceOption(info.EndOffset, info.StartOffset, myPackage + "." + info.Text, myPackage.Length + 1);
          }
        }
      }

      myGeneratedFile.Append(new GenerationResults(CSharpLanguage.Instance, "class ZZZ_Generated_Class{\n void foo(){\n", GeneratedRangeMapFactory.CreateGeneratedRangeMap(myFile)));
      myGeneratedFile.Append(myGeneratedMethodBody);
      myGeneratedFile.Append(new GenerationResults(CSharpLanguage.Instance, "}\n }\n", GeneratedRangeMapFactory.CreateGeneratedRangeMap(myFile)));

      return myGeneratedFile;
    }
예제 #3
0
        HashSet <INode> ProcessUberErrors(GenerationResults results)
        {
            var errNodes = new HashSet <INode>();
            var message  = new StringBuilder();
            var messages = ShaderUtil.GetShaderMessages(m_UberShader);

            message.AppendFormat(@"Preview shader for graph has {0} error{1}:\n", messages.Length, messages.Length != 1 ? "s" : "");
            foreach (var error in messages)
            {
                var node = results.sourceMap.FindNode(error.line);

                message.AppendFormat("Shader compilation error in {3} at line {1} (on {2}):\n{0}\n",
                                     error.message, error.line, error.platform,
                                     node != null ? string.Format("node {0} ({1})", node.name, node.guid) : "graph");
                message.AppendLine(error.messageDetails);
                message.AppendLine();

                if (node != null)
                {
                    m_Messenger.AddOrAppendError(this, node.tempId, error);
                    errNodes.Add(node);
                }
            }
            Debug.LogWarning(message.ToString());
            return(errNodes);
        }
예제 #4
0
 bool GenerateUberShader(ICollection <INode> errNodes, out GenerationResults results)
 {
     ShaderUtil.ClearCachedData(m_UberShader);
     results        = m_Graph.GetUberColorShader(errNodes);
     m_OutputIdName = results.outputIdProperty.referenceName;
     ShaderUtil.UpdateShaderAsset(m_UberShader, results.shader);
     return(ShaderUtil.ShaderHasError(m_UberShader));
 }
예제 #5
0
        /// <summary>
        /// Resets all of the active elements to the initial state, before any source code
        /// was generated.
        /// </summary>
        private void ResetElements()
        {
            mGenerationResults = null;
            previewFileComboBox.Items.Clear();
            previewFileComboBox.Items.Add(new ComboPath(null));
            previewFileComboBox.SelectedIndex = 0;

            previewTextBox.Text = string.Empty;

            cmdOutputTextBox.Text = string.Empty;

            UpdateAssemblerControls();
        }
예제 #6
0
        private void UpdateSettings()
        {
            var length = (int)sldLength.Value;

            var characters = _checks
                             .Where(x => x.IsChecked != null &&
                                    x.IsChecked.Value)
                             .SelectMany(x => x.Characters)
                             .ToArray();

            var results = new GenerationResults(
                characters, length);

            lstResults.ItemsSource = results;
        }
예제 #7
0
        public override ISecondaryDocumentGenerationResult Generate(PrimaryFileModificationInfo modificationInfo)
        {
            var psiFile = modificationInfo.NewPsiFile as IPsiFile;

            PsiLanguageType language = psiFile != null ? psiFile.Language : PsiLanguage.Instance;

            var gen = new CSharpFromPsiGenerator();
            GenerationResults result = gen.Generate(psiFile);

            return(new SecondaryDocumentGenerationResult(
                       result.Text.ToString(),
                       CSharpLanguage.Instance,
                       new RangeTranslatorWithGeneratedRangeMap(result.GeneratedRangeMap),
                       LexerFactoryWithPreprocessor(language)
                       ));
        }
예제 #8
0
        private void GenerateButton_Click(object sender, RoutedEventArgs e)
        {
            IGenerator gen = AssemblerInfo.GetGenerator(mSelectedAssemblerId);

            if (gen == null)
            {
                Debug.WriteLine("Unable to get generator for " + mSelectedAssemblerId);
                return;
            }
            gen.Configure(mProject, mWorkDirectory, mBaseFileName,
                          AssemblerVersionCache.GetVersion(mSelectedAssemblerId), AppSettings.Global);

            GenWorker    gw  = new GenWorker(gen);
            WorkProgress dlg = new WorkProgress(this, gw, false);

            dlg.ShowDialog();
            //Debug.WriteLine("Dialog returned: " + dlg.DialogResult);

            GenerationResults res = gw.Results;

            if (res == null)
            {
                // error or cancelation; errors already reported
                return;
            }

            ResetElements();
            mGenerationResults = res;
            previewFileComboBox.Items.Clear();
            foreach (string str in res.PathNames)
            {
                previewFileComboBox.Items.Add(new ComboPath(str));
            }
            previewFileComboBox.SelectedIndex = 0;      // should trigger update

            UpdateAssemblerControls();
        }
예제 #9
0
 public void RunWorkerCompleted(object results)
 {
     Results = (GenerationResults)results;
 }
예제 #10
0
        /// <summary>
        /// Generates source code for the specified test case, assembles it, and compares
        /// the output of both steps to expected values.  The process is repeated for every
        /// known assembler.
        ///
        /// If an assembler is known but not configured, the assembly step is skipped, and
        /// does not count as a failure.
        /// </summary>
        /// <param name="pathName">Full path to test case.</param>
        /// <returns>True if all assemblers worked as expected.</returns>
        private bool GenerateAndAssemble(string pathName)
        {
            ReportProgress(Path.GetFileName(pathName) + "...\r\n");

            // Create DisasmProject object, either as a new project for a plain data file,
            // or from a project file.
            DisasmProject project = InstantiateProject(pathName,
                                                       out FileLoadReport projectLoadReport);

            if (project == null)
            {
                ReportFailure();
                return(false);
            }

            int testNum = GetTestNum(pathName);

            // Create a temporary directory to work in.
            string workDir = CreateWorkDirectory(pathName);

            if (string.IsNullOrEmpty(workDir))
            {
                ReportFailure();
                project.Cleanup();
                return(false);
            }

            AppSettings settings = CreateNormalizedSettings();

            ApplyProjectSettings(settings, project);

            // Iterate through all known assemblers.
            bool didFail = false;

            foreach (AssemblerInfo.Id asmId in
                     (AssemblerInfo.Id[])Enum.GetValues(typeof(AssemblerInfo.Id)))
            {
                if (asmId == AssemblerInfo.Id.Unknown)
                {
                    continue;
                }

                string    fileName = Path.GetFileName(pathName);
                TaskTimer timer    = new TaskTimer();
                timer.StartTask("Full Test Duration");

                // Create results object and add it to the list.  We'll add stuff to it for
                // as far as we get.
                GenTestResults results = new GenTestResults(pathName, asmId);
                mResults.Add(results);
                results.ProjectLoadReport = projectLoadReport;

                // Generate source code.
                ReportProgress("  " + asmId.ToString() + " generate...");
                IGenerator gen = AssemblerInfo.GetGenerator(asmId);
                if (gen == null)
                {
                    ReportErrMsg("generator unavailable");
                    ReportProgress("\r\n");
                    //didFail = true;
                    continue;
                }
                timer.StartTask("Generate Source");
                gen.Configure(project, workDir, fileName,
                              AssemblerVersionCache.GetVersion(asmId), settings);
                GenerationResults genResults = gen.GenerateSource(mWorker);
                timer.EndTask("Generate Source");
                if (mWorker.CancellationPending)
                {
                    // The generator will stop early if a cancellation is requested.  If we
                    // don't break here, the compare function will report a failure, which
                    // isn't too problematic but looks funny.
                    break;
                }

                ReportProgress(" verify...");
                timer.StartTask("Compare Source to Expected");
                bool match = CompareGeneratedToExpected(pathName, genResults.PathNames);
                timer.EndTask("Compare Source to Expected");
                if (match)
                {
                    ReportSuccess();
                    results.GenerateOkay = true;
                }
                else
                {
                    ReportFailure();
                    didFail = true;

                    // The fact that it doesn't match the expected sources doesn't mean it's
                    // invalid.  Go ahead and try to build it.
                    //continue;
                }

                // Assemble code.
                ReportProgress("  " + asmId.ToString() + " assemble...");
                IAssembler asm = AssemblerInfo.GetAssembler(asmId);
                if (asm == null)
                {
                    ReportErrMsg("assembler unavailable");
                    ReportProgress("\r\n");
                    continue;
                }

                timer.StartTask("Assemble Source");
                asm.Configure(genResults, workDir);
                AssemblerResults asmResults = asm.RunAssembler(mWorker);
                timer.EndTask("Assemble Source");
                if (asmResults == null)
                {
                    ReportErrMsg("unable to run assembler");
                    ReportFailure();
                    didFail = true;
                    continue;
                }
                if (asmResults.ExitCode != 0)
                {
                    ReportErrMsg("assembler returned code=" + asmResults.ExitCode);
                    ReportFailure();
                    didFail = true;
                    continue;
                }

                results.AsmResults = asmResults;

                ReportProgress(" verify...");
                timer.StartTask("Compare Binary to Expected");
                FileInfo fi = new FileInfo(asmResults.OutputPathName);
                if (!fi.Exists)
                {
                    // This can happen if the assembler fails to generate output but doesn't
                    // report an error code (e.g. Merlin 32 in certain situations).
                    ReportErrMsg("asm output missing");
                    ReportFailure();
                    didFail = true;
                    continue;
                }
                else if (fi.Length != project.FileData.Length)
                {
                    ReportErrMsg("asm output mismatch: length is " + fi.Length + ", expected " +
                                 project.FileData.Length);
                    ReportFailure();
                    didFail = true;
                    continue;
                }
                else if (!FileUtil.CompareBinaryFile(project.FileData, asmResults.OutputPathName,
                                                     out int badOffset, out byte badFileVal))
                {
                    ReportErrMsg("asm output mismatch: offset +" + badOffset.ToString("x6") +
                                 " has value $" + badFileVal.ToString("x2") + ", expected $" +
                                 project.FileData[badOffset].ToString("x2"));
                    ReportFailure();
                    didFail = true;
                    continue;
                }
                timer.EndTask("Compare Binary to Expected");

                // Victory!
                results.AssembleOkay = true;
                ReportSuccess();

                timer.EndTask("Full Test Duration");
                results.Timer = timer;

                // We don't scrub the directory on success at this point.  We could, but we'd
                // need to remove only those files associated with the currently assembler.
                // Otherwise, a failure followed by a success would wipe out the unsuccessful
                // temporaries.
            }

            // If something failed, leave the bits around for examination.  Otherwise, try to
            // remove the directory and all its contents.
            if (!didFail && !RetainOutput)
            {
                ScrubWorkDirectory(workDir, testNum);
                RemoveWorkDirectory(workDir);
            }

            project.Cleanup();
            return(!didFail);
        }
예제 #11
0
        public GenerationResults GenerateConfigurations()
        {
            var configGenerationPreferences = _preferencesManager.GetPreferenceInstance <ConfigurationGeneratorPreferences>();

            //TODO - To API: Template Load stuff?
            ITemplate       template;
            TryCreateResult templateCreationResult = _templateFactory.TryCreateItem(configGenerationPreferences.TemplateFilePath, configGenerationPreferences.TemplateFileType, out template);

            using (template)
            {
                switch (templateCreationResult)
                {
                case TryCreateResult.FileNotFound:
                    return(GenerationResults.CreateFail(new ConfigurationGeneratorError(
                                                            ConfigurationGeneratorErrorCodes.TemplateFileNotFound,
                                                            $"Specified template file not found: {configGenerationPreferences.TemplateFilePath}")));

                case TryCreateResult.FailedByExtension:
                    return(GenerationResults.CreateFail(new ConfigurationGeneratorError(
                                                            ConfigurationGeneratorErrorCodes.TemplateTypeResolutionFailure,
                                                            $"Failed to resolve template type from file extension: {configGenerationPreferences.TemplateFilePath.GetFileExtension()}")));

                case TryCreateResult.FailedByType:
                    return(GenerationResults.CreateFail(new ConfigurationGeneratorError(
                                                            ConfigurationGeneratorErrorCodes.UnknownTemplateType,
                                                            $"Unknown template type: {configGenerationPreferences.TemplateFileType}")));
                }

                //TODO - To API: Settings Load stuff?
                ISettingsLoader settingsLoader;
                TryCreateResult settingsLoaderCreationResult = _configurationCollectionLoaderFactory.TryCreateItem(configGenerationPreferences.SettingsFilePath,
                                                                                                                   configGenerationPreferences.SettingsFileType, out settingsLoader);

                switch (settingsLoaderCreationResult)
                {
                case TryCreateResult.FileNotFound:
                    return(GenerationResults.CreateFail(new ConfigurationGeneratorError(
                                                            ConfigurationGeneratorErrorCodes.SettingsFileNotFound,
                                                            $"Specified settings file not found: {configGenerationPreferences.SettingsFilePath}")));

                case TryCreateResult.FailedByExtension:
                    return(GenerationResults.CreateFail(new ConfigurationGeneratorError(
                                                            ConfigurationGeneratorErrorCodes.SettingsLoaderTypeResolutionFailure,
                                                            $"Failed to resolve settings loader type from file extension: {configGenerationPreferences.SettingsFilePath.GetFileExtension()}")));

                case TryCreateResult.FailedByType:
                    return(GenerationResults.CreateFail(new ConfigurationGeneratorError(
                                                            ConfigurationGeneratorErrorCodes.UnknownSettingsLoaderType,
                                                            $"Unknown settings loader type: {configGenerationPreferences.SettingsFileType}")));
                }

                var result = settingsLoader.LoadSettings(configGenerationPreferences.SettingsFilePath);

                if (!result.Success)
                {
                    return(GenerationResults.CreateFail(result.Error));
                }

                IEnumerable <IDictionary <string, object> > loadedSettings = result.Value;

                var configurationCreationResult = _configurationFactory.CreateConfigurations(configGenerationPreferences, loadedSettings);
                if (!configurationCreationResult.Success)
                {
                    return(GenerationResults.CreateFail(configurationCreationResult.Error));
                }

                IEnumerable <IConfiguration> configurations = configurationCreationResult.Value;

                var configurationCollectionFilterPreferences = _preferencesManager.GetPreferenceInstance <ConfigurationCollectionFilterPreferences>();

                var globallyUsedTokens = new HashSet <string>();

                configurations = _configurationCollectionFilter.Filter(
                    configurationCollectionFilterPreferences,
                    configurations,
                    token => globallyUsedTokens.Add(token)); //NOPUSH - duplicate will throw error?


                //TODO: make this pipeline async and parallelised
                //TODO: need to extract this out - or maybe move into the template itself (after all, this does represent a real template with its data)
                using (var templateStream = File.OpenRead(configGenerationPreferences.TemplateFilePath))
                {
                    var loadResults = template.Load(templateStream);

                    if (!loadResults.Success)
                    {
                        return(GenerationResults.CreateFail(loadResults.TemplateLoadErrors));
                    }

                    var singleFileGenerationResults = new List <SingleFileGenerationResult>();

                    foreach (var configuration in configurations)
                    {
                        SingleTemplateRenderResults renderResult = template.Render(configuration);

                        if (renderResult.Errors.Any())
                        {
                            singleFileGenerationResults.Add(
                                new SingleFileGenerationResult(
                                    renderResult.Configuration,
                                    null,
                                    renderResult.Errors,
                                    false,
                                    false));
                        }
                        else
                        {
                            renderResult = _postProcessorPipeline.PostProcessResult(renderResult);
                            var writeResults = _fileOutputWriter.WriteOutput(renderResult);

                            //TODO: clean this up - why is the errors collection in here?
                            singleFileGenerationResults.Add(
                                new SingleFileGenerationResult(
                                    renderResult.Configuration,
                                    writeResults.FullPath,
                                    renderResult.Errors,
                                    writeResults.FileChanged,
                                    writeResults.WasWritten));
                        }
                    }

                    return(GenerationResults.CreateSuccess(singleFileGenerationResults));
                }
            }
        }