private static bool RootNamespaceWithoutException(ICodeModel model, string[] relevantTypes, bool filterRelevantTypesWithSourceDirectory, out IEnumerable <string> namespaces, out string result) { string[] sourceDirectories = model.SourceDirectories.Select(d => d.FullName).ToArray(); namespaces = model.Types.Where(c => !filterRelevantTypesWithSourceDirectory || sourceDirectories.Any(c.Value.FullName.StartsWith)) .Where(c => relevantTypes.Contains(c.Key.FullName)) .Select(p => p.Key) .Where(m => m.Namespace != null) .Select(m => m.Namespace) .ToArray(); if (!namespaces.Any()) { namespaces = model.Types.Where(c => sourceDirectories.Any(c.Value.FullName.StartsWith)) .Select(p => p.Key) .Where(m => m.Namespace != null) .Select(m => m.Namespace) .ToArray(); } if (!namespaces.Any()) { result = string.Empty; return(false); } result = string.Join(".", namespaces .Select(s => s.Split(new[] { "::" }, StringSplitOptions.RemoveEmptyEntries) .AsEnumerable()) .Transpose() .TakeWhile(s => s.All(x => x == s.First())).Select(s => s.First())); return(true); }
public CodePoint(ICodeModel codeModel, DialogContext dialogContext, object item, string more) { CodeModel = codeModel ?? throw new ArgumentNullException(nameof(codeModel)); DialogContext = dialogContext ?? throw new ArgumentNullException(nameof(dialogContext)); Item = item ?? throw new ArgumentNullException(nameof(item)); More = more; }
public override Entity Resolve(Entity owner, string key, bool fallback = false) { IDataType dataType = owner.Value <IDataType>(); switch (key) { case EntityKeys.NameKey: return(owner.Create(key, dataType.Name)); case EntityKeys.FullNameKey: string fullName = GetDataTypeFullName(); return(owner.Create(key, fullName)); default: throw new ContentProviderException(key, owner); } string GetDataTypeFullName() { ICodeModel rootCodeModel = owner.Root.Value <ICodeModel>(); return(dataType.PotentialFullNames.FirstOrDefault(fn => rootCodeModel.Type(fn) != null) ?? dataType.Name); } }
/// <summary> /// Enable Debug Adapter Protocol for the running adapter. /// </summary> /// <param name="botAdapter">The <see cref="BotAdapter"/> to enable.</param> /// <param name="port">port to listen on.</param> /// <param name="sourceMap">ISourceMap to use (default will be SourceMap()).</param> /// <param name="breakpoints">IBreakpoints to use (default will be SourceMap()).</param> /// <param name="terminate">Termination function (Default is Environment.Exit().</param> /// <param name="events">IEvents to use (Default is Events).</param> /// <param name="codeModel">ICodeModel to use (default is internal implementation).</param> /// <param name="dataModel">IDataModel to use (default is internal implementation).</param> /// <param name="logger">ILogger to use (Default is NullLogger).</param> /// <returns>The <see cref="BotAdapter"/>.</returns> public static BotAdapter UseDebugger( this BotAdapter botAdapter, int port, ISourceMap sourceMap = null, IBreakpoints breakpoints = null, Action terminate = null, IEvents events = null, ICodeModel codeModel = null, IDataModel dataModel = null, ILogger logger = null) { codeModel = codeModel ?? new CodeModel(); DebugSupport.SourceMap = sourceMap ?? new DebuggerSourceMap(codeModel); return(botAdapter.Use( #pragma warning disable CA2000 // Dispose objects before losing scope (excluding, the object ownership is transferred to the adapter and the adapter should dispose it) new DialogDebugAdapter( port: port, sourceMap: DebugSupport.SourceMap, breakpoints: breakpoints ?? DebugSupport.SourceMap as IBreakpoints, terminate: terminate, events: events, codeModel: codeModel, dataModel: dataModel, logger: logger))); #pragma warning restore CA2000 // Dispose objects before losing scope }
private IEnumerable <IField> GetAllInheritedFields(ICodeModel model, IType type) { IEnumerable <IType> allTypes = GetAllTypes(type); return(allTypes.SelectMany(t => t.Fields)); IEnumerable <IType> GetAllTypes(IType child) { yield return(child); foreach (IDataType baseDataType in child.BaseTypes.Where( t => t.Visibility.Equals("public", StringComparison.OrdinalIgnoreCase))) { IType realType = baseDataType.PotentialFullNames .Select(model.Type) .FirstOrDefault(t => t != null); if (realType == null) { continue; } foreach (IType baseType in GetAllTypes(realType)) { yield return(baseType); } } } }
public QuickInfoSource(QuickInfoSourceProvider provider, ITextBuffer subjectBuffer, ICodeModel codeModel) { m_provider = provider; m_subjectBuffer = subjectBuffer; _codeModel = codeModel; }
/// <summary> /// Enable Debug Adapter Protocol for the running adapter. /// </summary> /// <param name="botAdapter">The <see cref="BotAdapter"/> to enable.</param> /// <param name="port">port to listen on.</param> /// <param name="sourceMap">ISourceMap to use (default will be SourceMap()).</param> /// <param name="breakpoints">IBreakpoints to use (default will be SourceMap()).</param> /// <param name="terminate">Termination function (Default is Environment.Exit().</param> /// <param name="events">IEvents to use (Default is Events).</param> /// <param name="codeModel">ICodeModel to use (default is internal implementation).</param> /// <param name="dataModel">IDataModel to use (default is internal implementation).</param> /// <param name="logger">ILogger to use (Default is NullLogger).</param> /// <param name="coercion">ICoercion to use (default is internal implementation).</param> /// <returns>The <see cref="BotAdapter"/>.</returns> public static BotAdapter UseDebugger( this BotAdapter botAdapter, int port, ISourceMap sourceMap = null, IBreakpoints breakpoints = null, Action terminate = null, IEvents events = null, ICodeModel codeModel = null, IDataModel dataModel = null, ILogger logger = null, ICoercion coercion = null) { codeModel = codeModel ?? new CodeModel(); DebugSupport.SourceMap = sourceMap ?? new DebuggerSourceMap(codeModel); return(botAdapter.Use( new DialogDebugAdapter( port: port, sourceMap: DebugSupport.SourceMap, breakpoints: breakpoints ?? DebugSupport.SourceMap as IBreakpoints, terminate: terminate, events: events, codeModel: codeModel, dataModel: dataModel, logger: logger))); }
public async Task Initialize() { var config = new CodeModelConfiguration().FilterByNamespace("Tests.Assets.WebApi"); data = await CreateCodeModelFromProject(config, "Tests.Assets.WebApi"); settings = new Configuration(); }
public DialogDebugAdapter(int port, ISourceMap sourceMap, IBreakpoints breakpoints, Action terminate, IEvents events = null, ICodeModel codeModel = null, IDataModel dataModel = null, ILogger logger = null, ICoercion coercion = null) : base(logger) { this.events = events ?? new Events<DialogEvents>(); this.codeModel = codeModel ?? new CodeModel(); this.dataModel = dataModel ?? new DataModel(coercion ?? new Coercion()); this.sourceMap = sourceMap ?? throw new ArgumentNullException(nameof(sourceMap)); this.breakpoints = breakpoints ?? throw new ArgumentNullException(nameof(breakpoints)); this.terminate = terminate ?? new Action(() => Environment.Exit(0)); this.task = ListenAsync(new IPEndPoint(IPAddress.Any, port), cancellationToken.Token); }
internal Classifier(ITextBuffer buffer, IClassificationTypeRegistryService registry, IAnalyzerModel analyzerModel, ICodeModel codeModel) { _theBuffer = buffer; _succededFormat = registry.GetClassificationType("InlineSucceeded"); _failedFormat = registry.GetClassificationType("InlineFailed"); _analyzerModel = analyzerModel; _codeModel = codeModel; _analyzerModel.HasChanged += AnalyzerModel_HasChanged; }
public override Entity Resolve(Entity owner, string key, bool fallback = false) { IField field = owner.Value <IField>(); switch (key) { case EntityKeys.FieldNameKey: { return(owner.Create(key, field.Name)); } case EntityKeys.DataTypeKey: { IDataType fieldDataType = field.DataType; return(owner.Create(key, fieldDataType.Name, fieldDataType)); } case EntityKeys.ResolvedTypeKey: { ICodeModel model = owner.Root.Value <ICodeModel>(); IDataType fieldDataType = field.DataType; IType realType = fieldDataType.PotentialFullNames .Select(model.Type) .FirstOrDefault(t => t != null); return(owner.Create(key, realType?.Name, realType)); } case EntityKeys.MultiplicityKey: { return(owner.Create( key, field.Multiplicity.Select(m => owner.Create(key, new Func <string>(m.ToString), m)))); } case EntityKeys.IsArray: if (field.Multiplicity.Any()) { return(owner.Create(key, true.ToString(CultureInfo.InvariantCulture), true)); } return(owner.Create(key, false.ToString(CultureInfo.InvariantCulture), false)); default: { metaDataTemplate metaDataTemplate = FindFieldTemplate(key, owner); if (metaDataTemplate != null) { return(GetFieldTemplateEntity(metaDataTemplate, field, owner, key)); } throw new ContentProviderException(key, owner); } } }
public static string RootNamespace(this ICodeModel model, string[] relevantTypes) { if (!RootNamespaceWithoutException(model, relevantTypes, true, out IEnumerable <string> namespaces, out string result)) { return(string.Empty); } if (string.IsNullOrEmpty(result)) { throw new MultipleRootNamespacesException(namespaces); } return(result); }
public DialogDebugAdapter(IDebugTransport transport, ISourceMap sourceMap, IBreakpoints breakpoints, Action terminate, IEvents events = null, ICodeModel codeModel = null, IDataModel dataModel = null, ILogger logger = null, ICoercion coercion = null) { _transport = transport ?? throw new ArgumentNullException(nameof(transport)); _events = events ?? new Events <DialogEvents>(); _codeModel = codeModel ?? new CodeModel(); _dataModel = dataModel ?? new DataModel(coercion ?? new Coercion()); _sourceMap = sourceMap ?? throw new ArgumentNullException(nameof(sourceMap)); _breakpoints = breakpoints ?? throw new ArgumentNullException(nameof(breakpoints)); _terminate = terminate ?? (() => Environment.Exit(0)); _logger = logger ?? NullLogger.Instance; _arenas.Add(_output); // lazily complete circular dependency _transport.Accept = AcceptAsync; }
public bool Compare(ICodeModel codeModel) { var model = codeModel as TextCodeModel; if (model?.Wrods?.Any() == true && model.Wrods.Count == Wrods.Count) { int count = Wrods.Count; for (int i = 0; i < count; i++) { if (!string.Equals(Wrods[i], model.Wrods[i], StringComparison.OrdinalIgnoreCase)) { return(false); } } return(true); } return(false); }
public bool Compare(ICodeModel codeModel) { var model = codeModel as DefaultCodeModel; if (model?.CodeList?.Any() == true && model.CodeList.Count == CodeList.Count) { int count = CodeList.Count; for (int i = 0; i < count; i++) { if (CodeList[i].Compare(model.CodeList[i]) == false) { return(false); } } return(true); } return(false); }
public void Execute(Entity dataModel, ChangeObservable observable) { ProjectEntity project = ProjectEntity.Decorate(dataModel.Root); if (!project.Settings.IsPersistent) { try { ICodeModel codeModel = dataModel.Root.Value <ICodeModel>(); if (codeModel != null) { VirtualEntry acfFile = codeModel.SourceDirectories .SelectMany(directory => directory.Entries) .Where(entry => entry.Name.EndsWith(Constants.AcfConfigExtension, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (acfFile != null) { using (Stream xmlStream = (acfFile as VirtualFile).OpenRead()) using (XmlReader reader = XmlReader.Create(xmlStream)) { while (reader.Read()) { if (reader.MoveToContent() == XmlNodeType.Element && reader.Name == "Component") { string componenttype = reader.GetAttribute("type"); if (componenttype.Contains("::")) { throw new OldAcfConfigException(); } } } } } } } catch (XmlException) { executionContext.WriteWarning("From version 2021.6 on the component type attribute inside the .acf.config file" + " must use the namespace separator '.' instead of '::'!"); } } }
public static string RootNamespaceForOldTarget(this ICodeModel model, string[] relevantTypes, string[] additionalRelevantTypes) { if (!RootNamespaceWithoutException(model, relevantTypes.Concat(additionalRelevantTypes).ToArray(), false, out IEnumerable <string> namespaces, out string result)) { return(string.Empty); } string futureTargetResult = model.RootNamespace(relevantTypes); if (string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(futureTargetResult)) { throw new MultipleRootNamespacesForTargetException(namespaces); } if (string.IsNullOrEmpty(result)) { throw new MultipleRootNamespacesException(namespaces); } return(result); }
public async Task <IEnumerable <RenderingResult> > RenderAsync(string templateFilePath, string template, ICodeModel codeModel, IEnumerable <Type> typesThatContainCustomFunctions, EditorConfig editorConfig) { errorList.Clear(); output.Info("Rendering template"); var configuration = new NTypewriter.Configuration(); configuration.AddCustomFunctions(typesThatContainCustomFunctions.ToArray()); var configAdapter = new EditorConfigAdapterForScriban(editorConfig); var dataModels = new Dictionary <string, object>(); dataModels[DataScriptObject.DataVariableName] = codeModel; dataModels["codeModel"] = codeModel; dataModels[DataScriptObject.ConfigVariableName] = configAdapter; var result = await NTypeWriter.Render(template, dataModels, configuration, new ExternalOutputAdapter(output)); output.Info("Used configuration : " + editorConfig.ToString()); foreach (var message in result.Messages) { output.Write(message.ToString(), message.Type == MessageType.Error); errorList.AddError(templateFilePath, message); } errorList.Publish(); if (result.HasErrors) { throw new RuntimeException("Rendering template failed"); } output.Info("Template rendered successfully"); var rootDirectory = Path.GetDirectoryName(templateFilePath); output.Info($"Root directory : {rootDirectory})"); var renderedItems = result.Items.Select(x => new RenderingResult(x, rootDirectory)).ToList(); return(renderedItems); }
public DebuggerSourceMap(ICodeModel codeModel) { this.codeModel = codeModel ?? throw new ArgumentNullException(nameof(codeModel)); }
public static Entity GetRelationship(this templateRelationship relationship, TemplateDescription relationshipDescription, Entity owner, params string[] relationshipNames) { if (relationshipDescription.isRoot) { return(owner.Root); } ICodeModel codeModel = owner.Root.Value <ICodeModel>(); IType[] availableTypes = codeModel?.Types.Keys .Where(t => t.HasAttributeWithoutValue(relationshipDescription.name)) .ToArray() ?? Array.Empty <IType>(); Entity[] availableEntities = owner.EntityHierarchy() .Where(e => e.Type.Equals(relationshipDescription.name, StringComparison.OrdinalIgnoreCase)) .Where(e => e.HasValue <IType>() || e.HasValue <CommandDefinition>()) .ToArray(); if (relationship.multiplicity == multiplicity.One) { if (relationshipNames.Length != 1) { throw new RelationshipMultiplicityMismatchException(relationship.name, owner.Name); } string name = relationshipNames[0]; return(CreateRelationshipEntity(name)); } else { return(owner.Create(relationship.name.Plural(), relationshipNames.Select(CreateRelationshipEntity))); } Entity CreateRelationshipEntity(string name) { IType exactType = availableTypes.FirstOrDefault(t => t.FullName.Equals(name, StringComparison.OrdinalIgnoreCase)); IType[] relationshipTypes = exactType != null ? new[] { exactType } : availableTypes.Where(t => t.FullName.Contains(name, StringComparison.OrdinalIgnoreCase)) .ToArray(); Entity[] relationshipEntities = availableEntities.Where(e => e.Name?.Equals(name, StringComparison.OrdinalIgnoreCase) == true) .ToArray(); if (relationshipTypes.Length > 1) { throw new AmbiguousRelationshipTypeException(relationship.name, name, relationshipTypes); } if (relationshipTypes.Length == 0 && !relationshipEntities.Any()) { throw new RelationshipTypeNotFoundException(relationship.name, name, availableTypes); } IType relationshipType = relationshipTypes.SingleOrDefault(); if (relationshipType != null) { return(availableEntities.FirstOrDefault(e => e.HasValue <IType>() && e.Value <IType>() == relationshipType) ?? owner.Create(relationship.name, relationshipType.Name, relationshipType)); } if (relationshipEntities.Length > 1) { throw new AmbiguousRelationshipTypeException(relationship.name, name, relationshipEntities); } return(relationshipEntities.Single()); } }
public void Add(ICodeModel codeModel) { codeModels.Add(codeModel); }
public ThreadModel(ITurnContext turnContext, ICodeModel codeModel) { TurnContext = turnContext; CodeModel = codeModel; }
public async Task Initialize() { var config = new CodeModelConfiguration().FilterByNamespace("NTypewriter.CodeModel.Functions.Tests.Type"); data = await CreateCodeModelFromProject(config, "NTypewriter.CodeModel.Functions.Tests"); }
public void Initialize(Entity root) { ProjectEntity project = ProjectEntity.Decorate(root); TemplateEntity template = TemplateEntity.Decorate(root); Target[] availableTargets = sdkRepository.GetAllTargets().ToArray(); ICodeModel codeModel = root.Value <ICodeModel>(); SetProjectName(); SetProjectNamespace(); SetProjectType(); SetProjectTargets(); SetProjectEntities(); SetProjectIncludes(); void SetProjectName() { ProjectName = null; if (fileSystem.FileExists(System.IO.Path.Combine(root.Path, Constants.ProjectFileName))) { ProjectName = root.Name; } } void SetProjectNamespace() { ProjectNamespace = CodeEntity.Decorate(project).Namespace; } void SetProjectType() { ProjectType = project.Type; } void SetProjectTargets() { TargetsResult targetsResult = targetParser.Targets(project, false); ProjectTargets = targetsResult.ValidTargets .Select(t => new ProjectTarget(t, availableTargets.Any(at => t.Name == at.Name && at.LongVersion == t.LongVersion))); Exceptions = targetsResult.Errors; } void SetProjectEntities() { IEnumerable <CodeEntity> entities = template.EntityHierarchy.Select(e => { CodeEntity codeEntity = CodeEntity.Decorate(e); return(codeEntity); } ); ProjectCodeEntities = entities.Select(e => { TemplateEntity te = TemplateEntity.Decorate(e); return(e, te.RelatedEntites.Where(en => !en.Type.Contains("project"))); }) .Where(e => !e.Item1.Type.Contains("project")).ToDictionary(p => p.Item1, p => p.Item2); } void SetProjectIncludes() { IncludePaths = new List <IncludePath>(); IEnumerable <SdkInformation> relevantSdks = ProjectTargets.Select(t => availableTargets.FirstOrDefault(at => t.Target.Name == at.Name && at.LongVersion == t.Target.LongVersion)) .Where(t => t != null) .Select(sdkRepository.GetSdk) .Where(sdk => sdk != null) .Distinct(); var targetsWithIncludePaths = relevantSdks.Select(sdk => (sdk.Targets, sdk.IncludePaths.Concat(sdk.CompilerInformation.IncludePaths).Distinct())); foreach (var item in targetsWithIncludePaths) { foreach (Target target in item.Targets) { foreach (string includePath in item.Item2) { IncludePath existingIncludePath = IncludePaths.Where(i => i.PathValue.Equals(includePath, StringComparison.InvariantCulture)).FirstOrDefault(); if (existingIncludePath == null) { existingIncludePath = new IncludePath(includePath, true, new List <Target>()); IncludePaths.Add(existingIncludePath); } existingIncludePath.Targets = existingIncludePath.Targets.Concat(new[] { target }); } } } foreach (IncludePath codeModelIncludeDirectory in codeModel.IncludeDirectories) { IncludePath existingIncludePath = IncludePaths.Where(p => p.PathValue.Equals(codeModelIncludeDirectory.PathValue, StringComparison.InvariantCulture)).FirstOrDefault(); if (existingIncludePath == null) { IncludePaths.Add(codeModelIncludeDirectory); } else { foreach (Target target in codeModelIncludeDirectory.Targets) { if (!existingIncludePath.Targets.Contains(target)) { existingIncludePath.Targets = existingIncludePath.Targets.Concat(new[] { target }); } } } } } }
public void Initialize(Entity root) { ProjectEntity project = ProjectEntity.Decorate(root); TemplateEntity template = TemplateEntity.Decorate(root); Target[] availableTargets = sdkRepository.GetAllTargets().ToArray(); ICodeModel codeModel = root.Value <ICodeModel>(); SetProjectName(); SetProjectNamespace(); SetProjectType(); SetProjectTargets(); SetProjectEntities(); SetProjectIncludes(); void SetProjectName() { ProjectName = null; if (fileSystem.FileExists(System.IO.Path.Combine(root.Path, Constants.ProjectFileName))) { ProjectName = root.Name; } } void SetProjectNamespace() { ProjectNamespace = CodeEntity.Decorate(project).Namespace; } void SetProjectType() { ProjectType = project.Type; } void SetProjectTargets() { TargetsResult targetsResult = targetParser.Targets(project, false); ProjectTargets = targetsResult.ValidTargets .Select(t => new ProjectTarget(t, availableTargets.Any(at => t.Name == at.Name && at.LongVersion == t.LongVersion))); Exceptions = targetsResult.Errors; } void SetProjectEntities() { IEnumerable <CodeEntity> entities = template.EntityHierarchy.Select(e => { CodeEntity codeEntity = CodeEntity.Decorate(e); return(codeEntity); } ); ProjectCodeEntities = entities.Select(e => { TemplateEntity te = TemplateEntity.Decorate(e); return(e, te.RelatedEntites.Where(en => !en.Type.Contains("project"))); }) .Where(e => !e.Item1.Type.Contains("project")).ToDictionary(p => p.Item1, p => p.Item2); } void SetProjectIncludes() { IEnumerable <SdkInformation> relevantSdks = ProjectTargets.Select(t => availableTargets.FirstOrDefault(at => t.Target.Name == at.Name && at.LongVersion == t.Target.LongVersion)) .Where(t => t != null) .Select(sdkRepository.GetSdk) .Where(sdk => sdk != null) .Distinct(); IncludePaths = relevantSdks.SelectMany(sdk => sdk.IncludePaths) .Concat(relevantSdks.SelectMany(sdk => sdk.CompilerInformation.IncludePaths)) .Distinct() .ToDictionary(x => x, x => true); foreach (KeyValuePair <string, VirtualDirectory> codeModelIncludeDirectory in codeModel.IncludeDirectories) { if (!IncludePaths.ContainsKey(codeModelIncludeDirectory.Key)) { IncludePaths.Add(codeModelIncludeDirectory.Key, codeModelIncludeDirectory.Value != null); } } } }
public ThreadModel(ITurnContext turnContext, ICodeModel codeModel) : base(new Identifier <object>()) { TurnContext = turnContext; CodeModel = codeModel; }
public string Encode(ICodeModel code) { var model = code as TextCodeModel; return(model == null ? string.Empty : JsonConvert.SerializeObject(new { model.Wrods })); }
public string Encode(ICodeModel code) { var model = code as DefaultCodeModel; return(model == null ? string.Empty : JsonConvert.SerializeObject(new { model.CodeList })); }
public override Entity Resolve(Entity owner, string key, bool fallback = false) { if (key == EntityKeys.EscapeProjectNameFormatKey && owner.Type == EntityKeys.FormatKey) { return(EscapeProjectName()); } Entity rootEntity = CreateRootEntity(); rootEntity.SetMetaData(true, EntityKeys.IsRoot); return(rootEntity); Entity EscapeProjectName() { string value = owner.Owner?.Value <string>(); if (string.IsNullOrEmpty(value)) { return(owner.Create(key, string.Empty)); } value = Regex.Replace(value, @"[^a-zA-Z0-9_\.]", "_"); //Replace not allowed values with _ int length, newLength; do //Remove double _ and . { length = value.Length; value = value.Replace("__", "_"); value = value.Replace("..", "."); newLength = value.Length; } while (length != newLength); value = value.TrimEnd('.'); //Remove trailing dot string prefix = string.Empty; int lastPoint = value.LastIndexOf('.'); if (lastPoint >= 0) { prefix = value.Substring(0, lastPoint); value = value.Substring(lastPoint + 1); } if (value[0] == '_' && value.Length > 1) { value = "_" + new string(char.ToUpperInvariant(value[1]), 1) + value.Substring(2); } else { value = new string(char.ToUpperInvariant(value[0]), 1) + value.Substring(1); } if (!Regex.IsMatch(value, @"^_?[A-Z]")) {//Start with uppercase letter value = "Library"; } if (!string.IsNullOrEmpty(prefix)) { value = prefix + "." + value; } return(owner.Create(key, value)); } Entity CreateRootEntity() { if (HasRootInHierarchy(out Entity hierarchyRoot)) { return(hierarchyRoot); } if (owner.IsCommand()) { string rootFilePath = owner.GetPathCommandArgument(); VirtualDirectory baseDirectory = fileSystem.FileExists(rootFilePath) ? fileSystem.GetFile(rootFilePath).Parent : fileSystem.DirectoryExists(rootFilePath) ? fileSystem.GetDirectory(rootFilePath) : throw new FormattableException($"The path {rootFilePath} does not exist."); if (owner.HasTemplate()) { return(CreateRootBasedOnTemplate(baseDirectory)); } return(CreateRootBasedOnAllRootTemplates(baseDirectory)); } if (owner.IsTemplateOnly()) { TemplateDescription template = owner.Template(); TemplateDescription rootTemplate = FindRootTemplate(template); if (rootTemplate == null) { throw new RootTemplateNotFoundException(template.name); } return(owner.Create(rootTemplate.name)); } return(CreateFallback()); ICodeModel ParseCodeModel(VirtualDirectory virtualDirectory, Entity root) { try { ICodeModel model = parser.Parse(GetSourceDirectories(virtualDirectory), GetIncludeDirectories(virtualDirectory), out IEnumerable <CodeSpecificException> loggableExceptions); bool firstException = true; foreach (CodeSpecificException loggableException in loggableExceptions) { if (firstException) { executionContext.WriteInformation( "The following code errors were found inside the parsed include files. " + "Containing types cannot be used as port types.", false); firstException = false; } loggableException.CompleteCodeExceptions(virtualDirectory); executionContext.WriteError(loggableException.ToString(), false); } return(model); } catch (Exception exception) { exception.CompleteCodeExceptions(virtualDirectory); throw; } IDictionary <string, VirtualDirectory> GetIncludeDirectories(VirtualDirectory baseDirectory) { IEnumerable <string> includes = HasIncludeDirectoriesCommandArgument(owner) ? GetIncludeDirectoriesCommandArgument(owner) : Enumerable.Empty <string>(); Target[] projectTargets = GetProjectTargets(); if (projectTargets.Any()) { if (!includes.Any() && HasNoIncludeDetectionCommandArgument(owner) && !GetNoIncludeDetectionCommandArgument(owner)) { try { includes = informationService.RetrieveBuildSystemProperties(root, projectTargets[0], executionContext.Observable).IncludePaths; } catch (Exception e) { if (e is FormattableException || e is AggregateException) { executionContext.WriteWarning($"Automatic include detection via cmake could not be executed. See log for details."); executionContext.WriteError(e.ToString(), false); } else { throw; } } } } else { executionContext.WriteWarning($"The project in {baseDirectory.FullName} does not contain a valid target. " + $"Without a valid target port structures from within the SDK can not be generated " + $"and automatic include detection will not work as well."); } includes = includes.Concat(new[] { Path.Combine(Constants.IntermediateFolderName, Constants.GeneratedCodeFolderName) }); includes = includes.Concat(GetTargetIncludes()); IDictionary <string, VirtualDirectory> includeDirectories = includes.Distinct().ToDictionary(x => x, GetIncludeDirectory); return(includeDirectories); IEnumerable <string> GetTargetIncludes() { SdkInformation[] projectSdks = projectTargets.Select(sdkRepository.GetSdk) .Distinct() .ToArray(); return(projectSdks.SelectMany(s => s.IncludePaths.Concat(s.CompilerInformation.IncludePaths))); } VirtualDirectory GetIncludeDirectory(string path) { if (fileSystem.DirectoryExists(path, baseDirectory.FullName)) { return(fileSystem.GetDirectory(path, baseDirectory.FullName)); } executionContext.WriteWarning($"The include path {path} was not found and will not be used.", false); return(null); } Target[] GetProjectTargets() { ProjectEntity project = ProjectEntity.Decorate(root); TargetsResult targetsResult = targetParser.Targets(project, false); Target[] availableTargets = sdkRepository.GetAllTargets().ToArray(); Target[] targets = targetsResult.ValidTargets .Select(tr => availableTargets.FirstOrDefault( t => t.Name == tr.Name && t.LongVersion == tr.LongVersion)) .Where(t => t != null) .ToArray(); return(targets); } } ICollection <VirtualDirectory> GetSourceDirectories(VirtualDirectory baseDirectory) { IEnumerable <string> sources = HasSourceDirectoriesCommandArgument(owner) ? GetSourceDirectoriesCommandArgument(owner) : Enumerable.Empty <string>(); ICollection <VirtualDirectory> sourceDirectories = sources.Select(s => fileSystem.DirectoryExists(s, baseDirectory.FullName) ? fileSystem.GetDirectory(s, baseDirectory.FullName) : throw new FormattableException( $"The path {s} does not exist.")) .ToArray(); if (!sourceDirectories.Any()) { sourceDirectories = baseDirectory.Directories.Any(d => d.Name == Constants.SourceFolderName) ? new[] { baseDirectory.Directory(Constants.SourceFolderName) } : new[] { baseDirectory }; } return(sourceDirectories); } IEnumerable <string> GetSourceDirectoriesCommandArgument(Entity entity) { return(entity.Value <CommandDefinition>() ?.Argument <MultipleValueArgument>(EntityKeys.SourceDirectoryKey) ?.Values ?? entity.Value <CommandArgs>() ?.PropertyValue <IEnumerable <string> >(EntityKeys.SourceDirectoryKey) ?? Enumerable.Empty <string>()); } bool HasSourceDirectoriesCommandArgument(Entity entity) { return(entity.Value <CommandDefinition>() ?.Argument <MultipleValueArgument>(EntityKeys.SourceDirectoryKey) != null || entity.Value <CommandArgs>() ?.HasPropertyValue(EntityKeys.SourceDirectoryKey, typeof(IEnumerable <string>)) == true); } IEnumerable <string> GetIncludeDirectoriesCommandArgument(Entity entity) { return(entity.Value <CommandDefinition>() ?.Argument <MultipleValueArgument>(EntityKeys.IncludeDirectoryKey) ?.Values ?? entity.Value <CommandArgs>() ?.PropertyValue <IEnumerable <string> >(EntityKeys.IncludeDirectoryKey) ?? Enumerable.Empty <string>()); } bool HasIncludeDirectoriesCommandArgument(Entity entity) { return(entity.Value <CommandDefinition>() ?.Argument <MultipleValueArgument>(EntityKeys.IncludeDirectoryKey) != null || entity.Value <CommandArgs>() ?.HasPropertyValue(EntityKeys.IncludeDirectoryKey, typeof(IEnumerable <string>)) == true); } bool GetNoIncludeDetectionCommandArgument(Entity entity) { return(entity.Value <CommandDefinition>() ?.Argument <BoolArgument>(Constants.NoIncludePathDetection) ?.Value ?? entity.Value <CommandArgs>() ?.PropertyValue <bool>(Constants.NoIncludePathDetection.ToPropertyName()) ?? false); } bool HasNoIncludeDetectionCommandArgument(Entity entity) { return(entity.Value <CommandDefinition>() ?.Argument <BoolArgument>(Constants.NoIncludePathDetection) != null || entity.Value <CommandArgs>() ?.HasPropertyValue(Constants.NoIncludePathDetection.ToPropertyName(), typeof(bool)) == true); } } ICodeModel CreateCodeModel(Entity root) { VirtualDirectory rootDirectory = fileSystem.GetDirectory(root.Path); return(ParseCodeModel(rootDirectory, root)); } Entity CreateFallback(VirtualDirectory baseDirectory = null) { Entity fallbackEntity = null; try { if (owner.HasPathCommandArgument()) { VirtualDirectory rootDirectory = fileSystem.GetDirectory(owner.GetPathCommandArgument(), createNew: false); if (rootDirectory != null && fileSystem.DirectoryExists(rootDirectory.FullName)) { IEnumerable <VirtualFile> possibleComponents = rootDirectory.Files(searchString: "*.hpp", searchRecursive: true); bool result = possibleComponents.Where(c => { using (Stream fileStream = c.OpenRead()) using (StreamReader streamReader = new StreamReader(fileStream)) { string content = streamReader.ReadToEnd(); if (content.Contains("MetaComponentBase")) { fallbackEntity = owner.Create("acfproject"); } } return(false); }).Any(); } } } catch (Exception exception) { executionContext.WriteVerbose($"Error while creating fallback root entity.{Environment.NewLine}{exception}"); } if (fallbackEntity == null) { fallbackEntity = owner.Create("project"); } fallbackEntity.AddValue(() => CreateCodeModel(fallbackEntity)); if (baseDirectory != null) { fallbackEntity.AddValue(baseDirectory); } return(fallbackEntity); } bool HasRootInHierarchy(out Entity foundRoot) { foundRoot = owner.EntityHierarchy().FirstOrDefault(HasRootTemplate); return(foundRoot != null); bool HasRootTemplate(Entity possibleRoot) { return(possibleRoot.HasTemplate() && possibleRoot.Template().isRoot); } } TemplateDescription FindRootTemplate(TemplateDescription template) { Stack <TemplateDescription> unvisited = new Stack <TemplateDescription>(new[] { template }); List <TemplateDescription> visited = new List <TemplateDescription>(); while (unvisited.Any()) { TemplateDescription current = unvisited.Pop(); if (current.isRoot) { return(current); } visited.Add(current); foreach (templateRelationship relationship in current.Relationship) { TemplateDescription description = templateRepository.Template(relationship.type); if (description != null && !visited.Contains(description)) { unvisited.Push(description); } } } return(null); } Entity CreateRootBasedOnAllRootTemplates(VirtualDirectory baseDirectory) { return(IdentifyRoot(templateRepository.Templates.Where(t => t.isRoot), baseDirectory)); } Entity IdentifyRoot(IEnumerable <TemplateDescription> templateDescriptions, VirtualDirectory baseDirectory) { Entity root = null; foreach (TemplateDescription possibleTemplate in templateDescriptions.OrderByDescending(Depth)) { root = identifierRepository.FindAllEntities(possibleTemplate.name, owner, possibleTemplate.identifier) .FirstOrDefault(); if (root != null) { break; } } if (root != null) { root.AddValue(() => CreateCodeModel(root)); } else { root = CreateFallback(baseDirectory); } return(root); int Depth(TemplateDescription templateDescription) { int depth = 0; while (!string.IsNullOrEmpty(templateDescription?.basedOn)) { templateDescription = templateRepository.Template(templateDescription.basedOn); depth++; } return(depth); } } Entity CreateRootBasedOnTemplate(VirtualDirectory baseDirectory) { TemplateDescription template = owner.Template(); IEnumerable <TemplateDescription> possibleTemplates = FindAllRootTemplates(); return(IdentifyRoot(possibleTemplates, baseDirectory)); IEnumerable <TemplateDescription> FindAllRootTemplates() { TemplateDescription rootTemplate = FindRootTemplate(template); if (rootTemplate == null) { throw new RootTemplateNotFoundException(template.name); } List <TemplateDescription> result = new List <TemplateDescription>(); Stack <TemplateDescription> unvisited = new Stack <TemplateDescription>(); unvisited.Push(rootTemplate); while (unvisited.Any()) { TemplateDescription current = unvisited.Pop(); result.Add(current); foreach (TemplateDescription description in templateRepository.Templates .Where(t => t.basedOn ?.Equals(current.name, StringComparison .OrdinalIgnoreCase) == true)) { unvisited.Push(description); } } return(result); } } } }
public override Entity Resolve(Entity owner, string key, bool fallback = false) { if (key.StartsWith("is", StringComparison.OrdinalIgnoreCase)) { return(owner.Create(key, IsCheck(owner, key))); } switch (key) { case EntityKeys.TemplateKey: TemplateDescription template = templateRepository.Template(owner.Type); return(template != null ? owner.Create(key, owner.Type, template) : ParentTemplateEntity(owner)); case EntityKeys.RelatedKey: return(GetRelatedEntities(owner)); case EntityKeys.HiearchyKey: return(GetHierarchyEntities(owner)); default: //continue execution break; } IEnumerable <ForeachItemContainer> foreachItems = owner.Values <ForeachItemContainer>(); ForeachItemContainer foreachItem = foreachItems.FirstOrDefault(i => i.Key.Equals(key, StringComparison.OrdinalIgnoreCase)); if (foreachItem != null) { return(foreachItem.Current); } if (owner.Any(o => o.Value <templateFile>()?.key?.Equals(key, StringComparison.OrdinalIgnoreCase) == true)) { return(owner.First(o => o.Value <templateFile>()?.key?.Equals(key, StringComparison.OrdinalIgnoreCase) == true)); } if (owner.Value <templateFile>() != null) { Entity result = owner.Create(key, new Func <string>(() => owner.Value <templateFile>().GetType() .GetProperty(key)? .GetValue(owner.Value <templateFile>()) ?.ToString() ?? string.Empty)); result.SetContext(FindContext(owner)); return(result); } TemplateDescription ownerTemplate = owner.Value <TemplateDescription>(); switch (key) { case EntityKeys.TemplateFilesKey: Entity[] files = ownerTemplate.File.Concat(ownerTemplate.GeneratedFile ?? Enumerable.Empty <templateGeneratedFile>()) .Select(tf => owner.Create("TemplateFile", tf.template, tf)) .ToArray(); return(owner.Create("TemplateFiles", (IEnumerable <Entity>)files)); default: PropertyInfo info = ownerTemplate.GetType().GetProperty(key); if (info != null) { object value = info.GetValue(ownerTemplate); return(owner.Create(key, value?.ToString() ?? string.Empty, value)); } throw new ContentProviderException(key, owner); } Entity FindContext(Entity current) { while (current != null && current.Value <TemplateDescription>() == null) { current = current.Owner; } return(current?.Owner); } Entity GetRelatedEntities(Entity entity) { TemplateDescription template = entity.Template(); IType entityType = entity.Value <IType>(); (templateRelationship relationship, TemplateDescription template)[] relatedTemplates = GetRelatedTemplates(); List <(string tn, IType t)> related = new List <(string, IType)>(); if (entity.Root.HasValue <ICodeModel>()) { ICodeModel codeModel = entity.Root.Value <ICodeModel>(); foreach (IType type in codeModel.Types.Keys) { (templateRelationship rel, TemplateDescription des) = relatedTemplates.FirstOrDefault(t => type.HasAttributeWithoutValue(t.template.name)); bool isRelevant = false; if (rel != null) { if (template.TemplateNames(templateRepository) .Any(n => n.Equals(rel.type, StringComparison.OrdinalIgnoreCase))) { isRelevant = template.isRoot || type.Attributes.Any(a => a.Name.Equals(rel.name, StringComparison.OrdinalIgnoreCase) && a.Values.Any(v => IsRelatedType(entityType, v))); } else { isRelevant = des.isRoot || entityType?.Attributes.Any(a => a.Name.Equals(rel.name, StringComparison.OrdinalIgnoreCase) && a.Values.Any(v => IsRelatedType(type, v))) == true; } } if (isRelevant) { related.Add((des.name, type)); } } bool IsRelatedType(IType relatedType, string name) { if (relatedType?.FullName.Equals(name, StringComparison.Ordinal) == true) { return(true); } return(codeModel.Type(name) == null && relatedType?.FullName.Contains(name) == true); } } return(owner.Create(key, related.Select(r => owner.EntityHierarchy() .FirstOrDefault(e => e.HasValue <IType>() && e.Value <IType>() == r.t) ?? owner.Create(r.tn, r.t.FullName, r.t)))); (templateRelationship, TemplateDescription)[] GetRelatedTemplates()