Exemple #1
0
        //---------------------------------------------------------------------

        private IParameters ParseFile(string filename)
        {
            try {
                reader = OpenFile(filename);
                return(parser.Parse(reader));
            }
            finally {
                reader.Close();
            }
        }
Exemple #2
0
        public void Should_handle_form_parameters()
        {
            var file     = new MemoryStream();
            var formData = new Dictionary <string, object> {
                { "p1", "v1" },
                { "p2", "v2" },
                { "p3", file }
            };

            object[] actual = _target.Parse(GetType().GetMethod("FormDataMethod").GetParameters(), new JArray(), formData, new JsonSerializer());
            actual.Should().Have.SameSequenceAs(new object[] { "v1", "v2", file });
        }
        public void Should_handle_form_parameters()
        {
            var httpInputStream = TestUtils.StubHttpInputStream();
            var httpPostedFile  = TestUtils.StubHttpPostedFile(httpInputStream);
            var formData        = new Dictionary <string, object> {
                { "p1", "v1" },
                { "p2", "v2" },
                { "p3", httpPostedFile },
                { "p4", httpPostedFile }
            };

            object[] actual = _target.Parse(GetType().GetMethod("FormDataMethod").GetParameters(), new JArray(), formData, new JsonSerializer());
            actual.Should().Have.SameSequenceAs(new object[] { "v1", "v2", httpInputStream, httpPostedFile });
        }
Exemple #4
0
 private void CacheParameterValuesByCodes()
 {
     if (this.parameterValuesByCodes == null)
     {
         this.parameterValuesByCodes = ParametersParser.Parse(this.catalog.Parameters).ToDictionary(a => a.Key, a => a.Value);
     }
 }
Exemple #5
0
        public override Verb CreateVerb(string[] tokens)
        {
            if (!InClassDefinition)
            {
                return(null);
            }

            Color(position, tokens[1].Length, KeyWords);
            var name = tokens[2];

            Color(name.Length, Variables);
            var parameterLength = tokens[3].Length;

            Color(parameterLength, Structures);
            var index      = position + length;
            var parameters = new Parameters();

            if (parameterLength > 0)
            {
                var parametersParser = new ParametersParser();
                var newIndex         = parametersParser.Parse(source, index);
                if (!newIndex.If(out parameters, out index))
                {
                    return(null);
                }
            }

            overridePosition = index;

            var builder = new CodeBuilder();

            if (parameters.Length == 0)
            {
                var mangledName = MangledName(name);
                var cls         = new Class(parameters, objectBlock(name), new Block(), ClassName, new string[0], new Parameters(), false);
                var verb        = new CreateClass(mangledName, cls);
                builder.Verb(verb);
                builder.End();
                builder.Push();
                builder.FunctionInvoke(mangledName);
                builder.AssignToNewField(true, name, builder.Pop(true), global: true);
                builder.End();
            }
            else
            {
                var cls  = new Class(parameters, objectBlock(name), new Block(), ClassName, new string[0], new Parameters(), false);
                var verb = new CreateClass(name, cls);
                builder.Verb(verb);
            }
            if (HelperBlock == null)
            {
                HelperBlock = new Block();
            }
            foreach (var verb in builder.Block.AsAdded)
            {
                HelperBlock.Add(verb);
            }

            return(new NullOp());
        }
Exemple #6
0
        public override Verb CreateVerb(string[] tokens)
        {
            Color(position, tokens[1].Length, KeyWords);
            variableName = tokens[2];
            var open = tokens[3];

            Color(VariableName.Length, Types);
            Color(open.Length, Structures);
            parameters = null;
            var index = NextPosition;

            if (open == "(")
            {
                InClassDefinition = true;
                Color(open.Length, Structures);
                var parser = new ParametersParser();
                if (parser.Parse(source, index).If(out parameters, out var newIndex))
                {
                    index = newIndex;
                }
                else
                {
                    return(null);
                }

                InClassDefinition = false;
            }

            overridePosition = index;
            return(new NullOp());
        }
            public static string ParseQuery(HTTP.Parameters parameters)
            {
                var queryParameters = ParametersParser.Parse(parameters);
                var queryArray      = queryParameters.Select(pair => string.Format("{0}={1}", pair.Key, pair.Value));

                return(string.Join("&", queryArray));
            }
        public override Verb CreateVerb(string[] tokens)
        {
            var type             = tokens[2];
            var readOnly         = type == "val";
            var _override        = type == "set";
            var whitespaceLength = tokens[3].Length;

            Color(position, tokens[1].Length, Whitespaces);
            Color(type.Length, KeyWords);
            Color(whitespaceLength, Whitespaces);
            Color(tokens[4].Length, Structures);
            var parametersParser = new ParametersParser();
            var offset           = tokens[1].Length + type.Length + whitespaceLength + 1;

            if (parametersParser.Parse(source, position + offset).If(out var parameters, out var i) &&
                GetExpression(source, i, EndOfLine()).If(out var expression, out var j))
            {
                overridePosition = j;
                return(new MultiAssign(parameters, expression, readOnly, _override)
                {
                    Index = NextPosition
                });
            }

            return(null);
        }
        private void CreateOrEditDataTypeParameterValues(Member member, string parameters)
        {
            if (member.PropertyDataTypeId == null || string.IsNullOrEmpty(parameters))
            {
                return;
            }

            IDataTypeParameterRepository      dataTypeParameterRepository      = this.Storage.GetRepository <IDataTypeParameterRepository>();
            IDataTypeParameterValueRepository dataTypeParameterValueRepository = this.Storage.GetRepository <IDataTypeParameterValueRepository>();

            foreach (KeyValuePair <string, string> valueByCode in ParametersParser.Parse(parameters))
            {
                DataTypeParameter      dataTypeParameter      = dataTypeParameterRepository.WithDataTypeIdAndCode((int)member.PropertyDataTypeId, valueByCode.Key);
                DataTypeParameterValue dataTypeParameterValue = dataTypeParameterValueRepository.WithDataTypeParameterIdAndMemberId(dataTypeParameter.Id, member.Id);

                if (dataTypeParameterValue == null)
                {
                    dataTypeParameterValue = new DataTypeParameterValue();
                    dataTypeParameterValue.DataTypeParameterId = dataTypeParameter.Id;
                    dataTypeParameterValue.MemberId            = member.Id;
                    dataTypeParameterValue.Value = valueByCode.Value;
                    dataTypeParameterValueRepository.Create(dataTypeParameterValue);
                }

                else
                {
                    dataTypeParameterValue.Value = valueByCode.Value;
                    dataTypeParameterValueRepository.Edit(dataTypeParameterValue);
                }
            }

            this.Storage.Save();
        }
        public override Verb CreateVerb(string[] tokens)
        {
            var matcher = new Matcher();

            Color(position, length, Structures);
            var index = position + length;

            var parameters = new Parameters();

            if (variableParser.Scan(source, index))
            {
                var parserResult = variableParser.Result;
                var value        = parserResult.Value;
                var variable     = value.As <Variable>();
                if (variable.IsSome)
                {
                    parameters = new Parameters(new[]
                    {
                        new Parameter(variable.Value.Name)
                    });
                    index = parserResult.Position;
                }
                else
                {
                    return(null);
                }
            }
            else if (matcher.IsMatch(source.Skip(index), @"^ /s* '('"))
            {
                var matcherLength = matcher[0].Length;
                Color(matcherLength, Structures);
                index += matcherLength;
                var patternParametersParser = new ParametersParser(ParametersType.Pattern);
                if (patternParametersParser.Parse(source, ref index))
                {
                    parameters = patternParametersParser.Parameters;
                }
                else
                {
                    return(null);
                }
            }

            var block = anyBlockParser.Parse(source, ref index, false);

            if (block == null)
            {
                return(null);
            }
            var spatting = anyBlockParser.Splatting;

            overridePosition = index;
            return(new CreateLambda(parameters, block, spatting));
        }
        //---------------------------------------------------------------------

        private void TryParse(string filename,
                              int errorLineNum)
        {
            try {
                reader = OpenFile(filename);
                IParameters parameters = parser.Parse(reader);
            }
            catch (System.Exception e) {
                Data.Output.WriteLine();
                Data.Output.WriteLine(e.Message.Replace(Data.Directory, Data.DirPlaceholder));
                LineReaderException lrExc = e as LineReaderException;
                if (lrExc != null)
                {
                    Assert.AreEqual(errorLineNum, lrExc.LineNumber);
                }
                throw;
            }
            finally {
                reader.Close();
            }
        }
Exemple #12
0
        public override IActionResult Invoke(IRequestHandler requestHandler, Endpoint endpoint, IEnumerable <KeyValuePair <string, string> > parameters)
        {
            string url = string.Format("/{0}", requestHandler.HttpContext.GetRouteValue("url"));

            if (this.GetBoolArgument(ParametersParser.Parse(endpoint.Parameters), "UseCaching"))
            {
                return(requestHandler.HttpContext.RequestServices.GetService <ICache>().GetPageActionResultWithDefaultValue(
                           url + requestHandler.HttpContext.Request.QueryString, () => this.GetActionResult(requestHandler, endpoint, parameters, url)
                           ));
            }

            return(this.GetActionResult(requestHandler, endpoint, parameters, url));
        }
Exemple #13
0
        public override Verb CreateVerb(string[] tokens)
        {
            var type = tokens[2];
            var name = tokens[4];

            Color(position, tokens[1].Length, Whitespaces);
            Color(type.Length, KeyWords);
            Color(tokens[3].Length, Whitespaces);
            Color(name.Length, Operators);
            Color(tokens[5].Length, Structures);

            var index            = position + length;
            var parametersParser = new ParametersParser();
            var parsed           = parametersParser.Parse(source, index);

            parsed.If(out var parameters, out index).Must().BeTrue().OrThrow("Operator parser", () => "Parameters malformed");
            if (functionBodyParser.Parse(source, index).If(out var block, out var newIndex))
            {
                overridePosition = newIndex;
                var lambda   = new Lambda(new Region(), block, parameters, false);
                var affinity = 0;
                var pre      = false;
                switch (type)
                {
                case "nofix":
                    affinity = 0;
                    break;

                case "prefix":
                    affinity = 1;
                    pre      = true;
                    break;

                case "postfix":
                    affinity = 1;
                    break;

                case "infix":
                    affinity = 2;
                    break;
                }

                var userDefinedOperator = new UserDefinedOperator(affinity, pre, lambda);
                CompilerState.RegisterOperator(name, userDefinedOperator);

                return(new NullOp());
            }

            return(null);
        }
Exemple #14
0
        public override Verb CreateVerb(string[] tokens)
        {
            Color(position, tokens[1].Length, Structures);
            var        param = tokens[2];
            var        type  = tokens[4];
            Parameters parameters;
            var        index = NextPosition;

            if (param == "_")
            {
                Color(param.Length, Structures);
                parameters = new Parameters();
            }
            else if (param.StartsWith("("))
            {
                var leftLength = tokens[1].Length + 1;
                index = position + leftLength;
                Color(position, leftLength, Structures);
                if (!parameterParser.Parse(source, index).If(out parameters, out index))
                {
                    return(null);
                }

                index = NextPosition;
            }
            else
            {
                Color(param.Length, Variables);
                parameters = new Parameters(array(new Parameter(param)));
            }

            Color(position + tokens[1].Length + tokens[2].Length, tokens[3].Length, Whitespaces);
            Color(type.Length, Structures);
            parameters.Splatting = type == "=>";
            if (GetExpression(source, index, CloseParenthesis()).If(out var block, out var i))
            {
                block.Expression = false;
                var lambda = new Lambda(new Region(), block, parameters, false)
                {
                    Splatting = parameters.Splatting
                };
                result.Value     = lambda;
                overridePosition = i;
                return(new CreateLambda(parameters, block, parameters.Splatting));
            }

            return(null);
        }
Exemple #15
0
        public override Verb CreateVerb(string[] tokens)
        {
            Color(position, length, Structures);
            var index = NextPosition;
            var stack = new Stack <Parameters>();

            stack.Push(firstParameters);
            while (index < source.Length)
            {
                if (parametersParser.Parse(source, index).If(out var parameters, out var i))
                {
                    index = i;
                    stack.Push(parameters);
                    if (freeParser.Scan(source, index, pattern))
                    {
                        index = freeParser.Position;
                        freeParser.ColorAll(Structures);
                        continue;
                    }

                    break;
                }
            }

            if (index < source.Length && functionBodyParser.Parse(source, index).If(out var block, out var j))
            {
                var anyLambda = none <Lambda>();
                while (stack.Count > 0)
                {
                    var parameters = stack.Pop();
                    anyLambda = anyLambda.Map(l => getLambda(parameters, l)).DefaultTo(() => new Lambda(new Region(), block, parameters, false)).Some();
                }

                if (anyLambda.If(out var lambda))
                {
                    overridePosition = j;
                    return(new CreateFunction(functionName, lambda, false, visibility, overriding, null)
                    {
                        Index = position
                    });
                }
            }

            return(null);
        }
Exemple #16
0
        public override Verb CreateVerb(string[] tokens)
        {
            Color(position, tokens[1].Length, KeyWords);
            var macroName = tokens[2];

            Color(macroName.Length, Variables);
            Color(tokens[3].Length, Structures);
            var parametersParser = new ParametersParser();

            if (parametersParser.Parse(source, NextPosition).If(out var parameters, out var index) &&
                bodyParser.Parse(source, index).If(out var block, out var newIndex))
            {
                var parameterBlock = new ParameterBlock(parameters, block, parameters.Splatting);
                overridePosition = newIndex;
                return(new CreateMacro(macroName, parameterBlock));
            }

            return(null);
        }
Exemple #17
0
        private dynamic CreateDataSourceViewModel(IRequestHandler requestHandler, DataSource dataSource)
        {
            IDataSource dataSourceInstance = StringActivator.CreateInstance <IDataSource>(dataSource.CSharpClassName);

            if (dataSourceInstance is ISingleObjectDataSource)
            {
                return((dataSourceInstance as ISingleObjectDataSource).GetSerializedObject(
                           requestHandler, ParametersParser.Parse(dataSource.Parameters)
                           ));
            }

            if (dataSourceInstance is IMultipleObjectsDataSource)
            {
                return((dataSourceInstance as IMultipleObjectsDataSource).GetSerializedObjects(
                           requestHandler, ParametersParser.Parse(dataSource.Parameters)
                           ));
            }

            return(null);
        }
        public override Verb CreateVerb(string[] tokens)
        {
            Color(position, tokens[1].Length, KeyWords);
            var name = tokens[2];

            Color(name.Length, Variables);
            Color(tokens[3].Length, Structures);
            var parametersParser = new ParametersParser();

            if (parametersParser.Parse(source, NextPosition).If(out var parameters, out var i) &&
                functionBodyParser.Parse(source, i).If(out var block, out var j))
            {
                overridePosition = j;
                return(new CreatePseudoRecursion(name, parameters, block)
                {
                    Index = position
                });
            }

            return(null);
        }
Exemple #19
0
        public override Verb CreateVerb(string[] tokens)
        {
            Color(position, length, Structures);
            if (parametersParser.Parse(source, NextPosition).If(out var parameters, out var index))
            {
                (var _, var _, var _, var newIndex) = Ancestors(source, index);
                index             = newIndex;
                InClassDefinition = true;
                var objectBlock = new Block();
                GetBlock(source, index, true, InClass).If(out objectBlock, out index);
                InClassDefinition = false;
                var cls = new Class(parameters, objectBlock);
                overridePosition = index;
                result.Value     = cls;
                return(new CreateModule("", cls, false)
                {
                    Index = position
                });
            }

            return(null);
        }
Exemple #20
0
        public override Verb CreateVerb(string[] tokens)
        {
            Color(position, length, Structures);
            var index            = position + length;
            var parametersParser = new ParametersParser();

            if (parametersParser.Parse(source, ref index))
            {
                var parameters = parametersParser.Parameters;
                var block      = blockParser.Parse(source, ref index, false);
                overridePosition = index;
                var unpackedVariables = new List <string>();
                if (parameters.Length > 3)
                {
                    for (var i = 3; i < parameters.Length; i++)
                    {
                        unpackedVariables.Add(parameters[i].Name);
                    }
                }
                parameters.Splatting = blockParser.Splatting;
                return(new PushArrayParameters(parameters, block, unpackedVariables));
            }
            return(null);
        }
        public override Verb CreateVerb(string[] tokens)
        {
            Color(position, tokens[1].Length, Structures);
            Color(tokens[2].Length, Variables);

            var parametersParser = new ParametersParser();
            var index            = position + length;
            var matcher          = new Matcher();
            var current          = source.Skip(index);

            while (!matcher.IsMatch(current, "^ /(/s*) /'}'"))
            {
                if (matcher.IsMatch(current, $"^ /(/s*) /({REGEX_VARIABLE})"))
                {
                    var groups = matcher.Groups(0);
                    Color(index, groups[1].Length, Whitespaces);
                    var typeName = groups[2];
                    Color(typeName.Length, Variables);
                    Parameters parameters = null;
                    current = current.Skip(matcher.Length);
                    if (matcher.IsMatch(current, "^ /s* '('"))
                    {
                        Color(index, Structures);
                        index  += matcher.Length;
                        current = current.Skip(matcher.Length);
                        if (parametersParser.Parse(current, ref index))
                        {
                            current    = source.Skip(index);
                            parameters = parametersParser.Parameters;
                        }
                    }
                }
            }

            return(null);
        }
Exemple #22
0
        //---------------------------------------------------------------------

        private void ReadAndCheckParameters(string filename)
        {
            IParameters parameters;

            try {
                reader     = OpenFile(filename);
                parameters = parser.Parse(reader);
            }
            finally {
                reader.Close();
            }

            try {
                //  Now that we know the data file is properly formatted, read
                //  data from it and compare it against parameter object.
                reader    = OpenFile(filename);
                inputLine = new InputLine(reader);

                Assert.AreEqual(parser.LandisDataValue, ReadInputVar <string>("LandisData"));

                Assert.AreEqual(ReadInputVar <int>("Timestep"), parameters.Timestep);
                Assert.AreEqual(ReadInputVar <SeedingAlgorithms>("SeedingAlgorithm"),
                                parameters.SeedAlgorithm);

                inputLine.MatchName("MinRelativeBiomass");
                inputLine.GetNext();
                List <IEcoregion> ecoregions = ReadEcoregions();
                for (byte shadeClass = 1; shadeClass <= 5; shadeClass++)
                {
                    StringReader currentLine = new StringReader(inputLine.ToString());
                    Assert.AreEqual(shadeClass, ReadInputValue <byte>(currentLine));
                    foreach (IEcoregion ecoregion in ecoregions)
                    {
                        //  TODO: Eventually allow equality testing for Percentage
                        Assert.AreEqual((double)ReadInputValue <Percentage>(currentLine),
                                        (double)parameters.MinRelativeBiomass[shadeClass][ecoregion]);
                    }
                    inputLine.GetNext();
                }

                inputLine.MatchName("BiomassParameters");
                inputLine.GetNext();
                while (inputLine.VariableName != "EstablishProbabilities")
                {
                    StringReader currentLine = new StringReader(inputLine.ToString());
                    ISpecies     species     = ReadSpecies(currentLine);
                    Assert.AreEqual(ReadInputValue <double>(currentLine),
                                    parameters.LeafLongevity[species]);
                    Assert.AreEqual(ReadInputValue <double>(currentLine),
                                    parameters.WoodyDecayRate[species]);
                    Assert.AreEqual(ReadInputValue <double>(currentLine),
                                    parameters.MortCurveShapeParm[species]);
                    inputLine.GetNext();
                }

                CheckParameterTable("EstablishProbabilities",
                                    parameters.EstablishProbability,
                                    "MaxANPP");

                CheckParameterTable("MaxANPP",
                                    parameters.MaxANPP,
                                    "LeafLitter:DecayRates");

                const string AgeOnlyDisturbanceParms = "AgeOnlyDisturbances:BiomassParameters";
                CheckParameterTable("LeafLitter:DecayRates",
                                    parameters.LeafLitterDecayRate,
                                    AgeOnlyDisturbanceParms);

                if (parameters.AgeOnlyDisturbanceParms != null)
                {
                    Assert.AreEqual(ReadInputVar <string>(AgeOnlyDisturbanceParms),
                                    parameters.AgeOnlyDisturbanceParms);
                }
            }
            finally {
                inputLine = null;
                reader.Close();
            }
        }
Exemple #23
0
        private IActionResult GetActionResult(IRequestHandler requestHandler, Endpoint endpoint, IEnumerable <KeyValuePair <string, string> > parameters, string url)
        {
            dynamic viewModel = this.CreateViewModel(requestHandler, endpoint);

            return((requestHandler as Platformus.Barebone.Frontend.Controllers.ControllerBase).View(this.GetStringArgument(ParametersParser.Parse(endpoint.Parameters), "ViewName"), viewModel));
        }
        public override Verb CreateVerb(string[] tokens)
        {
            if (!InClassDefinition)
            {
                return(null);
            }

            Color(position, tokens[1].Length, Whitespaces);
            Color(tokens[2].Length, useCase ? KeyWords : Operators);
            Color(tokens[3].Length, Whitespaces);
            var caseName = tokens[4];

            Color(caseName.Length, Variables);
            var tokens5Length = tokens[5].Length;
            var type          = tokens[5].Trim();

            Color(tokens5Length, type == "=" ? Operators : Structures);
            var index          = position + length;
            var staticFunction = new CodeBuilder();

            if (tokens5Length > 0)
            {
                Parameters parameters;
                int        newIndex;
                switch (type)
                {
                case "=":
                    if (integerParser.Scan(source, index))
                    {
                        var parserResult = integerParser.Result;
                        EnumerationValue = (int)parserResult.Value.Number;
                        index            = parserResult.Position;
                        staticFunction.ValueAsArgument(EnumerationValue);
                        staticFunction.ValueAsArgument(caseName);
                    }
                    else if (hexParser.Scan(source, index))
                    {
                        var parserResult = hexParser.Result;
                        EnumerationValue = (int)parserResult.Value.Number;
                        index            = parserResult.Position;
                        staticFunction.ValueAsArgument(EnumerationValue);
                        staticFunction.ValueAsArgument(caseName);
                    }
                    else
                    {
                        return(null);
                    }

                    break;

                case "(":
                    var parametersParser = new ParametersParser();
                    if (parametersParser.Parse(source, index).If(out parameters, out newIndex))
                    {
                        index = newIndex;
                        foreach (var parameter in parameters.GetParameters())
                        {
                            staticFunction.Parameter(parameter);
                            staticFunction.VariableAsArgument(parameter.Name);
                        }

                        staticFunction.Parameter("value", ++EnumerationValue);
                        staticFunction.VariableAsArgument("value");
                        staticFunction.Parameter("name", caseName);
                        staticFunction.VariableAsArgument("name");
                    }

                    break;

                case "[":
                    staticFunction.ValueAsArgument(++EnumerationValue);
                    staticFunction.ValueAsArgument(caseName);
                    var patternParametersParser = new ParametersParser(ParametersType.Pattern);
                    if (patternParametersParser.Parse(source, index).If(out parameters, out newIndex))
                    {
                        index = newIndex;
                        foreach (var parameter in parameters.GetParameters())
                        {
                            staticFunction.Parameter(parameter);
                            staticFunction.VariableAsArgument(parameter.Name);
                        }
                    }

                    break;

                default:
                    return(null);
                }
            }
            else
            {
                staticFunction.ValueAsArgument(++EnumerationValue);
                staticFunction.ValueAsArgument(caseName);
            }

            staticFunction.Variable(ClassName);
            staticFunction.Invoke();

            var lambda      = staticFunction.Lambda();
            var staticBlock = new Block {
                new CreateFunction(caseName, lambda, false, Public, false, null)
            };

            AddStaticBlock(staticBlock);
            var commaParser = new EnumerationValueParser(false);

            if (commaParser.Scan(source, index))
            {
                index = commaParser.Result.Position;
            }

            overridePosition = index;
            return(new NullOp());
        }
Exemple #25
0
        public override Verb CreateVerb(string[] tokens)
        {
            var whitespaces = tokens[1];

            statementIndex = position + whitespaces.Length;

            var tokens2Length  = tokens[2].Length;
            var visibilityName = tokens[2].Trim();

            visibility = ParseVisibility(visibilityName);

            var tokens3Length = tokens[3].Length;

            _override = tokens3Length > 0;

            var tokens4Length = tokens[4].Length;
            var memoize       = tokens4Length > 0;

            var tokens5Length = tokens[5].Length;
            var type          = tokens[5].Trim();

            var tokens6Length = tokens[6].Length;

            functionName = LongToMangledPrefix(type, tokens[6].Trim());

            var parameterType  = tokens[7];
            var parametersType = ParametersType.Message;

            switch (parameterType)
            {
            case "(":
                parametersType = ParametersType.Standard;
                break;

            case "[":
                parametersType = ParametersType.Pattern;
                break;
            }

            var xMethod = false;
            var isDef   = true;

            lockedDown = false;
            var isInit   = false;
            var isCoFunc = false;

            switch (type)
            {
            case "cofunc":
                isCoFunc = true;
                break;

            case "xfunc":
                xMethod = true;
                break;

            case "pure":
                lockedDown = true;
                break;

            case "init":
                isDef  = false;
                isInit = true;
                break;
            }

            Reject(LockedDown && type == "set", VerboseName, "Setters not allowed in views");
            Reject(!InClassDefinition && visibilityName.IsNotEmpty(), VerboseName,
                   $"Visibility specifier {visibility} not allowed allowed outside of class definition");
            Reject(!InClassDefinition && !isDef, VerboseName, $"{type} specifier not allowed outside of a class definition");
            Reject(InClassDefinition && xMethod, VerboseName, "xfunc not allowed inside class definitions");
            Color(position, whitespaces.Length, Whitespaces);
            Color(tokens2Length, KeyWords);
            Color(tokens3Length, KeyWords);
            Color(tokens4Length, KeyWords);
            Color(tokens5Length, KeyWords);
            var invokable  = parametersType == ParametersType.Standard || parametersType == ParametersType.Pattern;
            var entityType = invokable ? Invokeables : Messaging;

            Color(tokens6Length, entityType);
            Color(parameterType.Length, Structures);

            var index            = NextPosition;
            var parametersParser = new ParametersParser(parametersType);

            if (parametersParser.Parse(source, index).If(out var parsed))
            {
                int newIndex;
                (parameters, newIndex) = parsed;
                index = newIndex;
                if (source.Skip(index).Take(1) == "(")
                {
                    var curriedFunctionParser = new CurriedFunctionParser(functionName, parameters, visibility, _override);
                    if (curriedFunctionParser.Scan(source, index))
                    {
                        overridePosition = curriedFunctionParser.Position;
                        return(curriedFunctionParser.Verb);
                    }
                }
            }
            else
            {
                var builder = new StringBuilder();
                var messageParameterParser = new MessageParameterParser();
                var variableParser         = new VariableParser();
                var parameterList          = new List <Parameter>();
                if (variableParser.Scan(source, index))
                {
                    var variable  = (Variable)variableParser.Value;
                    var parameter = new Parameter(variable.Name);
                    builder.Append(functionName);
                    builder.Append("_");
                    parameterList.Add(parameter);
                    index = variableParser.Position;
                }
                else
                {
                    return(null);
                }

                while (messageParameterParser.Scan(source, index))
                {
                    var parameter = new Parameter(messageParameterParser.ParameterName);
                    parameterList.Add(parameter);
                    builder.Append(messageParameterParser.MessageName);
                    builder.Append("_");
                    index = messageParameterParser.Result.Position;
                }

                functionName = builder.ToString();
                parameters   = new Parameters(parameterList);
            }

            RejectNull(parameters, VerboseName, "Parameters malformed");
            var currying = parametersParser.Currying;

            functionBodyParser.ExtractCondition = parametersType == ParametersType.Pattern;
            if (functionBodyParser.Parse(source, index).If(out var block, out var i))
            {
                index = i;
                var condition = functionBodyParser.Condition;
                var where = functionBodyParser.Where;
                Verb verb;
                if (isInit)
                {
                    verb         = createInitializer(index, block);
                    result.Value = lambda;
                    singleLine   = !functionBodyParser.MultiCapable;
                    return(verb);
                }

                if (isCoFunc)
                {
                    overridePosition = index;
                    var builder = new CofunctionBuilder(functionName, parameters, block);
                    return(builder.Generate());
                }

                verb           = createFunction(index, currying, condition, memoize, lockedDown, block);
                lambda.XMethod = xMethod;
                lambda.Expand  = type == "rec";
                result.Value   = lambda;
                singleLine     = !functionBodyParser.MultiCapable;
                if (lambda.Where == null)
                {
                    lambda.Where = where;
                }
                return(verb);
            }

            return(null);

/*         return functionBodyParser.Parse(source, index).Map((block, i) =>
 *       {
 *          index = i;
 *          var condition = functionBodyParser.Condition;
 *          var where = functionBodyParser.Where;
 *          Verb verb;
 *          if (isInit)
 *          {
 *             verb = createInitializer(index, block);
 *             result.Value = lambda;
 *             singleLine = !functionBodyParser.MultiCapable;
 *             return verb;
 *          }
 *
 *          if (isCoFunc)
 *          {
 *             overridePosition = index;
 *             var builder = new CofunctionBuilder(functionName, parameters, block);
 *             return builder.Generate();
 *          }
 *
 *          verb = createFunction(index, currying, condition, memoize, lockedDown, block);
 *          lambda.XMethod = xMethod;
 *          lambda.Expand = type == "rec";
 *          result.Value = lambda;
 *          singleLine = !functionBodyParser.MultiCapable;
 *          if (lambda.Where == null)
 *             lambda.Where = where;
 *          return verb;
 *       }, () => null);*/
        }
Exemple #26
0
        public override Verb CreateVerb(string[] tokens)
        {
            var isAbstract     = tokens[2].IsNotEmpty();
            var type           = tokens[3].Trim();
            var className      = tokens[4];
            var parameterBegin = tokens[5];

            ClassName         = className;
            EnumerationValue  = -1;
            CurrentVisibility = Object.VisibilityType.Public;

            Color(position, tokens[1].Length, Whitespaces);
            Color(tokens[2].Length, KeyWords);
            Color(tokens[3].Length, KeyWords);
            Color(className.Length, Types);
            Color(parameterBegin.Length, Structures);

            Parameters parameters;
            int        index;

            if (parameterBegin == "(" && type != "module")
            {
                Color(parameterBegin.Length, Structures);
                index = position + length;
                var parametersParser = new ParametersParser();
                var parsed           = parametersParser.Parse(source, index);
                if (!parsed.If(out parameters, out index))
                {
                    return(null);
                }

                if (type == "enum")
                {
                    parameters.Unshift(new Parameter("name"));
                    parameters.Unshift(new Parameter("value"));
                }
            }
            else if (type == "enum")
            {
                parameters = new Parameters(new[]
                {
                    new Parameter("value"),
                    new Parameter("name")
                });
                index = position + length;
            }
            else
            {
                parameters = new Parameters();
                index      = position + length;
            }

            (var superClass, var superParameters, var traits, var newIndex) = Ancestors(source, index);
            index = newIndex;

            var endParser = new EndParser();

            if (endParser.Scan(source, index))
            {
                index = endParser.Position;
            }

            Block objectBlock;

            InClassDefinition      = true;
            EnumerationMappingCode = new CodeBuilder();
            try
            {
                if (type == "enum")
                {
                    addEnumerationSupport(className);
                }
                LockedDown = type == "view";
                if (GetBlock(source, index, true, InClass).If(out var block, out newIndex))
                {
                    objectBlock = block;
                    index       = newIndex;
                    if (type == "enum")
                    {
                        addEnumerationInstanceSupport(ref objectBlock);
                    }
                }
                else
                {
                    objectBlock = new Block();
                }
            }
            finally
            {
                InClassDefinition = false;
                if (EnumerationMappingCode != null)
                {
                    AddStaticBlock(EnumerationMappingCode.Block);
                }
                EnumerationMappingCode = null;
                LockedDown             = false;
            }

            var checker = new InheritanceChecker(className, objectBlock, parameters, superClass, isAbstract, traits);
            var passes  = checker.Passes();

            Assert(passes.IsSuccessful, LOCATION, () => passes.Exception.Message);

            var cls = new Class(parameters, objectBlock, GetStaticBlock(), superClass, traits, superParameters,
                                type == "view");

            CompilerState.RegisterClass(ClassName, cls);
            result.Value     = cls;
            overridePosition = index;
            ClassName        = "";
            switch (type)
            {
            case "module":
                return(new CreateModule(className, cls, true)
                {
                    Index = position
                });

            case "extend":
                return(new CreateExtender(className, cls));

            default:
                var verb = new CreateClass(className, cls)
                {
                    HelperFunctions = HelperFunctions,
                    HelperBlock     = HelperBlock,
                    Index           = position
                };
                HelperFunctions = null;
                HelperBlock     = null;
                return(verb);
            }
        }
Exemple #27
0
        public override Verb CreateVerb(string[] tokens)
        {
            var whitespaces = tokens[1];

            statementIndex = position + whitespaces.Length;

            var tokens2Length  = tokens[2].Length;
            var visibilityName = tokens[2].Trim();

            visibility = ParseVisibility(visibilityName);

            var tokens3Length = tokens[3].Length;

            @override = tokens3Length > 0;

            var tokens4Length = tokens[4].Length;
            var memoize       = tokens4Length > 0;

            var tokens5Length = tokens[5].Length;
            var type          = tokens[5].Trim();

            var tokens6Length = tokens[6].Length;

            functionName = LongToMangledPrefix(type, tokens[6].Trim());

            var parameterType  = tokens[7];
            var parametersType = parameterType switch
            {
                "(" => ParametersType.Standard,
                "[" => ParametersType.Pattern,
                _ => ParametersType.Message
            };

            var xMethod = false;
            var isDef   = true;

            lockedDown = false;
            var isInit   = false;
            var isCoFunc = false;

            switch (type)
            {
            case "cofunc":
                isCoFunc = true;
                break;

            case "xfunc":
                xMethod = true;
                break;

            case "pure":
                lockedDown = true;
                break;

            case "init":
                isDef  = false;
                isInit = true;
                break;
            }

            if (lockedDown)
            {
                type.Must().Not.Equal("set").OrThrow(VerboseName, () => "Setters not allowed in views");
            }

            if (InClassDefinition)
            {
                xMethod.Must().Not.BeTrue().OrThrow(VerboseName, () => "xfunc not allowed inside class definitions");
            }
            else
            {
                visibilityName.Must().BeEmpty()
                .OrThrow(VerboseName, () => $"Visibility specifier {visibility} not allowed allowed outside of class definition");
                isDef.Must().BeTrue().OrThrow(VerboseName, () => $"{type} specifier not allowed outside of a class definition");
            }

            Color(position, whitespaces.Length, Whitespaces);
            Color(tokens2Length, KeyWords);
            Color(tokens3Length, KeyWords);
            Color(tokens4Length, KeyWords);
            Color(tokens5Length, KeyWords);
            var invokable  = parametersType == ParametersType.Standard || parametersType == ParametersType.Pattern;
            var entityType = invokable ? Invokeables : Messaging;

            Color(tokens6Length, entityType);
            Color(parameterType.Length, Structures);

            var index            = NextPosition;
            var parametersParser = new ParametersParser(parametersType);

            if (parametersParser.Parse(source, index).If(out parameters, out index))
            {
                if (source.Drop(index).Keep(1) == "(")
                {
                    var curriedFunctionParser = new CurriedFunctionParser(functionName, parameters, visibility, @override);
                    if (curriedFunctionParser.Scan(source, index))
                    {
                        overridePosition = curriedFunctionParser.Position;
                        return(curriedFunctionParser.Verb);
                    }
                }
            }
            else
            {
                var builder = new StringBuilder();
                var messageParameterParser = new MessageParameterParser();
                var variableParser         = new VariableParser();
                var parameterList          = new List <Parameter>();
                if (variableParser.Scan(source, index))
                {
                    var variable  = (Variable)variableParser.Value;
                    var parameter = new Parameter(variable.Name);
                    builder.Append(functionName);
                    builder.Append("_");
                    parameterList.Add(parameter);
                    index = variableParser.Position;
                }
                else
                {
                    return(null);
                }

                while (messageParameterParser.Scan(source, index))
                {
                    var parameter = new Parameter(messageParameterParser.ParameterName);
                    parameterList.Add(parameter);
                    builder.Append(messageParameterParser.MessageName);
                    builder.Append("_");
                    index = messageParameterParser.Result.Position;
                }

                functionName = builder.ToString();
                parameters   = new Parameters(parameterList);
            }

            parameters.Must().Not.BeNull().OrThrow(VerboseName, () => "Parameters malformed");
            var currying = parametersParser.Currying;

            functionBodyParser.ExtractCondition = parametersType == ParametersType.Pattern;
            if (functionBodyParser.Parse(source, index).If(out var block, out var i))
            {
                index = i;
                var condition = functionBodyParser.Condition;
                var where = functionBodyParser.Where;
                Verb verb;
                if (isInit)
                {
                    verb         = createInitializer(index, block);
                    result.Value = lambda;
                    singleLine   = !functionBodyParser.MultiCapable;
                    return(verb);
                }

                if (isCoFunc)
                {
                    overridePosition = index;
                    var builder = new CofunctionBuilder(functionName, parameters, block);
                    return(builder.Generate());
                }

                verb           = createFunction(index, currying, condition, memoize, lockedDown, block);
                lambda.XMethod = xMethod;
                lambda.Expand  = type == "rec";
                result.Value   = lambda;
                singleLine     = !functionBodyParser.MultiCapable;
                if (lambda.Where == null)
                {
                    lambda.Where = where;
                }

                return(verb);
            }

            return(null);
        }
        public IMaybe <Tuple <Parameters, Block, int> > Parse(string source, int index)
        {
            bool       splatting;
            Block      block;
            Parameters newParameters;
            int        newIndex;

            if (retrieveBlock(source, index, "").Assign(out newIndex, out splatting, out block))
            {
                index = newIndex;
                var every = new EveryFillInBlock(block, new List <Parameter>());
                every.ClosureBlock(block).Assign(out block, out newParameters, out splatting);
                return(tuple(newParameters, block, index).Some());
            }
            if (matcher.IsMatch(source.Substring(index), $"^ /(/s*) /(['(['] | {REGEX_VARIABLE})"))
            {
                Color(index, matcher[0, 1].Length, Whitespaces);
                var next = matcher[0, 2];
                index += matcher[0].Length;
                if (next == "(" || next == "[")
                {
                    var parametersType = next == "[" ? ParametersType.Pattern : ParametersType.Standard;
                    Color(next.Length, Structures);
                    var parametersParser = new ParametersParser(parametersType);
                    if (parametersParser.Parse(source, ref index))
                    {
                        newParameters = parametersParser.Parameters;
                    }
                    else
                    {
                        return(new None <Tuple <Parameters, Block, int> >());
                    }
                }
                else
                {
                    Color(next.Length, Variables);
                    var builder = new CodeBuilder();
                    builder.Variable(next);
                    if (next == "_")
                    {
                        if (retrieveBlock(source, index, next).Assign(out newIndex, out splatting, out block))
                        {
                            index = newIndex;
                            var every = new EveryFillInBlock(block, new List <Parameter>());
                            every.ClosureBlock(block).Assign(out block, out newParameters, out splatting);
                            return(tuple(newParameters, block, index).Some());
                        }
                        return(new None <Tuple <Parameters, Block, int> >());
                    }
                    var parametersParser = new ParametersParser();
                    if (parametersParser.Parse(builder.Block))
                    {
                        newParameters = parametersParser.Parameters;
                    }
                    else
                    {
                        return(new None <Tuple <Parameters, Block, int> >());
                    }
                }
                if (retrieveBlock(source, index, next).Assign(out newIndex, out splatting, out block))
                {
                    index = newIndex;
                    newParameters.Splatting = splatting;
                    return(tuple(newParameters, block, index).Some());
                }
            }
            return(new None <Tuple <Parameters, Block, int> >());
        }