Exemplo n.º 1
0
        static Upper()
        {
            string description = "Converts text to uppercase.";

            IEnumerable<ArgumentInfo> requiredArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("Text", "Text is the text you want converted to uppercase. Text can be a reference or text string.", ArgumentType.Text)
            };

            Info = new FunctionInfo(FunctionName, FunctionCategory.Text, description, requiredArguments);
        }
Exemplo n.º 2
0
        static Nand()
        {
            string description = "Returns the Sheffer stroke (or also known as the NAND operator) of two booleans.";

            IEnumerable<ArgumentInfo> requiredArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("Logical", "The first logical argument.", ArgumentType.Logical),
                new ArgumentInfo("Logical", "The second logical argument.", ArgumentType.Logical)
            };

            Info = new FunctionInfo(FunctionName, FunctionCategory.Text, description, requiredArguments);
        }
Exemplo n.º 3
0
        static Indirect()
        {
            string description = "Returns the reference of the cell specified by a text string.";

            IEnumerable<ArgumentInfo> requiredArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("Text",
                    "A reference to a cell that contains an A1-style reference, a name defined as a reference, or a reference to a cell as a text string.",
                    ArgumentType.Text),
            };

            Info = new FunctionInfo(FunctionName,FunctionCategory.LookupReference, description, requiredArguments);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Generates stub to receive the CLR call and then call the dynamic language code.
        /// </summary>
        public static void  EmitClrCallStub(CodeGen cg, Slot callTarget, int firstArg, CallType functionAttributes) {
            List<ReturnFixer> fixers = new List<ReturnFixer>(0);
            IList<Slot> args = cg.ArgumentSlots;
            int nargs = args.Count - firstArg;
            
            CallAction action;
            if ((functionAttributes & CallType.ArgumentList) != 0) {
                ArgumentInfo[] infos = CompilerHelpers.MakeRepeatedArray(ArgumentInfo.Simple, nargs);
                infos[nargs - 1] = new ArgumentInfo(ArgumentKind.List);

                action = CallAction.Make(new CallSignature(infos));
            } else {
                action = CallAction.Make(nargs);
            }

            bool fast;
            Slot site = cg.CreateDynamicSite(action, 
                CompilerHelpers.MakeRepeatedArray(typeof(object), nargs + 2), 
                out fast);

            site.EmitGet(cg);
            if (!fast) cg.EmitCodeContext();

            if (DynamicSiteHelpers.IsBigTarget(site.Type)) {
                cg.EmitTuple(site.Type.GetGenericArguments()[0], args.Count + 1, delegate(int index) {
                    if (index == 0) {
                        callTarget.EmitGet(cg);
                    } else {
                        ReturnFixer rf = ReturnFixer.EmitArgument(cg, args[index - 1]);
                        if (rf != null) fixers.Add(rf);
                    }
                });
            } else {
                callTarget.EmitGet(cg);

                for (int i = firstArg; i < args.Count; i++) {
                    ReturnFixer rf = ReturnFixer.EmitArgument(cg, args[i]);
                    if (rf != null) fixers.Add(rf);
                }
            }

            cg.EmitCall(site.Type, "Invoke"); 

            foreach (ReturnFixer rf in fixers) {
                rf.FixReturn(cg);
            }
            cg.EmitReturnFromObject();
        }
Exemplo n.º 5
0
        static GeoMean()
        {
            string description = "Returns the geometric mean of a sequance of numbers.";

            IEnumerable<ArgumentInfo> requiredArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("Number", "Positive number", ArgumentType.Number),
            };

            IEnumerable<ArgumentInfo> optionalArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("Number", "Positive number", ArgumentType.Number)
            };

            info = new FunctionInfo(FunctionName, FunctionCategory.Statistical, description, requiredArguments, optionalArguments, optionalArgumentsRepeatCount:255);
        }
Exemplo n.º 6
0
        static RepeatString()
        {
            IEnumerable<ArgumentInfo> requiredArguments = new ArgumentInfo[]
            {
                 new ArgumentInfo("Text", "Text is the text you want to repeat.", ArgumentType.Text)
            };

            IEnumerable<ArgumentInfo> optionalArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("NumberTimes", "NumberTimes is a positive number specifying the number of times to repeat text.", ArgumentType.Number)
            };

            string description = "REPEAT.STRING repeats some text a desired number of times.";

            Info = new FunctionInfo(FunctionName, FunctionCategory.Text, description, requiredArguments, optionalArguments, 1, false);
        }
        /// <summary>
        /// Serializes a navigational filtering argument info into an XML file.
        /// </summary>
        /// <param name="writer">XMLWriter where the argument is stored.</param>
        /// <param name="argument">Argument to serialize.</param>
        /// <returns>Returns the XMLWriter with the argument.</returns>
        public static XmlWriter Serialize(XmlWriter writer, ArgumentInfo argument)
        {
            writer.WriteStartElement(DTD.Request.ServiceRequest.Arguments.TagArgument);
            writer.WriteAttributeString(DTD.Request.ServiceRequest.Arguments.Argument.TagName, argument.Name);
            if (argument.Type == ModelType.Oid)
            {
                writer.WriteAttributeString(DTD.Request.ServiceRequest.Arguments.Argument.TagType, argument.ClassName);
            }
            else
            {
                writer.WriteAttributeString(DTD.Request.ServiceRequest.Arguments.Argument.TagType, Convert.MODELTypeToStringType(argument.Type));
            }

            if (argument.Value != null)
            {
                if (argument.Value is Oids.AlternateKey)
                {
                    XMLAlternateKeySerializer.Serialize(writer, (Oids.AlternateKey)argument.Value);
                }
                else if (argument.Value is Oids.Oid)
                {
                    XMLAdaptorOIDSerializer.Serialize(writer, argument.Value as Oids.Oid);
                }
                else
                {
                    string lvalue = Convert.TypeToXml(argument.Type, argument.Value); //<-- Convert TypeToXML()!!!!
                    if (lvalue.Length > 0)
                    {
                        writer.WriteStartElement(DTD.Request.ServiceRequest.Arguments.Argument.TagLiteral);
                        writer.WriteValue(lvalue);
                        writer.WriteEndElement();
                    }
                    else // Is <NULL>
                    {
                        writer.WriteElementString(DTD.Request.ServiceRequest.Arguments.Argument.TagNull, string.Empty);
                    }
                }
            }
            else // Is <NULL>
            {
                writer.WriteElementString(DTD.Request.ServiceRequest.Arguments.Argument.TagNull, string.Empty);
            }
            writer.WriteEndElement();
            return writer;
        }
Exemplo n.º 8
0
        static Arguments()
        {
            string description = "Returns number of used arguments.";

            IEnumerable<ArgumentInfo> requiredArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("First", "First argument.", ArgumentType.Any),
                new ArgumentInfo("Second", "Second argument.", ArgumentType.Any),
                new ArgumentInfo("Third", "Third argument.", ArgumentType.Any),
            };

            IEnumerable<ArgumentInfo> optionalArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("First", "First argument.", ArgumentType.Any),
                new ArgumentInfo("Second", "Second argument.", ArgumentType.Any),
                new ArgumentInfo("Third", "Third argument.", ArgumentType.Any),
            };

            Info = new FunctionInfo(FunctionName, FunctionCategory.MathTrig, description, requiredArguments, optionalArguments, optionalArgumentsRepeatCount: 3);
        }
Exemplo n.º 9
0
        static Add()
        {
            #region FunctionInfo

            string description = "Adds all the numbers in range of cells.";

            IEnumerable<ArgumentInfo> requiredArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("Number", "number1, number2,... are the numbers to sum. Logical values and text are ignored in cells, included if typed as arguments.", ArgumentType.Number),
            };

            IEnumerable<ArgumentInfo> optionalArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("Number", "number1, number2,... are the numbers to sum. Logical values and text are ignored in cells, included if typed as arguments.", ArgumentType.Number),
            };

            Info = new FunctionInfo(FunctionName, FunctionCategory.MathTrig, description, requiredArguments, optionalArguments, 254, true);

            #endregion
        }
Exemplo n.º 10
0
 public static ArgumentInfo <T> IfNull <T>(this ArgumentInfo <T> arg, in string type = ValidationType.IfNull, in string message = null)
Exemplo n.º 11
0
        internal DecorateActorStructure(ZDTextParser zdparser, DecorateCategoryInfo catinfo)
        {
            this.catinfo = catinfo; //mxd

            DecorateParser parser = (DecorateParser)zdparser;
            bool           done   = false; //mxd

            // First next token is the class name
            parser.SkipWhitespace(true);
            classname = parser.StripTokenQuotes(parser.ReadToken(ACTOR_CLASS_SPECIAL_TOKENS));

            if (string.IsNullOrEmpty(classname))
            {
                parser.ReportError("Expected actor class name");
                return;
            }

            //mxd. Fail on duplicates // [ZZ] archived +zscript
            if (parser.GetArchivedActorByName(classname) != null)
            {
                parser.ReportError("Actor \"" + classname + "\" is double-defined");
                return;
            }

            // Parse tokens before entering the actor scope
            while (parser.SkipWhitespace(true))
            {
                string token = parser.ReadToken();
                if (!string.IsNullOrEmpty(token))
                {
                    token = token.ToLowerInvariant();

                    switch (token)
                    {
                    case ":":
                        // The next token must be the class to inherit from
                        parser.SkipWhitespace(true);
                        inheritclass = parser.StripTokenQuotes(parser.ReadToken());
                        if (string.IsNullOrEmpty(inheritclass))
                        {
                            parser.ReportError("Expected class name to inherit from");
                            return;
                        }

                        // Find the actor to inherit from
                        baseclass = parser.GetArchivedActorByName(inheritclass);
                        break;

                    case "replaces":
                        // The next token must be the class to replace
                        parser.SkipWhitespace(true);
                        replaceclass = parser.StripTokenQuotes(parser.ReadToken());
                        if (string.IsNullOrEmpty(replaceclass))
                        {
                            parser.ReportError("Expected class name to replace");
                            return;
                        }
                        break;

                    case "native":
                        // Igore this token
                        break;

                    case "{":
                        // Actor scope begins here,
                        // break out of this parse loop
                        done = true;
                        break;

                    case "-":
                        // This could be a negative doomednum (but our parser sees the - as separate token)
                        // So read whatever is after this token and ignore it (negative doomednum indicates no doomednum)
                        parser.ReadToken();
                        break;

                    default:
                        //mxd. Property begins with $? Then the whole line is a single value
                        if (token.StartsWith("$"))
                        {
                            // This is for editor-only properties such as $sprite and $category
                            props[token] = new List <string> {
                                (parser.SkipWhitespace(false) ? parser.ReadLine() : "")
                            };
                            continue;
                        }

                        if (!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out doomednum))     // Check if numeric
                        {
                            // Not numeric!
                            parser.ReportError("Expected editor number or start of actor scope while parsing \"" + classname + "\"");
                            return;
                        }

                        //mxd. Range check
                        if ((doomednum < General.Map.FormatInterface.MinThingType) || (doomednum > General.Map.FormatInterface.MaxThingType))
                        {
                            // Out of bounds!
                            parser.ReportError("Actor \"" + classname + "\" has invalid editor number. Editor number must be between "
                                               + General.Map.FormatInterface.MinThingType + " and " + General.Map.FormatInterface.MaxThingType);
                            return;
                        }
                        break;
                    }

                    if (done)
                    {
                        break;       //mxd
                    }
                }
                else
                {
                    parser.ReportError("Unexpected end of structure");
                    return;
                }
            }

            // Now parse the contents of actor structure
            string previoustoken = "";

            done = false; //mxd
            while (parser.SkipWhitespace(true))
            {
                string token = parser.ReadToken();
                token = token.ToLowerInvariant();

                switch (token)
                {
                case "+":
                case "-":
                    // Next token is a flag (option) to set or remove
                    bool flagvalue = (token == "+");
                    parser.SkipWhitespace(true);
                    string flagname = parser.ReadToken();
                    if (!string.IsNullOrEmpty(flagname))
                    {
                        // Add the flag with its value
                        flagname        = flagname.ToLowerInvariant();
                        flags[flagname] = flagvalue;
                    }
                    else
                    {
                        parser.ReportError("Expected flag name");
                        return;
                    }
                    break;

                case "action":
                case "native":
                    // We don't need this, ignore up to the first next ;
                    while (parser.SkipWhitespace(true))
                    {
                        string t = parser.ReadToken();
                        if (string.IsNullOrEmpty(t) || t == ";")
                        {
                            break;
                        }
                    }
                    break;

                case "skip_super":
                    skipsuper = true;
                    break;

                case "states":
                    if (!parser.NextTokenIs("{", true))
                    {
                        return;
                    }

                    // Now parse actor states until we reach the end of the states structure
                    while (parser.SkipWhitespace(true))
                    {
                        string statetoken = parser.ReadToken();
                        if (!string.IsNullOrEmpty(statetoken))
                        {
                            // End of scope?
                            if (statetoken == "}")
                            {
                                // Done with the states,
                                // break out of this parse loop
                                break;
                            }
                            // State label?
                            else if (statetoken == ":")
                            {
                                if (!string.IsNullOrEmpty(previoustoken))
                                {
                                    // Parse actor state
                                    StateStructure st = new DecorateStateStructure(this, parser);
                                    if (parser.HasError)
                                    {
                                        return;
                                    }
                                    states[previoustoken.ToLowerInvariant()] = st;
                                }
                                else
                                {
                                    parser.ReportError("Expected actor state name");
                                    return;
                                }
                            }
                            else
                            {
                                // Keep token
                                previoustoken = statetoken;
                            }
                        }
                        else
                        {
                            parser.ReportError("Unexpected end of structure");
                            return;
                        }
                    }
                    break;

                case "var":     //mxd
                                // Type
                    parser.SkipWhitespace(true);
                    string        typestr = parser.ReadToken().ToUpperInvariant();
                    UniversalType type    = UniversalType.EnumOption;  // There is no Unknown type, so let's use something impossiburu...
                    switch (typestr)
                    {
                    case "INT": type = UniversalType.Integer; break;

                    case "FLOAT": type = UniversalType.Float; break;

                    default: parser.LogWarning("Unknown user variable type"); break;
                    }

                    // Name
                    parser.SkipWhitespace(true);
                    string name = parser.ReadToken();
                    if (string.IsNullOrEmpty(name))
                    {
                        parser.ReportError("Expected User Variable name");
                        return;
                    }
                    if (!name.StartsWith("user_", StringComparison.OrdinalIgnoreCase))
                    {
                        parser.ReportError("User Variable name must start with \"user_\" prefix");
                        return;
                    }
                    if (uservars.ContainsKey(name))
                    {
                        parser.ReportError("User Variable \"" + name + "\" is double defined");
                        return;
                    }
                    if (!skipsuper && baseclass != null && baseclass.uservars.ContainsKey(name))
                    {
                        parser.ReportError("User variable \"" + name + "\" is already defined in one of the parent classes");
                        return;
                    }

                    // Rest
                    parser.SkipWhitespace(true);
                    string next = parser.ReadToken();
                    if (next == "[")     // that's User Array. Let's skip it...
                    {
                        int arrlen = -1;
                        if (!parser.ReadSignedInt(ref arrlen))
                        {
                            parser.ReportError("Expected User Array length");
                            return;
                        }
                        if (arrlen < 1)
                        {
                            parser.ReportError("User Array length must be a positive value");
                            return;
                        }
                        if (!parser.NextTokenIs("]") || !parser.NextTokenIs(";"))
                        {
                            return;
                        }
                    }
                    else if (next != ";")
                    {
                        parser.ReportError("Expected \";\", but got \"" + next + "\"");
                        return;
                    }
                    else
                    {
                        // Add to collection
                        uservars.Add(name, type);
                    }
                    break;

                case "}":
                    //mxd. Get user vars from the BaseClass, if we have one
                    if (!skipsuper && baseclass != null && baseclass.uservars.Count > 0)
                    {
                        foreach (var group in baseclass.uservars)
                        {
                            uservars.Add(group.Key, group.Value);
                        }
                    }

                    // Actor scope ends here, break out of this parse loop
                    done = true;
                    break;

                // Monster property?
                case "monster":
                    // This sets certain flags we are interested in
                    flags["shootable"]      = true;
                    flags["countkill"]      = true;
                    flags["solid"]          = true;
                    flags["canpushwalls"]   = true;
                    flags["canusewalls"]    = true;
                    flags["activatemcross"] = true;
                    flags["canpass"]        = true;
                    flags["ismonster"]      = true;
                    break;

                // Projectile property?
                case "projectile":
                    // This sets certain flags we are interested in
                    flags["noblockmap"]     = true;
                    flags["nogravity"]      = true;
                    flags["dropoff"]        = true;
                    flags["missile"]        = true;
                    flags["activateimpact"] = true;
                    flags["activatepcross"] = true;
                    flags["noteleport"]     = true;
                    break;

                // Clearflags property?
                case "clearflags":
                    // Clear all flags
                    flags.Clear();
                    break;

                // Game property?
                case "game":
                    // Include all tokens on the same line
                    List <string> games = new List <string>();
                    while (parser.SkipWhitespace(false))
                    {
                        string v = parser.ReadToken();
                        if (string.IsNullOrEmpty(v))
                        {
                            parser.ReportError("Expected \"Game\" property value");
                            return;
                        }
                        if (v == "\n")
                        {
                            break;
                        }
                        if (v == "}")
                        {
                            return;               //mxd
                        }
                        if (v != ",")
                        {
                            games.Add(v.ToLowerInvariant());
                        }
                    }
                    props[token] = games;
                    break;

                // Property
                default:
                    // Property begins with $? Then the whole line is a single value
                    if (token.StartsWith("$"))
                    {
                        // This is for editor-only properties such as $sprite and $category
                        props[token] = new List <string> {
                            (parser.SkipWhitespace(false) ? parser.ReadLine() : "")
                        };
                    }
                    else
                    {
                        // Next tokens up until the next newline are values
                        List <string> values = new List <string>();
                        while (parser.SkipWhitespace(false))
                        {
                            string v = parser.ReadToken();
                            if (string.IsNullOrEmpty(v))
                            {
                                parser.ReportError("Unexpected end of structure");
                                return;
                            }
                            if (v == "\n")
                            {
                                break;
                            }
                            if (v == "}")
                            {
                                return;               //mxd
                            }
                            if (v != ",")
                            {
                                values.Add(v);
                            }
                        }

                        //mxd. Translate scale to xscale and yscale
                        if (token == "scale")
                        {
                            props["xscale"] = values;
                            props["yscale"] = values;
                        }
                        else
                        {
                            props[token] = values;
                        }
                    }
                    break;
                }

                if (done)
                {
                    break;       //mxd
                }
                // Keep token
                previoustoken = token;
            }

            // parsing done, process thing arguments
            ParseCustomArguments();

            //mxd. Check if baseclass is valid
            if (inheritclass.ToLowerInvariant() != "actor" && doomednum > -1)
            {
                //check if this class inherits from a class defined in game configuration
                Dictionary <int, ThingTypeInfo> things = General.Map.Config.GetThingTypes();
                string inheritclasscheck = inheritclass.ToLowerInvariant();

                foreach (KeyValuePair <int, ThingTypeInfo> ti in things)
                {
                    if (!string.IsNullOrEmpty(ti.Value.ClassName) && ti.Value.ClassName.ToLowerInvariant() == inheritclasscheck)
                    {
                        //states
                        // [ZZ] allow internal prefix here. it can inherit MapSpot, light, or other internal stuff.
                        if (states.Count == 0 && !string.IsNullOrEmpty(ti.Value.Sprite))
                        {
                            states.Add("spawn", new StateStructure(ti.Value.Sprite.StartsWith(DataManager.INTERNAL_PREFIX) ? ti.Value.Sprite : ti.Value.Sprite.Substring(0, 5)));
                        }

                        if (baseclass == null)
                        {
                            //flags
                            if (ti.Value.Hangs && !flags.ContainsKey("spawnceiling"))
                            {
                                flags["spawnceiling"] = true;
                            }

                            if (ti.Value.Blocking > 0 && !flags.ContainsKey("solid"))
                            {
                                flags["solid"] = true;
                            }

                            //properties
                            if (!props.ContainsKey("height"))
                            {
                                props["height"] = new List <string> {
                                    ti.Value.Height.ToString()
                                }
                            }
                            ;

                            if (!props.ContainsKey("radius"))
                            {
                                props["radius"] = new List <string> {
                                    ti.Value.Radius.ToString()
                                }
                            }
                            ;
                        }

                        // [ZZ] inherit arguments from game configuration
                        //
                        if (!props.ContainsKey("$clearargs"))
                        {
                            for (int i = 0; i < 5; i++)
                            {
                                if (args[i] != null)
                                {
                                    continue; // don't touch it if we already have overrides
                                }
                                ArgumentInfo arg = ti.Value.Args[i];
                                if (arg != null && arg.Used)
                                {
                                    args[i] = arg;
                                }
                            }
                        }

                        return;
                    }
                }

                if (baseclass == null)
                {
                    parser.LogWarning("Unable to find \"" + inheritclass + "\" class to inherit from, while parsing \"" + classname + ":" + doomednum + "\"");
                }
            }
        }

        #endregion
    }
}
Exemplo n.º 12
0
 public void Initialize()
 {
     _argumentInfo      = new ArgumentInfo();
     _argumentInfo.Name = "actual";
 }
Exemplo n.º 13
0
 public static ArgumentInfo <TFirstType> Member <TFirstType, TSecondType>(
     this ArgumentInfo <TFirstType> currentArg,
     in Expression <Func <TFirstType, TSecondType> > propertyExpression,
Exemplo n.º 14
0
 public static ArgumentInfo <T> If <T>(this ArgumentInfo <T> arg, Predicate <T> predicate, in string type = ValidationType.If, in string message = null)
Exemplo n.º 15
0
 public ValueArgumentHandler(ArgumentInfo argumentInfo)
     : base(argumentInfo)
 {
 }
Exemplo n.º 16
0
        static ServiceAction BuildAction(MethodInfo method,
                                         object service,
                                         Dictionary <string, StateVariableInfo> stateVariables)
        {
            var attributes = method.GetCustomAttributes(typeof(UpnpActionAttribute), false);

            if (attributes.Length != 0)
            {
                var attribute = (UpnpActionAttribute)attributes[0];
                if (Omit(method.DeclaringType, service, attribute.OmitUnless))
                {
                    return(null);
                }
                var name       = string.IsNullOrEmpty(attribute.Name) ? method.Name : attribute.Name;
                var parameters = method.GetParameters();
                var arguments  = new ArgumentInfo[parameters.Length];
                for (var i = 0; i < parameters.Length; i++)
                {
                    arguments[i] = BuildArgumentInfo(parameters[i], name, stateVariables);
                }
                var return_argument = BuildArgumentInfo(method.ReturnParameter, name, stateVariables, true);
                return(new ServiceAction(name, Combine(arguments, return_argument), args => {
                    Trace(name, args.Values);

                    var argument_array = new object[arguments.Length];
                    for (var i = 0; i < arguments.Length; i++)
                    {
                        var argument = arguments[i];
                        if (argument.Argument.Direction == ArgumentDirection.Out)
                        {
                            continue;
                        }

                        string value;
                        if (args.TryGetValue(argument.Argument.Name, out value))
                        {
                            var parameter_type = argument.ParameterInfo.ParameterType;
                            if (parameter_type.IsEnum)
                            {
                                // TODO handle attributes
                                foreach (var enum_value in Enum.GetValues(parameter_type))
                                {
                                    if (Enum.GetName(parameter_type, enum_value) == value)
                                    {
                                        argument_array[i] = enum_value;
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                argument_array[i] = Convert.ChangeType(value, parameter_type);
                            }
                        }
                        else
                        {
                            // TODO throw
                        }
                    }

                    object result;
                    try {
                        result = method.Invoke(service, argument_array);
                    } catch (TargetInvocationException e) {
                        if (e.InnerException is UpnpControlException)
                        {
                            throw e.InnerException;
                        }
                        else
                        {
                            throw new UpnpControlException(
                                UpnpError.Unknown(), "Unexpected exception.", e.InnerException);
                        }
                    }

                    var out_arguments = new Dictionary <string, string> ();
                    for (var i = 0; i < arguments.Length; i++)
                    {
                        if (arguments[i].Argument.Direction == ArgumentDirection.In)
                        {
                            continue;
                        }
                        var value = argument_array[i];
                        out_arguments.Add(arguments[i].Argument.Name, value != null ? value.ToString() : "");
                    }
                    if (return_argument != null)
                    {
                        out_arguments.Add(return_argument.Argument.Name, result.ToString());
                    }

                    Trace(name, out_arguments);

                    return out_arguments;
                }));
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 17
0
 public static ArgumentInfo <T> IfGreaterThan <T>(this ArgumentInfo <T> arg, T value, in string type = ValidationType.IfGreaterThan, in string message = null)
Exemplo n.º 18
0
 public static ArgumentInfo <string> IfNullOrWhiteSpace(this ArgumentInfo <string> arg, in string type = ValidationType.IfNullOrWhiteSpace, in string message = null)
Exemplo n.º 19
0
        public dynamic Parse(ArgumentInfo argumentInfo)
        {
            var value = argumentInfo.ValueInfo.Value;

            return(ParseString(argumentInfo, value));
        }
Exemplo n.º 20
0
        IDictionary <string, ArgumentInfo> GetSymbolNameMapper(Compilation compilation, INamedTypeSymbol classSymbol)
        {
            var nameMapper = new Dictionary <string, ArgumentInfo>();


            foreach (var baseParam in GetBaseTypeParameters())
            {
                var newName = NewArgumentName(baseParam.Name.ToCamelCase(), nameMapper);
                nameMapper[newName] = new ArgumentInfo
                {
                    ArgName          = newName,
                    ArgTypeSymbol    = baseParam.Type,
                    MemberName       = baseParam.Name,
                    MemberTypeSymbol = baseParam.Type,
                    Source           = ArgumentSource.BaseCtor
                };
            }
            foreach (var field in GetInstanceFields())
            {
                var newName = NewArgumentName(field.Name.ToCamelCase(), nameMapper);
                nameMapper[newName] = new ArgumentInfo
                {
                    ArgName          = newName,
                    ArgTypeSymbol    = field.Type,
                    MemberName       = field.Name,
                    MemberTypeSymbol = field.Type,
                    Source           = ArgumentSource.Field
                };
            }
            foreach (var property in GetInstanceProperties())
            {
                var newName = NewArgumentName(property.Name.ToCamelCase(), nameMapper);
                nameMapper[newName] = new ArgumentInfo
                {
                    ArgName          = newName,
                    ArgTypeSymbol    = property.Type,
                    MemberName       = property.Name,
                    MemberTypeSymbol = property.Type,
                    Source           = ArgumentSource.Property
                };
            }


            return(nameMapper);

            IEnumerable <IFieldSymbol> GetInstanceFields()
            {
                return(classSymbol.GetMembers().OfType <IFieldSymbol>()
                       .Where(p => !p.IsStatic && !p.IsConst && p.CanBeReferencedByName && !p.HasAttribute(typeof(AutoConstructorIgnoreAttribute))));
            }

            IEnumerable <IPropertySymbol> GetInstanceProperties()
            {
                return(classSymbol.GetMembers().OfType <IPropertySymbol>()
                       .Where(p => !p.IsStatic && !p.IsIndexer && p.CanBeReferencedByName && p.IsAutoProperty() && !p.HasAttribute(typeof(AutoConstructorIgnoreAttribute))));
            }

            ImmutableArray <IParameterSymbol> GetBaseTypeParameters()
            {
                if (classSymbol.BaseType == null)
                {
                    return(ImmutableArray <IParameterSymbol> .Empty);
                }

                // if found Microsoft.Extensions.DependencyInjection.ActivatorUtilitiesConstructorAttribute, use it first
                var primaryCtor = classSymbol.BaseType.Constructors
                                  .FirstOrDefault(p => p.HasAttribute(
                                                      "Microsoft.Extensions.DependencyInjection.ActivatorUtilitiesConstructorAttribute"));

                if (primaryCtor != null)
                {
                    return(primaryCtor.Parameters);
                }

                // use first minimum parameters
                var ctor = classSymbol.BaseType.Constructors.OrderBy(method => method.Parameters.Length)
                           .FirstOrDefault();

                if (ctor == null)
                {
                    return(ImmutableArray <IParameterSymbol> .Empty);
                }

                return(ctor.Parameters);
            }

            string NewArgumentName(string baseName, IDictionary <string, ArgumentInfo> ctx)
            {
                if (string.IsNullOrEmpty(baseName))
                {
                    baseName = "args";
                }

                string newName = baseName;
                int    index   = 1;

                while (ctx.ContainsKey(newName))
                {
                    newName = baseName + index++;
                }

                return(newName);
            }
        }
Exemplo n.º 21
0
 private char GetChar(ArgumentInfo argumentInfo, string value)
 {
     if (string.IsNullOrEmpty(value))
     {
         return(default);
Exemplo n.º 22
0
        public DynamicInvokeInfo(MethodBase method, IntPtr invokeThunk)
        {
            Method      = method;
            InvokeThunk = invokeThunk;

            _isStatic = method.IsStatic;

            // _isValueTypeInstanceMethod = method.DeclaringType?.IsValueType ?? false;

            ParameterInfo[] parameters = method.GetParametersNoCopy();

            _argumentCount = parameters.Length;

            if (_argumentCount != 0)
            {
                ArgumentInfo[] arguments = new ArgumentInfo[parameters.Length];
                for (int i = 0; i < parameters.Length; i++)
                {
                    Transform transform = default;

                    Type argumentType = parameters[i].ParameterType;
                    if (argumentType.IsByRef)
                    {
                        _needsCopyBack = true;
                        transform     |= Transform.ByRef;
                        argumentType   = argumentType.GetElementType() !;
                    }
                    Debug.Assert(!argumentType.IsByRef);

                    EETypePtr eeArgumentType = argumentType.GetEEType();

                    if (eeArgumentType.IsValueType)
                    {
                        Debug.Assert(argumentType.IsValueType);

                        if (eeArgumentType.IsByRefLike)
                        {
                            _argumentCount = ArgumentCount_NotSupported_ByRefLike;
                        }

                        if (eeArgumentType.IsNullable)
                        {
                            transform |= Transform.Nullable;
                        }
                    }
                    else if (eeArgumentType.IsPointer)
                    {
                        Debug.Assert(argumentType.IsPointer);

                        transform |= Transform.Pointer;
                    }
                    else
                    {
                        transform |= Transform.Reference;
                    }

                    arguments[i] = new ArgumentInfo(transform, eeArgumentType);
                }
                _arguments = arguments;
            }

            if (method is MethodInfo methodInfo)
            {
                Transform transform = default;

                Type returnType = methodInfo.ReturnType;
                if (returnType.IsByRef)
                {
                    transform |= Transform.ByRef;
                    returnType = returnType.GetElementType() !;
                }
                Debug.Assert(!returnType.IsByRef);

                EETypePtr eeReturnType = returnType.GetEEType();

                if (eeReturnType.IsValueType)
                {
                    Debug.Assert(returnType.IsValueType);

                    if (returnType != typeof(void))
                    {
                        if (eeReturnType.IsByRefLike)
                        {
                            _argumentCount = ArgumentCount_NotSupported_ByRefLike;
                        }

                        if ((transform & Transform.ByRef) == 0)
                        {
                            transform |= Transform.AllocateReturnBox;
                        }

                        if (eeReturnType.IsNullable)
                        {
                            transform |= Transform.Nullable;
                        }
                    }
                    else
                    {
                        if ((transform & Transform.ByRef) != 0)
                        {
                            _argumentCount = ArgumentCount_NotSupported; // ByRef to void return
                        }
                    }
                }
                else if (eeReturnType.IsPointer)
                {
                    Debug.Assert(returnType.IsPointer);

                    transform |= Transform.Pointer;
                    if ((transform & Transform.ByRef) == 0)
                    {
                        transform |= Transform.AllocateReturnBox;
                    }
                }
                else
                {
                    transform |= Transform.Reference;
                }

                _returnTransform = transform;
                _returnType      = eeReturnType;
            }
        }
Exemplo n.º 23
0
        private int defaultvalue;         //mxd

        #endregion

        #region ================== Properties

        #endregion

        #region ================== Methods

        //mxd
        public override void SetupArgument(TypeHandlerAttribute attr, ArgumentInfo arginfo)
        {
            defaultvalue = (int)arginfo.DefaultValue;
            base.SetupArgument(attr, arginfo);
        }
Exemplo n.º 24
0
 public IntArgumentHandler(ArgumentInfo argumentInfo)
     : base(argumentInfo)
 {
 }
Exemplo n.º 25
0
        // This sets up the control for a specific argument
        public void Setup(ArgumentInfo arginfo)
        {
            int oldvalue = 0;

            // Get the original value
            if (typehandler != null)
            {
                oldvalue = typehandler.GetIntValue();
            }

            // Get the type handler
            typehandler = General.Types.GetArgumentHandler(arginfo);

            // Clear combobox
            combobox.SelectedItem = null;
            combobox.Items.Clear();

            // Check if this supports enumerated options
            if (typehandler.IsEnumerable)
            {
                // Show the combobox
                button.Visible         = false;
                scrollbuttons.Visible  = false;
                combobox.DropDownStyle = ComboBoxStyle.DropDown;
                combobox.Items.AddRange(typehandler.GetEnumList().ToArray());
                combobox.DropDownWidth = Tools.GetDropDownWidth(combobox);                 //mxd
            }
            // Check if browsable
            else if (typehandler.IsBrowseable)
            {
                // Show the button
                button.Visible         = true;
                button.Image           = typehandler.BrowseImage;
                scrollbuttons.Visible  = false;
                combobox.DropDownStyle = ComboBoxStyle.Simple;
            }
            else
            {
                // Show textbox with scroll buttons
                button.Visible         = false;
                scrollbuttons.Visible  = true;
                combobox.DropDownStyle = ComboBoxStyle.Simple;
            }

            //mxd
            if (typehandler.IsEnumerable)
            {
                combobox.AutoCompleteMode   = AutoCompleteMode.Suggest;
                combobox.AutoCompleteSource = AutoCompleteSource.ListItems;
            }
            else
            {
                combobox.AutoCompleteMode   = AutoCompleteMode.None;
                combobox.AutoCompleteSource = AutoCompleteSource.None;
            }

            // Setup layout
            ArgumentBox_Resize(this, EventArgs.Empty);

            //mxd. If not mixed values, re-apply the old value
            if (!string.IsNullOrEmpty(combobox.Text))
            {
                SetValue(oldvalue);
            }
        }
Exemplo n.º 26
0
            protected override void RunInstruction(ComputerInstruction instruction, ArgumentInfo arg0, ArgumentInfo arg1, ref int instructionOffset)
            {
                switch (instruction.Operator)
                {
                case ComputerOperator.Send:
                    long message = arg0.Value;
                    LinkedProgram.messageQueue.Enqueue(message);
                    HaltRequested = ValueSent?.Invoke(message) ?? false;
                    break;

                case ComputerOperator.Receive:
                    bool received = messageQueue.TryDequeue(out long value);
                    if (!received)
                    {
                        // Reattempt receiving the value when continuing execution, halt until rerun
                        instructionOffset = 0;
                        HaltRequested     = true;
                        break;
                    }

                    Registers[arg0.RegisterName] = value;
                    break;

                default:
                    base.RunInstruction(instruction, arg0, arg1, ref instructionOffset);
                    return;
                }
            }
Exemplo n.º 27
0
 public static ArgumentInfo <List <TItem> > Every <TItem>(this ArgumentInfo <List <TItem> > arg, in Action <ArgumentInfo <TItem> > action) =>
        public bool Finalize()
        {
            ClearError();

            // parse class data
            foreach (ZScriptClassStructure cls in allclasseslist)
            {
                if (!cls.Process())
                {
                    return(false);
                }
            }

            // set datastream to null so that log messages aren't output using incorrect line numbers
            Stream odatastream = datastream;

            datastream = null;

            // inject superclasses, since everything is parsed by now
            Dictionary <int, ThingTypeInfo> things = General.Map.Config.GetThingTypes();

            foreach (ZScriptClassStructure cls in allclasseslist)
            {
                ActorStructure actor = cls.Actor;
                if (actor != null && cls.ParentName != null && cls.ParentName.ToLowerInvariant() != "thinker") // don't try to inherit this one
                {
                    actor.baseclass = GetArchivedActorByName(cls.ParentName, true);
                    string inheritclass = cls.ParentName;

                    //check if this class inherits from a class defined in game configuration
                    string inheritclasscheck = inheritclass.ToLowerInvariant();

                    // inherit args from base class
                    if (actor.baseclass != null)
                    {
                        for (int i = 0; i < 5; i++)
                        {
                            if (actor.args[i] == null)
                            {
                                actor.args[i] = actor.baseclass.args[i];
                            }
                        }
                    }

                    bool thingfound = false;
                    foreach (KeyValuePair <int, ThingTypeInfo> ti in things)
                    {
                        if (!string.IsNullOrEmpty(ti.Value.ClassName) && ti.Value.ClassName.ToLowerInvariant() == inheritclasscheck)
                        {
                            //states
                            // [ZZ] allow internal prefix here. it can inherit MapSpot, light, or other internal stuff.
                            if (actor.states.Count == 0 && !string.IsNullOrEmpty(ti.Value.Sprite))
                            {
                                actor.states.Add("spawn", new StateStructure(ti.Value.Sprite.StartsWith(DataManager.INTERNAL_PREFIX) ? ti.Value.Sprite : ti.Value.Sprite.Substring(0, 5)));
                            }

                            if (actor.baseclass == null)
                            {
                                //flags
                                if (ti.Value.Hangs && !actor.flags.ContainsKey("spawnceiling"))
                                {
                                    actor.flags["spawnceiling"] = true;
                                }

                                if (ti.Value.Blocking > 0 && !actor.flags.ContainsKey("solid"))
                                {
                                    actor.flags["solid"] = true;
                                }

                                //properties
                                if (!actor.props.ContainsKey("height"))
                                {
                                    actor.props["height"] = new List <string> {
                                        ti.Value.Height.ToString()
                                    }
                                }
                                ;

                                if (!actor.props.ContainsKey("radius"))
                                {
                                    actor.props["radius"] = new List <string> {
                                        ti.Value.Radius.ToString()
                                    }
                                }
                                ;
                            }

                            // [ZZ] inherit arguments from game configuration
                            //
                            if (!actor.props.ContainsKey("$clearargs"))
                            {
                                for (int i = 0; i < 5; i++)
                                {
                                    if (actor.args[i] != null)
                                    {
                                        continue; // don't touch it if we already have overrides
                                    }
                                    ArgumentInfo arg = ti.Value.Args[i];
                                    if (arg != null && arg.Used)
                                    {
                                        actor.args[i] = arg;
                                    }
                                }
                            }

                            thingfound = true;
                            break;
                        }

                        if (actor.baseclass == null && !thingfound)
                        {
                            LogWarning("Unable to find \"" + inheritclass + "\" class to inherit from, while parsing \"" + cls.ClassName + "\"");
                        }
                    }
                }
            }

            // validate user variables (no variables should shadow parent variables)
            foreach (ZScriptClassStructure cls in allclasseslist)
            {
                ActorStructure actor = cls.Actor;
                if (actor == null)
                {
                    continue;
                }
                ActorStructure actorbase = actor.baseclass;
                while (actorbase != null)
                {
                    foreach (string uservar in actor.uservars.Keys)
                    {
                        if (actorbase.uservars.ContainsKey(uservar))
                        {
                            actor.uservars.Clear();
                            ReportError("Variable \"" + uservar + "\" in class \"" + actor.classname + "\" shadows variable \"" + uservar + "\" in base class \"" + actorbase.classname + "\". This is not supported");
                            goto stopValidatingCompletely;
                        }
                    }

                    actorbase = actorbase.baseclass;
                }
            }
stopValidatingCompletely:
            datastream = odatastream;
            return(true);
        }
Exemplo n.º 29
0
 private static string GetArgumentFormat(ArgumentInfo argumentInfo)
 {
     return(!argumentInfo.IsBoolean ? argumentInfo.Name + " " + (string.IsNullOrEmpty(argumentInfo.Type) ? "VALUE" : argumentInfo.Type) : argumentInfo.Name);
 }
Exemplo n.º 30
0
 public ArgumentInfoDto(ArgumentInfo argumentInfo)
 {
     Name          = argumentInfo.Name;
     Description   = argumentInfo.Description;
     ExampleValues = argumentInfo.ExampleValues;
 }
        public void UpdateAddressSharedEntitiesForParameter(IParameterSymbol parameter, AnalysisEntity analysisEntity, ArgumentInfo <TAbstractAnalysisValue>?assignedValue)
        {
            if (parameter.RefKind != RefKind.None &&
                assignedValue?.AnalysisEntity != null)
            {
                var addressSharedEntities = ComputeAddressSharedEntities();
                var isReferenceCopy       = !addressSharedEntities.Any(a => a.Type.IsValueType);
                var copyValue             = new CopyAbstractValue(addressSharedEntities, isReferenceCopy);
                foreach (var entity in copyValue.AnalysisEntities)
                {
                    _addressSharedEntitiesBuilder[entity] = copyValue;
                }
            }

            ImmutableHashSet <AnalysisEntity> ComputeAddressSharedEntities()
            {
                RoslynDebug.Assert(assignedValue?.AnalysisEntity != null);

                var builder = PooledHashSet <AnalysisEntity> .GetInstance();

                AddIfHasKnownInstanceLocation(analysisEntity, builder);
                AddIfHasKnownInstanceLocation(assignedValue.AnalysisEntity, builder);

                // We need to handle multiple ref/out parameters passed the same location.
                // For example, "M(ref a, ref a);"
                if (_addressSharedEntitiesBuilder.TryGetValue(assignedValue.AnalysisEntity, out var existingValue))
                {
                    foreach (var entity in existingValue.AnalysisEntities)
                    {
                        AddIfHasKnownInstanceLocation(entity, builder);
                    }
                }

                // Also handle case where the passed in argument is also a ref/out parameter and has address shared entities.
                if (_addressSharedEntitiesBuilder.TryGetValue(analysisEntity, out existingValue))
                {
                    foreach (var entity in existingValue.AnalysisEntities)
                    {
                        AddIfHasKnownInstanceLocation(entity, builder);
                    }
                }

                Debug.Assert(builder.All(e => !e.HasUnknownInstanceLocation));
                return(builder.ToImmutableAndFree());
            }
Exemplo n.º 32
0
        public static Options Parse(string[] args)
        {
            var options = new Options();

            var          info    = ExtractInfo();
            ArgumentInfo actions = info.SingleOrDefault(x => x.Definition.IsNameless);
            IEnumerable <ArgumentInfo> arguments = info.Where(x => !x.Definition.IsNameless);

            var queue = new Queue <string>(args);

            while (queue.Count > 0)
            {
                var token = queue.Dequeue();
                if (token.StartsWith("-"))
                {
                    ArgumentInfo argument = null;

                    if (token.StartsWith("--"))
                    {
                        var name = token.Substring(2);
                        argument = arguments.SingleOrDefault(x => x.Definition.LongName == name);
                    }
                    else
                    {
                        var name = token.Substring(1).First();
                        argument = arguments.SingleOrDefault(x => x.Definition.ShortName == name);
                    }

                    if (argument == null)
                    {
                        throw new PackDmException("Argumento não reconhecido: " + token);
                    }

                    argument.Property.SetValue(options, true, null);
                    if (argument.HasValue)
                    {
                        if (queue.Count == 0)
                        {
                            throw new PackDmException("O argumento requer um valor: " + token);
                        }

                        var value = queue.Dequeue();

                        var list = argument.ValueProperty.GetValue(options, null) as List <string>;
                        if (list != null)
                        {
                            list.Add(value);
                        }
                        else
                        {
                            argument.ValueProperty.SetValue(options, value, null);
                        }
                    }
                }
                else
                {
                    actions.Property.SetValue(options, true, null);
                    var currentValue = actions.ValueProperty.GetValue(options, null);
                    var newValue     = (currentValue + " " + token).Trim();
                    actions.ValueProperty.SetValue(options, newValue, null);
                }
            }

            return(options);
        }
Exemplo n.º 33
0
        private static object Parse(string[] args, object result, Type resultType)
        {
            var mapper = new Dictionary <string, ArgumentInfo>();

            foreach (var p in resultType.GetProperties())
            {
                var argAttr = FxExtensions.FirstOrDefault(p.GetCustomAttributes(typeof(ArgumentAttribute), true)) as ArgumentAttribute;
                if (argAttr == null)
                {
                    continue;
                }

                // 未指定TagName,默认使用"--{PropertyName}"作为TagName
                string tagName = string.IsNullOrEmpty(argAttr.TagName) ? "--" + p.Name : argAttr.TagName;
                tagName = tagName.ToLowerInvariant();
                var argInfo = new ArgumentInfo()
                {
                    TagName  = tagName,
                    Optional = argAttr.Optional,
                    Property = p
                };
                mapper.Add(tagName, argInfo);
            }
            int index = 0;

            while (index < args.Length)
            {
                string tmp = args[index];
                if (mapper.TryGetValue(tmp.Trim().ToLowerInvariant(), out var argInfo))
                {
                    if (argInfo.IsSet)
                    {
                        throw new ParserException($"指定了重复参数:参数名={tmp}");
                    }

                    var prop = argInfo.Property;
                    // 布尔参数不需要读取值
                    if (prop.PropertyType == typeof(bool) ||
                        prop.PropertyType == typeof(bool?))
                    {
                        prop.SetValue(result, true, null);
                    }
                    else
                    {
                        if (++index >= args.Length)
                        {
                            throw new ParserException($"缺少参数值: 参数名={tmp}");
                        }
                        try
                        {
                            object value = ConvertData(args[index], prop.PropertyType);
                            prop.SetValue(result, value, null);
                        }
                        catch (Exception)
                        {
                            throw new ParserException($"参数值转换错误: 参数名={tmp}");
                        }
                    }
                    argInfo.IsSet = true;
                }
                index++;
            }
            foreach (var item in mapper.Values)
            {
                if (!item.Optional && !item.IsSet)
                {
                    throw new ParserException($"缺少必须的参数:参数名={item.TagName}");
                }
            }

            return(result);
        }
Exemplo n.º 34
0
		static BlackCard ( )
		{
			ArgumentInfo stock = new ArgumentInfo ( "" , "" , typeof ( Stock ) , new StockTransactDefineDomain ( true ) ) ;
			Arguments = new List <ArgumentInfo> { stock } ;
		}
Exemplo n.º 35
0
 public dynamic Parse(ArgumentInfo argumentInfo)
 {
     return(ParseString(argumentInfo.ValueInfo.Value, argumentInfo.IsImplicit, argumentInfo.TypeDisplayName));
 }
Exemplo n.º 36
0
        private static ISignatureInfo ParseSignature(string functionName, ParseContext context)
        {
            SignatureInfo        info = new SignatureInfo(functionName);
            List <IArgumentInfo> signatureArguments = new List <IArgumentInfo>();

            // RD data may contain function name(s) without braces
            if (context.Tokens.CurrentToken.TokenType == RTokenType.OpenBrace)
            {
                FunctionCall functionCall = new FunctionCall();
                functionCall.Parse(context, context.AstRoot);

                for (int i = 0; i < functionCall.Arguments.Count; i++)
                {
                    IAstNode arg = functionCall.Arguments[i];

                    string argName         = null;
                    string argDefaultValue = null;
                    bool   isEllipsis      = false;
                    bool   isOptional      = false;

                    ExpressionArgument expArg = arg as ExpressionArgument;
                    if (expArg != null)
                    {
                        argName = context.TextProvider.GetText(expArg.ArgumentValue);
                    }
                    else
                    {
                        NamedArgument nameArg = arg as NamedArgument;
                        if (nameArg != null)
                        {
                            argName         = context.TextProvider.GetText(nameArg.NameRange);
                            argDefaultValue = nameArg.DefaultValue != null?
                                              RdText.CleanRawRdText(context.TextProvider.GetText(nameArg.DefaultValue)) : string.Empty;
                        }
                        else
                        {
                            MissingArgument missingArg = arg as MissingArgument;
                            if (missingArg != null)
                            {
                                argName = string.Empty;
                            }
                            else
                            {
                                EllipsisArgument ellipsisArg = arg as EllipsisArgument;
                                if (ellipsisArg != null)
                                {
                                    argName    = "...";
                                    isEllipsis = true;
                                }
                            }
                        }
                    }

                    ArgumentInfo argInfo = new ArgumentInfo(argName);
                    argInfo.DefaultValue = argDefaultValue;
                    argInfo.IsEllipsis   = isEllipsis;
                    argInfo.IsOptional   = isOptional; // TODO: actually parse

                    signatureArguments.Add(argInfo);
                }
            }

            info.Arguments = signatureArguments;
            return(info);
        }
Exemplo n.º 37
0
 public string GetDisplayName(ArgumentInfo argumentInfo)
 {
     return(argumentInfo.UnderlyingType.Name);
 }
            protected override void SetValueForParameterOnEntry(IParameterSymbol parameter, AnalysisEntity analysisEntity, ArgumentInfo<CopyAbstractValue>? assignedValueOpt)
            {
                CopyAbstractValue copyValue;
                if (assignedValueOpt != null)
                {
                    var assignedEntities = assignedValueOpt.Value.AnalysisEntities;
                    if (assignedValueOpt.AnalysisEntityOpt != null && !assignedEntities.Contains(assignedValueOpt.AnalysisEntityOpt))
                    {
                        assignedEntities = assignedEntities.Add(assignedValueOpt.AnalysisEntityOpt);
                    }

                    var newAnalysisEntities = assignedEntities;
                    CopyAbstractValueKind newKind;
                    if (assignedValueOpt.Value.Kind.IsKnown())
                    {
                        newKind = assignedValueOpt.Value.Kind;
                    }
                    else if (assignedValueOpt.AnalysisEntityOpt == null || assignedValueOpt.AnalysisEntityOpt.Type.IsValueType)
                    {
                        newKind = CopyAbstractValueKind.KnownValueCopy;
                    }
                    else
                    {
                        newKind = CopyAbstractValueKind.KnownReferenceCopy;
                    }

                    foreach (var entity in assignedEntities)
                    {
                        if (CurrentAnalysisData.TryGetValue(entity, out var existingValue))
                        {
                            newAnalysisEntities = newAnalysisEntities.Union(existingValue.AnalysisEntities);
                            newKind = newKind.MergeIfBothKnown(existingValue.Kind);
                        }
                    }

                    copyValue = assignedValueOpt.Value.AnalysisEntities.Count == newAnalysisEntities.Count ?
                        assignedValueOpt.Value :
                        new CopyAbstractValue(newAnalysisEntities, newKind);
                }
                else
                {
                    copyValue = GetDefaultCopyValue(analysisEntity);
                }

                SetAbstractValue(CurrentAnalysisData, analysisEntity, copyValue, TryGetAddressSharedCopyValue, initializingParameters: true);
            }
Exemplo n.º 39
0
        private IIriTemplateMapping BuildTemplateMapping(DescriptionContext context, Uri templateUri, OperationInfo <Verb> operation, ArgumentInfo mapping)
        {
            IIriTemplateMapping templateMapping = context.ApiDocumentation.Context.Create <IIriTemplateMapping>(templateUri.AddFragment(mapping.VariableName));

            templateMapping.Variable    = mapping.VariableName;
            templateMapping.Required    = (mapping.Parameter.ParameterType.IsValueType) && (!mapping.Parameter.HasDefaultValue);
            templateMapping.Description = _xmlDocProvider.GetDescription(operation.UnderlyingMethod, mapping.Parameter);
            var linqBehaviors = mapping.Parameter.GetCustomAttributes <LinqServerBehaviorAttribute>(true);

            if (linqBehaviors.Any())
            {
                foreach (var visitor in _serverBehaviorAttributeVisitors)
                {
                    linqBehaviors.Accept(mapping.Parameter.ParameterType, visitor, templateMapping, context);
                }
            }
            else if (context.Type != typeof(object))
            {
                templateMapping.Property = GetMappingProperty(context, mapping.Parameter);
            }

            return(templateMapping);
        }
Exemplo n.º 40
0
        private bool ParseTypeMember()
        {
            var identifier = ParseGenericIdentifier();
            if (identifier == null)
                return false;

            if (IsWhitespace())
                SkipWhitespace();

            var member = new MemberInfo
            {
                Modifiers = new List<string>(modifiers),
                Arguments = new List<ArgumentInfo>(),
                Name = identifier,
                IsFunction = false,
                Decorators = new List<DecoratorInfo>(),
                Type = ""
            };

            modifiers.Clear();
            typeStack.Peek().Members.Add(member);

            if (Is(TokenType.Char, "?"))
            {
                member.IsOptional = true;
                SkipWhitespace();
            }

            if (Is(TokenType.Char, ":"))
            {
                SkipWhitespace();

                string defaultValue;
                member.Type = ParseTypeExpressionAndDefault(out defaultValue, () =>
                    Is(TokenType.Char, ";") || type == TokenType.EndOfLine);

                if (member.Type == null)
                    return false;

                member.InitialValue = defaultValue ?? "";
            }
            else if (Is(TokenType.Char, "("))
            {
                member.IsFunction = true;

                while (true)
                {
                    SkipWhitespace();

                    if (type == TokenType.Char &&
                        text == ")")
                        break;

                    if (type != TokenType.Identifier)
                        return false;

                    var argument = new ArgumentInfo()
                    {
                        Name = text,
                        Modifier = "",
                        Decorators = new List<DecoratorInfo>(),
                        InitialValue = "",
                        Type = ""
                    };

                    member.Arguments.Add(argument);

                    if (text == "private" ||
                        text == "public" ||
                        text == "protected")
                    {
                        argument.Modifier = text;

                        SkipWhitespace();
                        if (type != TokenType.Identifier)
                            return false;

                        argument.Name = text;
                    }

                    SkipWhitespace();

                    if (Is(TokenType.Char, "?"))
                    {
                        argument.IsOptional = true;
                        SkipWhitespace();
                    }

                    if (Is(TokenType.Char, ":"))
                    {
                        SkipWhitespace();

                        string defaultValue;
                        argument.Type = ParseTypeExpressionAndDefault(out defaultValue, () =>
                            Is(TokenType.Char, ",") ||
                            Is(TokenType.Char, ")"));

                        if (argument.Type == null)
                            return false;
                    }
                    else if (Is(TokenType.Char, "="))
                    {
                        argument.InitialValue = ParseExpression(() =>
                            Is(TokenType.Char, ",") ||
                            Is(TokenType.Char, ")"));

                        if (argument.InitialValue == null)
                            return false;
                    }

                    if (IsWhitespace())
                        SkipWhitespace();

                    if (Is(TokenType.Char, ","))
                        continue;

                    if (!Is(TokenType.Char, ")"))
                        return false;

                    break;
                }

                SkipWhitespace();

                if (Is(TokenType.Char, ":"))
                {
                    SkipWhitespace();

                    member.Type = ParseExpression(() =>
                        Is(TokenType.Char, ";") ||
                        Is(TokenType.Char, "{"));

                    if (member.Type == null)
                        return false;
                }

                if (IsWhitespace())
                    SkipWhitespace();

                if (Is(TokenType.Char, "{"))
                {
                    braceStack.Push("{");
                    return true;
                }
                else if (Is(TokenType.Char, ";"))
                {
                    return true;
                }
                else
                    return false;
            }
            else if (Is(TokenType.Char, "="))
            {
                SkipWhitespace();

                member.InitialValue = ParseExpression(() =>
                    Is(TokenType.Char, ";") ||
                    type == TokenType.EndOfLine);

                if (member.InitialValue == null)
                    return false;
            }
            else
                return true;

            return true;
        }
Exemplo n.º 41
0
 public EnumArgumentHandler(ArgumentInfo argumentInfo)
     : base(argumentInfo)
 {
 }
Exemplo n.º 42
0
 protected ArgumentHandler(ArgumentInfo argumentInfo)
 {
     ArgumentName = argumentInfo.Name;
     ArgumentProperty = argumentInfo.PropertyInfo;
     DefaultValue = argumentInfo.DefaultValue;
 }
Exemplo n.º 43
0
        public override void Execute(JoinPointContext context)
        {
            if (context == null)
            {
                TraceBuffer.WriteLine("OUT Tracing: Context not set!");
                return;
            }


            // Sender, Target, Methodname
            String sender = "unknown";

            if (context.Sender != null)
            {
                sender = context.Sender.GetType().FullName;
            }

            Type target = null;

            if (context.StartTarget != null)
            {
                target = context.StartTarget.GetType();
            }

            TraceBuffer.WriteLine("OUT Tracing: Sender={0}, Target={1}, MethodName={2} ", sender, target, context.StartSelector);

            System.Reflection.MethodInfo mi = target.GetMethod(context.StartSelector, BindingFlags.Public
                                                               | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance);

            if (mi != null && context.ArgumentCount > 0)
            {
                System.Reflection.ParameterInfo[] pi = mi.GetParameters();
                for (int j = 0; j < pi.Length; j++)
                {
                    if (pi[j].IsOut)
                    {
                        ArgumentInfo argumentInfo = context.GetArgumentInfo((short)(j + 1));

                        if (argumentInfo.Value == null)
                        {
                            TraceBuffer.WriteLine("  argument {0} (out) -> {1} = null", j + 1, pi[j].ParameterType.FullName);
                            continue;
                        }
                        String argvalue;
                        try
                        {
                            argvalue = argumentInfo.Value.ToString();
                        }
                        catch (Exception)
                        {
                            argvalue = "<exception>";
                        }
                        TraceBuffer.WriteLine("  argument {0} (out) -> {1} = {2}", j + 1, pi[j].ParameterType.FullName, argvalue);
                    }
                }
            }

            // Returnvalue
            if (context.HasReturnValue)
            {
                if (context.ReturnType == null)
                {
                    TraceBuffer.WriteLine("  return type = null");
                }
                else if (context.ReturnValue == null)
                {
                    TraceBuffer.WriteLine("  return type = {0}, return value = null", context.ReturnType.FullName);
                }
                else if (context.StartSelector != "ToString")
                {
                    TraceBuffer.WriteLine("  return type = {0}, return value = ", context.ReturnType.FullName);
                }
                else
                {
                    String returnValue;
                    try
                    {
                        returnValue = context.ReturnValue.ToString();
                    }
                    catch (Exception)
                    {
                        returnValue = "<exception>";
                    }
                    TraceBuffer.WriteLine("  return type = {0}, return value = (1)", context.ReturnType.FullName, returnValue);
                }
            }


            //Type t = context.GetProperty("target").GetType();
            ////Console.WriteLine("Tracing IN method: "+t.get_Name() + "." + rm.getSelector());
            //System.Reflection.MethodInfo[] mi = t.GetMethods(BindingFlags.Public
            //    | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance);
            //for (int i = 0; i < mi.Length; i++)
            //{
            //    //Console.WriteLine("\tSearching for method: "+rm.getSelector()+" == "+mi[i].get_Name());
            //    if (mi[i].Name == (string)context.GetProperty("selector"))
            //    {
            //        if (((object[])context.GetProperty("args")).Length == 0)
            //        {
            //            Object[] obj = new Object[0];
            //            Console.WriteLine("TracingOUT: " + t.Name + "." + (string)context.GetProperty("selector"));
            //            break;
            //        }
            //        int k = 0;
            //        ArrayList list = new ArrayList();
            //        System.Reflection.ParameterInfo[] pi = mi[i].GetParameters();
            //        for (int j = 0; j < pi.Length; j++)
            //        {
            //            if (pi[j].IsOut)
            //            {
            //                list.Add(context.GetProperty("Arg[" + k + "]"));
            //            }
            //            k++;
            //        }
            //        Console.WriteLine("TracingOUT[" + context.GetProperty("returnvalue") + "][" + list.ToArray().Length + "]: " + list.ToString());
            //        break;
            //    }
            //}
        }
Exemplo n.º 44
0
            public static ArgumentHandler GetArgumentHandler(ArgumentInfo argumentInfo)
            {
                var argumentType = argumentInfo.PropertyInfo.PropertyType;

                if (argumentType == typeof(int))
                {
                    return new IntArgumentHandler(argumentInfo);
                }

                if (argumentType == typeof(string))
                {
                    return new ValueArgumentHandler(argumentInfo);
                }

                if (argumentType.IsSubclassOf(typeof(Enum)))
                {
                    return new EnumArgumentHandler(argumentInfo);

                }
                throw new InvalidOperationException(string.Format("Unhandled type for argument {0}", argumentInfo.Name));
            }
Exemplo n.º 45
0
        protected override void RunInstruction(ComputerInstruction instruction, ArgumentInfo arg0, ArgumentInfo arg1, ref int instructionOffset)
        {
            switch (instruction.Operator)
            {
            case ComputerOperator.Send:
                lastSound = arg0.Value32;
                break;

            case ComputerOperator.Add:
                Registers[arg0.RegisterName] += arg1.Value;
                break;

            case ComputerOperator.Subtract:
                Registers[arg0.RegisterName] -= arg1.Value;
                break;

            case ComputerOperator.Multiply:
                Registers[arg0.RegisterName] *= arg1.Value;
                break;

            case ComputerOperator.Modulo:
                Registers[arg0.RegisterName] %= arg1.Value;
                break;

            case ComputerOperator.Receive:
                if (lastSound is 0)
                {
                    break;
                }
                HaltRequested = SoundRecoveredHandler(lastSound);
                break;

            default:
                base.RunInstruction(instruction, arg0, arg1, ref instructionOffset);
                return;
            }
        }