Example #1
0
        public bool Match(Slice slice)
        {
            BinaryExpression shift;
            id = slice.Expression as Identifier;
            if (id != null)
            {
                shift = ctx.GetValue(id) as BinaryExpression;
            }
            else
            {
                shift = slice.Expression as BinaryExpression;
            }
            if (shift == null)
                return false;
            if (shift.Operator != BinaryOperator.Shl)
                return false;
            Constant c = shift.Right as Constant;
            if (c == null)
                return false;
            if (c.ToInt32() != slice.Offset)
                return false;

            expr = shift.Left;
            dt = slice.DataType;
            return true;
        }
Example #2
0
 public ReflectedMethod(Identifier name, MethodBase method, Type targetType)
     : base(name, null, method, targetType)
 {
     DeclaringName = method.DeclaringType != targetType
         ? IdentifierFor.Method(method, method.DeclaringType)
         : name;
 }
Example #3
0
		public void UseCreate()
		{
			var id1 = new Identifier("foo", PrimitiveType.Word32, new TemporaryStorage("foo", 1, PrimitiveType.Word32));
			var use = new UseInstruction(id1);
			Assert.AreSame(id1, use.Expression);
			Assert.IsNull(use.OutArgument);
		}
Example #4
0
        public HashSet<Assign> findAssignment(Identifier i, HashSet<Statement> visitedNodes)
        {
            HashSet<Assign> assignStatements = new HashSet<Assign>();

            if (this is Assign && ((Assign)this).identifier.declaration == i.declaration)
            {
                assignStatements.Add((Assign)this);
                return assignStatements;
            }
            else if (this.cfgPredecessors.Count > 0)
            {
                foreach (Statement predecessor in this.cfgPredecessors)
                {
                    if (!(visitedNodes.Contains(predecessor)))
                    {
                        visitedNodes.Add(predecessor);
                        assignStatements.UnionWith(predecessor.findAssignment(i, visitedNodes));
                    }
                }

                return assignStatements;
            }
            else
            {
                throw new AccessException(i.row, i.col, "This value has not been initialised.");
            }
        }
Example #5
0
 public ExceptHandler(Exp type, Identifier name, SuiteStatement body, string filename, int start, int end)
     : base(filename, start, end)
 {
     this.type = type;
     this.name = name;
     this.body = body;
 }
		public override void WriteIdentifier(Identifier identifier)
		{
			var definition = GetCurrentDefinition();
			if (definition != null) {
				output.WriteDefinition(identifier.Name, definition, false);
				return;
			}
			
			object memberRef = GetCurrentMemberReference();

			if (memberRef != null) {
				output.WriteReference(identifier.Name, memberRef);
				return;
			}

			definition = GetCurrentLocalDefinition();
			if (definition != null) {
				output.WriteDefinition(identifier.Name, definition);
				return;
			}

			memberRef = GetCurrentLocalReference();
			if (memberRef != null) {
				output.WriteReference(identifier.Name, memberRef, true);
				return;
			}

			if (firstUsingDeclaration) {
				output.MarkFoldStart(defaultCollapsed: true);
				firstUsingDeclaration = false;
			}

			output.Write(identifier.Name);
		}
Example #7
0
 public DocumentedProperty(Identifier name, XmlNode xml, PropertyInfo property, Type targetType)
 {
     Property = property;
     Xml = xml;
     Name = name;
     TargetType = targetType;
 }
Example #8
0
 public PropertyIdentifier(string name, bool hasGet, bool hasSet, TypeIdentifier typeId)
     : base(name)
 {
     this.typeId = typeId;
     HasGet = hasGet;
     HasSet = hasSet;
 }
		public FunctionInvocationExpression(Identifier identifier, ExpressionNode[] arguments, bool hasStarModifier)
			: this()
		{
			_name = identifier;
			_arguments = arguments;
			_hasAsteriskModifier = hasStarModifier;
		}
 public static void GetXmlName( Member member, ref Identifier name, ref Identifier ns ) {
   AttributeList attrs = MetadataHelper.GetCustomAttributes( member, SystemTypes.XmlElementAttributeClass );
   if( attrs != null ) {
     for( int i = 0, n = attrs.Count; i < n; i++ ) {
       AttributeNode attr = attrs[i];
       if( attr == null ) continue;
       Literal litName = MetadataHelper.GetNamedAttributeValue(attr, idElementName);
       if (litName == null)
         litName = MetadataHelper.GetAttributeValue(attr,0);              
       Literal litNs = MetadataHelper.GetNamedAttributeValue(attr, idNamespace);
       name = (litName != null) ? Identifier.For(litName.Value as String) : Identifier.Empty;
       ns = (litNs != null) ? Identifier.For(litNs.Value as String) : Identifier.Empty;
       return;
     }
   }
   attrs = MetadataHelper.GetCustomAttributes( member, SystemTypes.XmlAttributeAttributeClass );
   if( attrs != null ) {
     for( int i2 = 0, n2 = attrs.Count; i2 < n2; i2++ ) {
       AttributeNode attr = attrs[i2];
       if( attr == null ) continue;
       Literal litName = MetadataHelper.GetNamedAttributeValue(attr, idElementName);
       if (litName == null)
         litName = MetadataHelper.GetAttributeValue(attr,0);              
       Literal litNs = MetadataHelper.GetNamedAttributeValue(attr, idNamespace);
       name = (litName != null) ? Identifier.For(litName.Value as String) : Identifier.Empty;
       ns = (litNs != null) ? Identifier.For(litNs.Value as String) : null;
       return;
     }
   }      
 }
Example #11
0
        public Control(ISensor sensor, ISettings settings, float minSoftwareValue,
            float maxSoftwareValue)
        {
            this.identifier = new Identifier(sensor.Identifier, "control");
              this.settings = settings;
              this.minSoftwareValue = minSoftwareValue;
              this.maxSoftwareValue = maxSoftwareValue;

              if (!float.TryParse(settings.GetValue(
              new Identifier(identifier, "value").ToString(), "0"),
            NumberStyles.Float, CultureInfo.InvariantCulture,
            out this.softwareValue))
              {
            this.softwareValue = 0;
              }
              int mode;
              if (!int.TryParse(settings.GetValue(
              new Identifier(identifier, "mode").ToString(),
              ((int)ControlMode.Default).ToString(CultureInfo.InvariantCulture)),
            NumberStyles.Integer, CultureInfo.InvariantCulture,
            out mode))
              {
            this.mode = ControlMode.Default;
              } else {
            this.mode = (ControlMode)mode;
              }
        }
Example #12
0
        public static WearingExpression New(string expression)
        {
            Identifier[] parsed;
            string[] parts = expression.Split(':');
            if (parts.Length == 1)
            {
                parsed = new Identifier[] { Identifier.Get(parts[0]) };
            }
            else if (parts.Length == 2)
            {
                Identifier first = Identifier.Get(parts[0]);
                string[] others;
                if (first == Identifier.DualWielding)
                {
                    others = parts[1].Split('-');
                }
                else
                {
                    others = parts[1].Split(',');
                }

                parsed = new Identifier[others.Length + 1];
                parsed[0] = first;
                for (int i = 0; i < others.Length; i++)
                {
                    parsed[i + 1] = Identifier.Get(others[i]);
                }
            }
            else
            {
                throw new FormatException();
            }

            return new WearingExpression(parsed);
        }
Example #13
0
 public Hardware(string name, Identifier identifier, ISettings settings) {
   this.settings = settings;
   this.identifier = identifier;
   this.name = name;
   this.customName = settings.GetValue(
     new Identifier(Identifier, "name").ToString(), name);
 }
Example #14
0
			/// <summary>
			/// Returns the value that matches the hash key given as the first given parameter.
			/// </summary>
			public override L20nObject Eval(LocaleContext ctx, params L20nObject[] argv)
			{
				if (m_Items.Count == 0 || argv.Length < 1)
				{
					return null;
				}
				
				var first = argv [0].Eval(ctx);
				
				Identifier id = first as Identifier;
				if (id == null)
				{
					var str = first as StringOutput;
					if (str == null)
					{
						Logger.Warning("Attributes: first variadic argument couldn't be evaluated as an <Identifier>");
						return id;
					}
					
					id = new Identifier(str.Value);
				}	
				
				L20nObject obj;
				if (!m_Items.TryGetValue(id.Value, out obj))
				{
					Logger.WarningFormat("{0} is not a valid <identifier>", id.Value);
					return null;
				}

				return obj;
			}
 /// <summary>
 ///     Initializes relationship navigation expression.
 /// </summary>
 internal RelshipNavigationExpr(Node refExpr, Node relshipTypeName, Identifier toEndIdentifier, Identifier fromEndIdentifier)
 {
     _refExpr = refExpr;
     _relshipTypeName = relshipTypeName;
     _toEndIdentifier = toEndIdentifier;
     _fromEndIdentifier = fromEndIdentifier;
 }
 /// <inheritdoc cref="NetworkingApiBuilder.UpdateNetworkAsync" />
 public Task<Network> UpdateNetworkAsync(Identifier networkId, NetworkDefinition network, CancellationToken cancellationToken = default(CancellationToken))
 {
     return _networkingApiBuilder
         .UpdateNetworkAsync(networkId, network, cancellationToken)
         .SendAsync()
         .ReceiveJson<Network>();
 }
Example #17
0
		public bool Match(BinaryExpression exp)
		{
			if (exp.Operator != Operator.IAdd)
				return false;
			id = exp.Left as Identifier;
			
			bin = exp.Right as BinaryExpression;
			if ((id == null || bin == null) && exp.Operator  == Operator.IAdd)
			{
				id = exp.Right as Identifier;
				bin = exp.Left as BinaryExpression;
			}
			if (id == null || bin == null)
				return false;

			if (bin.Operator != Operator.SMul && bin.Operator != Operator.UMul && bin.Operator != Operator.IMul)
				return false;

			Identifier idInner = bin.Left as Identifier;
			cInner = bin.Right as Constant;
			if (idInner == null ||cInner == null)
				return false;

			if (idInner != id)
				return false;

			return true;
		}
        public NamespaceSymbol(INamespaceParent parent, Identifier name, Func<NamespaceSymbol, IEnumerable<INamespaceMember>> members)
        {
            Parent = Guard.NotNull(parent, "parent");
            Name = Guard.NotNull(name, "name");

            Members = Guard.NotNull(members, "members")(this).ToArray();
        }
 /// <inheritdoc cref="NetworkingApiBuilder.GetNetworkAsync" />
 public Task<Network> GetNetworkAsync(Identifier networkId, CancellationToken cancellationToken = default(CancellationToken))
 {
     return _networkingApiBuilder
         .GetNetworkAsync(networkId, cancellationToken)
         .SendAsync()
         .ReceiveJson<Network>();
 }
        public void OutpReplaceManyUses()
        {
            ProcedureBuilder m = new ProcedureBuilder();
            Identifier foo = new Identifier("foo", PrimitiveType.Word32, null);
            Identifier bar = new Identifier("bar", PrimitiveType.Word32, null);
            Identifier pfoo = new Identifier("pfoo", PrimitiveType.Pointer32, null);

            Block block = m.Label("block");
            m.Assign(foo, 1);
            Statement stmFoo = m.Block.Statements.Last;
            m.Assign(bar, foo);
            Statement stmBar = m.Block.Statements.Last;

            SsaIdentifier ssaFoo = new SsaIdentifier(foo, foo, stmFoo, ((Assignment) stmFoo.Instruction).Src, false);
            ssaFoo.Uses.Add(stmBar);
            SsaIdentifier ssaBar = new SsaIdentifier(bar, bar, stmBar, ((Assignment) stmBar.Instruction).Src, false);

            SsaIdentifierCollection ssaIds = new SsaIdentifierCollection();
            ssaIds.Add(foo, ssaFoo);
            ssaIds.Add(bar, ssaBar);

            OutParameterTransformer opt = new OutParameterTransformer(m.Procedure, ssaIds);
            opt.ReplaceDefinitionsWithOutParameter(foo, pfoo);
            Assert.AreEqual(3, block.Statements.Count);
            Assert.AreEqual("foo = 0x00000001", block.Statements[0].Instruction.ToString());
            Assert.AreEqual("*pfoo = foo", block.Statements[1].Instruction.ToString());
            Assert.AreEqual("bar = foo", block.Statements[2].Instruction.ToString());
        }
Example #21
0
 public DocumentedField(Identifier name, XmlNode xml, FieldInfo field, Type targetType)
 {
     Field = field;
     Xml = xml;
     Name = name;
     TargetType = targetType;
 }
		public void Setup()
		{
            mem = new MemoryArea(Address.Ptr32(0x00100000), new byte[1024]);
            var arch = new FakeArchitecture();
            this.program = new Program
            {
                Architecture = arch,
                SegmentMap = new SegmentMap(
                    mem.BaseAddress,  
                    new ImageSegment(".text", mem, AccessMode.ReadWriteExecute)),
                Platform = new DefaultPlatform(null, arch),
            };
            store = program.TypeStore;
            factory = program.TypeFactory;
            globals = program.Globals;
			store.EnsureExpressionTypeVariable(factory, globals);

			StructureType s = new StructureType(null, 0);
			s.Fields.Add(0x00100000, PrimitiveType.Word32, null);

			TypeVariable tvGlobals = store.EnsureExpressionTypeVariable(factory, globals);
			EquivalenceClass eqGlobals = new EquivalenceClass(tvGlobals);
			eqGlobals.DataType = s;
			globals.TypeVariable.DataType = new Pointer(eqGlobals, 4);
			globals.DataType = globals.TypeVariable.DataType;
		}
		public void Setup()
		{
            var image = new LoadedImage(Address.Ptr32(0x00100000), new byte[1024]);
            var arch = new FakeArchitecture();
            var program = new Program
            {
                Image = image,
                Architecture = arch,
                ImageMap = image.CreateImageMap(),
                Platform = new DefaultPlatform(null, arch),
            };
            store = program.TypeStore;
            factory = program.TypeFactory;
            globals = program.Globals;
			store.EnsureExpressionTypeVariable(factory, globals);

			StructureType s = new StructureType(null, 0);
			s.Fields.Add(0x00100000, PrimitiveType.Word32, null);

			TypeVariable tvGlobals = store.EnsureExpressionTypeVariable(factory, globals);
			EquivalenceClass eqGlobals = new EquivalenceClass(tvGlobals);
			eqGlobals.DataType = s;
			globals.TypeVariable.DataType = new Pointer(eqGlobals, 4);
			globals.DataType = globals.TypeVariable.DataType;

            tcr = new TypedConstantRewriter(program);
		}
		public MethodParameterInfoContext(SourceLocation sourceLocation, int parameterIndex, Scope scope, Type expressionType, Identifier methodName)
			: base(sourceLocation, parameterIndex)
		{
			_scope = scope;
			_expressionType = expressionType;
			_methodName = methodName;
		}
Example #25
0
 public void Setup()
 {
     f = new Frame(PrimitiveType.Word16);
     argOff = f.EnsureStackArgument(4, PrimitiveType.Word16);
     argSeg = f.EnsureStackArgument(6, PrimitiveType.SegmentSelector);
     arg_alias = f.EnsureStackArgument(4, PrimitiveType.Pointer32);
 }
Example #26
0
 public void Setup()
 {
     mr = new MockRepository();
     program = new Program();
     proc = new Procedure("testProc", new Frame(PrimitiveType.Word32));
     block = proc.AddBlock("l00100000");
     trace = new RtlTrace(0x00100000);
     r0 = new Identifier("r0", PrimitiveType.Word32, new RegisterStorage("r0", 0, 0, PrimitiveType.Word32));
     r1 = new Identifier("r1", PrimitiveType.Word32, new RegisterStorage("r1", 1, 0, PrimitiveType.Word32));
     r2 = new Identifier("r2", PrimitiveType.Word32, new RegisterStorage("r2", 2, 0, PrimitiveType.Word32));
     sp = new Identifier("sp", PrimitiveType.Word32, new RegisterStorage("sp", 15, 0, PrimitiveType.Word32));
     grf = proc.Frame.EnsureFlagGroup(Registers.eflags, 3, "SCZ", PrimitiveType.Byte);
     var sc = new ServiceContainer();
     var listener = mr.Stub<DecompilerEventListener>();
     scanner = mr.StrictMock<IScanner>();
     arch = mr.Stub<IProcessorArchitecture>();
     program.Architecture = arch;
     program.SegmentMap = new SegmentMap(
         Address.Ptr32(0x00100000),
         new ImageSegment(
             ".text",
             new MemoryArea(Address.Ptr32(0x00100000), new byte[0x20000]),
             AccessMode.ReadExecute));
     arch.Replay();
     program.Platform = new DefaultPlatform(null, arch);
     arch.BackToRecord();
     arch.Stub(s => s.StackRegister).Return((RegisterStorage)sp.Storage);
     arch.Stub(s => s.PointerType).Return(PrimitiveType.Pointer32);
     scanner.Stub(s => s.Services).Return(sc);
     sc.AddService<DecompilerEventListener>(listener);
 }
 public PersonA(Identifier<int> id, string name, int age, int version)
 {
     _id = id;
       _name = name;
       _age = age;
       _version = version;
 }
		private Instruction Def(Identifier id, Expression src)
		{
			if (IsLocal(id))
				return new Store(new MemoryAccess(MemoryIdentifier.GlobalMemory, EffectiveAddress(id), id.DataType), src);
			else 
				return new Assignment(id, src);
		}
Example #29
0
		public LabelStatement(Identifier Label, Statement Labeled, TextSpan Location, TextPoint Colon)
			:base(Operation.Label,Location)
		{
			this.Label = Label;
			this.Labeled = Labeled;
			this.Colon = Colon;
		}
			void CheckName(TypeDeclaration node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty)
			{
				TypeResolveResult resolveResult = ctx.Resolve(node) as TypeResolveResult;
				if (resolveResult == null)
					return;
				var type = resolveResult.Type;
				if (type.DirectBaseTypes.Any(t => t.FullName == "System.Attribute")) {
					if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomAttributes, identifier, accessibilty)) {
						return;
					}
				} else if (type.DirectBaseTypes.Any(t => t.FullName == "System.EventArgs")) {
					if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomEventArgs, identifier, accessibilty)) {
						return;
					}
				} else if (type.DirectBaseTypes.Any(t => t.FullName == "System.Exception")) {
					if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomExceptions, identifier, accessibilty)) {
						return;
					}
				}

				var typeDef = type.GetDefinition();
				if (typeDef != null && typeDef.Attributes.Any(attr => attr.AttributeType.FullName == "NUnit.Framework.TestFixtureAttribute")) {
					if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.TestType, identifier, accessibilty)) {
						return;
					}
				}

				CheckNamedResolveResult(resolveResult, node, entity, identifier, accessibilty);
			}
 /// <inheritdoc cref="NetworkingApiBuilder.DeleteNetworkAsync" />
 public Task DeleteNetworkAsync(Identifier networkId, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(_networkingApiBuilder
            .DeleteNetworkAsync(networkId, cancellationToken)
            .SendAsync());
 }
Example #32
0
 public ODBCTranslatorTuple(SourceLineNumber sourceLineNumber, Identifier id = null) : base(TupleDefinitions.ODBCTranslator, sourceLineNumber, id)
 {
 }
Example #33
0
 public void ButtonPressed(Identifier layoutId, Location location, ButtonEvent buttonEvent)
 {
     MessageBox.Show($"Pressed: {layoutId} {location} {buttonEvent}");
 }
Example #34
0
 public static TSqlScript GetDeleteDb([NotNull] Identifier dbIdentifier)
 {
     return(new TSqlScript
     {
         Batches =
         {
             new TSqlBatch
             {
                 Statements =
                 {
                     new UseStatement
                     {
                         DatabaseName = new Identifier
                         {
                             Value = "master"
                         }
                     }
                 }
             },
             new TSqlBatch
             {
                 Statements =
                 {
                     new IfStatement
                     {
                         Predicate = new BooleanIsNullExpression
                         {
                             IsNot = true,
                             Expression = new FunctionCall
                             {
                                 FunctionName = new Identifier{
                                     Value = "DB_ID"
                                 },
                                 Parameters =   { new StringLiteral
                                                  {
                                                      Value = dbIdentifier.Value,
                                                      IsNational = true,
                                                  } }
                             }
                         },
                         ThenStatement = new BeginEndBlockStatement
                         {
                             StatementList = new StatementList
                             {
                                 Statements =
                                 {
                                     new AlterDatabaseSetStatement
                                     {
                                         DatabaseName = dbIdentifier,
                                         Options =
                                         {
                                             new DatabaseOption
                                             {
                                                 OptionKind = DatabaseOptionKind.SingleUser
                                             }
                                         },
                                         Termination = new AlterDatabaseTermination
                                         {
                                             ImmediateRollback = true
                                         },
                                     },
                                     new DropDatabaseStatement
                                     {
                                         Databases =
                                         {
                                             dbIdentifier
                                         },
                                     },
                                 }
                             }
                         }
                     },
                 }
             },
         }
     });
 }
Example #35
0
 private void Given_FramePointer(SsaProcedureBuilder m)
 {
     this.fp = m.Ssa.Identifiers.Add(m.Frame.FramePointer, null, null, false).Identifier;
 }
Example #36
0
 public override CallSite OnBeforeCall(Identifier sp, int returnAddressSize)
 {
     return(new CallSite(returnAddressSize, 0));
 }
Example #37
0
 public override void VisitIdentifier(Identifier id)
 {
     identifiers.Add(id);
 }
Example #38
0
 public HelpNamespaceSymbol(SourceLineNumber sourceLineNumber, Identifier id = null) : base(VSSymbolDefinitions.HelpNamespace, sourceLineNumber, id)
 {
 }
Example #39
0
        public override ActionResult OnProcess()
        {
            var hitBonus         = 0;
            var weapon           = Weapon.Get <RangeComponent>();
            var attackerName     = Identifier.GetNameOrId(Attacker);
            var defenderName     = Identifier.GetNameOrId(Defender);
            var attackerLocation = Attacker.Get <GameObject>();
            var defenderLocation = Defender.Get <GameObject>();

            //apply skill
            if (Attacker.Has <ControllerComponent>())
            {
                hitBonus += Attacker.Get <Creature>().Skills[weapon.Skill];
            }
            else
            {
                hitBonus += World.Mean;
            }

            if (weapon.ShotsRemaining <= 0)
            {
                Log.NormalFormat("{0} attempts to use the only to realize the weapon is not loaded",
                                 attackerName);
                return(ActionResult.Failed);
            }

            weapon.ShotsRemaining--;

            IEnumerable <Entity> entitiesOnPath;

            if (attackerLocation.Location == defenderLocation.Location)
            {
                // suicide?
                entitiesOnPath = attackerLocation.Level.GetEntitiesAt <BodyComponent>(defenderLocation.Location).ToList();
            }
            else
            {
                entitiesOnPath = GetTargetsOnPath(attackerLocation.Level, attackerLocation.Location, defenderLocation.Location).ToList();
            }

            int targetsInTheWay = 0;

            foreach (var currentEntity in entitiesOnPath)
            {
                var targetLocation = currentEntity.Get <GameObject>();

                double range        = targetLocation.DistanceTo(attackerLocation) * World.TileLengthInMeter;
                double rangePenalty = Math.Min(0, -World.StandardDeviation * RangePenaltyStdDevMultiplier * Math.Log(range) + World.StandardDeviation * 2 / 3);
                Logger.InfoFormat("Target: {2}, range to target: {0}, penalty: {1}", range, rangePenalty, defenderName);

                // not being targetted gives a sigma (std dev) penalty
                rangePenalty -= Defender.Id == currentEntity.Id ? 0 : World.StandardDeviation;

                int easeOfShot = (int)Math.Round(hitBonus + rangePenalty + (targetsInTheWay * RangePenaltyTileOccupied) + (TargettingPenalty ? BodyPartTargetted.TargettingPenalty : 0));
                Logger.InfoFormat("Ease of Shot: {0}, targetting penalty: {1}, weapon bonus: {2}, is original target: {3}",
                                  easeOfShot, BodyPartTargetted.TargettingPenalty, hitBonus,
                                  Defender.Id == currentEntity.Id);

                var result = Attack(attackerName, defenderName, easeOfShot);

                if (result == CombatEventResult.Hit)
                {
                    var damage = Math.Max(weapon.Damage.Roll(), 1);
                    int damageResistance, realDamage;

                    Damage(weapon.Damage.Roll(), weapon.Penetration, weapon.DamageType, out damageResistance, out realDamage);

                    Log.NormalFormat("{0} {1} {2}'s {3}.... and inflict {4} wounds.",
                                     attackerName, weapon.ActionDescriptionPlural, defenderName, BodyPartTargetted.Name, "todo-description");

                    Logger.Info(new CombatEventArgs(Attacker, Defender, Weapon, BodyPartTargetted, CombatEventResult.Hit, damage,
                                                    damageResistance, realDamage));
                    return(ActionResult.Success);
                }
                else if (result == CombatEventResult.Miss)
                {
                    if (Defender.Id == currentEntity.Id)                     // if this is where the actor targetted
                    {
                        Log.NormalFormat("{0} {1} {2}'s {3}.... and misses.",
                                         attackerName, weapon.ActionDescriptionPlural, defenderName, BodyPartTargetted.Name);
                    }

                    Logger.Info(new CombatEventArgs(Attacker, Defender, Weapon, BodyPartTargetted));
                    return(ActionResult.Failed);
                }
                else if (result == CombatEventResult.Dodge)
                {
                    if (Defender.Id == currentEntity.Id)                     // if this is where the actor targetted
                    {
                        Log.NormalFormat("{0} {1} {2}'s {3}.... and {2} dodges.",
                                         attackerName, weapon.ActionDescriptionPlural, defenderName, BodyPartTargetted.Name);
                    }

                    Logger.Info(new CombatEventArgs(Attacker, Defender, Weapon, BodyPartTargetted, CombatEventResult.Dodge));
                    return(ActionResult.Failed);
                }
                targetsInTheWay++;
            }

            // todo drop ammo casing

            Log.NormalFormat("{0} {1} and hits nothing", attackerName, weapon.ActionDescriptionPlural);
            return(ActionResult.Failed);
        }
 public bool EqualsTo(Identifier other) {
   return other._id == _id;
 }
Example #41
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="simulation">Simulation</param>
 /// <param name="posNode">Positive node</param>
 /// <param name="negNode">Negative (reference) node</param>
 public ComplexVoltageExport(Simulation simulation, Identifier posNode, Identifier negNode)
     : base(simulation)
 {
     PosNode = posNode ?? throw new ArgumentNullException(nameof(posNode));
     NegNode = negNode;
 }
Example #42
0
        private void GameplayWindow_KeyPressed(object sender, KeyboardEventArgs keyboardEvent)
        {
            var playerLocation = _player.Get <GameObject>();

            switch (keyboardEvent.KeyboardData.KeyCode)
            {
            case TCODKeyCode.Up:
            case TCODKeyCode.KeypadEight:                     // Up and 8 should have the same functionality
                Move(Direction.North);
                break;

            case TCODKeyCode.Down:
            case TCODKeyCode.KeypadTwo:
                Move(Direction.South);
                break;

            case TCODKeyCode.Left:
            case TCODKeyCode.KeypadFour:
                Move(Direction.West);
                break;

            case TCODKeyCode.KeypadFive:
                Enqueue(new WaitAction(_player));
                break;

            case TCODKeyCode.Right:
            case TCODKeyCode.KeypadSix:
                Move(Direction.East);
                break;

            case TCODKeyCode.KeypadSeven:
                Move(Direction.Northwest);
                break;

            case TCODKeyCode.KeypadNine:
                Move(Direction.Northeast);
                break;

            case TCODKeyCode.KeypadOne:
                Move(Direction.Southwest);
                break;

            case TCODKeyCode.KeypadThree:
                Move(Direction.Southeast);
                break;

            default:
            {
                if (keyboardEvent.KeyboardData.ControlKeys == ControlKeys.LeftControl || keyboardEvent.KeyboardData.ControlKeys == ControlKeys.RightControl)
                {
                    switch (keyboardEvent.KeyboardData.Character)
                    {
                    case 'r':
                    {
                        Enqueue(new ChangePostureAction(_player, Posture.Run));
                    }
                    break;

                    case 's':
                    {
                        Enqueue(new ChangePostureAction(_player, Posture.Stand));
                    }
                    break;

                    case 'c':
                    {
                        Enqueue(new ChangePostureAction(_player, Posture.Crouch));
                    }
                    break;

                    case 'p':
                    {
                        Enqueue(new ChangePostureAction(_player, Posture.Prone));
                    }
                    break;

                    case 'z':
                    {
                        Targets("Set AI of Entity", p =>
                                {
                                    var entitiesAtLocation = playerLocation.Level.GetEntitiesAt <ControllerComponent>(p).ToList();
                                    var npc     = entitiesAtLocation.First();
                                    var options = new List <Controller>
                                    {
                                        new DoNothing(),
                                        new NPC()
                                    };
                                    Options("What AI?",
                                            "No AI options.",
                                            options,
                                            o => o.GetType().Name,
                                            actor =>
                                    {
                                        var ap = npc.Get <ControllerComponent>().AP;
                                        npc.Remove <ControllerComponent>();
                                        npc.Add(new ControllerComponent(actor, ap));
                                    });
                                });
                    }
                    break;
                    }
                }
                else
                {
                    switch (keyboardEvent.KeyboardData.Character)
                    {
                    case 'A': {
                        Options("With that weapon?",
                                "No possible way of attacking.",
                                FilterEquippedItems <MeleeComponent>(_player).ToList(),
                                Identifier.GetNameOrId,
                                weapon => Directions("Attack where?",
                                                     p => Options("Attack where?",
                                                                  "Nothing at location to attack.",
                                                                  _player.Get <GameObject>().Level.GetEntitiesAt <BodyComponent, Creature>(p).ToList(),
                                                                  Identifier.GetNameOrId,
                                                                  defender => Options("Attack at what?",
                                                                                      String.Format("{0} has no possible part to attack.  How did we get here?", Identifier.GetNameOrId(defender)),
                                                                                      defender.Get <BodyComponent>().BodyPartsList,
                                                                                      bp => bp.Name,
                                                                                      bp => Enqueue(new MeleeAttackAction(_player,
                                                                                                                          defender,
                                                                                                                          weapon,
                                                                                                                          bp,
                                                                                                                          true))))));
                    }
                    break;

                    case 'f': {
                        Options("With what weapon?",
                                "No possible way of shooting target.",
                                FilterEquippedItems <RangeComponent>(_player).ToList(),
                                Identifier.GetNameOrId,
                                weapon => TargetsAt("Shoot where?",
                                                    World.TagManager.IsRegistered("target") ? World.TagManager.GetEntity("target").Get <GameObject>().Location : playerLocation.Location,
                                                    p => Options("Shoot at what?",
                                                                 "Nothing there to shoot.",
                                                                 _player.Get <GameObject>().Level.GetEntitiesAt <BodyComponent>(p),
                                                                 Identifier.GetNameOrId,
                                                                 delegate(Entity defender)
                                {
                                    World.TagManager.Register("target", defender);
                                    Enqueue(new RangeAttackAction(_player, defender, weapon, defender.Get <BodyComponent>().GetRandomPart()));
                                })));
                    }
                    break;

                    case 'F': {
                        Options("With what weapon?",
                                "No possible way of shooting target.",
                                FilterEquippedItems <RangeComponent>(_player).ToList(),
                                Identifier.GetNameOrId,
                                weapon => TargetsAt("Shoot where?",
                                                    World.TagManager.IsRegistered("target") ? World.TagManager.GetEntity("target").Get <GameObject>().Location : playerLocation.Location,
                                                    p => Options("Shoot at what?",
                                                                 "Nothing there to shoot.",
                                                                 _player.Get <GameObject>().Level.GetEntitiesAt <BodyComponent>(p),
                                                                 Identifier.GetNameOrId,
                                                                 defender => Options("What part?",
                                                                                     String.Format("{0} has no possible part to attack.  How did we get here?", Identifier.GetNameOrId(defender)),
                                                                                     defender.Get <BodyComponent>().BodyPartsList,
                                                                                     bp => bp.Name,
                                                                                     bp =>
                                {
                                    World.TagManager.Register("target", defender);
                                    Enqueue(new RangeAttackAction(_player, defender, weapon, bp, true));
                                }))));
                    }
                    break;

                    case 'r': {
                        Options("Reload what weapon?",
                                "No weapons to reload.",
                                FilterEquippedItems <RangeComponent>(_player).ToList(),
                                Identifier.GetNameOrId, weapon => Options("What ammo?",
                                                                          "No possible ammo for selected weapon.",
                                                                          _player.Get <ItemContainerComponent>().Items.Where(e => e.Has <AmmoComponent>() &&
                                                                                                                             e.Get <AmmoComponent>().Caliber == weapon.Get <RangeComponent>().AmmoCaliber).ToList(),
                                                                          Identifier.GetNameOrId,
                                                                          ammo => Enqueue(new ReloadAction(_player, weapon, ammo))));
                    }
                    break;

                    case 'u':
                        Directions("What direction?", p => Options("What object do you want to use?",
                                                                   "Nothing there to use.",
                                                                   playerLocation.Level.GetEntitiesAt <UseBroadcaster, VisibleComponent>(p).Where(e => e.Get <VisibleComponent>().VisibilityIndex > 0),
                                                                   Identifier.GetNameOrId,
                                                                   useable => Options(String.Format("Do what with {0}?", Identifier.GetNameOrId(useable)),
                                                                                      String.Format("No possible action on {0}", Identifier.GetNameOrId(useable)),
                                                                                      useable.Get <UseBroadcaster>().Actions.ToList(),
                                                                                      use => use.Description,
                                                                                      use => use.Use(_player, useable))));
                        break;

                    case 'd': {
                        var inventory = _player.Get <ItemContainerComponent>();
                        if (inventory.Count > 0)
                        {
                            ParentApplication.Push(new ItemWindow(new ItemWindowTemplate
                                    {
                                        Size             = MapPanel.Size,
                                        IsPopup          = true,
                                        HasFrame         = true,
                                        World            = World,
                                        Items            = inventory.Items,
                                        SelectSingleItem = false,
                                        ItemSelected     = i => DropItem(_player, i),
                                    }));
                        }
                        else
                        {
                            World.Log.Aborted("You are carrying no items to drop.");
                        }
                    }
                    break;

                    case 'g': {
                        var inventory = _player.Get <ItemContainerComponent>();

                        // get all items that have a location (eg present on the map) that are at the location where are player is
                        var items = playerLocation.Level.GetEntitiesAt <Item, VisibleComponent>(playerLocation.Location).Where(e => e.Get <VisibleComponent>().VisibilityIndex > 0 &&
                                                                                                                               !inventory.Items.Contains(e));

                        if (items.Count() > 0)
                        {
                            ParentApplication.Push(new ItemWindow(new ItemWindowTemplate
                                    {
                                        Size             = MapPanel.Size,
                                        IsPopup          = true,
                                        HasFrame         = true,
                                        World            = World,
                                        Items            = items,
                                        SelectSingleItem = false,
                                        ItemSelected     = i => PickUpItem(_player, i),
                                    }));
                        }
                        else
                        {
                            World.Log.Aborted("No items here to pick up.");
                        }
                    }
                    break;

                    case 'G': {
                        var inventory = _player.Get <ItemContainerComponent>();

                        // get all items that have a location (eg present on the map) that are at the location where are player is
                        var items = playerLocation.Level.GetEntitiesAt <Item, VisibleComponent>(playerLocation.Location).Where(e => e.Get <VisibleComponent>().VisibilityIndex > 0 &&
                                                                                                                               !inventory.Items.Contains(e));

                        if (items.Count() > 0)
                        {
                            Enqueue(new GetAllItemsAction(_player, items));
                        }
                        else
                        {
                            World.Log.Aborted("No items here to pick up.");
                        }
                    }
                    break;

                    case 'j': {
                        Directions("Jump what direction?", p => Enqueue(new JumpOverAction(_player, p - playerLocation.Location)));
                    }
                    break;

                    case 'i': {
                        var inventory = _player.Get <ItemContainerComponent>();
                        ParentApplication.Push(new ItemWindow(new ItemWindowTemplate
                                {
                                    Size             = MapPanel.Size,
                                    IsPopup          = true,
                                    HasFrame         = true,
                                    World            = World,
                                    Items            = inventory.Items,
                                    SelectSingleItem = false,
                                    ItemSelected     = i => World.Log.Normal(String.Format("This is a {0}, it weights {1}.", i.Get <Identifier>().Name, i.Get <Item>().Weight)),
                                }));
                    }
                    break;

                    case 'w':
                        ParentApplication.Push(new InventoryWindow(new InventoryWindowTemplate
                            {
                                Size     = MapPanel.Size,
                                IsPopup  = true,
                                HasFrame = true,
                                World    = World,
                                Items    = _player.Get <EquipmentComponent>().Slots.ToList(),
                            }));
                        break;

                    case 'p': {
                        Options("With what?",
                                "No lockpicks available.",
                                _player.Get <ItemContainerComponent>().Items.Where(i => i.Has <Lockpick>()),
                                Identifier.GetNameOrId,
                                lockpick => Directions("What direction?", p => Options("Select what to lockpick.",
                                                                                       "Nothing there to lockpick.",
                                                                                       _player.Get <GameObject>().Level.GetEntitiesAt <LockedFeature>(p),
                                                                                       Identifier.GetNameOrId,
                                                                                       feature => Enqueue(new LockpickAction(_player, lockpick, feature)))));
                    }
                    break;

                    case 'l':

                        ParentApplication.Push(
                            new LookWindow(
                                playerLocation.Location,
                                delegate(Point p)
                            {
                                StringBuilder sb       = new StringBuilder();
                                var entitiesAtLocation = playerLocation.Level.GetEntitiesAt(p);
                                sb.AppendLine(playerLocation.Level.GetTerrain(p).Definition);
                                foreach (var entity in entitiesAtLocation)
                                {
                                    sb.AppendFormat("Entity: {0} ", entity.Has <ReferenceId>() ? entity.Get <ReferenceId>().RefId : entity.Id.ToString());
                                    sb.AppendFormat("Name: {0} ", Identifier.GetNameOrId(entity));
                                    if (entity.Has <Scenery>())
                                    {
                                        sb.AppendFormat(entity.Get <Scenery>().ToString());
                                    }

                                    sb.AppendLine();
                                }

                                return(sb.ToString());
                            },
                                MapPanel,
                                PromptTemplate));
                        break;

                    case 'z':
                    {
                        _player.Get <ControllerComponent>().Cancel();
                    } break;

                    case '`': {
                        ParentApplication.Push(new DebugMenuWindow(new SkrWindowTemplate()
                                {
                                    World = World
                                }));
                    }
                    break;
                    }
                }
                break;
            }
            }
        }
Example #43
0
        /// <summary>
        /// Creates a new instance of this class that contains the CCI nodes for contract class.
        /// </summary>
        /// <param name="errorHandler">Delegate receiving errors. If null, errors are thrown as exceptions.</param>
        ///
        private ContractNodes(AssemblyNode assembly, Action <System.CodeDom.Compiler.CompilerError> errorHandler)
        {
            if (errorHandler != null)
            {
                this.ErrorFound += errorHandler;
            }

            AssemblyNode assemblyContainingContractClass = null;

            // Get the contract class and all of its members

            assemblyContainingContractClass = assembly;
            ContractClass = assembly.GetType(ContractNamespace, Identifier.For("Contract")) as Class;
            if (ContractClass == null)
            {
                // This is not a candidate, no warning as we try to find the right place where contracts live
                return;
            }

            ContractHelperClass = assembly.GetType(ContractInternalNamespace, Identifier.For("ContractHelper")) as Class;
            if (ContractHelperClass == null || !ContractHelperClass.IsPublic)
            {
                // look in alternate location
                var alternateNs = Identifier.For("System.Diagnostics.Contracts.Internal");
                ContractHelperClass = assembly.GetType(alternateNs, Identifier.For("ContractHelper")) as Class;
            }

            // Get ContractFailureKind

            ContractFailureKind = assemblyContainingContractClass.GetType(ContractNamespace, Identifier.For("ContractFailureKind")) as EnumNode;

            // Look for each member of the contract class

            var requiresMethods = ContractClass.GetMethods(RequiresName, SystemTypes.Boolean);

            for (int i = 0; i < requiresMethods.Count; i++)
            {
                var method = requiresMethods[i];
                if (method.TemplateParameters != null && method.TemplateParameters.Count == 1)
                {
                    // Requires<E>
                    RequiresExceptionMethod = method;
                }
                else if (method.TemplateParameters == null || method.TemplateParameters.Count == 0)
                {
                    RequiresMethod = method;
                }
            }

            // early test to see if the ContractClass we found has a Requires(bool) method. If it doesn't, we
            // silently think that this is not the right place.
            // We use this because contract reference assemblies have a Contract class, but it is not the right one, as it holds
            // just the 3 argument versions of all the contract methods.
            if (RequiresMethod == null)
            {
                ContractClass = null;
                return;
            }

            var requiresMethodsWithMsg = ContractClass.GetMethods(RequiresName, SystemTypes.Boolean, SystemTypes.String);

            for (int i = 0; i < requiresMethodsWithMsg.Count; i++)
            {
                var method = requiresMethodsWithMsg[i];
                if (method.TemplateParameters != null && method.TemplateParameters.Count == 1)
                {
                    // Requires<E>
                    RequiresExceptionWithMsgMethod = method;
                }

                else if (method.TemplateParameters == null || method.TemplateParameters.Count == 0)
                {
                    RequiresWithMsgMethod = method;
                }
            }

            EnsuresMethod = ContractClass.GetMethod(EnsuresName, SystemTypes.Boolean);

            EnsuresWithMsgMethod          = ContractClass.GetMethod(EnsuresName, SystemTypes.Boolean, SystemTypes.String);
            EnsuresOnThrowTemplate        = ContractClass.GetMethod(EnsuresOnThrowName, SystemTypes.Boolean);
            EnsuresOnThrowWithMsgTemplate = ContractClass.GetMethod(EnsuresOnThrowName, SystemTypes.Boolean, SystemTypes.String);

            InvariantMethod        = ContractClass.GetMethod(InvariantName, SystemTypes.Boolean);
            InvariantWithMsgMethod = ContractClass.GetMethod(InvariantName, SystemTypes.Boolean, SystemTypes.String);

            AssertMethod        = ContractClass.GetMethod(AssertName, SystemTypes.Boolean);
            AssertWithMsgMethod = ContractClass.GetMethod(AssertName, SystemTypes.Boolean, SystemTypes.String);

            AssumeMethod        = ContractClass.GetMethod(AssumeName, SystemTypes.Boolean);
            AssumeWithMsgMethod = ContractClass.GetMethod(AssumeName, SystemTypes.Boolean, SystemTypes.String);

            ResultTemplate = ContractClass.GetMethod(ResultName);

            TypeNode GenericPredicate = SystemTypes.SystemAssembly.GetType(
                Identifier.For("System"),
                Identifier.For("Predicate" + TargetPlatform.GenericTypeNamesMangleChar + "1"));

            if (GenericPredicate != null)
            {
                ForAllGenericTemplate = ContractClass.GetMethod(ForallName, SystemTypes.GenericIEnumerable, GenericPredicate);
                ExistsGenericTemplate = ContractClass.GetMethod(ExistsName, SystemTypes.GenericIEnumerable, GenericPredicate);

                if (ForAllGenericTemplate == null)
                {
                    // The problem might be that we are in the pre 4.0 scenario and using an out-of-band contract for mscorlib
                    // in which case the contract library is defined in that out-of-band contract assembly.
                    // If so, then ForAll and Exists are defined in terms of the System.Predicate defined in the out-of-band assembly.
                    var tempGenericPredicate = assemblyContainingContractClass.GetType(
                        Identifier.For("System"),
                        Identifier.For("Predicate" + TargetPlatform.GenericTypeNamesMangleChar + "1"));

                    if (tempGenericPredicate != null)
                    {
                        GenericPredicate = tempGenericPredicate;
                        TypeNode genericIEnum =
                            assemblyContainingContractClass.GetType(Identifier.For("System.Collections.Generic"),
                                                                    Identifier.For("IEnumerable" + TargetPlatform.GenericTypeNamesMangleChar + "1"));

                        ForAllGenericTemplate = ContractClass.GetMethod(ForallName, genericIEnum, GenericPredicate);
                        ExistsGenericTemplate = ContractClass.GetMethod(ExistsName, genericIEnum, GenericPredicate);
                    }
                }

                TypeNode PredicateOfInt = GenericPredicate.GetTemplateInstance(ContractClass, SystemTypes.Int32);
                if (PredicateOfInt != null)
                {
                    ForAllTemplate = ContractClass.GetMethod(ForallName, SystemTypes.Int32, SystemTypes.Int32, PredicateOfInt);
                    ExistsTemplate = ContractClass.GetMethod(ExistsName, SystemTypes.Int32, SystemTypes.Int32, PredicateOfInt);
                }
            }

            foreach (Member member in ContractClass.GetMembersNamed(ValueAtReturnName))
            {
                Method method = member as Method;
                if (method != null && method.Parameters.Count == 1)
                {
                    Reference reference = method.Parameters[0].Type as Reference;
                    if (reference != null && reference.ElementType.IsTemplateParameter)
                    {
                        ParameterTemplate = method;
                        break;
                    }
                }
            }

            foreach (Member member in ContractClass.GetMembersNamed(OldName))
            {
                Method method = member as Method;
                if (method != null && method.Parameters.Count == 1 && method.Parameters[0].Type.IsTemplateParameter)
                {
                    OldTemplate = method;
                    break;
                }
            }

            EndContract = ContractClass.GetMethod(EndContractBlockName);
            if (this.ContractFailureKind != null)
            {
                if (ContractHelperClass != null)
                {
                    RaiseFailedEventMethod = ContractHelperClass.GetMethod(ContractNodes.RaiseContractFailedEventName,
                                                                           this.ContractFailureKind, SystemTypes.String, SystemTypes.String, SystemTypes.Exception);

                    TriggerFailureMethod = ContractHelperClass.GetMethod(ContractNodes.TriggerFailureName,
                                                                         this.ContractFailureKind, SystemTypes.String, SystemTypes.String, SystemTypes.String, SystemTypes.Exception);
                }
            }

            // Get the attributes

            PureAttribute            = assemblyContainingContractClass.GetType(ContractNamespace, Identifier.For("PureAttribute")) as Class;
            InvariantMethodAttribute =
                assemblyContainingContractClass.GetType(ContractNamespace, Identifier.For("ContractInvariantMethodAttribute")) as Class;

            ContractClassAttribute =
                assemblyContainingContractClass.GetType(ContractNamespace, ContractClassAttributeName) as Class;

            ContractClassForAttribute =
                assemblyContainingContractClass.GetType(ContractNamespace, ContractClassForAttributeName) as Class;

            VerifyAttribute =
                assemblyContainingContractClass.GetType(ContractNamespace, Identifier.For("ContractVerificationAttribute")) as Class;
            SpecPublicAttribute =
                assemblyContainingContractClass.GetType(ContractNamespace, SpecPublicAttributeName) as Class;

            ReferenceAssemblyAttribute =
                assemblyContainingContractClass.GetType(ContractNamespace, Identifier.For("ContractReferenceAssemblyAttribute")) as Class;
            IgnoreAtRuntimeAttribute =
                assemblyContainingContractClass.GetType(ContractNamespace, RuntimeIgnoredAttributeName) as Class;

            // Check that every field in this class has been set

            foreach (System.Reflection.FieldInfo field in typeof(ContractNodes).GetFields())
            {
                if (field.GetValue(this) == null)
                {
                    string sig      = null;
                    bool   required = false;

                    object[] cas = field.GetCustomAttributes(typeof(RepresentationFor), false);
                    for (int i = 0, n = cas.Length; i < n; i++)
                    {
                        // should be exactly one
                        RepresentationFor rf = cas[i] as RepresentationFor;
                        if (rf != null)
                        {
                            sig      = rf.runtimeName;
                            required = rf.required;
                            break;
                        }
                    }

                    if (!required)
                    {
                        continue;
                    }

                    string msg = "Could not find contract node for '" + field.Name + "'";
                    if (sig != null)
                    {
                        msg = "Could not find the method/type '" + sig + "'";
                    }

                    if (ContractClass != null && ContractClass.DeclaringModule != null)
                    {
                        msg += " in assembly '" + ContractClass.DeclaringModule.Location + "'";
                    }

                    Module dm = ContractClass.DeclaringModule;

                    ClearFields();
                    CallErrorFound(dm, msg);

                    return;
                }
            }

            // Check that ContractFailureKind is okay

            if (this.ContractFailureKind.GetField(AssertName) == null ||
                this.ContractFailureKind.GetField(AssumeName) == null ||
                this.ContractFailureKind.GetField(InvariantName) == null ||
                this.ContractFailureKind.GetField(Identifier.For("Postcondition")) == null ||
                this.ContractFailureKind.GetField(Identifier.For("Precondition")) == null
                )
            {
                Module dm = ContractClass.DeclaringModule;

                ClearFields();
                CallErrorFound(dm, "The enum ContractFailureKind must have the values 'Assert', 'Assume', 'Invariant', 'Postcondition', and 'Precondition'.");
            }
        }
Example #44
0
 public void VisitIdentifier(Identifier id)
 {
     writer.Write(id.Name);
 }
Example #45
0
        public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            var response = Openid.GetResponse();

            if (response == null)
            {
                if (Identifier.TryParse(@params["oid"], out var id))
                {
                    try
                    {
                        IAuthenticationRequest request;

                        var realmUrlString = string.Empty;

                        if (@params.ContainsKey("realmUrl"))
                        {
                            realmUrlString = @params["realmUrl"];
                        }

                        if (!string.IsNullOrEmpty(realmUrlString))
                        {
                            request = Openid.CreateRequest(id, new Realm(realmUrlString));
                        }
                        else
                        {
                            request = Openid.CreateRequest(id);
                        }

                        request.AddExtension(new ClaimsRequest
                        {
                            Email      = DemandLevel.Require,
                            Nickname   = DemandLevel.Require,
                            Country    = DemandLevel.Request,
                            Gender     = DemandLevel.Request,
                            PostalCode = DemandLevel.Request,
                            TimeZone   = DemandLevel.Request,
                            FullName   = DemandLevel.Request,
                        });
                        var fetch = new FetchRequest();
                        fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                        //Duplicating attributes
                        fetch.Attributes.AddRequired("http://schema.openid.net/contact/email");//Add two more
                        fetch.Attributes.AddRequired("http://openid.net/schema/contact/email");
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.Alias);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Media.Images.Default);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.Middle);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Person.Gender);
                        fetch.Attributes.AddRequired(WellKnownAttributes.BirthDate.WholeBirthDate);
                        request.AddExtension(fetch);
                        request.RedirectToProvider();
                        //context.Response.End();//TODO This will throw thread abort
                    }
                    catch (ProtocolException ex)
                    {
                        return(LoginProfile.FromError(Signature, InstanceCrypto, ex));
                    }
                }
                else
                {
                    return(LoginProfile.FromError(Signature, InstanceCrypto, new Exception("invalid OpenID identifier")));
                }
            }
            else
            {
                // Stage 3: OpenID Provider sending assertion response
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    var spprofile    = response.GetExtension <ClaimsResponse>();
                    var fetchprofile = response.GetExtension <FetchResponse>();

                    var realmUrlString = string.Empty;
                    if (@params.ContainsKey("realmUrl"))
                    {
                        realmUrlString = @params["realmUrl"];
                    }

                    var profile = ProfileFromOpenId(spprofile, fetchprofile, response.ClaimedIdentifier.ToString(), realmUrlString);
                    return(profile);

                case AuthenticationStatus.Canceled:
                    return(LoginProfile.FromError(Signature, InstanceCrypto, new Exception("Canceled at provider")));

                case AuthenticationStatus.Failed:
                    return(LoginProfile.FromError(Signature, InstanceCrypto, response.Exception));
                }
            }
            return(null);
        }
Example #46
0
        public bool IsContractMethod(Identifier name, Method m, out TypeNode genericArg)
        {
            genericArg = null;
            if (m == null)
            {
                return(false);
            }

            if (m.Template != null)
            {
                if (m.TemplateArguments == null)
                {
                    return(false);
                }

                if (m.TemplateArguments.Count != 1)
                {
                    return(false);
                }

                genericArg = m.TemplateArguments[0];
                m          = m.Template;
            }

            if (m.Name == null)
            {
                return(false);
            }

            if (m.Name.UniqueIdKey != name.UniqueIdKey)
            {
                return(false);
            }

            if (m.DeclaringType == this.ContractClass)
            {
                return(true);
            }

            // Reference assemblies *always* use a three-argument method which is defined in the
            // reference assembly itself.
            // REVIEW: Could also check that the assembly m is defined in is marked with
            // the [ContractReferenceAssembly] attribute
            if (m.Parameters == null || m.Parameters.Count != 3)
            {
                return(false);
            }

            if (m.DeclaringType == null || m.DeclaringType.Namespace == null)
            {
                return(false);
            }

            if (m.DeclaringType.Namespace.Name == null ||
                m.DeclaringType.Namespace.Name != "System.Diagnostics.Contracts")
            {
                return(false);
            }

            if (m.DeclaringType.Name != null && m.DeclaringType.Name.Name == "Contract")
            {
                return(true);
            }

            return(false);
        }
Example #47
0
 public ModuleInstallUISequenceTuple(SourceLineNumber sourceLineNumber, Identifier id = null) : base(TupleDefinitions.ModuleInstallUISequence, sourceLineNumber, id)
 {
 }
Example #48
0
 public override CallSite OnBeforeCall(Identifier stackReg, int returnAddressSize)
 {
     throw new System.NotImplementedException();
 }
Example #49
0
 public DefInstruction(Identifier e)
 {
     Identifier = e;
 }
Example #50
0
 public override int GetHashCode()
 {
     unchecked {
         return(Identifier != null ? Identifier.GetHashCode() : 0);
     }
 }
Example #51
0
 public PropertiesSymbol(SourceLineNumber sourceLineNumber, Identifier id = null) : base(SymbolDefinitions.Properties, sourceLineNumber, id)
 {
 }
Example #52
0
 public void Match(Identifier id, Statement stm)
 {
     this.stmCur = stm;
     this.id     = id;
     stm.Instruction.Accept(this);
 }
Example #53
0
 public Expression VisitIdentifier(Identifier id)
 {
     return(ctx.GetValue(id));
 }
Example #54
0
 public UseInstruction(Expression e, Identifier argument)
 {
     this.Expression  = e;
     this.OutArgument = argument;
 }
Example #55
0
 public virtual void Visit(Identifier node)
 {
 }
Example #56
0
 public override CallSite OnBeforeCall(Identifier stackReg, int returnAddressSize)
 {
     return(new CallSite(0, 0));
 }
Example #57
0
 private bool Exist(Identifier id)
 {
     return(!(FindMember(id) is NullExpression));
 }
Example #58
0
 public static CharacterTable ComplexCharacterTable() => new CharacterTable
 {
     Entries = new List <ConversationCharacter>()
     {
         new ConversationCharacter()
         {
             ToaName  = Identifier.From("TOA1"),
             CharName = Identifier.From("NAM1"),
             CharCont = Identifier.From("CON1"),
             Entries  = new List <Info>()
             {
                 new Info()
                 {
                     LineSide       = LineSide.Right,
                     ConditionStart = 0x01010101,
                     ConditionEnd   = 0x02020202,
                     StringLabel    = Identifier.From("LAB1"),
                     StringIndex    = 0x14131211,
                     Frames         = new List <Frame>()
                     {
                         new Frame()
                         {
                             ToaAnimation         = 0x0101,
                             CharAnimation        = 0x0102,
                             CameraPositionTarget = 0x0103,
                             CameraDistance       = 0x0104,
                             StringIndex          = 0x0105,
                             ConversationSounds   = "SOUNDS1"
                         }
                     }
                 },
                 new Info()
                 {
                     LineSide       = LineSide.Left,
                     ConditionStart = 0x04040404,
                     ConditionEnd   = 0x08080808,
                     StringLabel    = Identifier.From("LAB2"),
                     StringIndex    = 0x24232221,
                     Frames         = new List <Frame>()
                     {
                         new Frame()
                         {
                             ToaAnimation         = 0x0201,
                             CharAnimation        = 0x0202,
                             CameraPositionTarget = 0x0203,
                             CameraDistance       = 0x0204,
                             StringIndex          = 0x0205,
                             ConversationSounds   = "SOUNDS2"
                         },
                         new Frame()
                         {
                             ToaAnimation         = 0x0301,
                             CharAnimation        = 0x0302,
                             CameraPositionTarget = 0x0303,
                             CameraDistance       = 0x0304,
                             StringIndex          = 0x0305,
                             ConversationSounds   = "SOUNDS3"
                         }
                     }
                 },
                 new Info()
                 {
                     LineSide       = LineSide.Right,
                     ConditionStart = 0x10101010,
                     ConditionEnd   = 0x20202020,
                     StringLabel    = Identifier.From("LAB3"),
                     StringIndex    = 0x34333231,
                     Frames         = new List <Frame>()
                     {
                         new Frame()
                         {
                             ToaAnimation         = 0x0401,
                             CharAnimation        = 0x0402,
                             CameraPositionTarget = 0x0403,
                             CameraDistance       = 0x0404,
                             StringIndex          = 0x0405,
                             ConversationSounds   = "SOUNDS4"
                         },
                         new Frame()
                         {
                             ToaAnimation         = 0x0501,
                             CharAnimation        = 0x0502,
                             CameraPositionTarget = 0x0503,
                             CameraDistance       = 0x0504,
                             StringIndex          = 0x0505,
                             ConversationSounds   = "SOUNDS5"
                         },
                         new Frame()
                         {
                             ToaAnimation         = 0x0601,
                             CharAnimation        = 0x0602,
                             CameraPositionTarget = 0x0603,
                             CameraDistance       = 0x0604,
                             StringIndex          = 0x0605,
                             ConversationSounds   = "SOUNDS6"
                         }
                     }
                 }
             }
         },
         new ConversationCharacter()
         {
             ToaName  = Identifier.From("TOA2"),
             CharName = Identifier.From("NAM2"),
             CharCont = Identifier.From("CON2"),
             Entries  = new List <Info>()
             {
                 new Info()
                 {
                     LineSide       = LineSide.Left,
                     ConditionStart = 0x40404040,
                     ConditionEnd   = 0x80808080,
                     StringLabel    = Identifier.From("LAB4"),
                     StringIndex    = 0x44434241,
                     Frames         = new List <Frame>()
                     {
                         new Frame()
                         {
                             ToaAnimation         = 0x0701,
                             CharAnimation        = 0x0702,
                             CameraPositionTarget = 0x0703,
                             CameraDistance       = 0x0704,
                             StringIndex          = 0x0705,
                             ConversationSounds   = "SOUNDS7"
                         }
                     }
                 },
                 new Info()
                 {
                     LineSide       = LineSide.Right,
                     ConditionStart = 0x11111111,
                     ConditionEnd   = 0x22222222,
                     StringLabel    = Identifier.From("LAB5"),
                     StringIndex    = 0x54535251,
                     Frames         = new List <Frame>()
                     {
                         new Frame()
                         {
                             ToaAnimation         = 0x0801,
                             CharAnimation        = 0x0802,
                             CameraPositionTarget = 0x0803,
                             CameraDistance       = 0x0804,
                             StringIndex          = 0x0805,
                             ConversationSounds   = "SOUNDS8"
                         }
                     }
                 }
             }
         },
         new ConversationCharacter()
         {
             ToaName  = Identifier.From("TOA3"),
             CharName = Identifier.From("NAM3"),
             CharCont = Identifier.From("CON3"),
             Entries  = new List <Info>()
             {
                 new Info()
                 {
                     LineSide       = LineSide.Left,
                     ConditionStart = 0x44444444,
                     ConditionEnd   = 0x88888888,
                     StringLabel    = Identifier.From("LAB6"),
                     StringIndex    = 0x64636261,
                     Frames         = new List <Frame>()
                     {
                         new Frame()
                         {
                             ToaAnimation         = 0x0901,
                             CharAnimation        = 0x0902,
                             CameraPositionTarget = 0x0903,
                             CameraDistance       = 0x0904,
                             StringIndex          = 0x0905,
                             ConversationSounds   = "SOUNDS9"
                         },
                         new Frame()
                         {
                             ToaAnimation         = 0x0A01,
                             CharAnimation        = 0x0A02,
                             CameraPositionTarget = 0x0A03,
                             CameraDistance       = 0x0A04,
                             StringIndex          = 0x0A05,
                             ConversationSounds   = "SOUNDSA"
                         },
                         new Frame()
                         {
                             ToaAnimation         = 0x0B01,
                             CharAnimation        = 0x0B02,
                             CameraPositionTarget = 0x0B03,
                             CameraDistance       = 0x0B04,
                             StringIndex          = 0x0B05,
                             ConversationSounds   = "SOUNDSB"
                         }
                     }
                 }
             }
         }
     }
 };
Example #59
0
 private bool IsSingleVariable(Identifier id)
 {
     return(id.Id.Count() == 1);
 }
Example #60
0
 public IWorld this[Identifier name] => _worlds[name];