private static Domain CalculateDomain(IVariable[] arguments) { if (arguments.All(a => a.IsBinary())) { return Domain.BinaryInteger; } if (IsDividingByConstant(arguments)) { if (arguments.All(a => a.IsInteger())) { if (arguments.All(a => a.IsPositiveOrZero() || a.IsBinary())) { return Domain.PositiveOrZeroInteger; } return Domain.AnyInteger; } else { if (arguments.All(a => a.IsPositiveOrZero() || a.IsBinary())) { return Domain.PositiveOrZeroReal; } return Domain.AnyReal; } } if (arguments.All(a => a.IsPositiveOrZero() || a.IsBinary())) { return Domain.PositiveOrZeroInteger; } return Domain.AnyInteger; }
public IVariable Set(IMilpManager milpManager, ConstraintType type, IVariable leftVariable, IVariable rightVariable) { IVariable any = milpManager.CreateAnonymous(Domain.AnyInteger); leftVariable.Set(ConstraintType.Equal,any.Operation(OperationType.Multiplication, rightVariable)); return leftVariable; }
public IVariable Set(IMilpManager milpManager, ConstraintType type, IVariable leftVariable, IVariable rightVariable) { switch (type) { case ConstraintType.Equal: milpManager.SetEqual(leftVariable, rightVariable); leftVariable.ConstantValue = rightVariable.ConstantValue ?? leftVariable.ConstantValue; rightVariable.ConstantValue = leftVariable.ConstantValue ?? rightVariable.ConstantValue; break; case ConstraintType.LessOrEqual: milpManager.SetLessOrEqual(leftVariable, rightVariable); break; case ConstraintType.GreaterOrEqual: milpManager.SetGreaterOrEqual(leftVariable, rightVariable); break; case ConstraintType.LessThan: milpManager.Operation(OperationType.IsLessThan, leftVariable, rightVariable) .Set(ConstraintType.Equal, milpManager.FromConstant(1)); break; case ConstraintType.GreaterThan: milpManager.Operation(OperationType.IsGreaterThan, leftVariable, rightVariable) .Set(ConstraintType.Equal, milpManager.FromConstant(1)); break; case ConstraintType.NotEqual: milpManager.Operation(OperationType.IsNotEqual, leftVariable, rightVariable) .Set(ConstraintType.Equal, milpManager.FromConstant(1)); break; default: throw new InvalidOperationException("Cannot set constraint"); } return leftVariable; }
private void AddVariable(IVariable v, bool isUsedByReference = false) { string n = _namer.GetVariableName(v.Name, _usedNames); _usedNames.Add(n); _result.Add(v, new VariableData(n, _currentMethod, isUsedByReference)); if (_isInsideLoop) _variablesDeclaredInsideLoop.Add(v); }
private static IEnumerable<IVariable> CalculateForVariable(IMilpManager milpManager, IVariable[] arguments, uint decompositionBase) { List<Tuple<IVariable, int>> variables = Enumerable.Range(0, GetDigitsCount(milpManager, decompositionBase)) .Select(i => { var baseRaised = (int)Math.Pow(decompositionBase, i); var variable = milpManager.CreateAnonymous(decompositionBase == 2 ? Domain.BinaryInteger : Domain.PositiveOrZeroInteger); if (decompositionBase > 2) { variable = variable.Set(ConstraintType.LessOrEqual,milpManager.FromConstant((int) decompositionBase - 1)); } return Tuple.Create(variable, baseRaised); }) .ToList(); milpManager.Operation(OperationType.Addition, variables.Select(v => v.Item1.Operation(OperationType.Multiplication, milpManager.FromConstant(v.Item2))) .ToArray()).Set(ConstraintType.Equal, arguments[0]); return variables.Select((v, index) => { var result = v.Item1; result.Expression = $"decomposition(digit: {index}, base: {decompositionBase}, {arguments[0].FullExpression()})"; return result; }); }
/// <summary> /// Default ctor /// </summary> public VariableStartEntry(int offset, Register register, IVariable variable, TypeReference type) : base(offset) { this.register = register; Variable = variable; name = variable.OriginalName; this.type = type; }
/// <summary> /// Constructor /// </summary> /// <param name="context"></param> /// <param name="statement"></param> /// <param name="variable"></param> /// <param name="explanation"></param> public InsertInListChange(InterpretationContext context, InsertStatement statement, IVariable variable, ExplanationPart explanation) : base(variable, null, null) { Context = context; Statement = statement; Explanation = explanation; }
public VariableState GetStatus (IVariable variable) { VariableState state; if (!states.TryGetValue (variable, out state)) return VariableState.None; return state; }
/// <summary> /// Constructor /// </summary> /// <param name="variable"></param> /// <param name="previousValue"></param> /// <param name="newValue"></param> public Change(IVariable variable, IValue previousValue, IValue newValue) { Variable = variable; PreviousValue = previousValue; NewValue = newValue; Applied = false; }
public ExpressionException(string message, int column, int length, IVariable variable) : base(message) { m_column = column; m_length = length; m_variable = variable; }
public VariableAggregationFilter(IVariable variable, [GreaterThan(0)]int stepSize, int minIndex, int maxIndex) { this.minIndex = minIndex; this.maxIndex = maxIndex; this.stepSize = stepSize; this.variable = variable; }
private IParameter AddParameter(IVariable variable) { var parameter = Owner.CreateParameter("value", variable.Type); Parameters.Add(parameter); return parameter; }
public override IVariable DivideVariableByConstant(IVariable variable, IVariable constant, Domain domain) { var newVariable = InternalDivideVariableByConstant(variable, constant, domain); newVariable.Domain = domain; newVariable.MilpManager = this; Variables[newVariable.Name] = newVariable; return newVariable; }
public IVariable Set(IMilpManager milpManager, CompositeConstraintType type, ICompositeConstraintParameters parameters, IVariable leftVariable, params IVariable[] rightVariable) { leftVariable.Operation(OperationType.DifferentValuesCount, rightVariable) .Set(ConstraintType.Equal, milpManager.FromConstant(rightVariable.Length + 1)); return leftVariable; }
private void cboSource_SelectedIndexChanged(object sender, EventArgs e) { string source = cboSource.Text; _variable = VariableFactory.Create(source); this.panel1.Controls.Clear(); this.panel1.Controls.Add(_variable.Editor); _variable.Editor.Dock = DockStyle.Fill; }
private ListViewItem CreateVariableItem(IVariable variable, IFrame frame) { var item = new ListViewItem(new string[4]); item.Tag = variable; item.UseItemStyleForSubItems = false; UpdateVariableItem(item, frame); return item; }
public LocalResolveResult(IVariable variable, IType type, object constantValue = null) : base(type) { if (variable == null) throw new ArgumentNullException("variable"); this.variable = variable; this.constantValue = constantValue; }
public IVariable[] CreateVariables() { var variables = new IVariable[Variables.Count]; for (int i = 0; i < variables.Length; i++) variables[i] = Variables[i].CreateVariable(); return variables; }
public void DefineVariable(string variable, IVariable value) { if(this.HasVariable(variable, false)) { throw new VariableAlreadyDefinedException("Variable \"" + variable + "\" has already been defined"); } this.variables[variable] = value; }
private object CreateBody(IVariable variable) { return new ForVariable { Name = variable.Name, Value = variable.Result, Timestamp = _clock.UtcNow }; }
public static bool AreEqualSearchTargets(IVariable t1, IVariable t2) { if (t1 != null && t2 != null) { return t1.Name == t2.Name && t1.Type == t2.Type; } return false; }
protected DebuggableAminoAcidBase(IGEPAminoAcid aminoAcid, IAminoAcidResult result, IRegistryCollection registries, IVariable resultingVariable, IDebuggableAminoAcidCollection arguments) { this.AminoAcid = aminoAcid; this.Result = result; this.Registries = registries; this.ResultingVariable = resultingVariable; this.Arguments = arguments; }
static IType UnpackTypeIfByRefParameter(IType type, IVariable v) { if (type.Kind == TypeKind.ByReference) { IParameter p = v as IParameter; if (p != null && (p.IsRef || p.IsOut)) return ((ByReferenceType)type).ElementType; } return type; }
public IVariable Set(IMilpManager milpManager, CompositeConstraintType type, ICompositeConstraintParameters parameters, IVariable leftVariable, params IVariable[] rightVariable) { rightVariable.Aggregate(milpManager.FromConstant(0), (current, variable) => current.Operation(OperationType.Addition, leftVariable.Operation(OperationType.IsEqual, variable))).Create() .Set(ConstraintType.Equal, milpManager.FromConstant(0)); return leftVariable; }
public VariableCompletionData(IVariable variable) : base() { if (variable == null) throw new ArgumentException("variable"); Variable = variable; Ambience.ConversionFlags = ConversionFlags.StandardConversionFlags; DisplayText = CompletionText = variable.Name; Description = Ambience.ConvertVariable(variable); Image = CompletionImage.Field.BaseImage; }
public VariableSetter(IElementCreationContext context, Guid variableId) : base(context) { if (variableId == Guid.Empty) throw new ArgumentException("variableId was default value.", nameof(variableId)); _variable = context.Owner.GetVariableOrThrow(variableId); _variable.NameChanged += VariableNameChanged; _parameter = AddParameter(_variable); }
public IDocument CreateDocument(IVariable sparkVariable, string index, string type) { object body = CreateBody(sparkVariable); return new Instance { IndexName = index, Type = type, Body = SerializeBody(body) }; }
protected static bool FindUsage (BaseRefactoringContext context, SyntaxTree unit, IVariable variable, AstNode declaration) { var found = false; refFinder.FindLocalReferences (variable, context.UnresolvedFile, unit, context.Compilation, (node, resolveResult) => { found = found || node != declaration; }, context.CancellationToken); return found; }
public void OnAttach(MachineInstance machine, out IVariable[] variables, out MethodInfo[] methods, out IRuntimeContextInstance instance) { variables = new IVariable[this.Count]; for (int i = 0; i < variables.Length; i++) { variables[i] = Variable.CreateContextPropertyReference(this, i); } methods = new MethodInfo[0]; instance = this; }
public VariableCompletionData(IVariable variable) { if (variable == null) throw new ArgumentNullException("variable"); Variable = variable; IAmbience ambience = new CSharpAmbience(); DisplayText = variable.Name; Description = ambience.ConvertVariable(variable); CompletionText = Variable.Name; this.Image = CompletionImage.Field.BaseImage; }
public PiExpression(IVariable v, Expression t, Expression e) { V = v; T = t; E = e; }
public static VariableExpression Var(IVariable variable) => new VariableExpression(variable);
public static LambdaExpression Lambda(IVariable v, Expression a, Expression b) => new LambdaExpression(v, a, b);
internal void LinkVariable(string name, IVariable v, Location location) { name = !string.IsNullOrWhiteSpace(name) ? name : throw new ArgumentException(nameof(name)); _variables[name] = new Variable(name, v, location); }
/// <summary> /// Return list of validations for composite type. /// </summary> /// <param name="p"></param> /// <param name="name"></param> /// <param name="method"></param> /// <param name="ancestors"></param> /// <param name="isCompositeProperties"></param> /// <returns></returns> public static List <string> ValidateCompositeType(this IVariable p, string name, HttpMethod method, HashSet <string> ancestors, bool isCompositeProperties = false) { List <string> x = new List <string>(); if (method != HttpMethod.Patch || !p.IsBodyParameter() || isCompositeProperties) { foreach (var prop in ((CompositeType)p.ModelType).Properties.Cast <PropertyGo>()) { var primary = prop.ModelType as PrimaryType; var sequence = prop.ModelType as SequenceType; var map = prop.ModelType as DictionaryTypeGo; var composite = prop.ModelType as CompositeType; var propName = prop.FieldName; if (primary != null || sequence != null || map != null) { x.AddRange(prop.ValidateType($"{name}.{propName}", method, true)); } else if (composite != null) { if (composite.IsPolymorphic) { // we do not generate validation for the polymophic types for now. // There is an issue in go-autorest that causes that we could not properly handle null value of a polymophic type continue; } if (ancestors.Contains(composite.Name)) { x.AddNullValidation($"{name}.{propName}", p.ModelTypeName, p.IsRequired); } else { ancestors.Add(composite.Name); x.AddRange(prop.ValidateCompositeType($"{name}.{propName}", method, ancestors, true)); ancestors.Remove(composite.Name); } } } } List <string> y = new List <string>(); if (x.Count > 0) { if (p.CheckNull() || isCompositeProperties) { y.AddRange(x.AddChain(name, p.ModelTypeName, NullConstraint, p.IsRequired)); } else { y.AddRange(x); } } else { if (p.IsRequired && (p.CheckNull() || isCompositeProperties)) { y.AddNullValidation(name, p.ModelTypeName, p.IsRequired); } } return(y); }
protected override bool IsTargetVariable(IVariable variable) { return(variable.Type.GetAllBaseTypeDefinitions().Any(t => t.KnownTypeCode == KnownTypeCode.IDisposable)); }
public static void Add(List <IdRegion> regions, Microsoft.Dafny.Program prog, Bpl.IToken tok, IVariable v, bool isDefinition, string kind, ICallable callableContext, ModuleDefinition context) { Contract.Requires(regions != null); Contract.Requires(prog != null); Contract.Requires(tok != null); Contract.Requires(v != null); if (InMainFileAndUserDefined(prog, tok)) { regions.Add(new IdRegion(tok, v, isDefinition, kind, callableContext, context)); } }
public static void Add(List <IdRegion> regions, Microsoft.Dafny.Program prog, Bpl.IToken tok, IVariable v, bool isDefinition, ICallable callableContext, ModuleDefinition context) { Contract.Requires(regions != null); Contract.Requires(prog != null); Contract.Requires(tok != null); Contract.Requires(v != null); Add(regions, prog, tok, v, isDefinition, null, callableContext, context); }
public SUBTRACT_Instruction(MonoLangParser.VarContext varContext, MonoLangParser.ExpressionContext[] expressionContext) { _variable = VariableFactory.BuildVariable(varContext); _expression = ExpressionFactory.BuildExpression(expressionContext[0]); }
public IList <ReferenceResult> FindReferences(AstNode rootNode, IVariable variable) { return(referenceFinder.FindReferences(rootNode, variable)); }
/// <summary> /// Find all properties from the model and fill this.properties. /// </summary> /// <param name="model">The mode object</param> protected virtual List <IVariable> FindAllProperties(object model) { List <IVariable> properties = new List <IVariable>(); bool filterByCategory = !((this.CategoryFilter == "") || (this.CategoryFilter == null)); bool filterBySubcategory = !((this.SubcategoryFilter == "") || (this.SubcategoryFilter == null)); if (model != null) { var orderedMembers = GetMembers(model); foreach (MemberInfo member in orderedMembers) { IVariable property = null; if (member is PropertyInfo) { property = new VariableProperty(model, member as PropertyInfo); } else if (member is FieldInfo) { property = new VariableField(model, member as FieldInfo); } if (property != null && property.Description != null && property.Writable) { // Only allow lists that are double[], int[], string[] or DateTime[] bool includeProperty = true; if (property.DataType.GetInterface("IList") != null) { includeProperty = true; } if (Attribute.IsDefined(member, typeof(SeparatorAttribute))) { SeparatorAttribute[] separators = Attribute.GetCustomAttributes(member, typeof(SeparatorAttribute)) as SeparatorAttribute[]; foreach (SeparatorAttribute separator in separators) { properties.Add(new VariableObject(separator.ToString())); // use a VariableObject for separators } } //If the above conditions have been met and, //If a CategoryFilter has been specified. //filter only those properties with a [Catagory] attribute that matches the filter. if (includeProperty && filterByCategory) { bool hasCategory = Attribute.IsDefined(member, typeof(CategoryAttribute), false); if (hasCategory) { CategoryAttribute catAtt = (CategoryAttribute)Attribute.GetCustomAttribute(member, typeof(CategoryAttribute)); if (catAtt.Category == this.CategoryFilter) { if (filterBySubcategory) { //the catAtt.Subcategory is by default given a value of //"Unspecified" if the Subcategory is not assigned in the Category Attribute. //so this line below will also handle "Unspecified" subcategories. includeProperty = (catAtt.Subcategory == this.SubcategoryFilter); } else { includeProperty = true; } } else { includeProperty = false; } } else { //if we are filtering on "Unspecified" category then there is no Category Attribute // just a Description Attribute on the property in the model. //So we still may need to include it in this case. if (this.CategoryFilter == "Unspecified") { includeProperty = true; } else { includeProperty = false; } } } if (ScalarsOnly && property.DataType.IsArray) { includeProperty = false; } if (property.Display != null && property.Display.Type == DisplayType.SubModel && property.Value != null) { includeProperty = false; properties.AddRange(FindAllProperties(property.Value)); } if (includeProperty) { properties.Add(property); } if (property.DataType == typeof(DataTable)) { grid.DataSource = property.Value as DataTable; } } } } return(properties); }
public virtual void Resize(int size1, int size2, IEnumerable <double> xCoordinates, IEnumerable <double> yCoordinates) { // TODO: extend to non-memory stores if (Arguments.Count == 0) { Components.Add(new Variable <double>("value")); // created argument variables index1 = new Variable <int>("index1") { FixedSize = size1, GenerateUniqueValueForDefaultValue = true }; index2 = new Variable <int>("index2") { FixedSize = size2, GenerateUniqueValueForDefaultValue = true }; // add arguments Arguments.Add(index1); Arguments.Add(index2); } index1.FixedSize = size1; index1.Values.Resize(size1); index2.FixedSize = size2; index2.Values.Resize(size2); if (x == null) { // setup points as a 2d variable x = new Variable <double>("x") { Arguments = { index1, index2 }, FixedSize = size1 * size2 }; // actually x, y are components: F = (value, x, y)(i, j) or even as IVariable<IPoint> y = new Variable <double>("y") { Arguments = { index1, index2 }, FixedSize = size1 * size2 }; } var newShape = new[] { size1, size2 }; x.FixedSize = size1 * size2; x.Values.Resize(newShape); y.FixedSize = size1 * size2; y.Values.Resize(newShape); foreach (var v in Components) { if (IsTimeDependent) { v.Values.Resize(new [] { 0, size1, size2 }); } else { v.Values.Resize(newShape); } } if (xCoordinates != null && yCoordinates != null) { x.SetValues(xCoordinates); y.SetValues(yCoordinates); } faces = null; // reset }
/// <summary> /// Creates a new variable dependency. /// </summary> /// <param name="variable">The variable to depend on.</param> public VariableDependency(IVariable variable) { Variable = variable ?? throw new ArgumentNullException(nameof(variable)); }
internal IOperand CompileIFFLAG([NotNull] IRoutineBuilder rb, [NotNull] ZilListoidBase clauses, [NotNull] ISourceLine src, bool wantResult, [CanBeNull] IVariable resultStorage) { resultStorage = resultStorage ?? rb.Stack; while (!clauses.IsEmpty) { ZilObject clause; (clause, clauses) = clauses; if (!(clause is ZilListoidBase list) || list.IsEmpty) { throw new CompilerError(CompilerMessages.All_Clauses_In_0_Must_Be_Lists, "IFFLAG"); } var(flag, body) = list; ZilObject value; bool match, isElse = false; ZilAtom shadyElseAtom = null; switch (flag) { case ZilAtom atom when(value = Context.GetCompilationFlagValue(atom)) != null: case ZilString str when(value = Context.GetCompilationFlagValue(str.Text)) != null: // name of a defined compilation flag match = value.IsTrue; break; case ZilForm form: form = Subrs.SubstituteIfflagForm(Context, form); match = ((ZilObject)form.Eval(Context)).IsTrue; break; case ZilAtom atom when atom.StdAtom != StdAtom.ELSE && atom.StdAtom != StdAtom.T: shadyElseAtom = atom; goto default; default: match = isElse = true; break; } // does this clause match? if (!match) { continue; } // emit code for clause var clauseResult = CompileClauseBody(rb, body, wantResult, resultStorage); // warn if this is an else clause and there are more clauses below if (!isElse || clauses.IsEmpty) { return(wantResult ? clauseResult : null); } var warning = new CompilerError(src, CompilerMessages._0_Clauses_After_Else_Part_Will_Never_Be_Evaluated, "IFFLAG"); if (shadyElseAtom != null) { // if the else clause wasn't introduced with ELSE or T, it might not have been meant as an else clause warning = warning.Combine(new CompilerError( flag.SourceLine, CompilerMessages.Undeclared_Compilation_Flag_0, shadyElseAtom)); } Context.HandleError(warning); return(wantResult ? clauseResult : null); } // no matching clauses if (wantResult) { rb.EmitStore(resultStorage, Game.Zero); } return(wantResult ? resultStorage : null); }
// public static implicit operator VariableExpression(IVariable variable) => new VariableExpression(variable); public void Deconstruct(out IVariable variable) { variable = Variable; }
internal IOperand CompileVERSION_P([NotNull] IRoutineBuilder rb, [NotNull] ZilListoidBase clauses, [NotNull] ISourceLine src, bool wantResult, [CanBeNull] IVariable resultStorage) { resultStorage = resultStorage ?? rb.Stack; while (!clauses.IsEmpty) { ZilObject clause; (clause, clauses) = clauses; if (!(clause is ZilListoidBase list) || list.IsEmpty) { throw new CompilerError(CompilerMessages.All_Clauses_In_0_Must_Be_Lists, "VERSION?"); } var(condition, body) = list; // check version condition int condVersion; switch (condition) { case ZilAtom atom: // ReSharper disable once SwitchStatementMissingSomeCases switch (atom.StdAtom) { case StdAtom.ZIP: condVersion = 3; break; case StdAtom.EZIP: condVersion = 4; break; case StdAtom.XZIP: condVersion = 5; break; case StdAtom.YZIP: condVersion = 6; break; case StdAtom.ELSE: case StdAtom.T: condVersion = 0; break; default: throw new CompilerError(CompilerMessages.Unrecognized_Atom_In_VERSION_Must_Be_ZIP_EZIP_XZIP_YZIP_ELSET); } break; case ZilFix fix: condVersion = fix.Value; if (condVersion < 3 || condVersion > 8) { throw new CompilerError(CompilerMessages.Version_Number_Out_Of_Range_Must_Be_38); } break; default: throw new CompilerError(CompilerMessages.Conditions_In_In_VERSION_Clauses_Must_Be_Atoms); } // does this clause match? if (condVersion != Context.ZEnvironment.ZVersion && condVersion != 0) { continue; } // emit code for clause var clauseResult = CompileClauseBody(rb, body, wantResult, resultStorage); if (condVersion == 0 && !clauses.IsEmpty) { Context.HandleError(new CompilerError(src, CompilerMessages._0_Clauses_After_Else_Part_Will_Never_Be_Evaluated, "VERSION?")); } return(wantResult ? clauseResult : null); } // no matching clauses if (wantResult) { rb.EmitStore(resultStorage, Game.Zero); } return(wantResult ? resultStorage : null); }
public VariableExpression(IVariable variable) { this.Variable = variable; }
internal IOperand CompileCOND([NotNull] IRoutineBuilder rb, [NotNull] ZilListoidBase clauses, [NotNull] ISourceLine src, bool wantResult, [CanBeNull] IVariable resultStorage) { var nextLabel = rb.DefineLabel(); var endLabel = rb.DefineLabel(); bool elsePart = false; resultStorage = resultStorage ?? rb.Stack; while (!clauses.IsEmpty) { ZilObject clause, origCondition, condition; ZilListoidBase body; (clause, clauses) = clauses; clause = clause.Unwrap(Context); switch (clause) { case ZilFalse _: // previously, FALSE was only allowed when returned by a macro call, but now we expand macros before generating any code continue; case ZilListoidBase list when list.IsEmpty: default: throw new CompilerError(CompilerMessages.All_Clauses_In_0_Must_Be_Lists, "COND"); case ZilListoidBase list: (origCondition, body) = list; condition = origCondition.Unwrap(Context); break; } // if condition is always true (i.e. not a FORM or a FALSE), this is the "else" part switch (condition) { case ZilForm _: // must be evaluated MarkSequencePoint(rb, condition); CompileCondition(rb, condition, condition.SourceLine, nextLabel, false); break; case ZilFalse _: // never true if (!(origCondition is ZilMacroResult)) { Context.HandleError(new CompilerError(condition, CompilerMessages._0_Condition_Is_Always_1, "COND", "false")); } continue; case ZilAtom atom when atom.StdAtom == StdAtom.T || atom.StdAtom == StdAtom.ELSE: // non-shady else part elsePart = true; break; default: // shady else part (always true, but not T or ELSE) Context.HandleError(new CompilerError(condition, CompilerMessages._0_Condition_Is_Always_1, "COND", "true")); elsePart = true; break; } // emit code for clause var clauseResult = CompileClauseBody(rb, body, wantResult, resultStorage); if (wantResult && clauseResult != resultStorage) { rb.EmitStore(resultStorage, clauseResult); } // jump to end if (!clauses.IsEmpty || wantResult && !elsePart) { rb.Branch(endLabel); } rb.MarkLabel(nextLabel); if (elsePart) { if (!clauses.IsEmpty) { Context.HandleError(new CompilerError(src, CompilerMessages._0_Clauses_After_Else_Part_Will_Never_Be_Evaluated, "COND")); } break; } nextLabel = rb.DefineLabel(); } if (wantResult && !elsePart) { rb.EmitStore(resultStorage, Game.Zero); } rb.MarkLabel(endLabel); return(wantResult ? resultStorage : null); }
public static PiExpression Pi(IVariable v, Expression a, Expression b) => new PiExpression(v, a, b);
internal IOperand CompileBoolean([NotNull] IRoutineBuilder rb, [NotNull] ZilListoidBase args, [NotNull] ISourceLine src, bool and, bool wantResult, [CanBeNull] IVariable resultStorage) { if (!args.IsCons(out var first, out var rest)) { return(and ? Game.One : Game.Zero); } if (rest.IsEmpty) { if (wantResult) { return(CompileAsOperand(rb, first, src, resultStorage)); } CompileStmt(rb, first, false); return(Game.Zero); } ILabel lastLabel; if (!wantResult) { // easy path - don't need to preserve the values lastLabel = rb.DefineLabel(); while (!rest.IsEmpty) { var nextLabel = rb.DefineLabel(); CompileCondition(rb, first, src, nextLabel, and); rb.Branch(lastLabel); rb.MarkLabel(nextLabel); (first, rest) = rest; } CompileStmt(rb, first, false); rb.MarkLabel(lastLabel); return(Game.Zero); } // hard path - need to preserve the values and return the last one evaluated var tempAtom = ZilAtom.Parse("?TMP", Context); lastLabel = rb.DefineLabel(); IVariable tempVar = null; ILabel trueLabel = null; resultStorage = resultStorage ?? rb.Stack; var nonStackResultStorage = resultStorage == rb.Stack ? null : resultStorage; IVariable TempVarProvider() { if (tempVar != null) { return(tempVar); } PushInnerLocal(rb, tempAtom, LocalBindingType.CompilerTemporary, src); tempVar = Locals[tempAtom].LocalBuilder; return(tempVar); } ILabel TrueLabelProvider() { return(trueLabel ?? (trueLabel = rb.DefineLabel())); } IOperand result; while (!rest.IsEmpty) { var nextLabel = rb.DefineLabel(); /* TODO: use "value or predicate" context here - if the expr is naturally a predicate, * branch to a final label and synthesize the value without using a temp var, * otherwise use the returned value */ if (and) { // for AND we only need the result of the last expr; otherwise we only care about truth value CompileCondition(rb, first, src, nextLabel, true); rb.EmitStore(resultStorage, Game.Zero); rb.Branch(lastLabel); } else { // for OR, if the value is true we want to return it; otherwise discard it and try the next expr // however, if the expr is a predicate anyway, we can branch out of the OR if it's true; // otherwise fall through to the next expr if (first.IsPredicate(Context.ZEnvironment.ZVersion)) { CompileCondition(rb, first, src, TrueLabelProvider(), true); // fall through to nextLabel } else { result = CompileAsOperandWithBranch(rb, first, nonStackResultStorage, nextLabel, false, TempVarProvider); if (result != resultStorage) { rb.EmitStore(resultStorage, result); } rb.Branch(lastLabel); } } rb.MarkLabel(nextLabel); (first, rest) = rest; } result = CompileAsOperand(rb, first, src, resultStorage); if (result != resultStorage) { rb.EmitStore(resultStorage, result); } if (trueLabel != null) { rb.Branch(lastLabel); rb.MarkLabel(trueLabel); rb.EmitStore(resultStorage, Game.One); } rb.MarkLabel(lastLabel); if (tempVar != null) { PopInnerLocal(tempAtom); } return(resultStorage); }
public void Deconstruct(out IVariable v, out Expression t, out Expression e) { v = V; t = T; e = E; }
public bool ContainsProvider(IVariable provider) => _unsettable.Any(instance => instance.Provider == provider);
public LambdaExpression(IVariable v, Expression t, Expression e) { V = v; T = t; E = e; }
//public static IExpression GetValueOriginal(this IDictionary<IVariable, IExpression> equalities, IVariable variable) //{ // var result = equalities.ContainsKey(variable) ? equalities[variable] : variable; // return result; //} public static IExpression GetValue(this IDictionary <IVariable, IExpression> equalities, IVariable variable) { IExpression result = variable; while (variable != null && equalities.ContainsKey(variable)) { result = equalities[variable]; variable = result as IVariable; } return(result); }
ICompletionData ICompletionDataFactory.CreateVariableCompletionData(IVariable variable) { return(new VariableCompletionData(variable)); }
public void RunApp(string cmdLine, string currentDir = null, bool wait = false, [ByRef] IVariable retCode = null) { var sInfo = ProcessContext.PrepareProcessStartupInfo(cmdLine, currentDir); var p = new System.Diagnostics.Process(); p.StartInfo = sInfo; p.Start(); if (wait) { p.WaitForExit(); if (retCode != null) { retCode.Value = ValueFactory.Create(p.ExitCode); } } }
// Applies AND operator public override void ApplyChange(IVariable <bool> value) { Value = Value && value.GetValue(); }
public IMember LookupNameInScopes(string name, out IScope scope, out IVariable v, LookupOptions options) { scope = null; var classMembers = (options & LookupOptions.ClassMembers) == LookupOptions.ClassMembers; switch (options) { case LookupOptions.All: case LookupOptions.Normal: // Regular lookup: all scopes and builtins. for (var s = CurrentScope; s != null; s = (Scope)s.OuterScope) { if (s.Variables.TryGetVariable(name, out var v1) && (!v1.IsClassMember || classMembers)) { scope = s; break; } } break; case LookupOptions.Global: case LookupOptions.Global | LookupOptions.Builtins: // Global scope only. if (GlobalScope.Variables.Contains(name)) { scope = GlobalScope; } break; case LookupOptions.Nonlocal: case LookupOptions.Nonlocal | LookupOptions.Builtins: // All scopes but current and global ones. for (var s = CurrentScope.OuterScope as Scope; s != null && s != GlobalScope; s = (Scope)s.OuterScope) { if (s.Variables.Contains(name)) { scope = s; break; } } break; case LookupOptions.Local: case LookupOptions.Local | LookupOptions.Builtins: // Just the current scope if (CurrentScope.Variables.Contains(name)) { scope = CurrentScope; } break; default: Debug.Fail("Unsupported name lookup combination"); break; } v = scope?.Variables[name]; var value = v?.Value; if (value == null && options.HasFlag(LookupOptions.Builtins)) { var builtins = Interpreter.ModuleResolution.BuiltinsModule; value = Interpreter.ModuleResolution.BuiltinsModule.GetMember(name); if (Module != builtins && options.HasFlag(LookupOptions.Builtins)) { value = builtins.GetMember(name); scope = builtins.GlobalScope; } } return(value); }
public void FindLocalReferences(ParseInformation parseInfo, ITextSource fileContent, IVariable variable, ICompilation compilation, Action <SearchResultMatch> callback, CancellationToken cancellationToken) { throw new NotImplementedException(); }
public override void SetValue(IVariable <bool> value) { Value = value.GetValue(); }