/// <summary> /// Инициализирует экземпляр указанным количеством модулей лент. /// </summary> /// <param name="count">Кодичество создаваемых модулей.</param> public TuringTapes(int count) { _units = new List<TuringUnit>(); _symbols = new SymbolSet(); Count = count; }
/// <summary> /// Возвращает алфавит, использованный в списке операций для машины Тьюринга. /// </summary> /// <param name="operations">Список операций для машины Тьюринга.</param> /// <returns>Алфавит.</returns> public static SymbolSet GetAlphabet(List<Operation> operations) { List<TuringOperation> ops = operations.Cast<TuringOperation>().ToList(); SymbolSet result = new SymbolSet(); int i, j, n, m; n = ops.Count; for(i = 0; i < n; i++) { m = ops[i].State.Converts.Length; for(j = 0; j < m; j++) { try { AddChars(result, ops[i].State.Converts[j].Input); AddChars(result, ops[i].State.Converts[j].Output); } catch { throw new Exception("Размер алфавита операций превысил допустимое значение"); } } } return result; }
private TuringMachine(SerializationInfo info, StreamingContext context) { _tapes = info.GetValue("t", typeof(TuringTapes)) as TuringTapes; _symbols = info.GetValue("s", typeof(SymbolSet)) as SymbolSet; _tapes.TapeUpdated += _tapes_TapeUpdated; }
/// <summary> /// Инициализирует машину Тьюринга единственной пустой лентой. /// </summary> public TuringMachine() { _tapes = new TuringTapes(1); _stateIndex = -1; _states = null; _symbols = new SymbolSet(); _tapes.TapeUpdated += _tapes_TapeUpdated; }
/// <summary> /// Инициализирует машину Тьюринга заданным количеством лент. /// </summary> /// <param name="tapesCount">Количество создаваемых лент.</param> public TuringMachine(int tapesCount) { if (tapesCount < 1) throw new ArgumentException("Количество лент должно быть положительным"); _tapes = new TuringTapes(tapesCount); _stateIndex = -1; _states = null; _symbols = new SymbolSet(); }
/// <summary> /// Проверяет, есть ли указанные символы в алфавите. Если нет, то добавляет их. /// </summary> /// <param name="al">Расширяемый алфавит.</param> /// <param name="chars">Массив добавляемых символов.</param> private static void AddChars(SymbolSet al, char[] chars) { int n = chars.Length; for(int i = 0; i < n; i++) { if(!al.CharExists(chars[i])) { al.AddChar(chars[i]); } } }
private TuringTapes(SerializationInfo info, StreamingContext context) { int n = info.GetInt32("n"); _units = new List<TuringUnit>(); for (int i = 0; i < n; i++) _units.Add(info.GetValue("u" + i.ToString(), typeof(TuringUnit)) as TuringUnit); _symbols = info.GetValue("s", typeof(SymbolSet)) as SymbolSet; _defaultChar = info.GetChar("c"); _units.ForEach(x => x.Tape.Update += Tape_Update); }
public TileSetLoader(string path) { m_path = path; m_symbolSet = LoadSymbolSet("TileSet.xaml"); }
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) { global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); SymbolSet ds = new SymbolSet(); global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny(); any1.Namespace = "http://www.w3.org/2001/XMLSchema"; any1.MinOccurs = new decimal(0); any1.MaxOccurs = decimal.MaxValue; any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; sequence.Items.Add(any1); global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny(); any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"; any2.MinOccurs = new decimal(1); any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; sequence.Items.Add(any2); global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute(); attribute1.Name = "namespace"; attribute1.FixedValue = ds.Namespace; type.Attributes.Add(attribute1); global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute(); attribute2.Name = "tableTypeName"; attribute2.FixedValue = "SymbolTableDataTable"; type.Attributes.Add(attribute2); type.Particle = sequence; global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); try { global::System.Xml.Schema.XmlSchema schema = null; dsSchema.Write(s1); for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext();) { schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); s2.SetLength(0); schema.Write(s2); if ((s1.Length == s2.Length)) { s1.Position = 0; s2.Position = 0; for (; ((s1.Position != s1.Length) && (s1.ReadByte() == s2.ReadByte()));) { ; } if ((s1.Position == s1.Length)) { return(type); } } } } finally { if ((s1 != null)) { s1.Close(); } if ((s2 != null)) { s2.Close(); } } } xs.Add(dsSchema); return(type); }
internal ResolvedAttributeSet FetchResolvedAttributes(ResolveOptions resOpt = null, AttributeContextParameters acpInContext = null) { bool wasPreviouslyResolving = this.Ctx.Corpus.isCurrentlyResolving; this.Ctx.Corpus.isCurrentlyResolving = true; if (resOpt == null) { resOpt = new ResolveOptions(this); } const string kind = "rasb"; ResolveContext ctx = this.Ctx as ResolveContext; string cacheTag = ctx.Corpus.CreateDefinitionCacheTag(resOpt, this, kind, acpInContext != null ? "ctx" : ""); dynamic rasbCache = null; if (cacheTag != null) { ctx.Cache.TryGetValue(cacheTag, out rasbCache); } CdmAttributeContext underCtx = null; // store the previous document set, we will need to add it with // children found from the constructResolvedTraits call SymbolSet currDocRefSet = resOpt.SymbolRefSet; if (currDocRefSet == null) { currDocRefSet = new SymbolSet(); } resOpt.SymbolRefSet = new SymbolSet(); // get the moniker that was found and needs to be appended to all // refs in the children attribute context nodes string fromMoniker = resOpt.FromMoniker; resOpt.FromMoniker = null; if (rasbCache == null) { if (this.resolvingAttributes) { // re-entered this attribute through some kind of self or looping reference. this.Ctx.Corpus.isCurrentlyResolving = wasPreviouslyResolving; return(new ResolvedAttributeSet()); } this.resolvingAttributes = true; // if a new context node is needed for these attributes, make it now if (acpInContext != null) { underCtx = CdmAttributeContext.CreateChildUnder(resOpt, acpInContext); } rasbCache = this.ConstructResolvedAttributes(resOpt, underCtx); this.resolvingAttributes = false; // register set of possible docs CdmObjectDefinition oDef = this.FetchObjectDefinition <CdmObjectDefinitionBase>(resOpt); if (oDef != null) { ((CdmCorpusDefinition)ctx.Corpus).RegisterDefinitionReferenceSymbols(oDef, kind, resOpt.SymbolRefSet); // get the new cache tag now that we have the list of docs cacheTag = ((CdmCorpusDefinition)ctx.Corpus).CreateDefinitionCacheTag(resOpt, this, kind, acpInContext != null ? "ctx" : null); // save this as the cached version if (!string.IsNullOrWhiteSpace(cacheTag)) { ctx.Cache[cacheTag] = rasbCache; } if (!string.IsNullOrWhiteSpace(fromMoniker) && acpInContext != null && (this is CdmObjectReferenceBase) && (this as CdmObjectReferenceBase).NamedReference != null) { // create a fresh context CdmAttributeContext oldContext = acpInContext.under.Contents[acpInContext.under.Contents.Count - 1] as CdmAttributeContext; acpInContext.under.Contents.RemoveAt(acpInContext.under.Contents.Count - 1); underCtx = CdmAttributeContext.CreateChildUnder(resOpt, acpInContext); CdmAttributeContext newContext = oldContext.CopyAttributeContextTree(resOpt, underCtx, rasbCache.ResolvedAttributeSet, null, fromMoniker); // since THIS should be a refererence to a thing found in a moniker document, it already has a moniker in the reference // this function just added that same moniker to everything in the sub-tree but now this one symbol has too many // remove one string monikerPathAdded = $"{fromMoniker}/"; if (newContext.Definition != null && newContext.Definition.NamedReference != null && newContext.Definition.NamedReference.StartsWith(monikerPathAdded)) { // slice it off the front newContext.Definition.NamedReference = newContext.Definition.NamedReference.Substring(monikerPathAdded.Length); } } } } else { // cache found. if we are building a context, then fix what we got instead of making a new one if (acpInContext != null) { // make the new context underCtx = CdmAttributeContext.CreateChildUnder(resOpt, acpInContext); rasbCache.ResolvedAttributeSet.AttributeContext.CopyAttributeContextTree(resOpt, underCtx, rasbCache.ResolvedAttributeSet, null, fromMoniker); } } // merge child document set with current currDocRefSet.Merge(resOpt.SymbolRefSet); resOpt.SymbolRefSet = currDocRefSet; this.Ctx.Corpus.isCurrentlyResolving = wasPreviouslyResolving; return(rasbCache?.ResolvedAttributeSet); }
protected string BuildLegacySIDCTag(LibraryStandardIdentityGroup sig, SymbolSet ss, SymbolSetEntity e, SymbolSetEntityEntityType eType, EntitySubTypeType eSubType) { string result = _configHelper.SIDCIsNew; if (ss != null && e != null) { uint partA = 1000000000 + (ss.SymbolSetCode.DigitOne * (uint)100000) + (ss.SymbolSetCode.DigitTwo * (uint)10000); if (sig != null) { partA = partA + (sig.StandardIdentityGroupCode * (uint)1000000); } uint partB = (e.EntityCode.DigitOne * (uint)1000000000) + (e.EntityCode.DigitTwo * (uint)100000000); if (eType != null) { partB = partB + (eType.EntityTypeCode.DigitOne * (uint)10000000) + (eType.EntityTypeCode.DigitTwo * (uint)1000000); } if (eSubType != null) { partB = partB + (eSubType.EntitySubTypeCode.DigitOne * (uint)100000) + (eSubType.EntitySubTypeCode.DigitTwo * (uint)10000); } Symbol symbol = _configHelper.Librarian.MakeSymbol(new SIDC(partA, partB)); // // If the symbol has a 2525C equivalent, return it // if (symbol != null) { if (symbol.SymbolStatus == SymbolStatusEnum.statusEnumOld) { result = symbol.LegacySIDC; if (sig == null && result.Substring(1, 1) == "P") { result = result.Substring(0, 1) + "*" + result.Substring(2); } if (result.Substring(14, 1) == "X") { result = result.Substring(0, 10) + "****X"; } else if (result.Substring(0, 1) == "W") { result = result.Substring(0, 13) + "**"; } else if (result.Substring(10, 5) == "-----") { result = result.Substring(0, 10) + "*****"; } else if (result.Substring(11, 4) == "----") { result = result.Substring(0, 11) + "****"; } } } else { logger.Warn("Symbol could not be built from: " + partA + ":" + partB); } } return(result); }
public static PooledDisposer <PooledHashSet <INamedTypeSymbol> > GetSymbolSet(out SymbolSet instance) { var pooledInstance = s_symbolSetPool.Allocate(); Debug.Assert(pooledInstance.Count == 0); instance = pooledInstance; return(new PooledDisposer <PooledHashSet <INamedTypeSymbol> >(pooledInstance)); }
private string _buildName(SymbolSet ss, SymbolSetLegacySymbol legacySymbol) { // Builds a seperated string of components names for all the 2525D elements // used to make this legacy symbol string result = ""; Librarian lib = _configHelper.Librarian; if (legacySymbol.EntityID != "") { _entity = lib.Entity(ss, legacySymbol.EntityID); } else { _entity = null; } if (_entity != null && legacySymbol.EntityTypeID != "") { _entityType = lib.EntityType(_entity, legacySymbol.EntityTypeID); } else { _entityType = null; } if (_entityType != null && legacySymbol.EntitySubTypeID != "") { _entitySubType = lib.EntitySubType(ss, _entityType, legacySymbol.EntitySubTypeID); } else { _entitySubType = null; } if (legacySymbol.ModifierOneID != "") { _modifier1 = lib.ModifierOne(ss, legacySymbol.ModifierOneID); } else { _modifier1 = null; } if (legacySymbol.ModifierTwoID != "") { _modifier2 = lib.ModifierTwo(ss, legacySymbol.ModifierTwoID); } else { _modifier2 = null; } result = _entityExport.NameIt(null, ss, _entity, _entityType, _entitySubType); if (_modifier1 != null && _modifier1.Label != "Unspecified" && _modifier1.Label != "Not Applicable") { result = result + _configHelper.DomainSeparator + _modifierExport.NameIt(ss, "1", _modifier1); } if (_modifier2 != null && _modifier2.Label != "Unspecified" && _modifier2.Label != "Not Applicable") { result = result + _configHelper.DomainSeparator + _modifierExport.NameIt(ss, "2", _modifier2); } return(result); }
internal override ResolvedTraitSet FetchResolvedTraits(ResolveOptions resOpt = null) { if (resOpt == null) { resOpt = new ResolveOptions(this, this.Ctx.Corpus.DefaultResolutionDirectives); } const string kind = "rtsb"; ResolveContext ctx = this.Ctx as ResolveContext; // this may happen 0, 1 or 2 times. so make it fast CdmTraitDefinition baseTrait = null; ResolvedTraitSet baseRts = null; List <dynamic> baseValues = null; System.Action GetBaseInfo = () => { if (this.ExtendsTrait != null) { baseTrait = this.ExtendsTrait.FetchObjectDefinition <CdmTraitDefinition>(resOpt); if (baseTrait != null) { baseRts = this.ExtendsTrait.FetchResolvedTraits(resOpt); if (baseRts?.Size == 1) { ParameterValueSet basePv = baseRts.Get(baseTrait)?.ParameterValues; if (basePv != null) { baseValues = basePv.Values; } } } } }; // see if one is already cached // if this trait has parameters, then the base trait found through the reference might be a different reference // because trait references are unique per argument value set. so use the base as a part of the cache tag // since it is expensive to figure out the extra tag, cache that too! if (this.BaseIsKnownToHaveParameters == null) { GetBaseInfo(); // is a cache tag needed? then make one this.BaseIsKnownToHaveParameters = false; if (baseValues?.Count > 0) { this.BaseIsKnownToHaveParameters = true; } } string cacheTagExtra = ""; if (this.BaseIsKnownToHaveParameters == true) { cacheTagExtra = this.ExtendsTrait.Id.ToString(); } string cacheTag = ctx.Corpus.CreateDefinitionCacheTag(resOpt, this, kind, cacheTagExtra); dynamic rtsResultDynamic = null; if (cacheTag != null) { ctx.Cache.TryGetValue(cacheTag, out rtsResultDynamic); } ResolvedTraitSet rtsResult = rtsResultDynamic as ResolvedTraitSet; // store the previous reference symbol set, we will need to add it with // children found from the constructResolvedTraits call SymbolSet currSymbolRefSet = resOpt.SymbolRefSet; if (currSymbolRefSet == null) { currSymbolRefSet = new SymbolSet(); } resOpt.SymbolRefSet = new SymbolSet(); // if not, then make one and save it if (rtsResult == null) { GetBaseInfo(); if (baseTrait != null) { // get the resolution of the base class and use the values as a starting point for this trait's values if (!this.HasSetFlags) { // inherit these flags if (this.Elevated == null) { this.Elevated = baseTrait.Elevated; } if (this.Ugly == null) { this.Ugly = baseTrait.Ugly; } if (this.AssociatedProperties == null) { this.AssociatedProperties = baseTrait.AssociatedProperties; } } } this.HasSetFlags = true; ParameterCollection pc = this.FetchAllParameters(resOpt); List <dynamic> av = new List <dynamic>(); List <bool> wasSet = new List <bool>(); this.ThisIsKnownToHaveParameters = pc.Sequence.Count > 0; for (int i = 0; i < pc.Sequence.Count; i++) { // either use the default value or (higher precidence) the value taken from the base reference dynamic value = (pc.Sequence[i] as CdmParameterDefinition).DefaultValue; dynamic baseValue = null; if (baseValues != null && i < baseValues.Count) { baseValue = baseValues[i]; if (baseValue != null) { value = baseValue; } } av.Add(value); wasSet.Add(false); } // save it ResolvedTrait resTrait = new ResolvedTrait(this, pc, av, wasSet); rtsResult = new ResolvedTraitSet(resOpt); rtsResult.Merge(resTrait, false); // register set of possible symbols ctx.Corpus.RegisterDefinitionReferenceSymbols(this.FetchObjectDefinition <CdmObjectDefinitionBase>(resOpt), kind, resOpt.SymbolRefSet); // get the new cache tag now that we have the list of docs cacheTag = ctx.Corpus.CreateDefinitionCacheTag(resOpt, this, kind, cacheTagExtra); if (!string.IsNullOrWhiteSpace(cacheTag)) { ctx.Cache[cacheTag] = rtsResult; } } else { // cache found // get the SymbolSet for this cached object string key = CdmCorpusDefinition.CreateCacheKeyFromObject(this, kind); ((CdmCorpusDefinition)ctx.Corpus).DefinitionReferenceSymbols.TryGetValue(key, out SymbolSet tempSymbolRefSet); resOpt.SymbolRefSet = tempSymbolRefSet; } // merge child document set with current currSymbolRefSet.Merge(resOpt.SymbolRefSet); resOpt.SymbolRefSet = currSymbolRefSet; return(rtsResult); }
private static bool TypeHasBaseTypeInSet(INamedTypeSymbol type, SymbolSet set) { var baseType = type.BaseType?.OriginalDefinition; return(baseType != null && set.Contains(baseType)); }
internal override ResolvedTraitSet FetchResolvedTraits(ResolveOptions resOpt = null) { if (resOpt == null) { resOpt = new ResolveOptions(this); } if (this.NamedReference != null && this.AppliedTraits == null) { const string kind = "rts"; ResolveContext ctx = this.Ctx as ResolveContext; string objDefName = this.FetchObjectDefinitionName(); string cacheTag = ((CdmCorpusDefinition)ctx.Corpus).CreateDefinitionCacheTag(resOpt, this, kind, "", true); dynamic rtsResultDynamic = null; if (cacheTag != null) { ctx.Cache.TryGetValue(cacheTag, out rtsResultDynamic); } ResolvedTraitSet rtsResult = rtsResultDynamic as ResolvedTraitSet; // store the previous document set, we will need to add it with // children found from the constructResolvedTraits call SymbolSet currSymRefSet = resOpt.SymbolRefSet; if (currSymRefSet == null) { currSymRefSet = new SymbolSet(); } resOpt.SymbolRefSet = new SymbolSet(); if (rtsResult == null) { CdmObjectDefinition objDef = this.FetchObjectDefinition <CdmObjectDefinition>(resOpt); if (objDef != null) { rtsResult = (objDef as CdmObjectDefinitionBase).FetchResolvedTraits(resOpt); if (rtsResult != null) { rtsResult = rtsResult.DeepCopy(); } // register set of possible docs ((CdmCorpusDefinition)ctx.Corpus).RegisterDefinitionReferenceSymbols(objDef, kind, resOpt.SymbolRefSet); // get the new cache tag now that we have the list of docs cacheTag = ((CdmCorpusDefinition)ctx.Corpus).CreateDefinitionCacheTag(resOpt, this, kind, "", true); if (!string.IsNullOrWhiteSpace(cacheTag)) { ctx.Cache[cacheTag] = rtsResult; } } } else { // cache was found // get the SymbolSet for this cached object string key = CdmCorpusDefinition.CreateCacheKeyFromObject(this, kind); ((CdmCorpusDefinition)ctx.Corpus).DefinitionReferenceSymbols.TryGetValue(key, out SymbolSet tempDocRefSet); resOpt.SymbolRefSet = tempDocRefSet; } // merge child document set with current currSymRefSet.Merge(resOpt.SymbolRefSet); resOpt.SymbolRefSet = currSymRefSet; return(rtsResult); } else { return(base.FetchResolvedTraits(resOpt)); } }
public Librarian(string configPath = "") { InitializeNLog(); // // Deserialize the configuration xml to get the location of the symbology library // XmlSerializer serializer = new XmlSerializer(typeof(JMSMLConfig)); serializer.UnknownNode += new XmlNodeEventHandler(serializer_UnknownNode); serializer.UnknownAttribute += new XmlAttributeEventHandler(serializer_UnknownAttribute); if (configPath != "") { _configPath = configPath; } else { string s = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); _configPath = Path.Combine(s, "jmsml.config"); } if (File.Exists(_configPath)) { using (FileStream fs = new FileStream(_configPath, FileMode.Open, FileAccess.Read)) { if (fs.CanRead) { _configData = (JMSMLConfig)serializer.Deserialize(fs); } else { logger.Error("Unreadable config file: " + _configPath); } } } else { logger.Error("Config file is missing: " + _configPath); } // // If the config data was good then... // if (_configData != null) { // // Deserialize the library's base xml to get the base contents of the symbology standard // serializer = new XmlSerializer(typeof(Library)); string path = _configData.LibraryPath + "/" + _configData.LibraryName; if (File.Exists(path)) { using (FileStream fsLibrary = new FileStream(path, FileMode.Open, FileAccess.Read)) { if (fsLibrary.CanRead) { this._library = (Library)serializer.Deserialize(fsLibrary); // // Deserialize each symbolSet xml // foreach (LibraryDimension dimension in this._library.Dimensions) { foreach (LibraryDimensionSymbolSetRef ssRef in dimension.SymbolSets) { ushort ssCode = CodeToShort(ssRef.SymbolSetCode); if (!_sortedSymbolSets.ContainsKey(ssCode)) { path = _configData.LibraryPath + "/" + ssRef.Instance; if (File.Exists(path)) { using (FileStream fsSymbolSet = new FileStream(path, FileMode.Open, FileAccess.Read)) { if (fsSymbolSet.CanRead) { serializer = new XmlSerializer(typeof(SymbolSet)); SymbolSet ss = (SymbolSet)serializer.Deserialize(fsSymbolSet); if (ss != null) { _sortedSymbolSets.Add(ssCode, ss); _symbolSets.Add(ss); } } else { logger.Error("Unreadable symbol set: " + path); } } } else { logger.Error("Symbol set is missing: " + path); } } } } // // Create special invalid and retired symbols for this library // _invalidSymbol = new Symbol(this, SIDC.INVALID); _retiredSymbol = new Symbol(this, SIDC.RETIRED); } else { logger.Error("Unreadable symbol library: " + path); } } } else { logger.Error("Specified library is missing: " + path); } } }
internal virtual ResolvedTraitSet FetchResolvedTraits(ResolveOptions resOpt = null) { bool wasPreviouslyResolving = this.Ctx.Corpus.isCurrentlyResolving; this.Ctx.Corpus.isCurrentlyResolving = true; if (resOpt == null) { resOpt = new ResolveOptions(this, this.Ctx.Corpus.DefaultResolutionDirectives); } const string kind = "rtsb"; ResolveContext ctx = this.Ctx as ResolveContext; string cacheTagA = ctx.Corpus.CreateDefinitionCacheTag(resOpt, this, kind); ResolvedTraitSetBuilder rtsbAll = null; if (this.TraitCache == null) { this.TraitCache = new Dictionary <string, ResolvedTraitSetBuilder>(); } else if (!string.IsNullOrWhiteSpace(cacheTagA)) { this.TraitCache.TryGetValue(cacheTagA, out rtsbAll); } // store the previous document set, we will need to add it with // children found from the constructResolvedTraits call SymbolSet currDocRefSet = resOpt.SymbolRefSet; if (currDocRefSet == null) { currDocRefSet = new SymbolSet(); } resOpt.SymbolRefSet = new SymbolSet(); if (rtsbAll == null) { rtsbAll = new ResolvedTraitSetBuilder(); if (!resolvingTraits) { resolvingTraits = true; this.ConstructResolvedTraits(rtsbAll, resOpt); resolvingTraits = false; } CdmObjectDefinitionBase objDef = this.FetchObjectDefinition <CdmObjectDefinitionBase>(resOpt); if (objDef != null) { // register set of possible docs ctx.Corpus.RegisterDefinitionReferenceSymbols(objDef, kind, resOpt.SymbolRefSet); if (rtsbAll.ResolvedTraitSet == null) { // nothing came back, but others will assume there is a set in this builder rtsbAll.ResolvedTraitSet = new ResolvedTraitSet(resOpt); } // get the new cache tag now that we have the list of docs cacheTagA = ctx.Corpus.CreateDefinitionCacheTag(resOpt, this, kind); if (!string.IsNullOrWhiteSpace(cacheTagA)) { this.TraitCache[cacheTagA] = rtsbAll; } } } else { // cache was found // get the SymbolSet for this cached object string key = CdmCorpusDefinition.CreateCacheKeyFromObject(this, kind); ctx.Corpus.DefinitionReferenceSymbols.TryGetValue(key, out SymbolSet tempDocRefSet); resOpt.SymbolRefSet = tempDocRefSet; } // merge child document set with current currDocRefSet.Merge(resOpt.SymbolRefSet); resOpt.SymbolRefSet = currDocRefSet; this.Ctx.Corpus.isCurrentlyResolving = wasPreviouslyResolving; return(rtsbAll.ResolvedTraitSet); }
public ICollection <TypeSymbol> ImportMetadata(ICollection <string> references, SymbolSet symbols) { Debug.Assert(references != null); Debug.Assert(symbols != null); _symbols = symbols; MetadataSource mdSource = new MetadataSource(); bool hasLoadErrors = mdSource.LoadReferences(references, _errorHandler); ICollection <TypeSymbol> importedTypes = null; if (hasLoadErrors == false) { importedTypes = ImportAssemblies(mdSource); } if (_resolveError) { return(null); } #if STATIC_ARRAY_EXTENSIONS // Update instance members that need to be generated as static methods ConvertInstanceMembersToStaticMembers(); #endif // STATIC_ARRAY_EXTENSIONS return(importedTypes); }
private void _UpdateFromCurrent() { // Search for the appropriate JMSML Library elements, given the current (2525D) // SIDC for this Symbol. string first10 = _sidc.PartAString; string second10 = _sidc.PartBString; _librarian.ResetStatusCode(); _version = _librarian.Version(Convert.ToUInt16(first10.Substring(0, 1)), Convert.ToUInt16(first10.Substring(1, 1))); _context = _librarian.Context(Convert.ToUInt16(first10.Substring(2, 1))); _standardIdentity = _librarian.StandardIdentity(Convert.ToUInt16(first10.Substring(3, 1))); _sig = _librarian.StandardIdentityGroup(_standardIdentity); _symbolSet = _librarian.SymbolSet(Convert.ToUInt16(first10.Substring(4, 1)), Convert.ToUInt16(first10.Substring(5, 1))); if (_symbolSet != null) { _dimension = _librarian.DimensionBySymbolSet(_symbolSet.ID); } if (_context != null && _dimension != null && _standardIdentity != null) { _affiliation = _librarian.Affiliation(_context.ID, _dimension.ID, _standardIdentity.ID); } _status = _librarian.Status(Convert.ToUInt16(first10.Substring(6, 1))); _hqTFDummy = _librarian.HQTFDummy(Convert.ToUInt16(first10.Substring(7, 1))); _amplifierGroup = _librarian.AmplifierGroup(Convert.ToUInt16(first10.Substring(8, 1))); if (_amplifierGroup != null) { _amplifier = _librarian.Amplifier(_amplifierGroup, Convert.ToUInt16(first10.Substring(9, 1))); } if (_symbolSet != null) { _entity = _librarian.Entity(_symbolSet, Convert.ToUInt16(second10.Substring(0, 1)), Convert.ToUInt16(second10.Substring(1, 1))); if (_entity != null) { _entityType = _librarian.EntityType(_entity, Convert.ToUInt16(second10.Substring(2, 1)), Convert.ToUInt16(second10.Substring(3, 1))); } if (_entityType != null) { _entitySubType = _librarian.EntitySubType(_entityType, Convert.ToUInt16(second10.Substring(4, 1)), Convert.ToUInt16(second10.Substring(5, 1))); if (_entitySubType == null) { _entitySubType = _librarian.EntitySubType(_symbolSet, Convert.ToUInt16(second10.Substring(4, 1)), Convert.ToUInt16(second10.Substring(5, 1))); } } _modifierOne = _librarian.ModifierOne(_symbolSet, Convert.ToUInt16(second10.Substring(6, 1)), Convert.ToUInt16(second10.Substring(7, 1))); _modifierTwo = _librarian.ModifierTwo(_symbolSet, Convert.ToUInt16(second10.Substring(8, 1)), Convert.ToUInt16(second10.Substring(9, 1))); _legacySymbol = _librarian.LegacySymbol(_symbolSet, _entity, _entityType, _entitySubType, _modifierOne, _modifierTwo); } _librarian.LogConversionResult(_sidc.PartAString + ", " + _sidc.PartBString); _ValidateStatus(); }
internal SymbolSetLegacySymbol LegacySymbol(SymbolSet symbolSet, SymbolSetEntity entity, SymbolSetEntityEntityType entityType, EntitySubTypeType entitySubType, ModifiersTypeModifier modifierOne, ModifiersTypeModifier modifierTwo) { SymbolSetLegacySymbol retObj = null; if (symbolSet != null) { if (symbolSet.LegacySymbols != null) { int match = 0; foreach (SymbolSetLegacySymbol lObj in symbolSet.LegacySymbols) { if (entity != null) { if (lObj.EntityID != "NA") { if (lObj.EntityID == entity.ID) { match++; } } } else if (lObj.EntityID == "NA") { match++; } if (entityType != null) { if (lObj.EntityTypeID != "NA") { if (lObj.EntityTypeID == entityType.ID) { match++; } } } else if (lObj.EntityTypeID == "NA") { match++; } if (entitySubType != null) { if (lObj.EntitySubTypeID != "NA") { if (lObj.EntitySubTypeID == entitySubType.ID) { match++; } } } else if (lObj.EntitySubTypeID == "NA") { match++; } if (modifierOne != null) { if (lObj.ModifierOneID != "NA") { if (lObj.ModifierOneID == modifierOne.ID) { match++; } } } else if (lObj.ModifierOneID == "NA") { match++; } if (modifierTwo != null) { if (lObj.ModifierTwoID != "NA") { if (lObj.ModifierTwoID == modifierTwo.ID) { match++; } } } else if (lObj.ModifierTwoID == "NA") { match++; } if (match == 5) { return(lObj); } match = 0; } } } _statusFlag -= 65536; return(retObj); }
internal SymbolSetLegacySymbol LegacySymbol(string legacySIDC, ref LibraryDimension dimensionOut, ref SymbolSet ssOut) { SymbolSetLegacySymbol retObj = null; dimensionOut = null; ssOut = null; string codingSchemeLetter = legacySIDC.Substring(0, 1); string code = legacySIDC.Substring(2, 1); string firstLetterInFunction = legacySIDC.Substring(4, 1); foreach (LibraryDimension lObj in _library.Dimensions) { if (lObj.LegacyDimensionCode != null) { foreach (LegacyLetterCodeType lObj2 in lObj.LegacyDimensionCode) { if ((lObj2.Value == code && lObj2.FirstFunctionLetter == "" && lObj2.CodingSchemeLetter == "") || (lObj2.Value == code && lObj2.FirstFunctionLetter == firstLetterInFunction && lObj2.CodingSchemeLetter == "") || (lObj2.Value == code && lObj2.FirstFunctionLetter == "" && lObj2.CodingSchemeLetter == codingSchemeLetter) || (lObj2.Value == code && lObj2.FirstFunctionLetter == firstLetterInFunction && lObj2.CodingSchemeLetter == codingSchemeLetter)) { if (lObj.SymbolSets != null) { foreach (LibraryDimensionSymbolSetRef ssRef in lObj.SymbolSets) { SymbolSet ss = this.SymbolSet(ssRef.ID); if (ss != null) { retObj = this.LegacySymbol(ss, legacySIDC); if (retObj != null) { dimensionOut = lObj; ssOut = ss; return(retObj); } } } } } } } } if (retObj == null) { _statusFlag -= 4; // Can't find a Dimension _statusFlag -= 16; // Can't find a SymbolSet _statusFlag -= 65536; // Can't find a LegacySymbol } return(retObj); }
internal ResolvedAttributeSet FetchResolvedAttributes(ResolveOptions resOpt = null, AttributeContextParameters acpInContext = null) { bool wasPreviouslyResolving = this.Ctx.Corpus.isCurrentlyResolving; this.Ctx.Corpus.isCurrentlyResolving = true; if (resOpt == null) { resOpt = new ResolveOptions(this, this.Ctx.Corpus.DefaultResolutionDirectives); } bool inCircularReference = false; bool wasInCircularReference = resOpt.InCircularReference; if (this is CdmEntityDefinition entity) { inCircularReference = resOpt.CurrentlyResolvingEntities.Contains(entity); resOpt.CurrentlyResolvingEntities.Add(entity); resOpt.InCircularReference = inCircularReference; // uncomment this line as a test to turn off allowing cycles //if (inCircularReference) //{ // return new ResolvedAttributeSet(); //} } int currentDepth = resOpt.DepthInfo.CurrentDepth; const string kind = "rasb"; ResolveContext ctx = this.Ctx as ResolveContext; ResolvedAttributeSetBuilder rasbResult = null; ResolvedAttributeSetBuilder rasbCache = this.FetchObjectFromCache(resOpt, acpInContext); CdmAttributeContext underCtx; // store the previous document set, we will need to add it with // children found from the constructResolvedTraits call SymbolSet currDocRefSet = resOpt.SymbolRefSet; if (currDocRefSet == null) { currDocRefSet = new SymbolSet(); } resOpt.SymbolRefSet = new SymbolSet(); // if using the cache passes the maxDepth, we cannot use it if (rasbCache != null && resOpt.DepthInfo.CurrentDepth + rasbCache.ResolvedAttributeSet.DepthTraveled > resOpt.DepthInfo.MaxDepth) { rasbCache = null; } if (rasbCache == null) { // a new context node is needed for these attributes, // this tree will go into the cache, so we hang it off a placeholder parent // when it is used from the cache (or now), then this placeholder parent is ignored and the things under it are // put into the 'receiving' tree underCtx = CdmAttributeContext.GetUnderContextForCacheContext(resOpt, this.Ctx, acpInContext); rasbCache = this.ConstructResolvedAttributes(resOpt, underCtx); if (rasbCache != null) { // register set of possible docs CdmObjectDefinition oDef = this.FetchObjectDefinition <CdmObjectDefinitionBase>(resOpt); if (oDef != null) { ctx.Corpus.RegisterDefinitionReferenceSymbols(oDef, kind, resOpt.SymbolRefSet); if (this.ObjectType == CdmObjectType.EntityDef) { // if we just got attributes for an entity, take the time now to clean up this cached tree and prune out // things that don't help explain where the final set of attributes came from if (underCtx != null) { var scopesForAttributes = new HashSet <CdmAttributeContext>(); underCtx.CollectContextFromAtts(rasbCache.ResolvedAttributeSet, scopesForAttributes); // the context node for every final attribute if (!underCtx.PruneToScope(scopesForAttributes)) { return(null); } } } // get the new cache tag now that we have the list of docs string cacheTag = ctx.Corpus.CreateDefinitionCacheTag(resOpt, this, kind, acpInContext != null ? "ctx" : null); // save this as the cached version if (!string.IsNullOrWhiteSpace(cacheTag)) { ctx.AttributeCache[cacheTag] = rasbCache; } } // get the 'underCtx' of the attribute set from the acp that is wired into // the target tree underCtx = rasbCache.ResolvedAttributeSet.AttributeContext?.GetUnderContextFromCacheContext(resOpt, acpInContext); } } else { // get the 'underCtx' of the attribute set from the cache. The one stored there was build with a different // acp and is wired into the fake placeholder. so now build a new underCtx wired into the output tree but with // copies of all cached children underCtx = rasbCache.ResolvedAttributeSet.AttributeContext?.GetUnderContextFromCacheContext(resOpt, acpInContext); //underCtx.ValidateLineage(resOpt); // debugging } if (rasbCache != null) { // either just built something or got from cache // either way, same deal: copy resolved attributes and copy the context tree associated with it // 1. deep copy the resolved att set (may have groups) and leave the attCtx pointers set to the old tree // 2. deep copy the tree. // 1. deep copy the resolved att set (may have groups) and leave the attCtx pointers set to the old tree rasbResult = new ResolvedAttributeSetBuilder { ResolvedAttributeSet = rasbCache.ResolvedAttributeSet.Copy() }; // 2. deep copy the tree and map the context references. if (underCtx != null) // null context? means there is no tree, probably 0 attributes came out { if (!underCtx.AssociateTreeCopyWithAttributes(resOpt, rasbResult.ResolvedAttributeSet)) { return(null); } } } if (this is CdmEntityAttributeDefinition) { // current depth should now be set to this entity attribute level resOpt.DepthInfo.CurrentDepth = currentDepth; // now at the top of the chain where max depth does not influence the cache if (currentDepth == 0) { resOpt.DepthInfo.MaxDepthExceeded = false; } } if (!inCircularReference && this.ObjectType == CdmObjectType.EntityDef) { // should be removed from the root level only // if it is in a circular reference keep it there resOpt.CurrentlyResolvingEntities.Remove(this as CdmEntityDefinition); } resOpt.InCircularReference = wasInCircularReference; // merge child document set with current currDocRefSet.Merge(resOpt.SymbolRefSet); resOpt.SymbolRefSet = currDocRefSet; this.Ctx.Corpus.isCurrentlyResolving = wasPreviouslyResolving; return(rasbResult?.ResolvedAttributeSet); }
public ICollection <TypeSymbol> BuildMetadata(ParseNodeList compilationUnits, SymbolSet symbols, CompilerOptions options) { Debug.Assert(compilationUnits != null); Debug.Assert(symbols != null); _symbols = symbols; _symbolTable = symbols; _options = options; string scriptName = GetAssemblyScriptName(compilationUnits); if (String.IsNullOrEmpty(scriptName)) { _errorHandler.ReportError("You must declare a ScriptAssembly attribute.", String.Empty); } else if (Utility.IsValidScriptName(scriptName) == false) { string errorMessage = "The ScriptAssembly attribute referenced an invalid name '{0}'. Script names must only contain letters, numbers, dots or underscores."; _errorHandler.ReportError(String.Format(errorMessage, scriptName), String.Empty); } symbols.ScriptName = scriptName; string scriptPrefix = GetAssemblyScriptPrefix(compilationUnits); if (String.IsNullOrEmpty(scriptPrefix) == false) { if (Utility.IsValidIdentifier(scriptPrefix) == false) { string errorMessage = "The ScriptQualifier attribute referenced an invalid prefix '{0}'. Script prefix must be valid identifiers."; _errorHandler.ReportError(String.Format(errorMessage, scriptPrefix), String.Empty); } } else { scriptPrefix = scriptName.Replace(".", String.Empty); } symbols.ScriptPrefix = scriptPrefix; string assemblyScriptNamespace = GetAssemblyScriptNamespace(compilationUnits); List <TypeSymbol> types = new List <TypeSymbol>(); // Build all the types first. // Types need to be loaded upfront so that they can be used in resolving types associated // with members. foreach (CompilationUnitNode compilationUnit in compilationUnits) { foreach (NamespaceNode namespaceNode in compilationUnit.Members) { string namespaceName = namespaceNode.Name; NamespaceSymbol namespaceSymbol = symbols.GetNamespace(namespaceName); List <string> imports = null; Dictionary <string, string> aliases = null; ParseNodeList usingClauses = namespaceNode.UsingClauses; if ((usingClauses != null) && (usingClauses.Count != 0)) { foreach (ParseNode usingNode in namespaceNode.UsingClauses) { if (usingNode is UsingNamespaceNode) { if (imports == null) { imports = new List <string>(usingClauses.Count); } string referencedNamespace = ((UsingNamespaceNode)usingNode).ReferencedNamespace; if (imports.Contains(referencedNamespace) == false) { imports.Add(referencedNamespace); } } else { Debug.Assert(usingNode is UsingAliasNode); if (aliases == null) { aliases = new Dictionary <string, string>(); } UsingAliasNode aliasNode = (UsingAliasNode)usingNode; aliases[aliasNode.Alias] = aliasNode.TypeName; } } } // Add parent namespaces as imports in reverse order since they // are searched in that fashion. string[] namespaceParts = namespaceName.Split('.'); for (int i = namespaceParts.Length - 2; i >= 0; i--) { string partialNamespace; if (i == 0) { partialNamespace = namespaceParts[0]; } else { partialNamespace = String.Join(".", namespaceParts, 0, i + 1); } if (imports == null) { imports = new List <string>(); } if (imports.Contains(partialNamespace) == false) { imports.Add(partialNamespace); } } // Build type symbols for all user-defined types foreach (TypeNode typeNode in namespaceNode.Members) { UserTypeNode userTypeNode = typeNode as UserTypeNode; if (userTypeNode == null) { continue; } // Check if we have overriding script namespace for this type. string typeScriptNamespace = GetScriptNamespace(userTypeNode.Attributes); if (String.IsNullOrEmpty(typeScriptNamespace)) { typeScriptNamespace = assemblyScriptNamespace; } ClassSymbol partialTypeSymbol = null; bool isPartial = false; if ((userTypeNode.Modifiers & Modifiers.Partial) != 0) { partialTypeSymbol = (ClassSymbol)((ISymbolTable)namespaceSymbol).FindSymbol(userTypeNode.Name, /* context */ null, SymbolFilter.Types); if ((partialTypeSymbol != null) && partialTypeSymbol.IsApplicationType) { // This class will be considered as a partial class isPartial = true; // Merge code model information for the partial class onto the code model node // for the primary partial class. Interesting bits of information include things // such as base class etc. that is yet to be processed. CustomTypeNode partialTypeNode = (CustomTypeNode)partialTypeSymbol.ParseContext; partialTypeNode.MergePartialType((CustomTypeNode)userTypeNode); // Merge interesting bits of information onto the primary type symbol as well // representing this partial class BuildType(partialTypeSymbol, userTypeNode); if (String.IsNullOrEmpty(typeScriptNamespace) == false) { partialTypeSymbol.ScriptNamespace = typeScriptNamespace; } } } TypeSymbol typeSymbol = BuildType(userTypeNode, namespaceSymbol); if (typeSymbol != null) { typeSymbol.SetParseContext(userTypeNode); typeSymbol.SetParentSymbolTable(symbols); if (imports != null) { typeSymbol.SetImports(imports); } if (aliases != null) { typeSymbol.SetAliases(aliases); } if (String.IsNullOrEmpty(typeScriptNamespace) == false) { typeSymbol.ScriptNamespace = typeScriptNamespace; } if (isPartial == false) { namespaceSymbol.AddType(typeSymbol); } else { // Partial types don't get added to the namespace, so we don't have // duplicated named items. However, they still do get instantiated // and processed as usual. // // The members within partial classes refer to the partial type as their parent, // and hence derive context such as the list of imports scoped to the // particular type. // However, the members will get added to the primary partial type's list of // members so they can be found. // Effectively the partial class here gets created just to hold // context of type-symbol level bits of information such as the list of // imports, that are consumed when generating code for the members defined // within a specific partial class. ((ClassSymbol)typeSymbol).SetPrimaryPartialClass(partialTypeSymbol); } types.Add(typeSymbol); } } } } // Build inheritance chains foreach (TypeSymbol typeSymbol in types) { if (typeSymbol.Type == SymbolType.Class) { BuildTypeInheritance((ClassSymbol)typeSymbol); } } // Import members foreach (TypeSymbol typeSymbol in types) { BuildMembers(typeSymbol); } // Associate interface members with interface member symbols foreach (TypeSymbol typeSymbol in types) { if (typeSymbol.Type == SymbolType.Class) { BuildInterfaceAssociations((ClassSymbol)typeSymbol); } } // Load resource values if (_symbols.HasResources) { foreach (TypeSymbol typeSymbol in types) { if (typeSymbol.Type == SymbolType.Resources) { BuildResources((ResourcesSymbol)typeSymbol); } } } // Load documentation if (_options.EnableDocComments) { Stream docCommentsStream = options.DocCommentFile.GetStream(); if (docCommentsStream != null) { try { XmlDocument docComments = new XmlDocument(); docComments.Load(docCommentsStream); symbols.SetComments(docComments); } finally { options.DocCommentFile.CloseStream(docCommentsStream); } } } return(types); }
internal override ResolvedTraitSet FetchResolvedTraits(ResolveOptions resOpt = null) { if (resOpt == null) { resOpt = new ResolveOptions(this, this.Ctx.Corpus.DefaultResolutionDirectives); } const string kind = "rtsb"; var ctx = this.Ctx as ResolveContext; // get referenced trait var trait = this.FetchObjectDefinition <CdmTraitDefinition>(resOpt); ResolvedTraitSet rtsTrait = null; if (trait == null) { return(ctx.Corpus.CreateEmptyResolvedTraitSet(resOpt)); } // see if one is already cached // cache by name unless there are parameter if (trait.ThisIsKnownToHaveParameters == null) { // never been resolved, it will happen soon, so why not now? rtsTrait = trait.FetchResolvedTraits(resOpt); } bool cacheByPath = true; if (trait.ThisIsKnownToHaveParameters != null) { cacheByPath = !((bool)trait.ThisIsKnownToHaveParameters); } string cacheTag = ctx.Corpus.CreateDefinitionCacheTag(resOpt, this, kind, "", cacheByPath, trait.AtCorpusPath); dynamic rtsResult = null; if (cacheTag != null) { ctx.Cache.TryGetValue(cacheTag, out rtsResult); } // store the previous reference symbol set, we will need to add it with // children found from the constructResolvedTraits call SymbolSet currSymRefSet = resOpt.SymbolRefSet; if (currSymRefSet == null) { currSymRefSet = new SymbolSet(); } resOpt.SymbolRefSet = new SymbolSet(); // if not, then make one and save it if (rtsResult == null) { // get the set of resolutions, should just be this one trait if (rtsTrait == null) { // store current symbol ref set SymbolSet newSymbolRefSet = resOpt.SymbolRefSet; resOpt.SymbolRefSet = new SymbolSet(); rtsTrait = trait.FetchResolvedTraits(resOpt); // bubble up symbol reference set from children if (newSymbolRefSet != null) { newSymbolRefSet.Merge(resOpt.SymbolRefSet); } resOpt.SymbolRefSet = newSymbolRefSet; } if (rtsTrait != null) { rtsResult = rtsTrait.DeepCopy(); } // now if there are argument for this application, set the values in the array if (this.Arguments != null && rtsResult != null) { // if never tried to line up arguments with parameters, do that if (!this.ResolvedArguments) { this.ResolvedArguments = true; ParameterCollection param = trait.FetchAllParameters(resOpt); CdmParameterDefinition paramFound = null; dynamic aValue = null; int iArg = 0; if (this.Arguments != null) { foreach (CdmArgumentDefinition argument in this.Arguments) { paramFound = param.ResolveParameter(iArg, argument.Name); argument.ResolvedParameter = paramFound; aValue = argument.Value; aValue = ctx.Corpus.ConstTypeCheck(resOpt, this.InDocument, paramFound, aValue); argument.Value = aValue; iArg++; } } } if (this.Arguments != null) { foreach (CdmArgumentDefinition a in this.Arguments) { rtsResult.SetParameterValueFromArgument(trait, a); } } } // register set of possible symbols ctx.Corpus.RegisterDefinitionReferenceSymbols(this.FetchObjectDefinition <CdmObjectDefinition>(resOpt), kind, resOpt.SymbolRefSet); // get the new cache tag now that we have the list of symbols cacheTag = ctx.Corpus.CreateDefinitionCacheTag(resOpt, this, kind, "", cacheByPath, trait.AtCorpusPath); if (!string.IsNullOrWhiteSpace(cacheTag)) { ctx.Cache[cacheTag] = rtsResult; } } else { // cache was found // get the SymbolSet for this cached object string key = CdmCorpusDefinition.CreateCacheKeyFromObject(this, kind); ctx.Corpus.DefinitionReferenceSymbols.TryGetValue(key, out SymbolSet tempDocRefSet); resOpt.SymbolRefSet = tempDocRefSet; } // merge child document set with current currSymRefSet.Merge(resOpt.SymbolRefSet); resOpt.SymbolRefSet = currSymRefSet; return(rtsResult); }
string IEntityExport.Line(LibraryStandardIdentityGroup sig, SymbolSet ss, EntitySubTypeType eSubType) { IEntityExport iEx = this; return(iEx.Line(sig, ss, null, null, eSubType)); }
static bool TypeMatches(INamedTypeSymbol type, SymbolSet set) => s_isInterface(type) && TypeHasInterfaceInSet(type, set);
string IEntityExport.Line(LibraryStandardIdentityGroup sig, SymbolSet ss, SymbolSetEntity e, SymbolSetEntityEntityType eType, EntitySubTypeType eSubType) { _notes = ""; string result = ""; string graphic = ""; IconType iType = IconType.MAIN; string graphicPath = _configHelper.GetPath(ss.ID, FindEnum.FindEntities); if (eSubType != null) { if (eSubType.Graphic != "" && eSubType.Icon != IconType.FULL_FRAME) { graphic = eSubType.Graphic; } else if (sig != null) { graphic = GrabGraphic(eSubType.CloverGraphic, eSubType.RectangleGraphic, eSubType.SquareGraphic, eSubType.DiamondGraphic, sig.GraphicSuffix); } iType = eSubType.Icon; } else if (eType != null) { if (eType.Graphic != "" && eType.Icon != IconType.FULL_FRAME) { graphic = eType.Graphic; } else if (sig != null) { graphic = GrabGraphic(eType.CloverGraphic, eType.RectangleGraphic, eType.SquareGraphic, eType.DiamondGraphic, sig.GraphicSuffix); } iType = eType.Icon; } else if (e != null) { if (e.Graphic != "" && e.Icon != IconType.FULL_FRAME) { graphic = e.Graphic; } else if (sig != null) { graphic = GrabGraphic(e.CloverGraphic, e.RectangleGraphic, e.SquareGraphic, e.DiamondGraphic, sig.GraphicSuffix); } iType = e.Icon; } // Suppressed as considered redundant information //if (iType == IconType.NA) // _notes = _notes + "icon is NA - entity is never to be drawn;"; //else if(iType != IconType.MAIN) // _notes = _notes + "icon is " + Convert.ToString(iType) + ";"; string itemRootedPath = _configHelper.BuildRootedPath(graphicPath, graphic); string itemOriginalPath = _configHelper.BuildOriginalPath(graphicPath, graphic); if (!File.Exists(itemOriginalPath)) { _notes = _notes + "image file does not exist;"; } string itemName = BuildEntityItemName(sig, ss, e, eType, eSubType); string itemTags = BuildEntityItemTags(sig, ss, e, eType, eSubType, _omitSource, _omitLegacy); string itemID = BuildEntityCode(sig, ss, e, eType, eSubType); string itemGeometry = GeometryIs(e, eType, eSubType); string itemCategory = BuildEntityItemCategory(ss, iType, itemGeometry); result = itemRootedPath + "," + Convert.ToString(_configHelper.PointSize) + "," + itemName + "," + itemCategory + "," + itemTags + "," + itemID + "," + itemGeometry + "," + _notes; return(result); }
private static async Task DescendInheritanceTreeInProjectAsync( bool searchInMetadata, SymbolSet result, SymbolSet currentMetadataTypes, SymbolSet currentSourceAndMetadataTypes, Project project, Func <INamedTypeSymbol, SymbolSet, bool> typeMatches, Func <INamedTypeSymbol, bool> shouldContinueSearching, bool transitive, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); Debug.Assert(project.SupportsCompilation); // First see what derived metadata types we might find in this project. This is only necessary if we // started with a metadata type (i.e. a source type could not have a descendant type found in metadata, // but a metadata type could have descendant types in source and metadata). if (searchInMetadata) { using var _ = GetSymbolSet(out var tempBuffer); await AddDescendantMetadataTypesInProjectAsync( currentMetadataTypes, result : tempBuffer, project, typeMatches, shouldContinueSearching, transitive, cancellationToken).ConfigureAwait(false); // Add all the matches we found to the result set. AssertContents(tempBuffer, assert: s_isInMetadata, "Found type was not from metadata"); AddRange(tempBuffer, result); // Now, if we're doing a transitive search, add these found types to the 'current' sets we're // searching for more results for. These will then be used when searching for more types in the next // project (which our caller controls). if (transitive) { AddRange(tempBuffer, currentMetadataTypes, shouldContinueSearching); AddRange(tempBuffer, currentSourceAndMetadataTypes, shouldContinueSearching); } } { using var _ = GetSymbolSet(out var tempBuffer); // Now search the project and see what source types we can find. await AddDescendantSourceTypesInProjectAsync( currentSourceAndMetadataTypes, result : tempBuffer, project, typeMatches, shouldContinueSearching, transitive, cancellationToken).ConfigureAwait(false); // Add all the matches we found to the result set. AssertContents(tempBuffer, assert: s_isInSource, "Found type was not from source"); AddRange(tempBuffer, result); // Now, if we're doing a transitive search, add these types to the currentSourceAndMetadataTypes // set. These will then be used when searching for more types in the next project (which our caller // controls). We don't have to add this to currentMetadataTypes since these will all be // source types. if (transitive) { AddRange(tempBuffer, currentSourceAndMetadataTypes, shouldContinueSearching); } } }
public ICollection <TypeSymbol> ImportMetadata(ICollection <string> references, SymbolSet symbols) { Debug.Assert(references != null); Debug.Assert(symbols != null); _symbols = symbols; MetadataSource mdSource = new MetadataSource(); bool hasLoadErrors = mdSource.LoadReferences(references, _errorHandler); ICollection <TypeSymbol> importedTypes = null; if (hasLoadErrors == false) { importedTypes = ImportAssemblies(mdSource); } if (_resolveError) { return(null); } return(importedTypes); }
private static async Task AddDescendantSourceTypesInProjectAsync( SymbolSet currentSourceAndMetadataTypes, SymbolSet result, Project project, Func <INamedTypeSymbol, SymbolSet, bool> typeMatches, Func <INamedTypeSymbol, bool> shouldContinueSearching, bool transitive, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // We're going to be sweeping over this project over and over until we reach a // fixed point. In order to limit GC and excess work, we cache all the semantic // models and DeclaredSymbolInfo for the documents we look at. // Because we're only processing a project at a time, this is not an issue. var cachedModels = new ConcurrentSet <SemanticModel>(); using var _1 = GetSymbolSet(out var typesToSearchFor); using var _2 = GetSymbolSet(out var tempBuffer); typesToSearchFor.AddAll(currentSourceAndMetadataTypes); var projectIndex = await ProjectIndex.GetIndexAsync(project, cancellationToken).ConfigureAwait(false); // As long as there are new types to search for, keep looping. while (typesToSearchFor.Count > 0) { foreach (var type in typesToSearchFor) { cancellationToken.ThrowIfCancellationRequested(); switch (type.SpecialType) { case SpecialType.System_Object: await AddMatchingTypesAsync( cachedModels, projectIndex.ClassesThatMayDeriveFromSystemObject, result : tempBuffer, predicateOpt : n => n.BaseType?.SpecialType == SpecialType.System_Object, cancellationToken).ConfigureAwait(false); break; case SpecialType.System_ValueType: await AddMatchingTypesAsync( cachedModels, projectIndex.ValueTypes, result : tempBuffer, predicateOpt : null, cancellationToken).ConfigureAwait(false); break; case SpecialType.System_Enum: await AddMatchingTypesAsync( cachedModels, projectIndex.Enums, result : tempBuffer, predicateOpt : null, cancellationToken).ConfigureAwait(false); break; case SpecialType.System_MulticastDelegate: await AddMatchingTypesAsync( cachedModels, projectIndex.Delegates, result : tempBuffer, predicateOpt : null, cancellationToken).ConfigureAwait(false); break; } await AddSourceTypesThatDeriveFromNameAsync( typeMatches, cachedModels, typesToSearchFor, projectIndex, result : tempBuffer, type.Name, cancellationToken).ConfigureAwait(false); } PropagateTemporaryResults( result, typesToSearchFor, tempBuffer, transitive, shouldContinueSearching); } }
public SymbolImplementation BuildField(FieldSymbol fieldSymbol) { _rootScope = new SymbolScope((ISymbolTable)fieldSymbol.Parent); _currentScope = _rootScope; Expression initializerExpression; FieldDeclarationNode fieldDeclarationNode = (FieldDeclarationNode)fieldSymbol.ParseContext; Debug.Assert(fieldDeclarationNode != null); VariableInitializerNode initializerNode = (VariableInitializerNode)fieldDeclarationNode.Initializers[0]; if (initializerNode.Value != null) { ExpressionBuilder expressionBuilder = new ExpressionBuilder(this, fieldSymbol, _errorHandler, _options); initializerExpression = expressionBuilder.BuildExpression(initializerNode.Value); if (initializerExpression is MemberExpression) { initializerExpression = expressionBuilder.TransformMemberExpression((MemberExpression)initializerExpression); } } else { object defaultValue = null; TypeSymbol fieldType = fieldSymbol.AssociatedType; SymbolSet symbolSet = fieldSymbol.SymbolSet; if (fieldType.Type == SymbolType.Enumeration) { // The default for named values is null, so this only applies to // regular enum types EnumerationSymbol enumType = (EnumerationSymbol)fieldType; if (enumType.UseNamedValues == false) { defaultValue = 0; } } else if ((fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.Integer)) || (fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.UnsignedInteger)) || (fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.Long)) || (fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.UnsignedLong)) || (fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.Short)) || (fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.UnsignedShort)) || (fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.Byte)) || (fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.SignedByte)) || (fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.Double)) || (fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.Single)) || (fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.Decimal))) { defaultValue = 0; } else if (fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.Boolean)) { defaultValue = false; } initializerExpression = new LiteralExpression(symbolSet.ResolveIntrinsicType(IntrinsicType.Object), defaultValue); } List <Statement> statements = new List <Statement>(); statements.Add(new ExpressionStatement(initializerExpression, /* isFragment */ true)); return(new SymbolImplementation(statements, null)); }
public string Line(SymbolSet ss, SymbolSetLegacySymbol legacySymbol) { string result = ""; string name = _buildName(ss, legacySymbol); string entityCode = ""; string extraIcon = ""; // Special care is needed with special entity subtypes bool isEntitySubTypeSpecial = false; if (_entitySubType != null) { if (_configHelper.IsSpecialEntitySubtype(ss, _entitySubType)) { entityCode = _entityExport.CodeIt(null, ss, _entity, _entityType, null); extraIcon = _entityExport.CodeIt(null, ss, null, null, _entitySubType); isEntitySubTypeSpecial = true; } else { entityCode = _entityExport.CodeIt(null, ss, _entity, _entityType, _entitySubType); } } else { entityCode = _entityExport.CodeIt(null, ss, _entity, _entityType, _entitySubType); } string mod1Code = ""; string mod2Code = ""; if (_modifier1 != null && _modifier1.Label != "Unspecified" && _modifier1.Label != "Not Applicable") { mod1Code = _modifierExport.CodeIt(ss, "1", _modifier1); } if (_modifier2 != null && _modifier2.Label != "Unspecified" && _modifier2.Label != "Not Applicable") { mod2Code = _modifierExport.CodeIt(ss, "2", _modifier2); } bool fullFrame = false; string geometry = _entityExport.GeometryIt(_entity, _entityType, _entitySubType); if (_entitySubType != null && !isEntitySubTypeSpecial) { fullFrame = _entitySubType.Icon == IconType.FULL_FRAME; } else if (_entityType != null) { fullFrame = _entityType.Icon == IconType.FULL_FRAME; } else if (_entity != null) { fullFrame = _entity.Icon == IconType.FULL_FRAME; } string fullFrameOutput = fullFrame ? "TRUE" : ""; result = name; result = result + "," + _buildSIDCKey(ss, legacySymbol); // + "Key2525C"; result = result + "," + entityCode; // + "MainIcon"; result = result + "," + mod1Code; // + "Modifier1"; result = result + "," + mod2Code; // + "Modifier2"; result = result + "," + extraIcon; // + "ExtraIcon"; result = result + "," + fullFrameOutput; // + "FullFrame"; result = result + "," + geometry; // + "GeometryType"; result = result + ","; // + "Status"; result = result + ","; // + "Notes"; return(result); }
public TileSet(string symbolInfoName) { this.Name = symbolInfoName; m_symbolSet = LoadSymbolSet(this.Name + ".xaml"); }
protected string BuildEntityItemTags(SymbolSet ss, SymbolSetEntity e, SymbolSetEntityEntityType eType, SymbolSetEntityEntityTypeEntitySubType eSubType, bool omitSource) { // Constructs a string of semicolon delimited tags that users can utilize to search // for or find a given symbol. // The information concatenated together for this comes from a given SymbolSet and // entity (type and sub type). Information includes the Label attributes, geometry // type, location of the original graphic file, the code, etc. string result = ss.Label.Replace(',', '-') + ";" + e.Label.Replace(',', '-'); string graphic = ""; string geometry = ""; if (eType != null) { result = result + ";" + eType.Label.Replace(',', '-'); } if (eSubType != null) { result = result + ";" + eSubType.Label.Replace(',', '-'); // Add the type of geometry geometry = _geometryList[(int)eSubType.GeometryType]; // The following is a work around because our symbol system doesn't // need the export of multiple SVG files for the same symbol. // TODO: handle this differently, but for now, we export the square // graphic if there are in fact multiple files. if (eSubType.Icon == IconType.FULL_FRAME) { graphic = eSubType.SquareGraphic; _notes = _notes + "icon touches frame;"; } else if (eSubType.Icon == IconType.NA) { graphic = ""; } else { graphic = eSubType.Graphic; } } else if (eType != null) { // Add the type of geometry geometry = _geometryList[(int)eType.GeometryType]; // TODO: handle this differently, but for now, we export the square // graphic if there are in fact multiple files. if (eType.Icon == IconType.FULL_FRAME) { graphic = eType.SquareGraphic; _notes = _notes + "icon touches frame;"; } else if (eType.Icon == IconType.NA) { graphic = ""; } else { graphic = eType.Graphic; } } else if (e != null) { // Add the type of geometry geometry = _geometryList[(int)e.GeometryType]; // TODO: handle this differently, but for now, we export the square // graphic if there are in fact multiple files. if (e.Icon == IconType.FULL_FRAME) { graphic = e.SquareGraphic; _notes = _notes + "icon touches frame;"; } else if (e.Icon == IconType.NA) { graphic = ""; } else { graphic = e.Graphic; } } if (!omitSource) { result = result + ";" + _configHelper.GetPath(ss.ID, FindEnum.FindEntities, true) + "\\" + graphic; } result = result + ";" + geometry; result = result + ";" + BuildEntityItemName(ss, e, eType, eSubType); result = result + ";" + BuildEntityCode(ss, e, eType, eSubType); if (result.Length > 255) { // Can't have a tag string greater than 255 in length. // Human interaction will be required to resolve these on a case by case basis. _notes = _notes + "styleItemTags > 255;"; } return(result); }
internal static Symbol GetByAlias(this SymbolSet symbolSet, string alias) => symbolSet.SingleOrDefault(symbol => symbol.Name.Equals(alias) || symbol is IdentifierSymbol id && id.HasAlias(alias));
protected string BuildEntityItemTags(LibraryStandardIdentityGroup sig, SymbolSet ss, SymbolSetEntity e, SymbolSetEntityEntityType eType, EntitySubTypeType eSubType, bool omitSource, bool omitLegacy) { // Constructs a string of semicolon delimited tags that users can utilize to search // for or find a given symbol. // The information concatenated together for this comes from a given SymbolSet and // entity (type and sub type). Information includes the Label attributes, geometry // type, location of the original graphic file, the code, etc. string result = ss.Label.Replace(',', '-'); string graphic = ""; string geometry = ""; string iType = "NO_ICON"; string[] xmlTags = null; if (e == null && eType == null && eSubType != null) { result = result + ";" + "Special Entity Subtypes"; } if (e != null) { result = result + ";" + e.Label.Replace(',', '-'); iType = Convert.ToString(e.Icon); } if (eType != null) { result = result + ";" + eType.Label.Replace(',', '-'); iType = Convert.ToString(eType.Icon); } if (eSubType != null) { result = result + ";" + eSubType.Label.Replace(',', '-'); iType = Convert.ToString(eSubType.Icon); // Add the type of geometry geometry = _geometryList[(int)eSubType.GeometryType]; if (eSubType.Icon == IconType.FULL_FRAME) { if (sig != null) { graphic = GrabGraphic(eSubType.CloverGraphic, eSubType.RectangleGraphic, eSubType.SquareGraphic, eSubType.DiamondGraphic, sig.GraphicSuffix); } _notes = _notes + "icon touches frame;"; } else if (eSubType.Icon == IconType.NA) { graphic = ""; } else { graphic = eSubType.Graphic; } // Grab any custom XML tags that might exist xmlTags = eSubType.Tags; } else if (eType != null) { // Add the type of geometry geometry = _geometryList[(int)eType.GeometryType]; if (eType.Icon == IconType.FULL_FRAME) { if (sig != null) { graphic = GrabGraphic(eType.CloverGraphic, eType.RectangleGraphic, eType.SquareGraphic, eType.DiamondGraphic, sig.GraphicSuffix); } _notes = _notes + "icon touches frame;"; } else if (eType.Icon == IconType.NA) { graphic = ""; } else { graphic = eType.Graphic; } // Grab any custom XML tags that might exist xmlTags = eType.Tags; } else if (e != null) { // Add the type of geometry geometry = _geometryList[(int)e.GeometryType]; if (e.Icon == IconType.FULL_FRAME) { if (sig != null) { graphic = GrabGraphic(e.CloverGraphic, e.RectangleGraphic, e.SquareGraphic, e.DiamondGraphic, sig.GraphicSuffix); } _notes = _notes + "icon touches frame;"; } else if (e.Icon == IconType.NA) { graphic = ""; } else { graphic = e.Graphic; } // Grab any custom XML tags that might exist xmlTags = e.Tags; } // Create the unique ID/code for this object string code = BuildEntityCode(sig, ss, e, eType, eSubType); // If there is a standard identity group, add it if (sig != null) { result = result + ";" + sig.Label; } // Add any custom XML or export tags that might exist result = _configHelper.AddCustomTags(result, code, xmlTags); // Add an equivalent 2525C SIDC tag, if one exists if (!omitLegacy) { string sidcTag = BuildLegacySIDCTag(sig, ss, e, eType, eSubType); if (sidcTag != "") { result = result + ";" + sidcTag; } } // Add the icon's type result = result + ";" + iType; // Add the svg source if (!omitSource) { result = result + ";" + _configHelper.GetPath(ss.ID, FindEnum.FindEntities, true) + "\\" + graphic; } // Add the three most important pieces of information result = result + ";" + geometry; result = result + ";" + BuildEntityItemName(sig, ss, e, eType, eSubType); result = result + ";" + code; if (result.Length > 255) { // Can't have a tag string greater than 255 in length. // Human interaction will be required to resolve these on a case by case basis. _notes = _notes + "styleItemTags > 255;"; } return(result); }
public ResourcesBuilder(SymbolSet symbols) { _symbols = symbols; }
protected string BuildEntityCode(LibraryStandardIdentityGroup sig, SymbolSet ss, SymbolSetEntity e, SymbolSetEntityEntityType eType, EntitySubTypeType eSubType) { // Constructs a string containing the symbol set and entity codes for a given // set of those objects. string code = ""; if (ss != null) { code = code + Convert.ToString(ss.SymbolSetCode.DigitOne) + Convert.ToString(ss.SymbolSetCode.DigitTwo); } if (e == null && eType == null && eSubType != null) { // Deal with the special entity sub types as a special case code = code + eSubType.EntityCode + eSubType.EntityTypeCode + Convert.ToString(eSubType.EntitySubTypeCode.DigitOne) + Convert.ToString(eSubType.EntitySubTypeCode.DigitTwo); } else { // Almost everything is dealt with below if (e != null) { code = code + Convert.ToString(e.EntityCode.DigitOne) + Convert.ToString(e.EntityCode.DigitTwo); } else { code = code + "00"; } if (eType != null) { code = code + Convert.ToString(eType.EntityTypeCode.DigitOne) + Convert.ToString(eType.EntityTypeCode.DigitTwo); } else { code = code + "00"; } if (eSubType != null) { code = code + Convert.ToString(eSubType.EntitySubTypeCode.DigitOne) + Convert.ToString(eSubType.EntitySubTypeCode.DigitTwo); } else { code = code + "00"; } } if (sig != null) { code = code + sig.GraphicSuffix; } return(code); }
private void AfterDeserialization(StreamingContext context) { _stateIndex = -1; _states = null; _symbols = new SymbolSet(); }