public void ShouldValidateAnnotationsAttributes()
 {
     var annotations = new Annotations { Foo = "as" };
     var validator = new AttributesValidator();
     validator.Validate(ValidationContext, annotations);
     
     Assert.IsFalse(ValidationContext.IsValid);
     Assert.AreEqual(2, ValidationContext.Keys.Count);
 }
 public PeptideGroupDocNode(PeptideGroup id, Annotations annotations, ProteinMetadata proteinMetadata,
     PeptideDocNode[] children, bool autoManageChildren)
     : base(id, annotations, children, autoManageChildren)
 {
     if (Equals(id.Name, proteinMetadata.Name))
         proteinMetadata = proteinMetadata.ChangeName(null);  // Make it clear that the name hasn't been altered
     if (Equals(id.Description, proteinMetadata.Description))
         proteinMetadata = proteinMetadata.ChangeDescription(null);  // Make it clear that the description hasn't been altered
     _proteinMetadata = proteinMetadata;
 }
 public override bool IsActiveFor(AssemblyDefinition assembly)
 {
     return(Annotations.GetAction(assembly) == AssemblyAction.Link);
 }
Beispiel #4
0
 protected virtual void RemoveAssembly(AssemblyDefinition assembly)
 {
     Annotations.SetAction(assembly, AssemblyAction.Delete);
 }
Beispiel #5
0
 bool IsMarkedAssembly(AssemblyDefinition assembly)
 {
     return(Annotations.IsMarked(assembly.MainModule));
 }
Beispiel #6
0
	static void ParseEnum (Annotations properties, MemberInfo parent, Tokenizer tokenizer)
	{
		FieldInfo field;
		StringBuilder value = new StringBuilder ();
		TypeInfo type = new TypeInfo ();

		type.Annotations = properties;
		type.IsEnum = true;

		tokenizer.AcceptOrThrow (Token2Type.Identifier, "enum");
		if (tokenizer.CurrentToken.type == Token2Type.Identifier) {
			type.Name = tokenizer.GetIdentifier ();
		} else {
			type.Name = "<anonymous>";
		}
		parent.Children.Add (type);

		tokenizer.AcceptOrThrow (Token2Type.Punctuation, "{");

		//Console.WriteLine ("ParseEnum: {0}", name);

		while (tokenizer.CurrentToken.type == Token2Type.Identifier) {
			field = new FieldInfo ();
			field.Name = tokenizer.GetIdentifier ();
			value.Length = 0;
			if (tokenizer.Accept (Token2Type.Punctuation, "=")) {
				while (tokenizer.CurrentToken.value != "," && tokenizer.CurrentToken.value != "}") {
					value.Append (" ");
					value.Append (tokenizer.CurrentToken.value);
					tokenizer.Advance (true);
				}
			}
			field.Value = value.ToString ();
			type.Children.Add (field);
			//Console.WriteLine ("ParseEnum: {0}: {1} {2} {3}", name, field, value.Length != 0 != null ? "=" : "", value);

			if (!tokenizer.Accept (Token2Type.Punctuation, ","))
				break;
		}

		tokenizer.AcceptOrThrow (Token2Type.Punctuation, "}");
		tokenizer.AcceptOrThrow (Token2Type.Punctuation, ";");
	}
Beispiel #7
0
        private TransitionDocNode GetMoleculeTransition(SrmDocument document, DataGridViewRow row, Peptide pep, TransitionGroup group, bool requireProductInfo)
        {
            var massType =
                document.Settings.TransitionSettings.Prediction.FragmentMassType;

            var molecule = ReadPrecursorOrProductColumns(document, row, !requireProductInfo); // Re-read the product columns, or copy precursor
            if (requireProductInfo && molecule == null)
            {
                return null;
            }
            var ion = molecule.ToCustomIon();
            var ionType = (!requireProductInfo || // We inspected the input list and found only precursor info
                          ((ion.MonoisotopicMass.Equals(pep.CustomIon.MonoisotopicMass) &&
                           ion.AverageMass.Equals(pep.CustomIon.AverageMass)))) // Same mass, must be a precursor transition
                ? IonType.precursor
                : IonType.custom;
            double mass = ion.GetMass(massType);

            var transition = new Transition(group, molecule.Charge, null, ion, ionType);
            var annotations = document.Annotations;
            if (!string.IsNullOrEmpty(molecule.Note))
            {
                var note = document.Annotations.Note;
                note = string.IsNullOrEmpty(note) ? molecule.Note : (note + "\r\n" + molecule.Note); // Not L10N
                annotations = new Annotations(note, document.Annotations.ListAnnotations(), 0);
            }
            return new TransitionDocNode(transition, annotations, null, mass, null, null, null);
        }
Beispiel #8
0
        public void ExceptionsShouldnotPreventRecordToOtherTracers()
        {
            var tracerThatThrows = new Mock <ITracer>();

            tracerThatThrows.Setup(tracer1 => tracer1.Record(It.IsAny <Record>())).Throws(new Exception());
            TraceManager.RegisterTracer(tracerThatThrows.Object);


            var tracerThatDontThrow = new Mock <ITracer>();

            TraceManager.RegisterTracer(tracerThatDontThrow.Object); // on the assumption that tracer registration order is preserved

            var record = new Record(new SpanState(0, null, 1, isSampled: null, isDebug: false), TimeUtils.UtcNow, Annotations.ClientRecv());

            TraceManager.Push(record);

            tracerThatThrows.Verify(t => t.Record(It.IsAny <Record>()));
            tracerThatDontThrow.Verify(t => t.Record(It.IsAny <Record>()));
        }
Beispiel #9
0
        protected override MethodDefinition MarkMethod(MethodReference reference)
        {
            var method = base.MarkMethod(reference);

            if (method == null)
            {
                return(null);
            }

            var t = method.DeclaringType;

            // We have special processing that prevents protocol interfaces from being marked if they're
            // only used by being implemented by a class, but the linker will not mark interfaces if a method implemented by an interface
            // is marked: this means we need special processing to preserve a protocol interface whose methods have been implemented.
            if (RegisterProtocols && t.HasInterfaces && method.IsVirtual)
            {
                foreach (var r in t.Interfaces)
                {
                    var i = r.InterfaceType.Resolve();
                    if (i == null)
                    {
                        continue;
                    }
                    if (Annotations.IsMarked(i))
                    {
                        continue;
                    }
                    if (!LinkContext.StaticRegistrar.HasAttribute(i, Namespaces.Foundation, "ProtocolAttribute"))
                    {
                        continue;
                    }

                    var isProtocolImplementation = false;
                    // Are there any explicit overrides?
                    foreach (var @override in method.Overrides)
                    {
                        if (!i.Methods.Contains(@override.Resolve()))
                        {
                            continue;
                        }
                        isProtocolImplementation = true;
                        break;
                    }
                    if (!isProtocolImplementation)
                    {
                        // Are there any implicit overrides (identical name and signature)?
                        foreach (var imethod in i.Methods)
                        {
                            if (!StaticRegistrar.MethodMatch(imethod, method))
                            {
                                continue;
                            }
                            isProtocolImplementation = true;
                            break;
                        }
                    }
                    if (isProtocolImplementation)
                    {
                        MarkType(r.InterfaceType);
                        Bundler.Driver.Log(9, "Marking {0} because the method {1} implements one of its methods.", r.InterfaceType, method.FullName);
                    }
                }
            }

            // special processing to find [BlockProxy] attributes in _Extensions types
            // ref: https://bugzilla.xamarin.com/show_bug.cgi?id=23540
            if (method.HasCustomAttributes && t.HasInterfaces)
            {
                string selector = null;
                foreach (var r in t.Interfaces)
                {
                    var i = r.InterfaceType.Resolve();
                    if (i == null || !i.HasCustomAttribute(Namespaces.Foundation, "ProtocolAttribute"))
                    {
                        continue;
                    }
                    if (selector == null)
                    {
                        // delay and don't compute each time
                        foreach (var ca in method.CustomAttributes)
                        {
                            if (!ca.Constructor.DeclaringType.Is(Namespaces.Foundation, "ExportAttribute"))
                            {
                                continue;
                            }
                            selector = ca.ConstructorArguments [0].Value as string;
                            break;
                        }
                    }
                    string name  = null;
                    bool   match = false;
                    foreach (var ca in i.CustomAttributes)
                    {
                        if (!ca.Constructor.DeclaringType.Is(Namespaces.Foundation, "ProtocolMemberAttribute"))
                        {
                            continue;
                        }
                        foreach (var p in ca.Properties)
                        {
                            switch (p.Name)
                            {
                            case "Selector":
                                match = (p.Argument.Value as string == selector);
                                break;

                            case "Name":
                                name = p.Argument.Value as string;
                                break;
                            }
                        }
                        if (match)
                        {
                            break;
                        }
                    }
                    if (!match || name == null)
                    {
                        continue;
                    }
                    // _Extensions time...
                    var td = i.Module.GetType(i.Namespace, i.Name.Substring(1) + "_Extensions");
                    if (td != null && td.HasMethods)
                    {
                        foreach (var m in td.Methods)
                        {
                            if (!m.HasParameters || (m.Name != name) || !m.IsOptimizableCode(LinkContext))
                            {
                                continue;
                            }
                            bool proxy = false;
                            match = method.Parameters.Count == m.Parameters.Count - 1;
                            if (match)
                            {
                                for (int n = 1; n < m.Parameters.Count; n++)
                                {
                                    var p  = m.Parameters [n];
                                    var pt = p.ParameterType;
                                    match &= method.Parameters [n - 1].ParameterType.Is(pt.Namespace, pt.Name);
                                    proxy |= p.HasCustomAttribute(Namespaces.ObjCRuntime, "BlockProxyAttribute");
                                }
                            }
                            if (match && proxy)
                            {
                                // one cannot simply mark the `ca.ConstructorArguments [0].Value` type,
                                // e.g. Trampolines.NIDActionArity1V26
                                // as the relation to *_Extensions will be reflected at runtime
                                MarkMethod(m);
                            }
                        }
                    }
                }
            }
            return(method);
        }
Beispiel #10
0
 public void AddAnnotationToGridView(AnnotationDef annotationDef, Annotations annotations)
 {
     var row = dataGridView1.Rows[dataGridView1.Rows.Add()];
     row.Tag = annotationDef;
     row.Cells[colName.Index].Value = annotationDef.Name;
     var value = annotations.GetAnnotation(annotationDef);
     if (annotationDef.Type == AnnotationDef.AnnotationType.true_false)
     {
         row.Cells[colValue.Index] = new DataGridViewCheckBoxCell {Value = value};
     }
     else if (annotationDef.Type == AnnotationDef.AnnotationType.value_list)
     {
         var cell = new DataGridViewComboBoxCell();
         row.Cells[colValue.Index] = cell;
         cell.Items.Add(string.Empty);
         foreach (var item in annotationDef.Items)
         {
             cell.Items.Add(item);
         }
         cell.Value = value;
     }
     else
     {
         var cell = row.Cells[colValue.Index];
         if (annotationDef.Type == AnnotationDef.AnnotationType.number)
         {
             cell.ValueType = typeof (double);
         }
         cell.Value = value;
     }
 }
Beispiel #11
0
 FindMatch MatchAnnotations(Annotations annotations)
 {
     if (annotations == null)
     {
         return null;
     }
     var match = MatchText(annotations.Note);
     if (match != null)
     {
         return match.ChangeNote(true);
     }
     foreach (var keyValuePair in annotations.ListAnnotations())
     {
         string annotationText = keyValuePair.Key == keyValuePair.Value
                                     ? keyValuePair.Value
                                     : keyValuePair.Key + "=" + keyValuePair.Value; // Not L10N
         match = MatchText(annotationText);
         if (match != null)
         {
             return match.ChangeAnnotationName(keyValuePair.Key);
         }
     }
     return null;
 }
Beispiel #12
0
 public static LabeledStatement Labeled(LabelTarget label, Expression body, Annotations annotations) {
     ContractUtils.RequiresNotNull(label, "label");
     RequiresCanRead(body, "body");
     return new LabeledStatement(annotations, label, body);
 }
Beispiel #13
0
 internal LabeledStatement(Annotations annotations, LabelTarget label, Expression expression)
     : base(ExpressionType.LabeledStatement, typeof(void), annotations) {
     _label = label;
     _expression = expression;
 }
 public PeptideGroupDocNode(PeptideGroup id, Annotations annotations, string name, string description,
     PeptideDocNode[] children, bool autoManageChildren)
     : this(id, annotations, new ProteinMetadata(name, description), children, autoManageChildren)
 {
 }
Beispiel #15
0
 protected virtual bool SetIsClustered(bool?value) => Annotations.SetAnnotation(SqlServerAnnotationNames.Clustered, value);
Beispiel #16
0
        protected virtual void MarkType(TypeReference reference)
        {
            if (reference == null)
            {
                return;
            }

            reference = GetOriginalType(reference);

            if (reference is GenericParameter)
            {
                return;
            }

//			if (IgnoreScope (reference.Scope))
//				return;

            TypeDefinition type = ResolveTypeDefinition(reference);

            if (type == null)
            {
                throw new ResolutionException(reference);
            }

            if (CheckProcessed(type))
            {
                return;
            }

            MarkScope(type.Scope);
            MarkType(type.BaseType);
            MarkType(type.DeclaringType);
            MarkCustomAttributes(type);

            if (IsMulticastDelegate(type))
            {
                MarkMethodCollection(type.Constructors);
                MarkMethodCollection(type.Methods);
            }

            if (IsSerializable(type) && type.HasConstructors)
            {
                MarkMethodsIf(type.Constructors, IsDefaultConstructorPredicate);
                MarkMethodsIf(type.Constructors, IsSpecialSerializationConstructorPredicate);
            }

            MarkTypeSpecialCustomAttributes(type);

            MarkGenericParameterProvider(type);

            if (type.IsValueType)
            {
                MarkFields(type);
            }

            if (type.HasInterfaces)
            {
                foreach (TypeReference iface in type.Interfaces)
                {
                    MarkType(iface);
                }
            }

            if (type.HasMethods)
            {
                MarkMethodsIf(type.Methods, IsVirtualAndHasPreservedParent);
            }

            if (type.HasConstructors)
            {
                MarkMethodsIf(type.Constructors, IsStaticConstructorPredicate);
            }

            Annotations.Mark(type);

            ApplyPreserveInfo(type);
        }
Beispiel #17
0
        public void Init(SrmDocument document, IList<IdentityPath> selPaths)
        {
            AnnotationDef.AnnotationTargetSet annotationTarget;
            var annotations = MergeAnnotations(document, selPaths, out annotationTarget);

            textNote.Text = _originalText = annotations.Note ?? string.Empty;
            _originalAnnotations = annotations;

            foreach (var annotationDef in document.Settings.DataSettings.AnnotationDefs)
            {
                // Definition must apply to all targets.
                if (!annotationTarget.Intersect(annotationDef.AnnotationTargets).Equals(annotationTarget))
                {
                    continue;
                }
                AddAnnotationToGridView(annotationDef, annotations);
            }
            if (dataGridView1.Rows.Count == 0)
            {
                splitContainer1.Panel2Collapsed = true;
            }

            ColorIndex = annotations.ColorIndex;
            if (ColorIndex >= 0 && ColorIndex < toolStrip1.Items.Count)
                ((ToolStripButton) toolStrip1.Items[ColorIndex]).Checked = true;

            ClearAll = false;
        }
Beispiel #18
0
 /// <summary>
 ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
 ///     directly from your code. This API may change or be removed in future releases.
 /// </summary>
 public virtual bool CanSetName([CanBeNull] string value)
 => Annotations.CanSetAnnotation(RelationalAnnotationNames.Name, value);
Beispiel #19
0
 protected override void Process()
 {
     CheckOutputDirectory();
     Annotations.SaveDependencies();
 }
Beispiel #20
0
        public ChromatogramSet(string name, 
            IEnumerable<MsDataFileUri> msDataFileNames,
            Annotations annotations,
            OptimizableRegression optimizationFunction)
            : base(new ChromatogramSetId(), name)
        {
            MSDataFileInfos = msDataFileNames.ToList().ConvertAll(path => new ChromFileInfo(path));

            OptimizationFunction = optimizationFunction;
            Annotations = annotations;
            SampleType = SampleType.DEFAULT;
        }
        public SrmDocument ConvertToSmallMolecules(SrmDocument document, 
            ConvertToSmallMoleculesMode mode = ConvertToSmallMoleculesMode.formulas,
            bool invertCharges = false,
            bool ignoreDecoys=false)
        {
            if (mode == ConvertToSmallMoleculesMode.none)
                return document;
            var newdoc = new SrmDocument(document.Settings);
            var note = new Annotations(TestingConvertedFromProteomic, null, 1); // Mark this as a testing node so we don't sort it

            newdoc = (SrmDocument)newdoc.ChangeIgnoreChangingChildren(true); // Retain copied results

            foreach (var peptideGroupDocNode in document.MoleculeGroups)
            {
                if (!peptideGroupDocNode.IsProteomic)
                {
                    newdoc = (SrmDocument)newdoc.Add(peptideGroupDocNode); // Already a small molecule
                }
                else
                {
                    var newPeptideGroup = new PeptideGroup();
                    var newPeptideGroupDocNode = new PeptideGroupDocNode(newPeptideGroup,
                        peptideGroupDocNode.Annotations.Merge(note), peptideGroupDocNode.Name,
                        peptideGroupDocNode.Description, new PeptideDocNode[0],
                        peptideGroupDocNode.AutoManageChildren);
                    foreach (var mol in peptideGroupDocNode.Molecules)
                    {
                        var peptideSequence = mol.Peptide.Sequence;
                        // Create a PeptideDocNode with the presumably baseline charge and label
                        var precursorCharge = (mol.TransitionGroups.Any() ? mol.TransitionGroups.First().TransitionGroup.PrecursorCharge : 0) * (invertCharges ? -1 : 1);
                        var isotopeLabelType = mol.TransitionGroups.Any() ? mol.TransitionGroups.First().TransitionGroup.LabelType : IsotopeLabelType.light;
                        var moleculeCustomIon = ConvertToSmallMolecule(mode, document, mol, precursorCharge, isotopeLabelType);
                        var precursorCustomIon = moleculeCustomIon;
                        var newPeptide = new Peptide(moleculeCustomIon);
                        var newPeptideDocNode = new PeptideDocNode(newPeptide, newdoc.Settings, null, null,
                            null, null, mol.ExplicitRetentionTime, note, mol.Results, new TransitionGroupDocNode[0],
                            mol.AutoManageChildren);

                        foreach (var transitionGroupDocNode in mol.TransitionGroups)
                        {
                            if (transitionGroupDocNode.IsDecoy)
                            {
                                if (ignoreDecoys)
                                    continue;
                                throw new Exception("There is no translation from decoy to small molecules"); // Not L10N
                            }

                            if (transitionGroupDocNode.TransitionGroup.PrecursorCharge != Math.Abs(precursorCharge) ||
                                !Equals(isotopeLabelType, transitionGroupDocNode.TransitionGroup.LabelType))
                            {
                                // Different charges or labels mean different ion formulas
                                precursorCharge = transitionGroupDocNode.TransitionGroup.PrecursorCharge * (invertCharges ? -1 : 1);
                                isotopeLabelType = transitionGroupDocNode.TransitionGroup.LabelType;
                                precursorCustomIon = ConvertToSmallMolecule(mode, document, mol, precursorCharge, isotopeLabelType);
                            }

                            var newTransitionGroup = new TransitionGroup(newPeptide, precursorCustomIon, precursorCharge, isotopeLabelType);
                            // Remove any library info, since for the moment at least small molecules don't support this and it won't roundtrip
                            var resultsNew = RemoveTransitionGroupChromInfoLibraryInfo(transitionGroupDocNode);
                            var newTransitionGroupDocNode = new TransitionGroupDocNode(newTransitionGroup,
                                transitionGroupDocNode.Annotations.Merge(note), document.Settings,
                                null, null, transitionGroupDocNode.ExplicitValues, resultsNew, null,
                                transitionGroupDocNode.AutoManageChildren);
                            var mzShift = invertCharges ? 2.0 * BioMassCalc.MassProton : 0;  // We removed hydrogen rather than added
                            Assume.IsTrue((Math.Abs(newTransitionGroupDocNode.PrecursorMz + mzShift - transitionGroupDocNode.PrecursorMz) - Math.Abs(transitionGroupDocNode.TransitionGroup.PrecursorCharge * BioMassCalc.MassElectron)) <= 1E-5);

                            foreach (var transition in transitionGroupDocNode.Transitions)
                            {
                                double mass = 0;
                                var transitionCharge = transition.Transition.Charge * (invertCharges ? -1 : 1);
                                var ionType = IonType.custom;
                                CustomIon transitionCustomIon;
                                double mzShiftTransition = 0;
                                if (transition.Transition.IonType == IonType.precursor)
                                {
                                    ionType = IonType.precursor;
                                    transitionCustomIon = new DocNodeCustomIon(precursorCustomIon.Formula,
                                        string.IsNullOrEmpty(precursorCustomIon.Formula) ? precursorCustomIon.MonoisotopicMass : (double?) null,
                                        string.IsNullOrEmpty(precursorCustomIon.Formula) ? precursorCustomIon.AverageMass : (double?) null,
                                        SmallMoleculeNameFromPeptide(peptideSequence, transitionCharge));
                                    mzShiftTransition = invertCharges ? 2.0 * BioMassCalc.MassProton : 0;  // We removed hydrogen rather than added
                                }
                                else if (transition.Transition.IonType == IonType.custom)
                                {
                                    transitionCustomIon = transition.Transition.CustomIon;
                                    mass = transitionCustomIon.MonoisotopicMass;
                                }
                                else
                                {
                                    // TODO - try to get fragment formula?
                                    mass = BioMassCalc.CalculateIonMassFromMz(transition.Mz, transition.Transition.Charge);
                                    transitionCustomIon = new DocNodeCustomIon(mass, mass,// We can't really get at mono vs average mass from m/z, but for test purposes this is fine
                                        transition.Transition.FragmentIonName);
                                }
                                if (mode == ConvertToSmallMoleculesMode.masses_and_names)
                                {
                                    // Discard the formula if we're testing the use of mass-with-names (for matching in ratio calcs) target specification
                                    transitionCustomIon = new DocNodeCustomIon(transitionCustomIon.MonoisotopicMass, transitionCustomIon.AverageMass,
                                        transition.Transition.FragmentIonName);
                                }
                                else if (mode == ConvertToSmallMoleculesMode.masses_only)
                                {
                                    // Discard the formula and name if we're testing the use of mass-only target specification
                                    transitionCustomIon = new DocNodeCustomIon(transitionCustomIon.MonoisotopicMass, transitionCustomIon.AverageMass);
                                }

                                var newTransition = new Transition(newTransitionGroup, ionType,
                                    null, transition.Transition.MassIndex, transition.Transition.Charge * (invertCharges ? -1 : 1), null,
                                    transitionCustomIon);
                                if (ionType == IonType.precursor)
                                {
                                    mass = document.Settings.GetFragmentMass(transitionGroupDocNode.TransitionGroup.LabelType, null, newTransition, newTransitionGroupDocNode.IsotopeDist);
                                }
                                var newTransitionDocNode = new TransitionDocNode(newTransition, transition.Annotations.Merge(note),
                                    null, mass, transition.IsotopeDistInfo, null,
                                    transition.Results);
                                Assume.IsTrue((Math.Abs(newTransitionDocNode.Mz + mzShiftTransition - transition.Mz) - Math.Abs(transitionGroupDocNode.TransitionGroup.PrecursorCharge * BioMassCalc.MassElectron)) <= 1E-5, String.Format("unexpected mz difference {0}-{1}={2}", newTransitionDocNode.Mz , transition.Mz, newTransitionDocNode.Mz - transition.Mz)); // Not L10N
                                newTransitionGroupDocNode =
                                    (TransitionGroupDocNode)newTransitionGroupDocNode.Add(newTransitionDocNode);
                            }
                            if (newPeptideDocNode != null)
                                newPeptideDocNode = (PeptideDocNode)newPeptideDocNode.Add(newTransitionGroupDocNode);
                        }
                        newPeptideGroupDocNode =
                            (PeptideGroupDocNode)newPeptideGroupDocNode.Add(newPeptideDocNode);
                    }
                    newdoc = (SrmDocument)newdoc.Add(newPeptideGroupDocNode);
                }
            }

            // No retention time prediction for small molecules (yet?)
            newdoc = newdoc.ChangeSettings(newdoc.Settings.ChangePeptideSettings(newdoc.Settings.PeptideSettings.ChangePrediction(
                        newdoc.Settings.PeptideSettings.Prediction.ChangeRetentionTime(null))));

            return newdoc;
        }
Beispiel #22
0
	// Returns false if there are no more tokens (reached end of code)
	static bool ParseClassOrStruct (Annotations annotations, MemberInfo parent, Tokenizer tokenizer)
	{
		TypeInfo type = new TypeInfo ();

		type.Annotations = annotations;
		type.Header = tokenizer.CurrentFile;
		type.Parent = parent;

		type.IsPublic = tokenizer.Accept (Token2Type.Identifier, "public");

		if (tokenizer.Accept (Token2Type.Identifier, "class")) {
			type.IsClass = true;
		} else if (tokenizer.Accept (Token2Type.Identifier, "struct")) {
			type.IsStruct = true;
			type.IsValueType = true;
		} else if (tokenizer.Accept (Token2Type.Identifier, "union")) {
			type.IsStruct = true; // Not entirely correct, but a union can be parsed as a struct
			type.IsValueType = true;
		} else {
			throw new Exception (string.Format ("Expected 'class' or 'struct', not '{0}'", tokenizer.CurrentToken.value));
		}

		if (tokenizer.CurrentToken.type == Token2Type.Identifier) {
			type.Name = tokenizer.GetIdentifier ();
		} else {
			type.Name = "<anonymous>";
		}

		if (tokenizer.Accept (Token2Type.Punctuation, ";")) {
			// A forward declaration.
			//Console.WriteLine ("ParseType: Found a forward declaration to {0}", type.Name);
			return true;
		}

		if (tokenizer.Accept (Token2Type.Punctuation, ":")) {
			if (!tokenizer.Accept (Token2Type.Identifier, "public") && type.IsClass)
				throw new Exception (string.Format ("The base class of {0} is not public.", type.Name));

			type.Base = ParseTypeReference (tokenizer);

			// accept multiple inheritance the easy way
			while (tokenizer.CurrentToken.value == ",") {
				tokenizer.Accept (Token2Type.Punctuation, ",");

				while (tokenizer.CurrentToken.value != "," &&
				       tokenizer.CurrentToken.value != "{")
					tokenizer.GetIdentifier ();
			}

			//Console.WriteLine ("ParseType: Found {0}'s base class: {1}", type.Name, type.Base);
		}

		tokenizer.AcceptOrThrow (Token2Type.Punctuation, "{");

		//Console.WriteLine ("ParseType: Found a type: {0} in {1}", type.Name, type.Header);
		parent.Children.Add (type);
		ParseMembers (type, tokenizer);

		tokenizer.AcceptOrThrow (Token2Type.Punctuation, "}");

		if (tokenizer.CurrentToken.type == Token2Type.Identifier)
			tokenizer.Advance (true);

		if (tokenizer.CurrentToken.value != ";")
			throw new Exception (string.Format ("Expected ';', not '{0}'", tokenizer.CurrentToken.value));

		return tokenizer.Advance (false);
	}
Beispiel #23
0
 private bool SetDatabaseName(string value)
 => Annotations.SetAnnotation(_fullAnnotationNames?.DatabaseName, value);
 public PeptideGroupDocNode(PeptideGroup id, Annotations annotations, string name, string description,
     PeptideDocNode[] children)
     : this(id, annotations, name, description, children, true)
 {
 }
Beispiel #25
0
 public void Reset()
 {
     Series.Clear();
     Axes.Clear();
     Annotations.Clear();
 }
Beispiel #26
0
 bool CanSweepNamesForMember(IMemberDefinition member, MetadataTrimming metadataTrimming)
 {
     return((Context.MetadataTrimming & metadataTrimming) != 0 && !Annotations.IsReflectionUsed(member));
 }
Beispiel #27
0
 /// <summary>
 /// Adds an intra document link.
 /// </summary>
 /// <param name="rect">The rect.</param>
 /// <param name="destinationPage">The destination page.</param>
 public PdfLinkAnnotation AddDocumentLink(PdfRectangle rect, int destinationPage)
 {
     PdfLinkAnnotation annotation = PdfLinkAnnotation.CreateDocumentLink(rect, destinationPage);
     Annotations.Add(annotation);
     return annotation;
 }
Beispiel #28
0
        public void AnnotationMergeTest()
        {
            const string note1 = "This is a test";
            const string note2 = "Different note";
            // Self-merge
            var annotations1 = new Annotations(note1, null, -1);

            Assert.AreSame(annotations1, annotations1.Merge(annotations1));

            // Merge with equal annotation
            var annotations2 = new Annotations(note1, null, -1);

            Assert.AreSame(annotations1, annotations1.Merge(annotations2));

            // Merge with empty note annotation
            var emptyNote = new Annotations(null, null, -1);

            Assert.AreSame(annotations1, annotations1.Merge(emptyNote));
            Assert.AreSame(annotations1, emptyNote.Merge(annotations1));

            // Merge with different not annotation
            var annotations3 = new Annotations(note2, null, -1);
            var mergeNote    = annotations1.Merge(annotations3);

            Assert.IsTrue(mergeNote.Note.Contains(note1));
            Assert.IsTrue(mergeNote.Note.Contains(note2));

            // Merge annotation with a note that is already present
            Assert.AreSame(mergeNote, mergeNote.Merge(annotations2));

            // Check color merging
            var annotationsColor = new Annotations("color", null, 0);

            Assert.AreEqual(0, annotations1.Merge(annotationsColor).ColorIndex);
            Assert.AreEqual(0, annotationsColor.Merge(annotations1).ColorIndex);

            // Merge with actual annotations
            const string annotationName1     = "Test";
            const string annotationName2     = "FullText";
            const string annotationValue2    = "Hello";
            var          annotationsComplex1 = new Annotations(note1, new[] { new KeyValuePair <string, string>(annotationName1, "Test") }, -1);

            Assert.AreSame(annotationsComplex1, annotations1.Merge(annotationsComplex1));
            Assert.AreSame(annotationsComplex1, annotationsComplex1.Merge(annotations1));

            // Merge with disjoint annotations
            var annotationsComplex2 = new Annotations(note1, new[] { new KeyValuePair <string, string>(annotationName2, annotationValue2) }, -1);
            var complexMerge        = annotationsComplex1.Merge(annotationsComplex2);

            Assert.AreEqual(2, complexMerge.ListAnnotations().Length);
            Assert.AreEqual(0, complexMerge.ListAnnotations().IndexOf(a => Equals(a.Key, annotationName1)));
            Assert.AreEqual(1, complexMerge.ListAnnotations().IndexOf(a => Equals(a.Key, annotationName2)));

            // Merge with conflicting annotations
            var annotationsComplex3 = new Annotations(null,
                                                      new[]
            {
                new KeyValuePair <string, string>("NewName", "Value"),
                new KeyValuePair <string, string>(annotationName2, "Error")
            },
                                                      -1);

            AssertEx.ThrowsException <InvalidDataException>(() => complexMerge.Merge(annotationsComplex3));

            // Merge with same annotation
            var annotationsComplex4 = new Annotations(null,
                                                      new[]
            {
                new KeyValuePair <string, string>("NewName", "Value"),
                new KeyValuePair <string, string>(annotationName2, annotationValue2)
            },
                                                      -1);

            Assert.AreEqual(3, complexMerge.Merge(annotationsComplex4).ListAnnotations().Length);
        }
Beispiel #29
0
 /// <summary>
 /// Adds a link to a file.
 /// </summary>
 /// <param name="rect">The rect.</param>
 /// <param name="fileName">Name of the file.</param>
 public PdfLinkAnnotation AddFileLink(PdfRectangle rect, string fileName)
 {
     PdfLinkAnnotation annotation = PdfLinkAnnotation.CreateFileLink(rect, fileName);
     Annotations.Add(annotation);
     return annotation;
 }
Beispiel #30
0
 void AnnotateMethods(MethodDefinition @base, MethodDefinition @override)
 {
     Annotations.AddBaseMethod(@override, @base);
     Annotations.AddOverride(@base, @override);
 }
Beispiel #31
0
 /// <summary>
 /// Adds a link to the Web.
 /// </summary>
 /// <param name="rect">The rect.</param>
 /// <param name="url">The URL.</param>
 public PdfLinkAnnotation AddWebLink(PdfRectangle rect, string url)
 {
     PdfLinkAnnotation annotation = PdfLinkAnnotation.CreateWebLink(rect, url);
     Annotations.Add(annotation);
     return annotation;
 }
Beispiel #32
0
        protected virtual bool IgnoreScope(IMetadataScope scope)
        {
            AssemblyDefinition assembly = ResolveAssembly(scope);

            return(Annotations.GetAction(assembly) != AssemblyAction.Link);
        }
Beispiel #33
0
 void AddPreservedMethod(MethodDefinition key, MethodDefinition method)
 {
     Annotations.AddPreservedMethod(key, method);
 }
Beispiel #34
0
        public IActionResult PostAnnotations([FromBody] Annotations annotations)
        {
            _dataService.CreateAnnotation(annotations.Body, annotations.UserId, annotations.PostId);

            return(Created($"api/annotations/{annotations}", annotations));
        }
 public bool IsInspectionDisabled(string inspectionName)
 {
     return(Annotations.Any(annotation =>
                            annotation.AnnotationType == AnnotationType.Ignore &&
                            ((IgnoreAnnotation)annotation).IsIgnored(inspectionName)));
 }
Beispiel #36
0
        void ProcessDispose(MethodDefinition bd, MethodDefinition cd)
        {
            bool skip = false;

            // did we detect some fields that could be removed ?
            if (dispose_methods.Contains(cd))
            {
                // removed unmarked fields
                skip = FilterDispose(cd);
                // return value tells us if the Dispose method is now "empty" and could be skipped to the next
                // (non-empty) base.Dispose
                if (skip)
                {
                    // if it does nothing then it should not be part of the final binary
                    //cd.DeclaringType.Methods.Remove (cd);
                }
            }

            var overrides = Annotations.GetOverrides(cd);

            if (overrides == null)
            {
                return;
            }

            // every subclass-Dispose should be calling base-Dispose
            foreach (MethodDefinition od in overrides)
            {
                // we do not need to process unmarked code (it won't be part of the final binary)
                if (!Annotations.IsMarked(od))
                {
                    continue;
                }
                // we do NOT process non-generated code - we could break user code
                if (!od.IsGeneratedCode())
                {
                    continue;
                }

                ProcessDispose(skip ? bd : cd, od);

                // check if we need to replace the base.Dipose call
                if (bd == cd)
                {
                    continue;
                }

                // replace "base.Dispose". In C# this always looks fine - but in IL it's the base type that's
                // used (and needs to change to remove the "empty" Dispose methods)
                foreach (Instruction ins in od.Body.Instructions)
                {
                    if (ins.OpCode.Code != Code.Call)
                    {
                        continue;
                    }

                    // we can cross the assembly borders and the Dispose method might not be
                    // part of the existing member references so we import it in such cases
                    if (od.Module != bd.Module)
                    {
                        ins.Operand = od.Module.ImportReference(bd);
                    }
                    else
                    {
                        ins.Operand = bd;
                    }
                    break;
                }
            }
        }
 protected virtual IEnumerable <MigrationOperation> Add([NotNull] IModel target, [NotNull] DiffContext diffContext)
 => GetSchemas(target).SelectMany(Add)
 .Concat(target.GetRootEntityTypes().SelectMany(t => Add(t, diffContext)))
 .Concat(Annotations.For(target).Sequences.SelectMany(Add))
 .Concat(target.GetEntityTypes().SelectMany(t => t.GetDeclaredForeignKeys()).SelectMany(k => Add(k, diffContext)));
Beispiel #38
0
        public void ExceptionsShouldBeLogged()
        {
            const string errorMessage = "Something bad happened";

            var tracerThatThrow = new Mock <ITracer>();

            tracerThatThrow.Setup(tracer1 => tracer1.Record(It.IsAny <Record>())).Throws(new Exception(errorMessage));
            TraceManager.RegisterTracer(tracerThatThrow.Object);

            var record = new Record(new SpanState(0, null, 1, isSampled: null, isDebug: false), TimeUtils.UtcNow, Annotations.ClientRecv());

            Assert.DoesNotThrow(() => TraceManager.Push(record));

            _mockLogger.Verify(logger1 => logger1.LogWarning(It.Is <string>(s => s.Contains(errorMessage))), Times.Once());
        }
 protected virtual IEnumerable <MigrationOperation> Remove([NotNull] IModel source, [NotNull] DiffContext diffContext) =>
 source.GetRootEntityTypes().SelectMany(t => Remove(t, diffContext))
 .Concat(Annotations.For(source).Sequences.SelectMany(Remove));
 private IEnumerable <IIndex> GetIndexesInHierarchy(IEntityType entityType)
 => entityType.GetDeclaredIndexes().Concat(entityType.GetDerivedTypes().SelectMany(t => t.GetDeclaredIndexes()))
 .Distinct((x, y) => Annotations.For(x).Name == Annotations.For(y).Name);
 private IEnumerable <IProperty> GetPropertiesInHierarchy(IEntityType entityType)
 => entityType.GetDeclaredProperties().Concat(entityType.GetDerivedTypes().SelectMany(t => t.GetDeclaredProperties()))
 .Distinct((x, y) => Annotations.For(x).ColumnName == Annotations.For(y).ColumnName);
Beispiel #42
0
 public ChromatogramSet ChangeAnnotations(Annotations prop)
 {
     return ChangeProp(ImClone(this), im => im.Annotations = prop);
 }
 protected virtual string[] GetColumns([NotNull] IEnumerable <IProperty> properties)
 => properties.Select(p => Annotations.For(p).ColumnName).ToArray();
        /// <summary>
        /// Removes peaks and annotations that were in the document but not in the file, so that all peptide results that were not explicitly imported as part of this file are now blank
        /// </summary>
        /// <param name="docNew">SrmDocument for which missing peaks should be removed</param>
        /// <param name="trackAdjustedResults">List of peaks that were in the imported file</param>
        /// <param name="changePeaks">If true, remove both peaks and annotations.  If false, only remove annotations</param>
        /// <returns></returns>
        private SrmDocument RemoveMissing(SrmDocument docNew, ICollection<ResultsKey> trackAdjustedResults, bool changePeaks)
        {
            var measuredResults = docNew.Settings.MeasuredResults;
            var chromatogramSets = measuredResults.Chromatograms;
            for (int i = 0; i < chromatogramSets.Count; ++i)
            {
                var set = chromatogramSets[i];
                var nameSet = set.Name;
                for (int k = 0; k < docNew.MoleculeCount; ++k)
                {
                    IdentityPath pepPath = docNew.GetPathTo((int)SrmDocument.Level.Molecules, k);
                    var pepNode = (PeptideDocNode)Document.FindNode(pepPath);
                    if (pepNode.IsDecoy)
                        continue;
                    if (pepNode.GlobalStandardType != null)
                        continue;
                    foreach (var groupNode in pepNode.TransitionGroups)
                    {
                        var groupPath = new IdentityPath(pepPath, groupNode.Id);
                        var chromInfos = groupNode.Results[i];
                        if (chromInfos == null)
                            continue;

                        foreach (var groupChromInfo in chromInfos)
                        {
                            if (groupChromInfo == null)
                                continue;
                            var key = new ResultsKey(groupChromInfo.FileId.GlobalIndex, groupNode.Id);
                            if (!trackAdjustedResults.Contains(key))
                            {
                                CountMissing++;
                                var fileId = groupChromInfo.FileId;
                                var fileInfo = set.GetFileInfo(fileId);
                                var filePath = fileInfo.FilePath;
                                // Remove annotations for defs that were imported into the document and were on this peptide prior to import
                                var newAnnotationValues = groupChromInfo.Annotations.ListAnnotations().ToList();
                                newAnnotationValues = newAnnotationValues.Where(a => !AnnotationsAdded.Contains(a.Key)).ToList();
                                var newAnnotations = new Annotations(groupChromInfo.Annotations.Note, newAnnotationValues, groupChromInfo.Annotations.ColorIndex);
                                var newGroupNode = groupNode.ChangePrecursorAnnotations(fileId, newAnnotations);
                                if (!ReferenceEquals(groupNode, newGroupNode))
                                    docNew = (SrmDocument) docNew.ReplaceChild(groupPath.Parent, newGroupNode);
                                // Adjust peaks to null if they weren't in the file
                                if (changePeaks)
                                {
                                    docNew = docNew.ChangePeak(groupPath, nameSet, filePath,
                                        null, null, null, UserSet.IMPORTED, null, false);
                                }
                            }
                        }
                    }
                }
            }
            return docNew;
        }
 protected virtual IEnumerable <string> GetSchemas([NotNull] IModel model)
 => model.GetRootEntityTypes().Select(t => Annotations.For(t).Schema).Where(s => !string.IsNullOrEmpty(s))
 .Distinct();
Beispiel #46
0
	static bool ParseMembers (MemberInfo parent, Tokenizer tokenizer)
	{
		Annotations properties = new Annotations ();
		TypeInfo parent_type = parent as TypeInfo;
		string accessibility;
		TypeReference returntype;
		bool is_dtor;
		bool is_ctor;
		bool is_virtual;
		bool is_static;
		bool is_const;
		bool is_extern;
		string name;

		//Console.WriteLine ("ParseMembers ({0})", type.Name);

		do {
			returntype = null;
			is_dtor = is_ctor = is_virtual = is_static = false;
			is_extern = is_const = false;
			name = null;
			properties = new Annotations ();

			if (parent_type != null)
				accessibility = parent_type.IsStruct ? "public" : "private";
			else
				accessibility = "public";

			try {
				if (tokenizer.Accept (Token2Type.Punctuation, ";"))
					continue;
			} catch {
				return false;
			}

			if (tokenizer.CurrentToken.value == "}")
				return true;

			while (tokenizer.CurrentToken.type == Token2Type.CommentProperty) {
				properties.Add (tokenizer.CurrentToken.value);
				tokenizer.Advance (true);
			}

			//Console.WriteLine ("ParseMembers: Current token: {0}", tokenizer.CurrentToken);

			if (tokenizer.CurrentToken.type == Token2Type.Identifier) {
				string v = tokenizer.CurrentToken.value;
				switch (v) {
				case "public":
				case "protected":
				case "private":
					accessibility = v;
					tokenizer.Advance (true);
					tokenizer.Accept (Token2Type.Punctuation, ":");
					continue;
				case "enum":
					ParseEnum (properties, parent, tokenizer);
					continue;
				case "friend":
					while (!tokenizer.Accept (Token2Type.Punctuation, ";")) {
						tokenizer.Advance (true);
					}
					continue;
				case "struct":
				case "class":
				case "union":
					if (!ParseClassOrStruct (properties, parent, tokenizer))
						return false;
					continue;
				case "typedef":
					StringBuilder requisite = new StringBuilder ();
					requisite.Append (tokenizer.CurrentToken.value);
					requisite.Append (' ');
					tokenizer.Advance (true);
					while (!tokenizer.Accept (Token2Type.Punctuation, ";")) {
						requisite.Append (tokenizer.CurrentToken.value);
						requisite.Append (' ');
						if (tokenizer.CurrentToken.value == "{") {
							tokenizer.Advance (true);
							while (!tokenizer.Accept (Token2Type.Punctuation, "}")) {
								requisite.Append (tokenizer.CurrentToken.value);
								requisite.Append (' ');
								tokenizer.Advance (true);
							}
							requisite.Append (tokenizer.CurrentToken.value);
							requisite.Append (' ');
						}
						tokenizer.Advance (true);
					}
					requisite.Append (";");
					if (properties.ContainsKey ("CBindingRequisite"))
						cbinding_requisites.AppendLine (requisite.ToString ());

					continue;
				case "EVENTHANDLER":
					while (!tokenizer.Accept (Token2Type.Punctuation, ";"))
						tokenizer.Advance (true);
					continue;
				case "template":
					tokenizer.Advance (true);
					tokenizer.AcceptOrThrow (Token2Type.Punctuation, "<");
					tokenizer.AcceptOrThrow (Token2Type.Identifier, "typename");
					tokenizer.GetIdentifier ();
					tokenizer.AcceptOrThrow (Token2Type.Punctuation, ">");
					continue;
				case "using":
					tokenizer.Advance (true);
					continue;
				case "namespace":
					tokenizer.Advance (true);
					tokenizer.GetIdentifier ();
					tokenizer.Accept (Token2Type.Punctuation, "{");
					continue;
				case "mutable":
					tokenizer.Advance (true);
					continue;
				}
			}

			do {
				if (tokenizer.Accept (Token2Type.Identifier, "virtual")) {
					is_virtual = true;
					continue;
				}

				if (tokenizer.Accept (Token2Type.Identifier, "static")) {
					is_static = true;
					continue;
				}

				if (tokenizer.Accept (Token2Type.Identifier, "const")) {
					is_const = true;
					continue;
				}

				if (tokenizer.Accept (Token2Type.Identifier, "extern")) {
					is_extern = true;
					continue;
				}

				if (tokenizer.Accept (Token2Type.Identifier, "volatile")) {
					continue;
				}

				if (tokenizer.Accept (Token2Type.Identifier, "G_GNUC_INTERNAL")) {
					continue;
				}

			    break;
			} while (true);

			if (is_extern && tokenizer.Accept (Token2Type.Literal, "C")) {
				tokenizer.SyncWithEndBrace ();
				continue;
			}

			if (tokenizer.Accept (Token2Type.Punctuation, "~")) {
				is_dtor = true;
				if (!is_virtual) {
					TypeInfo ti = parent as TypeInfo;
					if (ti != null && ti.Base != null)
						Console.WriteLine ("The class {0} has a non-virtual destructor, and it's base class is {2} ({1}).", parent.Name, parent.Header, ti != null && ti.Base != null ? ti.Base.Value : "<none>");
				}
			}

			if (is_dtor) {
				name = "~" + tokenizer.GetIdentifier ();
				returntype = new TypeReference ("void");
			} else {
				returntype = ParseTypeReference (tokenizer);

				if (tokenizer.CurrentToken.value == "<") {
					tokenizer.Advance (true);
					while (!tokenizer.Accept (Token2Type.Punctuation, ">"))
						tokenizer.Advance (true);
				}

				if (returntype.Value == parent.Name && tokenizer.CurrentToken.value == "(") {
					is_ctor = true;
					name = returntype.Value;
					returntype.Value += "*";
				} else {
					name = tokenizer.GetIdentifier ();
				}
			}
			returntype.IsConst = is_const;
			returntype.IsReturnType = true;

			//Console.WriteLine ("ParseMembers: found member '{0}' is_ctor: {1}", name, is_ctor);

			if (tokenizer.Accept (Token2Type.Punctuation, "(")) {
				// Method
				MethodInfo method = new MethodInfo ();
				method.Header = tokenizer.CurrentFile;
				method.Parent = parent;
				method.Annotations = properties;
				method.Name = name;
				method.IsConstructor = is_ctor;
				method.IsDestructor = is_dtor;
				method.IsVirtual = is_virtual;
				method.IsStatic = is_static;
				method.IsPublic = accessibility == "public";
				method.IsPrivate = accessibility == "private";
				method.IsProtected = accessibility == "protected";
				method.ReturnType = returntype;

				//Console.WriteLine ("ParseMembers: found method '{0}' is_ctor: {1}", name, is_ctor);

				if (!tokenizer.Accept (Token2Type.Punctuation, ")")) {
					string param_value = null;
					do {
						ParameterInfo parameter = new ParameterInfo (method);

						while (tokenizer.CurrentToken.type == Token2Type.CommentProperty) {
							parameter.Annotations.Add (tokenizer.CurrentToken.value);
							tokenizer.Advance (true);
						}

						if (tokenizer.Accept (Token2Type.Punctuation, ".") && tokenizer.Accept (Token2Type.Punctuation, ".") && tokenizer.Accept (Token2Type.Punctuation, ".")) {
							// ... variable argument declaration
							parameter.ParameterType = new TypeReference ("...");
						} else {
							if (tokenizer.CurrentToken.type == Token2Type.Identifier) {
								if (tokenizer.Accept (Token2Type.Identifier, "Moonlight")) {
									tokenizer.Accept (Token2Type.Punctuation, ":");
									tokenizer.Accept (Token2Type.Punctuation, ":");
								}
							}
							parameter.ParameterType = ParseTypeReference (tokenizer);
						}

						if (tokenizer.CurrentToken.value != "," && tokenizer.CurrentToken.value != ")") {
							parameter.Name = tokenizer.GetIdentifier ();
							if (tokenizer.Accept (Token2Type.Punctuation, "[")) {
								if (tokenizer.CurrentToken.type == Token2Type.Identifier)
									tokenizer.Advance (true);
								tokenizer.AcceptOrThrow (Token2Type.Punctuation, "]");
							}
							if (tokenizer.Accept (Token2Type.Punctuation, "=")) {
								param_value = string.Empty;
								if (tokenizer.Accept (Token2Type.Punctuation, "-"))
									param_value = "-";
								param_value += tokenizer.GetIdentifier ();
								if (tokenizer.Accept (Token2Type.Punctuation, ":")) {
									tokenizer.AcceptOrThrow (Token2Type.Punctuation, ":");
									param_value += "::" + tokenizer.GetIdentifier ();
								}
							}
						}
						method.Parameters.Add (parameter);
						//Console.WriteLine ("ParseMember: got parameter, type: '{0}' name: '{1}' value: '{2}'", parameter.ParameterType.Value, parameter.Name, param_value);
					} while (tokenizer.Accept (Token2Type.Punctuation, ","));
					tokenizer.AcceptOrThrow (Token2Type.Punctuation, ")");
				}

				parent.Children.Add (method);

				//Allow const member functions, ignore the const keyword
				tokenizer.Accept (Token2Type.Identifier, "const");

				if (tokenizer.CurrentToken.value == "{") {
					//Console.WriteLine ("ParseMember: member has body, skipping it");
					tokenizer.SyncWithEndBrace ();
				} else if (is_ctor && tokenizer.Accept (Token2Type.Punctuation, ":")) {
					// ctor method implemented in header with field initializers and/or base class ctor call
					tokenizer.FindStartBrace ();
					tokenizer.SyncWithEndBrace ();
					//Console.WriteLine ("ParseMember: skipped ctor method implementation");
				} else if (tokenizer.Accept (Token2Type.Punctuation, "=")) {
					// pure virtual method
					tokenizer.AcceptOrThrow (Token2Type.Identifier, "0");
					tokenizer.AcceptOrThrow (Token2Type.Punctuation, ";");
					method.IsAbstract = true;
				} else {
					if (tokenizer.Accept (Token2Type.Identifier,  "__attribute__")) {
						tokenizer.AcceptOrThrow (Token2Type.Punctuation, "(");
						tokenizer.AcceptOrThrow (Token2Type.Punctuation, "(");
						if (tokenizer.CurrentToken.type == Token2Type.Identifier)
							tokenizer.Advance (true);
						tokenizer.AcceptOrThrow (Token2Type.Punctuation, ")");
						tokenizer.AcceptOrThrow (Token2Type.Punctuation, ")");
					}
					tokenizer.AcceptOrThrow (Token2Type.Punctuation, ";");
				}
			} else {
				if (is_ctor || is_dtor)
					throw new Exception (string.Format ("Expected '(', not '{0}'", tokenizer.CurrentToken.value));

				if (name == "operator") {
					while (true) {
						if (tokenizer.CurrentToken.value == ";") {
							// End of operator
							break;
						} else if (tokenizer.CurrentToken.value == "{") {
							// In-line implementation
							tokenizer.SyncWithEndBrace ();
							break;
						}
						tokenizer.Advance (true);
					}
					//Console.WriteLine ("ParseMembers: skipped operator");
				} else {
					FieldInfo field = new FieldInfo ();
					field.IsConst = is_const;
					field.IsStatic = is_static;
					field.IsExtern = is_extern;
					field.Name = name;
					field.FieldType = returntype;
					field.IsPublic = accessibility == "public";
					field.IsPrivate = accessibility == "private";
					field.IsProtected = accessibility == "protected";
					field.Annotations = properties;

					// Field
					do {
						//Console.WriteLine ("ParseMembers: found field '{0}'", name);
						field.Parent = parent;
						parent.Children.Add (field);

						if (tokenizer.Accept (Token2Type.Punctuation, "[")) {
							while (!tokenizer.Accept (Token2Type.Punctuation, "]")) {
								tokenizer.Advance (true);
							}
						}
						if (tokenizer.Accept (Token2Type.Punctuation, ":")) {
							field.BitField = tokenizer.GetIdentifier ();
						}
						if (tokenizer.Accept (Token2Type.Punctuation, ",")) {
							field = new FieldInfo ();
							if (tokenizer.Accept (Token2Type.Punctuation, "*")) {
								// ok
							}
							field.Name = tokenizer.GetIdentifier ();
							field.FieldType = returntype;
							continue;
						}
						if (tokenizer.Accept (Token2Type.Punctuation, "=")) {
							tokenizer.Advance (true); /* this can be an arbitrary long expression, sync with the ';'?  */
						}
						break;
					} while (true);

					tokenizer.Accept (Token2Type.Punctuation, ";");
				}
			}
		} while (true);
	}
Beispiel #47
0
        void UpdateAssemblyReferencesToRemovedAssemblies(AssemblyDefinition assembly)
        {
            var action = Annotations.GetAction(assembly);

            switch (action)
            {
            case AssemblyAction.Copy:
            case AssemblyAction.Delete:
            case AssemblyAction.Link:
            case AssemblyAction.Save:
            case AssemblyAction.Skip:
                return;

            case AssemblyAction.CopyUsed:
            case AssemblyAction.AddBypassNGen:
            case AssemblyAction.AddBypassNGenUsed:
                foreach (var reference in assembly.MainModule.AssemblyReferences)
                {
                    AssemblyDefinition?ad = Context.Resolver.Resolve(reference);
                    if (ad == null)
                    {
                        continue;
                    }

                    RemoveUnmarkedAssembly(ad);
                    if (Annotations.GetAction(ad) != AssemblyAction.Delete)
                    {
                        continue;
                    }

                    // Assembly was removed in the output but it's referenced by
                    // other assembly with action which does not update references

                    switch (action)
                    {
                    case AssemblyAction.CopyUsed:
                        //
                        // Assembly has a reference to another assembly which has been fully removed. This can
                        // happen when for example the reference assembly is 'copy-used' and it's not needed.
                        //
                        // or
                        //
                        // Assembly can contain type references with
                        // type forwarders to deleted assembly (facade) when
                        // facade assemblies are not kept. For that reason we need to
                        // rewrite the copy to save to update the scopes not to point
                        // forwarding assembly (facade).
                        //
                        //		foo.dll -> facade.dll    -> lib.dll
                        //		copy    |  copy (delete) |  link
                        //
                        Annotations.SetAction(assembly, AssemblyAction.Save);
                        continue;

                    case AssemblyAction.AddBypassNGenUsed:
                        Annotations.SetAction(assembly, AssemblyAction.AddBypassNGen);
                        goto case AssemblyAction.AddBypassNGen;

                    case AssemblyAction.AddBypassNGen:
                        BypassNGenToSave.Add(assembly);
                        continue;
                    }
                }
                break;

            default:
                throw new ArgumentOutOfRangeException(action.ToString());
            }
        }
        public void AnnotationMergeTest()
        {
            const string note1 = "This is a test";
            const string note2 = "Different note";
            // Self-merge
            var annotations1 = new Annotations(note1, null, -1);
            Assert.AreSame(annotations1, annotations1.Merge(annotations1));

            // Merge with equal annotation
            var annotations2 = new Annotations(note1, null, -1);
            Assert.AreSame(annotations1, annotations1.Merge(annotations2));

            // Merge with empty note annotation
            var emptyNote = new Annotations(null, null, -1);
            Assert.AreSame(annotations1, annotations1.Merge(emptyNote));
            Assert.AreSame(annotations1, emptyNote.Merge(annotations1));

            // Merge with different not annotation
            var annotations3 = new Annotations(note2, null, -1);
            var mergeNote = annotations1.Merge(annotations3);
            Assert.IsTrue(mergeNote.Note.Contains(note1));
            Assert.IsTrue(mergeNote.Note.Contains(note2));

            // Merge annotation with a note that is already present
            Assert.AreSame(mergeNote, mergeNote.Merge(annotations2));

            // Check color merging
            var annotationsColor = new Annotations("color", null, 0);
            Assert.AreEqual(0, annotations1.Merge(annotationsColor).ColorIndex);
            Assert.AreEqual(0, annotationsColor.Merge(annotations1).ColorIndex);

            // Merge with actual annotations
            const string annotationName1 = "Test";
            const string annotationName2 = "FullText";
            const string annotationValue2 = "Hello";
            var annotationsComplex1 = new Annotations(note1, new[] {new KeyValuePair<string, string>(annotationName1, "Test")}, -1);
            Assert.AreSame(annotationsComplex1, annotations1.Merge(annotationsComplex1));
            Assert.AreSame(annotationsComplex1, annotationsComplex1.Merge(annotations1));

            // Merge with disjoint annotations
            var annotationsComplex2 = new Annotations(note1, new[] {new KeyValuePair<string, string>(annotationName2, annotationValue2)}, -1);
            var complexMerge = annotationsComplex1.Merge(annotationsComplex2);
            Assert.AreEqual(2, complexMerge.ListAnnotations().Length);
            Assert.AreEqual(0, complexMerge.ListAnnotations().IndexOf(a => Equals(a.Key, annotationName1)));
            Assert.AreEqual(1, complexMerge.ListAnnotations().IndexOf(a => Equals(a.Key, annotationName2)));

            // Merge with conflicting annotations
            var annotationsComplex3 = new Annotations(null,
                                                      new[]
                                                          {
                                                              new KeyValuePair<string, string>("NewName", "Value"),
                                                              new KeyValuePair<string, string>(annotationName2, "Error")
                                                          },
                                                      -1);
            AssertEx.ThrowsException<InvalidDataException>(() => complexMerge.Merge(annotationsComplex3));

            // Merge with same annotation
            var annotationsComplex4 = new Annotations(null,
                                                      new[]
                                                          {
                                                              new KeyValuePair<string, string>("NewName", "Value"),
                                                              new KeyValuePair<string, string>(annotationName2, annotationValue2)
                                                          },
                                                      -1);
            Assert.AreEqual(3, complexMerge.Merge(annotationsComplex4).ListAnnotations().Length);
        }
Beispiel #49
0
        public PeptideDocNode(Peptide id,
            SrmSettings settings,
            ExplicitMods mods,
            ModifiedSequenceMods sourceKey,
            string standardType,
            int? rank,
            ExplicitRetentionTimeInfo explicitRetentionTimeInfo,
            Annotations annotations,
            Results<PeptideChromInfo> results,
            TransitionGroupDocNode[] children,
            bool autoManageChildren)
            : base(id, annotations, children, autoManageChildren)
        {
            ExplicitMods = mods;
            SourceKey = sourceKey;
            GlobalStandardType = standardType;
            Rank = rank;
            ExplicitRetentionTime = explicitRetentionTimeInfo;
            Results = results;
            BestResult = CalcBestResult();

            if (settings != null)
            {
                var calcPre = settings.GetPrecursorCalc(IsotopeLabelType.light, ExplicitMods);
                ModifiedSequence = calcPre.GetModifiedSequence(Peptide.Sequence, false);
                ModifiedSequenceDisplay = calcPre.GetModifiedSequence(Peptide.Sequence, true);
            }
        }