Exemplo n.º 1
1
 public ArrayAdapter(IValue array)
 {
     _array = array;
     _list = array.ActualType.CreateGenericListInstance().As<IList>();
     _listType = _list.GetType().ToCachedType();
     _listType.InvokeAction("AddRange", _list, array.Instance);
 }
Exemplo n.º 2
0
 public ReadLineResult ReadLine(out SectionType secType, out string line, out string key, out IValue value)
 {
     secType = SectionType.None;
     line = string.Empty;
     key = string.Empty;
     value = null;
     if (streamReader == null)
     {
         return ReadLineResult.Error;
     }
     line = streamReader.ReadLine();
     if (line == null)
     {
         return ReadLineResult.Null;
     }
     if (line == string.Empty)
     {
         return ReadLineResult.OK;
     }
     string trimmedLine = line.Trim();
     if (trimmedLine == string.Empty)
     {
         secType = SectionType.Spaces;
         return ReadLineResult.OK;
     }
     // line = trimmedLine;
     return this.ParseLine(trimmedLine, ref secType, out key, out value);
 }
Exemplo n.º 3
0
        public void AddComponent(XmlElement parent, PropertyAuditingData propertyAuditingData,
								 IValue value, ICompositeMapperBuilder mapper, string entityName,
								 EntityXmlMappingData xmlMappingData, bool firstPass, bool insertable)
        {
            var propComponent = (Component) value;

            var componentMapper = mapper.AddComponent(propertyAuditingData.GetPropertyData(),
                                                                          propComponent.ComponentClassName);

            // The property auditing data must be for a component.
            var componentAuditingData = (ComponentAuditingData) propertyAuditingData;

            // Adding all properties of the component
            foreach (var property in propComponent.PropertyIterator)
            {
                var componentPropertyAuditingData = componentAuditingData.GetPropertyAuditingData(property.Name);

                // Checking if that property is audited
                if (componentPropertyAuditingData != null)
                {
                    mainGenerator.AddValue(parent, property.Value, componentMapper, entityName, xmlMappingData,
                            componentPropertyAuditingData, property.IsInsertable && insertable, firstPass);
                }
            }
        }
Exemplo n.º 4
0
 public void Send(
     IValue receiver,
     ValueSymbol selector,
     IList<IValue> args,
     VM vm,
     SourceInfo info
 )
 {
     IValueFunc func = null;
     foreach (ValueSymbol klass in KlassList)
     {
         if (vm.Env.LookupMethod(klass, selector, out func))
         {
             break;
         }
     }
     if (func == null)
     {
         throw new RheaException(
             string.Format(
                 "invalid selector for {0}: {1}",
                 receiver,
                 selector.Name.ToIdentifier()
             ),
             info
         );
     }
     List<IValue> newArgs = new List<IValue>();
     newArgs.Add(receiver);
     newArgs.AddRange(args);
     func.Call(newArgs, vm, info);
 }
Exemplo n.º 5
0
        public static IPersistentValue MapValue(IValue value)
        {
            var component = value as Component;
            if(component != null)
            {
                return new PersistentComponent(MapProperties(component.PropertyIterator));
            }
            var collection = value as Collection;
            if(collection != null)
            {
                return new PersistentCollection(MapValue(collection.Element));
            }
            var toOne = value as ToOne;
            if(toOne != null)
            {
                return new PersistentToOne(toOne.ReferencedEntityName);
            }

            var oneToMany = value as OneToMany;
            if(oneToMany != null)
            {
                return new PersistentOneToMany(oneToMany.ReferencedEntityName);
            }
            return null;
        }
        public ExceptionDialog(IThread thread)
        {
            InitializeComponent();
            this.Icon = _icon;

            _exceptionValue = thread.CurrentException;
            _sourceLocation = thread.GetCurrentSourceRange();

            // no need to hook to UILanguageChanged as this dialog will be closed 
            // before the user gets any chance to update the UI language.
            var _componentMuiIdentifiers = new Dictionary<object, string>()
            {
                {this, "ExceptionDialog.Title"},
                {headerLabel, "ExceptionDialog.ExceptionOccured"},
                {fileLabel, "ExceptionDialog.File"},
                {locationLabel, "ExceptionDialog.Location"},
                {messageLabel, "ExceptionDialog.Message"},
                {closeButton, "ExceptionDialog.Close"},
                {goToFileButton, "ExceptionDialog.GoToFile"},
                {detailsButton, "ExceptionDialog.Details"},
            };
            
            DebuggerBase.Instance.MuiProcessor.ApplyLanguageOnComponents(_componentMuiIdentifiers);

            fileTextBox.Text = _sourceLocation.FilePath.FullPath;
            locationTextBox.Text = DebuggerBase.Instance.MuiProcessor.GetString("ExceptionDialog.LocationFormat",
                "line=" + _sourceLocation.Line,
                "column=" + _sourceLocation.Column);
            messageTextBox.Text = _exceptionValue.ValueAsString(thread);
        }
        public void ForceEarlyReturn(IValue returnValue)
        {
            Contract.Requires<ArgumentNullException>(returnValue != null, "returnValue");
            Contract.Requires<VirtualMachineMismatchException>(this.GetVirtualMachine().Equals(returnValue.GetVirtualMachine()));

            throw new NotImplementedException();
        }
        private void AddCustomValue(XmlElement parent, PropertyAuditingData propertyAuditingData,
            IValue value, ISimpleMapperBuilder mapper, bool insertable, bool key)
        {
            if (parent != null) {
                XmlElement prop_mapping = MetadataTools.AddProperty(parent, propertyAuditingData.Name,
                        null, insertable, key);

                //CustomType propertyType = (CustomType) value.getType();

                XmlElement type_mapping = parent.OwnerDocument.CreateElement("type");
                prop_mapping.AppendChild(type_mapping);
                type_mapping.SetAttribute("name", value.GetType().Name);

                if (value is SimpleValue) {
                    IDictionary<string, string> typeParameters = ((SimpleValue)value).TypeParameters;
                    if (typeParameters != null) {
                        foreach (KeyValuePair<string,string> paramKeyValue in typeParameters) {
                            XmlElement type_param = parent.OwnerDocument.CreateElement("param");
                            type_param.SetAttribute("name", (String) paramKeyValue.Key);
                            type_param["name"].Value =  paramKeyValue.Value;
                        }
                    }
                }

                MetadataTools.AddColumns(prop_mapping, (IEnumerator<ISelectable>)value.ColumnIterator);
            }

            if (mapper != null) {
                mapper.Add(propertyAuditingData.getPropertyData());
            }
        }
        //@SuppressWarnings({"unchecked"})
        public void AddOneToOneNotOwning(PropertyAuditingData propertyAuditingData, IValue value,
            ICompositeMapperBuilder mapper, String entityName)
        {
            OneToOne propertyValue = (OneToOne)value;

            String owningReferencePropertyName = propertyValue.ReferencedPropertyName; // mappedBy
            EntityConfiguration configuration = mainGenerator.EntitiesConfigurations[entityName];
            if (configuration == null) {
                throw new MappingException("An audited relation to a non-audited entity " + entityName + "!");
            }

            IdMappingData ownedIdMapping = configuration.IdMappingData;

            if (ownedIdMapping == null) {
                throw new MappingException("An audited relation to a non-audited entity " + entityName + "!");
            }

            String lastPropertyPrefix = MappingTools.createToOneRelationPrefix(owningReferencePropertyName);
            String referencedEntityName = propertyValue.ReferencedEntityName;

            // Generating the id mapper for the relation
            IIdMapper ownedIdMapper = ownedIdMapping.IdMapper.PrefixMappedProperties(lastPropertyPrefix);

            // Storing information about this relation
            mainGenerator.EntitiesConfigurations[entityName].AddToOneNotOwningRelation(
                    propertyAuditingData.Name, owningReferencePropertyName,
                    referencedEntityName, ownedIdMapper);

            // Adding mapper for the id
            PropertyData propertyData = propertyAuditingData.getPropertyData();
            mapper.AddComposite(propertyData, new OneToOneNotOwningMapper(owningReferencePropertyName,
                    referencedEntityName, propertyData));
        }
Exemplo n.º 10
0
        public void CreateAssignment(IValueRegister targetRegister, IValue value)
        {
            JavaScriptRegister registerToUse = targetRegister as JavaScriptRegister;
            JavaScriptValue valueToUse = value as JavaScriptValue;

            AppendFormatLine("{0} = {1};", registerToUse.Expression, valueToUse.Expression);
        }
Exemplo n.º 11
0
        internal MethodExitEventArgs(VirtualMachine virtualMachine, SuspendPolicy suspendPolicy, EventRequest request, ThreadReference thread, Location location, IValue returnValue)
            : base(virtualMachine, suspendPolicy, request, thread, location)
        {
            Contract.Requires<ArgumentNullException>(returnValue != null, "returnValue");

            _returnValue = returnValue;
        }
Exemplo n.º 12
0
        public void CreateAssignment(IValueRegister targetRegister, IValue value)
        {
            JavaScriptRegister registerToUse = targetRegister as JavaScriptRegister;
            JavaScriptValue valueToUse = value as JavaScriptValue;

            AppendFormatLine("{0} = {1};", registerToUse.Expression, valueToUse.Expression.Replace("\n", "\n" + new String('\t', IndentationLevel)));
        }
Exemplo n.º 13
0
 public override void CallAsFunction(int methodNumber, IValue[] arguments, out IValue retValue)
 {
     if (methodNumber == 0)
         retValue = ValueFactory.Create(this.Count());
     else
         retValue = null;
 }
Exemplo n.º 14
0
        private static void AddCustomValue(XmlElement parent, PropertyAuditingData propertyAuditingData,
									IValue value, ISimpleMapperBuilder mapper, bool insertable, 
									bool key, System.Type typeOfUserImplementation)
        {
            if (parent != null)
            {
                var prop_mapping = MetadataTools.AddProperty(parent, propertyAuditingData.Name,
                        null, insertable, key);
                MetadataTools.AddColumns(prop_mapping, value.ColumnIterator.OfType<Column>());
                var typeElement = parent.OwnerDocument.CreateElement("type");
                typeElement.SetAttribute("name", typeOfUserImplementation.AssemblyQualifiedName);

                var simpleValue = value as SimpleValue;
                if (simpleValue != null)
                {
                    var typeParameters = simpleValue.TypeParameters;
                    if (typeParameters != null)
                    {
                        foreach (var paramKeyValue in typeParameters)
                        {
                            var type_param = typeElement.OwnerDocument.CreateElement("param");
                            type_param.SetAttribute("name", paramKeyValue.Key);
                            type_param.InnerText =  paramKeyValue.Value;
                            typeElement.AppendChild(type_param);
                        }
                    }
                }
                prop_mapping.AppendChild(typeElement);
            }

            if (mapper != null)
            {
                mapper.Add(propertyAuditingData.GetPropertyData());
            }
        }
Exemplo n.º 15
0
 /// <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;
 }
Exemplo n.º 16
0
        public static ObjectNodeBase CreateDeserializable(string name, IValue @object, INode parent,
            Context context, CachedMember member = null)
        {
            var type = @object.SpecifiedType;
            var kind = GetTypeKind(type, context.Options);

            if (kind == TypeKind.Simple)
            {
                if (parent == null) throw new TypeNotSupportedException("simple type",
                    @object.SpecifiedType, Mode.Deserialize, "complex types");
                return new ValueNode(context, name, @object, member, parent);
            }

            Func<object> factory = () => ObjectFactory.CreateInstance(type,
                context.Options.Deserialization.ObjectFactory, parent.MapOrDefault(x => x.Value));

            if (member == null || parent == null) @object.Instance = factory();
            else @object = ValueFactory.Create(@object, factory);

            switch (kind)
            {
                case TypeKind.Dictionary: return new DictionaryNode(context, name, @object, member, parent);
                case TypeKind.Enumerable: return new EnumerableNode(context, name, @object, member, parent);
                default: return new ObjectNode(context, name, @object, member, parent);
            }
        }
Exemplo n.º 17
0
 public MemberDefinition(CachedMember member, string name, IValue value)
 {
     Name = name;
     Value = value;
     Member = member;
     IsNodeType = value.SpecifiedType.Type.CanBeCastTo<INode>();
 }
Exemplo n.º 18
0
 public static IVariable Create(IValue val)
 {
     return new Variable()
     {
         _val = val
     };
 }
        //@SuppressWarnings({"unchecked"})
        public void AddComponent(XmlElement parent, PropertyAuditingData propertyAuditingData,
            IValue value, ICompositeMapperBuilder mapper, String entityName,
            EntityXmlMappingData xmlMappingData, bool firstPass)
        {
            Component prop_component = (Component) value;

            ICompositeMapperBuilder componentMapper = mapper.AddComponent(propertyAuditingData.getPropertyData(),
                    prop_component.ComponentClassName);

            // The property auditing data must be for a component.
            ComponentAuditingData componentAuditingData = (ComponentAuditingData) propertyAuditingData;

            // Adding all properties of the component
            IEnumerator<Property> properties = (IEnumerator<Property>) prop_component.PropertyIterator.GetEnumerator();
            while (properties.MoveNext()) {
                Property property = properties.Current;

                PropertyAuditingData componentPropertyAuditingData =
                        componentAuditingData.getPropertyAuditingData(property.Name);

                // Checking if that property is audited
                if (componentPropertyAuditingData != null) {
                    mainGenerator.AddValue(parent, property.Value, componentMapper, entityName, xmlMappingData,
                            componentPropertyAuditingData, property.IsInsertable, firstPass);
                }
            }
        }
Exemplo n.º 20
0
        public bool AddBasic(XmlElement parent, PropertyAuditingData propertyAuditingData,
					 IValue value, ISimpleMapperBuilder mapper, bool insertable, bool key)
        {
            var type = value.Type;
            var custType = type as CustomType;
            var compType = type as CompositeCustomType;
            if (type is ImmutableType || type is MutableType)
            {
                AddSimpleValue(parent, propertyAuditingData, value, mapper, insertable, key);
            }
            else if (custType != null)
            {
                AddCustomValue(parent, propertyAuditingData, value, mapper, insertable, key, custType.UserType.GetType());
            }
            else if (compType != null)
            {
                AddCustomValue(parent, propertyAuditingData, value, mapper, insertable, key, compType.UserType.GetType());
            }
            else
            {
                return false;
            }

            return true;
        }
        private IValue doFunctionCall(ParserRuleContext context, string targetFunctionName, List<IValue> parameters, IValue target, ClepsType targetType, bool allowVoidReturn)
        {
            IValue dereferencedTarget = target == null? null : GetDereferencedRegisterOrNull(target);
            BasicClepsType dereferencedType = target == null? targetType as BasicClepsType : dereferencedTarget.ExpressionType as BasicClepsType;

            if (dereferencedType == null)
            {
                string errorMessage = String.Format("Could not dereference expression on type {0}", targetType.GetClepsTypeString());
                Status.AddError(new CompilerError(FileName, context.Start.Line, context.Start.Column, errorMessage));
                //just return something to avoid stalling
                return CodeGenerator.CreateByte(0);
            }

            ClepsClass targetClepsClass = ClassManager.GetClass(dereferencedType.GetClepsTypeString());


            List<ClepsVariable> functionOverloads;
            bool isStatic;
            if (targetClepsClass.StaticMemberMethods.ContainsKey(targetFunctionName))
            {
                isStatic = true;
                functionOverloads = targetClepsClass.StaticMemberMethods[targetFunctionName];
            }
            else if (target != null && targetClepsClass.MemberMethods.ContainsKey(targetFunctionName))
            {
                isStatic = false;
                functionOverloads = targetClepsClass.MemberMethods[targetFunctionName];
            }
            else
            {
                string errorMessage = String.Format("Class {0} does not contain a {1}static function called {2}.", targetClepsClass.FullyQualifiedName, target == null? "" : "member or ",targetFunctionName);
                Status.AddError(new CompilerError(FileName, context.Start.Line, context.Start.Column, errorMessage));
                //Just return something to avoid stalling compilation
                return CodeGenerator.CreateByte(0);
            }

            int matchedPosition;
            string fnMatchErrorMessage;

            if (!FunctionOverloadManager.FindMatchingFunctionType(TypeManager, functionOverloads, parameters, out matchedPosition, out fnMatchErrorMessage))
            {
                Status.AddError(new CompilerError(FileName, context.Start.Line, context.Start.Column, fnMatchErrorMessage));
                //Just return something to avoid stalling compilation
                return CodeGenerator.CreateByte(0);
            }

            FunctionClepsType chosenFunctionType = functionOverloads[matchedPosition].VariableType as FunctionClepsType;

            if (!allowVoidReturn && chosenFunctionType.ReturnType == VoidClepsType.GetVoidType())
            {
                string errorMessage = String.Format("Function {0} does not return a value", targetFunctionName);
                Status.AddError(new CompilerError(FileName, context.Start.Line, context.Start.Column, errorMessage));
                //Just return something to avoid stalling compilation
                return CodeGenerator.CreateByte(0);
            }

            IValue returnValue = CodeGenerator.GetFunctionCallReturnValue(isStatic? null : dereferencedTarget, dereferencedType, targetFunctionName, chosenFunctionType, parameters);
            return returnValue;
        }
Exemplo n.º 22
0
 /// <summary>
 ///     Checks the return value for a conversion to EFS type
 /// </summary>
 /// <param name="value"></param>
 /// <param name="type"></param>
 public void CheckReturnValue(IValue value, Type type)
 {
     if (value == null)
     {
         throw new FaultException<EFSServiceFault>(
             new EFSServiceFault("Cannot convert to EFS value " + DisplayValue() + " for type " + type.FullName));
     }
 }
Exemplo n.º 23
0
 public MemberValue(IValue value, CachedMember member, Func<CachedType, bool> useActualType)
 {
     _value = value;
     _member = member;
     var type = member.Type;
     SpecifiedType = useActualType(type) && Instance != null ? Instance.ToCachedType() : type;
     IsReadonly = _member.IsReadonly;
 }
Exemplo n.º 24
0
        public void SetValue(ILocalVariable variable, IValue value)
        {
            Contract.Requires<ArgumentNullException>(variable != null, "variable");
            Contract.Requires<VirtualMachineMismatchException>(this.GetVirtualMachine().Equals(variable.GetVirtualMachine()));
            Contract.Requires<VirtualMachineMismatchException>(value == null || this.GetVirtualMachine().Equals(value.GetVirtualMachine()));

            throw new NotImplementedException();
        }
Exemplo n.º 25
0
        public int CompareTo(IValue other)
        {
            GuidWrapper otherUuid = other.GetRawValue() as GuidWrapper;
            if (otherUuid == null)
                throw RuntimeException.ComparisonNotSupportedException();

            return _value.CompareTo(otherUuid._value);
        }
Exemplo n.º 26
0
        public void TestCombineDifInitial(IDeclaredParameter loopVarName, IValue ivalSize, IValue initialValue1, IValue initialValue2)
        {
            var p1 = new StatementForLoop(loopVarName, ivalSize, initialValue1);
            var p2 = new StatementForLoop(loopVarName, ivalSize, initialValue2);

            var r = p1.TryCombineStatement(p2, new dummyOpt());
            Assert.IsFalse(r, "Should always be equal");
        }
Exemplo n.º 27
0
 public EntityValueSetState(Guid metadataDefinitionIdentity, MetadataDefinitionName name, IDataType dataType, string regex, IValue supplied)
 {
     MetadataDefinitionIdentity = metadataDefinitionIdentity;
     Name = name;
     DataType = dataType;
     Regex = regex;
     Values = supplied;
 }
Exemplo n.º 28
0
 public HttpRequestBodyString(string body, IValue encoding = null)
 {
     _data = body;
     if (encoding == null)
         _encoding = new UTF8Encoding(true);
     else
         _encoding = TextEncodingEnum.GetEncoding(encoding);
 }
Exemplo n.º 29
0
        public void SetValue(IField field, IValue value)
        {
            Contract.Requires<ArgumentNullException>(field != null, "field");
            Contract.Requires<VirtualMachineMismatchException>(this.GetVirtualMachine().Equals(field.GetVirtualMachine()));
            Contract.Requires<VirtualMachineMismatchException>(value == null || this.GetVirtualMachine().Equals(value.GetVirtualMachine()));

            throw new NotImplementedException();
        }
Exemplo n.º 30
0
        public static COMWrapperContext Create(string progId, IValue[] arguments)
        {
            var type = Type.GetTypeFromProgID(progId, true);

            object instance = Activator.CreateInstance(type, MarshalArguments(arguments));

            return InitByInstance(type, instance);
        }
Exemplo n.º 31
0
 public virtual void SetPropValue(int propNum, IValue newVal)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 32
0
 public void InjectGlobalProperty(string name, IValue value, bool readOnly)
 {
     _env.InjectGlobalProperty(value, name, readOnly);
 }
Exemplo n.º 33
0
 public void Delete(IValue Column)
 {
     Column = Column.GetRawValue();
     _columns.Remove(GetColumnByIIndex(Column));
 }
Exemplo n.º 34
0
 public override void SetPropValue(int propNum, IValue newVal)
 {
     throw new RuntimeException("Свойство только для чтения");
 }
Exemplo n.º 35
0
 /// <summary>
 /// Constructor for this class.
 /// </summary>
 /// <param name="value">The parameter value associated with the instruction. The type of the value depends on the loader instruction it is connected with</param>
 /// <param name="textLength">The length (character count) of the value in the source code it was parsed from</param>
 public LoaderInstructionParameters(IValue value, int textLength)
 {
     mValue      = value;
     mTextLength = textLength;
 }
Exemplo n.º 36
0
        internal static IValue Compare(List <IValue> list, Scope scope)
        {
            IValue first = list.First();

            return(first.MetaType.Compare.Invoke(list, scope).First());
        }
Exemplo n.º 37
0
 public void SetParameter(string ParametrName, IValue ParametrValue)
 {
     _parameters.Insert(ParametrName, ParametrValue);
 }
Exemplo n.º 38
0
 public bool Equal(IValue value) => ReferenceEquals(this, value);
Exemplo n.º 39
0
 bool IEquatable <IValue> .Equals(IValue other) =>
 other is Null;
Exemplo n.º 40
0
 public ValueBuilderImpl(IValue value) : this(_ => value)
 {
 }
 /// <inheritdoc/>
 public override bool CanParseLiteral(IValue value) => true;
 /// <inheritdoc/>
 public override object ParseLiteral(IValue value) => value.Value;
Exemplo n.º 43
0
 /// <summary>
 /// Given two IValue's, do the expression conversion.
 /// </summary>
 /// <param name="renames"></param>
 /// <param name="p1"></param>
 /// <param name="p2"></param>
 /// <returns></returns>
 public static Tuple <bool, IEnumerable <Tuple <string, string> > > RequireForEquivForExpression(this Tuple <bool, IEnumerable <Tuple <string, string> > > renames, IValue p1, IValue p2)
 {
     return(renames
            .RequireForEquivForExpression(p1.RawValue, p1.Dependants.Select(p => p.RawValue),
                                          p2.RawValue, p2.Dependants.Select(p => p.RawValue)));
 }
Exemplo n.º 44
0
        public IParseResult Parse(IEnumerator <string> args)
        {
            bool         first       = true;
            TClass       parsedClass = new();
            List <Error> errors      = new();
            HashSet <IOption <TClass> > optionsRemaining  = new(allOptions);
            HashSet <ISwitch <TClass> > switchesRemaining = new(allSwitches);
            List <string> multiValuesFound = new();
            int           valuesFound      = 0;

            while (args.MoveNext())
            {
                string a = args.Current;
                // If the user asks for help, immediately stop parsing
                if (config.StringComparer.Equals(a, config.ShortHelpSwitch) || config.StringComparer.Equals(a, config.LongHelpSwitch))
                {
                    errors.Add(new Error(ErrorCode.HelpRequested, string.Empty));
                    return(new FailedParseWithVerb <TClass>(this, errors));
                }

                // It is POSSIBLE for the user to set up a verb with arguments that also has a sub-verb as much as I hate that idea
                // So only allow the first argument to be the verb. It should be interpreted as a value or whatever if found elsewhere.
                // If it happens to be a verb, we just hand over the parsing
                if (first && verbsByName.TryGetValue(a, out IVerb? verb))
                {
                    return(verb.Parse(args));
                }

                if (allOptionsByName.TryGetValue(a, out IOption <TClass>?oval))
                {
                    if (args.MoveNext())
                    {
                        a = args.Current;
                        // The option might only have a short or long name. However if both return false, that means we already saw it.
                        if (optionsRemaining.Remove(oval))
                        {
                            Error error = oval.SetValue(parsedClass, a);
                            if (error.ErrorCode != ErrorCode.Ok)
                            {
                                errors.Add(error);
                            }
                        }
                        else
                        {
                            errors.Add(new Error(ErrorCode.DuplicateOption, "An Option appeared twice: " + a));
                        }
                    }
                    else
                    {
                        errors.Add(new Error(ErrorCode.OptionMissingValue, "An Option was missing a value: " + a));
                    }
                }
                else if (allSwitchesByName.TryGetValue(a, out ISwitch <TClass>?sval))
                {
                    // The switch might only have a short or long name. However if both return false, that means we already saw it.
                    if (switchesRemaining.Remove(sval))
                    {
                        Error error = sval.SetValue(parsedClass, string.Empty);
                        if (error.ErrorCode != ErrorCode.Ok)
                        {
                            errors.Add(error);
                        }
                    }
                    else
                    {
                        errors.Add(new Error(ErrorCode.DuplicateSwitch, "A Switch appeared twice: " + a));
                    }
                }
                // Might be a Value
                else if (valuesFound < AllValues.Count)
                {
                    Error error = AllValues[valuesFound++].SetValue(parsedClass, a);
                    if (error.ErrorCode != ErrorCode.Ok)
                    {
                        errors.Add(error);
                    }
                }
                // Might be a MultiValue, unless it starts with something that should be ignored
                else if (MultiValue != null)                // && !MultiValue.HasIgnoredPrefix(arg))
                {
                    multiValuesFound.Add(a);
                }
                // It's something unrecognized
                else
                {
                    errors.Add(new Error(ErrorCode.UnexpectedArgument, "Found an unexpected argument: " + a));
                }
                first = false;
            }
            // Set all remaining values to default
            for (int i = valuesFound; i < AllValues.Count; i++)
            {
                Error error = AllValues[i].SetValue(parsedClass, null);
                if (error.ErrorCode != ErrorCode.Ok)
                {
                    errors.Add(error);
                }
            }
            bool gotMultiValue = false;

            // Set the MultiValue
            if (MultiValue != null)
            {
                Error error = MultiValue.SetValue(parsedClass, multiValuesFound);
                gotMultiValue = true;
                if (error.ErrorCode != ErrorCode.Ok)
                {
                    errors.Add(error);
                }
            }
            // Set all remaining options and switches to their default values
            foreach (IOption <TClass> opt in optionsRemaining)
            {
                Error error = opt.SetValue(parsedClass, null);
                if (error.ErrorCode != ErrorCode.Ok)
                {
                    errors.Add(error);
                }
            }
            foreach (ISwitch <TClass> sw in switchesRemaining)
            {
                Error error = sw.SetValue(parsedClass, null);
                if (error.ErrorCode != ErrorCode.Ok)
                {
                    errors.Add(error);
                }
            }
            // Make sure all of the stuff we've set so far is good, if not then bail out
            if (errors.Count > 0)
            {
                return(new FailedParseWithVerb <TClass>(this, errors));
            }

            // Evaluate dependencies; we know we got the value if it doesn't appear in our lists of remaining stuff
            foreach (IOption <TClass> opt in allOptions)
            {
                Error error = opt.EvaluateDependencies(parsedClass, !optionsRemaining.Contains(opt));
                if (error.ErrorCode != ErrorCode.Ok)
                {
                    errors.Add(error);
                }
            }
            foreach (ISwitch <TClass> sw in allSwitches)
            {
                Error error = sw.EvaluateDependencies(parsedClass, !switchesRemaining.Contains(sw));
                if (error.ErrorCode != ErrorCode.Ok)
                {
                    errors.Add(error);
                }
            }
            // As for values, we can use the valuesFound variable
            for (int i = 0; i < allValues.Count; i++)
            {
                IValue <TClass> val   = allValues[i];
                Error           error = val.EvaluateDependencies(parsedClass, valuesFound > i);
                if (error.ErrorCode != ErrorCode.Ok)
                {
                    errors.Add(error);
                }
            }
            if (MultiValue != null)
            {
                Error error = MultiValue.EvaluateDependencies(parsedClass, gotMultiValue);
                if (error.ErrorCode != ErrorCode.Ok)
                {
                    errors.Add(error);
                }
            }
            if (errors.Count > 0)
            {
                return(new FailedParseWithVerb <TClass>(this, errors));
            }
            string?errMsg = ValidateObject?.Invoke(parsedClass);

            if (string.IsNullOrEmpty(errMsg))
            {
                return(new SuccessfulParse <TClass>(this, parsedClass));
            }
            else
            {
                errors.Add(new Error(ErrorCode.ObjectFailedValidation, errMsg));
                return(new FailedParseWithVerb <TClass>(this, errors));
            }
        }
Exemplo n.º 45
0
 public override Completion InternalCall(IValue thisValue, IReadOnlyList <IValue> arguments)
 {
     throw new NotImplementedException("Array(...) is not implemented");
 }
Exemplo n.º 46
0
        public static byte[] Encode(this IValue value)
        {
            var codec = new Codec();

            return(codec.Encode(value));
        }
Exemplo n.º 47
0
 static IValue _OptimizeIValue(IValue n)
 {
     n = ExpressionConverterVisitor.Visit(n);
     return(n);
 }
Exemplo n.º 48
0
 public virtual object?ParseLiteral(IValue value) => value switch
 {
Exemplo n.º 49
0
        protected override object VisitReturnStatement(ReturnStatementSyntax node)
        {
            IValue v = node.Expression == null ? null : _VisitExpression(node.Expression);

            return(new ReturnStatement(v));
        }
Exemplo n.º 50
0
 public MPair(IValue a, IValue b)
 {
     First = a;
     Rest  = b;
 }
Exemplo n.º 51
0
 public override IValue GetIndexedValue(IValue index)
 {
     return(GetColumnByIIndex(index));
 }
Exemplo n.º 52
0
        IValue Parse(string aExpression)
        {
            aExpression = aExpression.Trim();
            int index = aExpression.IndexOf('(');

            while (index >= 0)
            {
                SubstitudeBracket(ref aExpression, index);
                index = aExpression.IndexOf('(');
            }
            if (aExpression.Contains(','))
            {
                string[]      parts = aExpression.Split(',');
                List <IValue> exp   = new List <IValue>(parts.Length);
                for (int i = 0; i < parts.Length; i++)
                {
                    string s = parts[i].Trim();
                    if (!string.IsNullOrEmpty(s))
                    {
                        exp.Add(Parse(s));
                    }
                }
                return(new MultiParameterList(exp.ToArray()));
            }
            else if (aExpression.Contains('+'))
            {
                string[]      parts = aExpression.Split('+');
                List <IValue> exp   = new List <IValue>(parts.Length);
                for (int i = 0; i < parts.Length; i++)
                {
                    string s = parts[i].Trim();
                    if (!string.IsNullOrEmpty(s))
                    {
                        exp.Add(Parse(s));
                    }
                }
                if (exp.Count == 1)
                {
                    return(exp[0]);
                }
                return(new OperationSum(exp.ToArray()));
            }
            else if (aExpression.Contains('-'))
            {
                string[]      parts = aExpression.Split('-');
                List <IValue> exp   = new List <IValue>(parts.Length);
                if (!string.IsNullOrEmpty(parts[0].Trim()))
                {
                    exp.Add(Parse(parts[0]));
                }
                for (int i = 1; i < parts.Length; i++)
                {
                    string s = parts[i].Trim();
                    if (!string.IsNullOrEmpty(s))
                    {
                        exp.Add(new OperationNegate(Parse(s)));
                    }
                }
                if (exp.Count == 1)
                {
                    return(exp[0]);
                }
                return(new OperationSum(exp.ToArray()));
            }
            else if (aExpression.Contains('*'))
            {
                string[]      parts = aExpression.Split('*');
                List <IValue> exp   = new List <IValue>(parts.Length);
                for (int i = 0; i < parts.Length; i++)
                {
                    exp.Add(Parse(parts[i]));
                }
                if (exp.Count == 1)
                {
                    return(exp[0]);
                }
                return(new OperationProduct(exp.ToArray()));
            }
            else if (aExpression.Contains('/'))
            {
                string[]      parts = aExpression.Split('/');
                List <IValue> exp   = new List <IValue>(parts.Length);
                if (!string.IsNullOrEmpty(parts[0].Trim()))
                {
                    exp.Add(Parse(parts[0]));
                }
                for (int i = 1; i < parts.Length; i++)
                {
                    string s = parts[i].Trim();
                    if (!string.IsNullOrEmpty(s))
                    {
                        exp.Add(new OperationReciprocal(Parse(s)));
                    }
                }
                return(new OperationProduct(exp.ToArray()));
            }
            else if (aExpression.Contains('^'))
            {
                int pos = aExpression.IndexOf('^');
                var val = Parse(aExpression.Substring(0, pos));
                var pow = Parse(aExpression.Substring(pos + 1));
                return(new OperationPower(val, pow));
            }
            int pPos = aExpression.IndexOf("&");

            if (pPos > 0)
            {
                string fName = aExpression.Substring(0, pPos);
                foreach (var M in m_Funcs)
                {
                    if (fName == M.Key)
                    {
                        var      inner       = aExpression.Substring(M.Key.Length);
                        var      param       = Parse(inner);
                        var      multiParams = param as MultiParameterList;
                        IValue[] parameters;
                        if (multiParams != null)
                        {
                            parameters = multiParams.Parameters;
                        }
                        else
                        {
                            parameters = new IValue[] { param }
                        };
                        return(new CustomFunction(M.Key, M.Value, parameters));
                    }
                }
            }
            foreach (var C in m_Consts)
            {
                if (aExpression == C.Key)
                {
                    return(new CustomFunction(C.Key, (p) => C.Value(), null));
                }
            }
            int index2a = aExpression.IndexOf('&');
            int index2b = aExpression.IndexOf(';');

            if (index2a >= 0 && index2b >= 2)
            {
                var inner = aExpression.Substring(index2a + 1, index2b - index2a - 1);
                int bracketIndex;
                if (int.TryParse(inner, out bracketIndex) && bracketIndex >= 0 && bracketIndex < m_BracketHeap.Count)
                {
                    return(Parse(m_BracketHeap[bracketIndex]));
                }
                else
                {
                    throw new ParseException("Can't parse substitude token");
                }
            }
            double doubleValue;

            if (double.TryParse(aExpression, out doubleValue))
            {
                return(new Number(doubleValue));
            }
            if (ValidIdentifier(aExpression))
            {
                if (m_Context.Parameters.ContainsKey(aExpression))
                {
                    return(m_Context.Parameters[aExpression]);
                }
                var val = new Parameter(aExpression);
                m_Context.Parameters.Add(aExpression, val);
                return(val);
            }

            throw new ParseException("Reached unexpected end within the parsing tree");
        }
Exemplo n.º 53
0
 public void setParent(IValue parent)
 {
     return;
 }
Exemplo n.º 54
0
 public virtual void CallAsFunction(int methodNumber, IValue[] arguments, out IValue retValue)
 {
     throw new NotImplementedException();
 }
 public override object ParseLiteral(IValue value) => throw new System.NotImplementedException();
Exemplo n.º 56
0
 public virtual IValue GetIndexedValue(IValue index)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 57
0
 /// <summary>
 /// After applying the renames, make sure the two statements are the same.
 /// </summary>
 /// <param name="renames"></param>
 /// <param name="p1"></param>
 /// <param name="p2"></param>
 /// <returns></returns>
 public static Tuple <bool, IEnumerable <Tuple <string, string> > > RequireAreSame(this Tuple <bool, IEnumerable <Tuple <string, string> > > renames, IValue p1, IValue p2)
 {
     return(renames
            .RequireAreSame(p1.RawValue, p2.RawValue));
 }
Exemplo n.º 58
0
 public virtual void SetIndexedValue(IValue index, IValue val)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 59
0
 public If(IValue condition, Program scope1)
 {
     this.condition = condition;
     this.scope1    = scope1;
 }
Exemplo n.º 60
0
 public IValueBuilder If(IValue condition) =>
 Create(this, new ValueBuilderImpl(condition), (l, r) => r.IsTrue() ? l : null,
        (l, r) => $"{r}.IsTrue ? {l} : null");