private bool LoadSegment(NeSegment neSeg, ByteMemoryArea mem) { Array.Copy( RawImage, (uint)neSeg.DataOffset << this.cbFileAlignmentShift, mem.Bytes, neSeg.LinearAddress - (int)mem.BaseAddress.ToLinear(), neSeg.DataLength); AccessMode access = (neSeg.Flags & 1) != 0 ? AccessMode.ReadWrite : AccessMode.ReadExecute; var seg = this.segmentMap.AddSegment( mem, neSeg.Address !.Selector !.Value.ToString("X4"), access); var stg = new TemporaryStorage( string.Format("seg{0:X4}", seg.Address !.Selector !.Value), 0, PrimitiveType.SegmentSelector); seg.Identifier = Identifier.Create(stg); if ((neSeg.Flags & NE_STFLAGS_RELOCATIONS) == 0) { return(true); } var rdr = new LeImageReader( RawImage, neSeg.DataLength + ((uint)neSeg.DataOffset << this.cbFileAlignmentShift)); int count = rdr.ReadLeInt16(); return(ApplyRelocations(rdr, count, neSeg)); }
public void Run(AstNode compilationUnit) { // First determine all the namespaces that need to be imported: compilationUnit.AcceptVisitor(new FindRequiredImports(this), null); importedNamespaces.Add("System"); // always import System, even when not necessary if (context.Settings.UsingDeclarations) { // Now add using declarations for those namespaces: foreach (string ns in GetNamespacesInReverseOrder()) { // we go backwards (OrderByDescending) through the list of namespaces because we insert them backwards // (always inserting at the start of the list) string[] parts = ns.Split('.'); AstType nsType = new SimpleType(parts[0]).WithAnnotation(TextTokenType.NamespacePart); for (int i = 1; i < parts.Length; i++) { nsType = new MemberType { Target = nsType, MemberNameToken = Identifier.Create(parts[i]).WithAnnotation(TextTokenType.NamespacePart) }.WithAnnotation(TextTokenType.NamespacePart); } compilationUnit.InsertChildAfter(null, new UsingDeclaration { Import = nsType }, SyntaxTree.MemberRole); } } if (!context.Settings.FullyQualifyAmbiguousTypeNames) { return; } if (context.CurrentModule != null) { FindAmbiguousTypeNames(context.CurrentModule.Types, internalsVisible: true); var asmDict = new Dictionary <AssemblyDef, List <AssemblyDef> >(AssemblyEqualityComparer.Instance); foreach (var r in context.CurrentModule.GetAssemblyRefs()) { AssemblyDef d = context.CurrentModule.Context.AssemblyResolver.Resolve(r, context.CurrentModule); if (d == null) { continue; } List <AssemblyDef> list; if (!asmDict.TryGetValue(d, out list)) { asmDict.Add(d, list = new List <AssemblyDef>()); } list.Add(d); } foreach (var list in asmDict.Values) { FindAmbiguousTypeNames(GetTypes(list), internalsVisible: false); } } // verify that the SimpleTypes refer to the correct type (no ambiguities) compilationUnit.AcceptVisitor(new FullyQualifyAmbiguousTypeNamesVisitor(this), null); }
public IEnumerable <CodeAction> GetActions(RefactoringContext context) { var catchClause = context.GetNode <CatchClause>(); if (catchClause == null) { yield break; } if (!catchClause.Type.IsNull) { yield break; } yield return(new CodeAction(context.TranslateString("Add type specifier"), script => { var newType = context.CreateShortType("System", "Exception"); var namingHelper = new NamingHelper(context); var newIdentifier = Identifier.Create(namingHelper.GenerateVariableName(newType, "e")); script.Replace(catchClause, new CatchClause { Type = newType, VariableNameToken = newIdentifier, Body = catchClause.Body.Clone() as BlockStatement }); script.Select(newType); })); }
public override IEnumerable <CodeAction> GetActions(RefactoringContext context) { var entity = context.GetNode <ConstructorDeclaration>(); if (entity == null) { yield break; } var type = entity.Parent as TypeDeclaration; if (type == null || entity.Name == type.Name) { yield break; } var typeDeclaration = entity.GetParent <TypeDeclaration>(); yield return(new CodeAction(context.TranslateString("This is a constructor"), script => { script.Replace(entity.NameToken, Identifier.Create(typeDeclaration.Name, TextLocation.Empty)); }, entity)); yield return(new CodeAction(context.TranslateString("This is a void method"), script => { var generatedMethod = new MethodDeclaration(); generatedMethod.Modifiers = entity.Modifiers; generatedMethod.ReturnType = new PrimitiveType("void"); generatedMethod.Name = entity.Name; generatedMethod.Parameters.AddRange(entity.Parameters.Select(parameter => (ParameterDeclaration)parameter.Clone())); generatedMethod.Body = (BlockStatement)entity.Body.Clone(); generatedMethod.Attributes.AddRange(entity.Attributes.Select(attribute => (AttributeSection)attribute.Clone())); script.Replace(entity, generatedMethod); }, entity)); }
public void WhenIsValidWithKnownSupportedPrefix_ThenReturnsTrue() { this.factory.AddSupportedPrefix("another"); var result = this.factory.IsValid(Identifier.Create("another_123456789012")); result.Should().BeTrue(); }
public void Load_ConsumerInstanceContainer_ConsumerInstanceContainer() { var consumer = new TestConsumer { Name = "qux" }; Assert.AreEqual("TestConsumer[qux].Empty", Identifier.Create <TestConsumer, EmptyConfiguration>(consumer, c => c.Name).ToString()); }
public void IEquatable_SameProperties_Equal() { var path1 = Identifier.Create <TestConsumer, CData.Bar>(null, NameType.Simple); var path2 = Identifier.Create <TestConsumer, CData.Bar>(null, NameType.Simple); Assert.AreEqual(path1.GetHashCode(), path2.GetHashCode()); Assert.IsTrue(path1.Equals(path2)); }
public VariableInitializer(object nameAnnotation, string name, Expression initializer = null) { this.NameToken = Identifier.Create(name); if (nameAnnotation != null) { this.NameToken.AddAnnotation(nameAnnotation); } this.Initializer = initializer; }
public async Task WhenAddingNewEventPromoter_ShouldSucceed() { // SETUP Identifier id = Identifier.Create(); PromoterName name = new PromoterName($"test_{nameof(PromoterName)}"); // EXECUTE await this.useCase.Execute(id, name); }
public void WhenGetAndNotExists_ThenReturnsNull() { this.repository.Setup(repo => repo.Retrieve(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <RepositoryEntityMetadata>())) .Returns((CommandEntity)null); var result = this.storage.Get <TestDtoWithId>(Identifier.Create("anid")); result.Should().BeNull(); }
public void WhenAutoMapperMapsIdentifier_ThenMapsToStringValue() { var @object = new TestObject { StringValue = Identifier.Create("avalue") }; var result = @object.ConvertTo <TestDto>(); result.StringValue.Should().Be("avalue"); }
/// <summary> /// Ensures a register access in this function. /// </summary> /// <param name="reg"></param> /// <param name="name"></param> /// <param name="vt"></param> /// <returns></returns> public Identifier EnsureRegister(RegisterStorage reg) { Identifier?id = FindRegister(reg); if (id == null) { id = Identifier.Create(reg); identifiers.Add(id); } return(id); }
public void CommandId_Contains_Identifier() { var commandLine = new CommandLine { { Identifier.Empty, "baz" }, { Identifier.Empty, "qux" }, { Identifier.Create("foo"), "bar" }, }; Assert.AreEqual(Identifier.Create("baz"), commandLine.CommandId()); }
public void ToString_SameConsequtiveLiterals_Collapsed() { Assert.AreEqual( "foo.bar[baz]", Identifier.Create( Token.Literal("foo"), Token.Literal("foo"), Token.Literal("bar"), Token.Element("baz") ).ToString() ); }
public override object VisitSimpleType(SimpleType simpleType, object data) { // Handle type arguments first, so that the fixed-up type arguments get moved over to the MemberType, // if we're also creating one here. base.VisitSimpleType(simpleType, data); ITypeDefOrRef tr = simpleType.Annotation <ITypeDefOrRef>(); // Fully qualify any ambiguous type names. if (tr == null) { return(null); } var nss = GetNamespace(tr).ToString(); if (IsAmbiguous(nss, null, GetName(tr))) { AstType ns; if (string.IsNullOrEmpty(nss)) { ns = new SimpleType("global").WithAnnotation(TextTokenKind.Keyword); } else { string[] parts = nss.Split('.'); if (IsAmbiguous(string.Empty, parts[0], null)) { // conflict between namespace and type name/member name ns = new MemberType { Target = new SimpleType("global").WithAnnotation(TextTokenKind.Keyword), IsDoubleColon = true, MemberNameToken = Identifier.Create(parts[0]).WithAnnotation(TextTokenKind.NamespacePart) }.WithAnnotation(TextTokenKind.NamespacePart); } else { ns = new SimpleType(parts[0]).WithAnnotation(TextTokenKind.NamespacePart); } for (int i = 1; i < parts.Length; i++) { ns = new MemberType { Target = ns, MemberNameToken = Identifier.Create(parts[i]).WithAnnotation(TextTokenKind.NamespacePart) }.WithAnnotation(TextTokenKind.NamespacePart); } } MemberType mt = new MemberType(); mt.Target = ns; mt.IsDoubleColon = string.IsNullOrEmpty(nss); mt.MemberNameToken = (Identifier)simpleType.IdentifierToken.Clone(); mt.CopyAnnotationsFrom(simpleType); simpleType.TypeArguments.MoveTo(mt.TypeArguments); simpleType.ReplaceWith(mt); } return(null); }
public void WhenGet_ThenReturnsDto() { var dto = new TestDtoWithId { Id = "anid" }; this.repository.Setup(repo => repo.Retrieve(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <RepositoryEntityMetadata>())) .Returns(CommandEntity.FromType(dto)); var result = this.storage.Get <TestDtoWithId>(Identifier.Create("anid")); result.Id.Should().Be("anid"); }
public string Generate(ISymbol symbol) { if (symbol == null) { throw new ArgumentNullException("symbol"); } StringWriter writer = new StringWriter(); _writer = new TextWriterTokenWriter(writer); _policy = FormattingOptionsFactory.CreateMono(); TypeSystemAstBuilder astBuilder = CreateAstBuilder(); astBuilder.AlwaysUseShortTypeNames = true; AstNode node = astBuilder.ConvertSymbol(symbol); if (symbol is ITypeDefinition) { WriteTypeDeclarationName((ITypeDefinition)symbol, _writer, _policy); } else if (symbol is IMember) { WriteMemberDeclarationName((IMember)symbol, _writer, _policy); } else { _writer.WriteIdentifier(Identifier.Create(symbol.Name)); } if (HasParameters(symbol)) { _writer.WriteToken(symbol.SymbolKind == SymbolKind.Indexer ? Roles.LBracket : Roles.LPar, symbol.SymbolKind == SymbolKind.Indexer ? "[" : "("); IEnumerable <ParameterDeclaration> parameters = new List <ParameterDeclaration>(node.GetChildrenByRole(Roles.Parameter)); if (symbol is IMethod && ((IMethod)symbol).IsExtensionMethod) { parameters = parameters.Skip(1); } WriteCommaSeparatedList(parameters); _writer.WriteToken(symbol.SymbolKind == SymbolKind.Indexer ? Roles.RBracket : Roles.RPar, symbol.SymbolKind == SymbolKind.Indexer ? "]" : ")"); } if (_includePlaceholders) { _writer.WriteToken(Roles.Text, "$0"); } return(writer.ToString()); }
public async Task CanExecuteMultipleCommands() { var executeCount = 0; using (var context = CreateContext( commands => commands .Add(Identifier.Create("a"), Execute <SimpleBag>((i, b, c) => executeCount++)) .Add(Identifier.Create("b"), Execute <SimpleBag>((i, b, c) => executeCount++)) )) { await context.Executor.ExecuteAsync <object>("a|b", default); Assert.AreEqual(2, executeCount); } }
// on every class or member reference, use IdentifierCollectingVisitor's table to either add the correct mapping, or use intermediary public override void VisitIdentifier(Identifier identifier) { // If I'm in any methods, replace references to parameters foreach (EntityDeclaration method in identifier.Ancestors.OfType <MethodDeclaration>().Union <EntityDeclaration>(identifier.Ancestors.OfType <ConstructorDeclaration>())) { // Get the corresponding parameter name KeyValuePair <string, string> param = KeyValuePair.Create(IntermediaryWhenMapped(method.Name), identifier.Name); if (IdentifierCollectingVisitor.paramIntermediary.ContainsKey(param)) { identifier.ReplaceWith(Identifier.Create(GetMappedOrIntermediary(IdentifierCollectingVisitor.paramIntermediary[param]))); return; } } identifier.ReplaceWith(Identifier.Create(GetMappedOrIntermediary(identifier.Name))); }
public Identifier EnsureFlagGroup(FlagGroupStorage grf) { if (grf.FlagGroupBits == 0) { throw new ArgumentException("Argument must have non-zero flag group bits.", nameof(grf)); } var id = FindFlagGroup(grf.FlagRegister, grf.FlagGroupBits); if (id == null) { id = Identifier.Create(new FlagGroupStorage(grf.FlagRegister, grf.FlagGroupBits, grf.Name, grf.DataType)); identifiers.Add(id); } return(id); }
public Identifier EnsureFlagGroup(RegisterStorage freg, uint grfMask, string name, DataType dt) { if (grfMask == 0) { throw new ArgumentException("Argument must be non-zero.", nameof(grfMask)); } Identifier?id = FindFlagGroup(freg, grfMask); if (id == null) { id = Identifier.Create(new FlagGroupStorage(freg, grfMask, name, dt)); identifiers.Add(id); } return(id); }
public void Initialize() { this.logger = new Mock <ILogger>(); this.idFactory = new Mock <IIdentifierFactory>(); this.idFactory.Setup(idf => idf.Create(It.IsAny <IIdentifiableEntity>())) .Returns("anid".ToIdentifier); this.domainFactory = new Mock <IDomainFactory>(); this.domainFactory.Setup(df => df.RehydrateValueObject(typeof(Identifier), It.IsAny <string>())) .Returns((Type type, string value) => Identifier.Create(value)); this.repository = new Mock <IRepository>(); this.repository.Setup(repo => repo.Query(It.IsAny <string>(), It.IsAny <QueryClause <Checkpoint> >(), It.IsAny <RepositoryEntityMetadata>())) .Returns(new List <QueryEntity>()); this.store = new ReadModelCheckpointStore(this.logger.Object, this.idFactory.Object, this.domainFactory.Object, this.repository.Object); }
public async Task CanExecuteMultipleCommands() { var counters = new Dictionary <Identifier, int>(); using (var context = CreateContext( commands => commands .Add(Identifier.Create("a"), ExecuteHelper.Count <SimpleBag>(counters)) .Add(Identifier.Create("b"), ExecuteHelper.Count <SimpleBag>(counters)) )) { await context.Executor.ExecuteAsync <object>("a|b", default); Assert.Equal(1, counters["a"]); Assert.Equal(1, counters["b"]); } }
public async Task CanExecuteCommandByAnyName() { var executeCount = 0; using (var context = CreateContext( commands => commands .Add(Identifier.Create("a", "b"), Execute <SimpleBag>((name, bag, ct) => { executeCount++; })) )) { await context.Executor.ExecuteAsync <object>("a", default); await context.Executor.ExecuteAsync <object>("b", default); Assert.AreEqual(2, executeCount); } }
Identifier ReplaceBackingFieldUsage(Identifier identifier) { if (identifier.Name.StartsWith("<") && identifier.Name.EndsWith(">k__BackingField")) { var parent = identifier.Parent; var mrr = parent.Annotation <MemberResolveResult>(); var field = mrr?.Member as IField; if (field != null && field.IsCompilerGenerated()) { var propertyName = identifier.Name.Substring(1, identifier.Name.Length - 1 - ">k__BackingField".Length); var property = field.DeclaringTypeDefinition.GetProperties(p => p.Name == propertyName, GetMemberOptions.IgnoreInheritedMembers).FirstOrDefault(); if (property != null) { parent.RemoveAnnotations <MemberResolveResult>(); parent.AddAnnotation(new MemberResolveResult(mrr.TargetResult, property)); return(Identifier.Create(propertyName)); } } } return(null); }
void WriteTypeDeclarationName(ITypeDefinition typeDef, TextWriterTokenWriter formatter, CSharpFormattingOptions formattingPolicy) { TypeSystemAstBuilder astBuilder = CreateAstBuilder(); if (typeDef.DeclaringTypeDefinition != null) { WriteTypeDeclarationName(typeDef.DeclaringTypeDefinition, formatter, formattingPolicy); formatter.WriteToken(Roles.Dot, "."); } else if ((ConversionFlags & ConversionFlags.UseFullyQualifiedTypeNames) == ConversionFlags.UseFullyQualifiedTypeNames) { formatter.WriteIdentifier(Identifier.Create(typeDef.Namespace)); formatter.WriteToken(Roles.Dot, "."); } formatter.WriteIdentifier(Identifier.Create(typeDef.Name)); if ((ConversionFlags & ConversionFlags.ShowTypeParameterList) == ConversionFlags.ShowTypeParameterList) { var outputVisitor = new CSharpOutputVisitor(formatter, formattingPolicy); outputVisitor.WriteTypeParameters(astBuilder.ConvertEntity(typeDef).GetChildrenByRole(Roles.TypeParameter)); } }
public void Anpi_SelectProcedure() { codeViewSvc.Setup(s => s.DisplayProcedure( It.IsAny <Program>(), It.Is <Procedure>(proc => proc.Name == "foo_proc"), true)); Given_Interactor(); form.Object.Show(); Procedure p = new Procedure(program.Architecture, "foo_proc", Address.Ptr32(0x12346), program.Architecture.CreateFrame()); p.Signature = FunctionType.Func( Identifier.Create(Registers.eax), new Identifier("arg04", PrimitiveType.Word32, new StackArgumentStorage(4, PrimitiveType.Word32))); var p2 = new Procedure(program.Architecture, "bar", Address.Ptr32(0x12345), program.Architecture.CreateFrame()); program.Procedures.Add(p.EntryAddress, p); program.Procedures.Add(p2.EntryAddress, p2); interactor.EnterPage(); //form.BrowserList.Items[1].Selected = true; //form.BrowserList.FocusedItem = form.BrowserList.Items[1]; }
public static IRuleBuilderOptions <TDto, string> IsEntityId <TDto>(this IRuleBuilderInitial <TDto, string> rule, IIdentifierFactory identifierFactory) { return(rule.Must(id => id.HasValue() && identifierFactory.IsValid(Identifier.Create(id)))); }
bool CheckNamedResolveResult(ResolveResult resolveResult, AstNode node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty) { bool wasHandled = false; foreach (var rule in service.Rules) { if (!rule.AffectedEntity.HasFlag(entity)) { continue; } if (!rule.VisibilityMask.HasFlag(accessibilty)) { continue; } if (!rule.IncludeInstanceMembers || !rule.IncludeStaticEntities) { EntityDeclaration typeSystemEntity; if (node is VariableInitializer) { typeSystemEntity = node.Parent as EntityDeclaration; } else { typeSystemEntity = node as EntityDeclaration; } if (!rule.IncludeInstanceMembers) { if (typeSystemEntity == null || !typeSystemEntity.HasModifier(Modifiers.Static) || typeSystemEntity.HasModifier(Modifiers.Sealed)) { continue; } } if (!rule.IncludeStaticEntities) { if (typeSystemEntity == null || typeSystemEntity.HasModifier(Modifiers.Static) || typeSystemEntity.HasModifier(Modifiers.Sealed)) { continue; } } } wasHandled = true; if (!rule.IsValid(identifier.Name)) { IList <string> suggestedNames; var msg = rule.GetErrorMessage(ctx, identifier.Name, out suggestedNames); var actions = new List <CodeAction>(suggestedNames.Select(n => new CodeAction(string.Format(ctx.TranslateString("Rename to '{0}'"), n), (Script script) => { if (resolveResult == null) { resolveResult = ctx.Resolve(node); } if (resolveResult is MemberResolveResult) { script.Rename(((MemberResolveResult)resolveResult).Member, n); } else if (resolveResult is TypeResolveResult) { var def = ((TypeResolveResult)resolveResult).Type.GetDefinition(); if (def != null) { script.Rename(def, n); } else { script.RenameTypeParameter(((TypeResolveResult)resolveResult).Type, n); } } else if (resolveResult is LocalResolveResult) { script.Rename(((LocalResolveResult)resolveResult).Variable, n); } else { script.Replace(identifier, Identifier.Create(n)); } }))); if (entity != AffectedEntity.Namespace && entity != AffectedEntity.Label) { actions.Add(new CodeAction(string.Format(ctx.TranslateString("Rename '{0}'..."), identifier.Name), (Script script) => { if (resolveResult == null) { resolveResult = ctx.Resolve(node); } if (resolveResult is MemberResolveResult) { script.Rename(((MemberResolveResult)resolveResult).Member); } else if (resolveResult is TypeResolveResult) { var def = ((TypeResolveResult)resolveResult).Type.GetDefinition(); if (def != null) { script.Rename(def); } else { script.RenameTypeParameter(((TypeResolveResult)resolveResult).Type); } } else if (resolveResult is LocalResolveResult) { script.Rename(((LocalResolveResult)resolveResult).Variable); } })); } AddIssue(identifier, msg, actions); } } return(wasHandled); }
public UsingAliasDeclaration(string alias, AstType import) { AddChild(Identifier.Create (alias, AstLocation.Empty), AliasRole); AddChild(import, ImportRole); }