Ejemplo n.º 1
0
        public string TokenLiteral()
        {
            if (Statements.Any())
            {
                return(Statements.First().TokenLiteral());
            }

            return(string.Empty);
        }
Ejemplo n.º 2
0
        public void GoTop()
        {
            if (!Statements.Any())
            {
                return;
            }

            Logger.Debug($"{nameof(GoTop)}");
            StatementsGrid.Select(new GridCellRange(0, 0), true);
        }
Ejemplo n.º 3
0
        public void GoBottom()
        {
            if (!Statements.Any())
            {
                return;
            }

            Logger.Debug($"{nameof(GoBottom)}");
            StatementsGrid.Select(new GridCellRange(Statements.Count() - 1, 0), true);
        }
Ejemplo n.º 4
0
 public IfBlockElseSegment(IEnumerable <ICodeBlock> statements)
 {
     if (statements == null)
     {
         throw new ArgumentNullException("statements");
     }
     Statements = statements.ToList().AsReadOnly();
     if (Statements.Any(s => s == null))
     {
         throw new ArgumentException("Null reference encountered in statements set");
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Return the code. This code is actually pretty simple - we just loop over the secondary
        /// array.
        /// </summary>
        /// <returns></returns>
        public override IEnumerable <string> CodeItUp()
        {
            if (Statements.Any())
            {
                yield return(string.Format("for (int {0} = 0; {0} < {1}.size(); {0}++)", _counter.RawValue, _groupArray.RawValue));

                foreach (var l in RenderInternalCode())
                {
                    yield return("  " + l);
                }
            }
        }
Ejemplo n.º 6
0
        public void Translate(ActionSet actionSet)
        {
            foreach (var statement in Statements)
            {
                statement.Translate(actionSet);
            }

            if (!Statements.Any(s => s is ReturnAction))
            {
                BlockScope?.EndScope(actionSet, false);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Generate the code to do the looping. No need to generate anything if there is nothing to do! :-)
        /// </summary>
        /// <returns></returns>
        public override System.Collections.Generic.IEnumerable <string> CodeItUp()
        {
            if (Statements.Any())
            {
                yield return(string.Format("int {0} = {1};", arrIndex, ArrayLength.RawValue));

                yield return(string.Format("for (int {0}={2}; {0} < {1}; {0}++)", _loopVariable.RawValue, arrIndex, InitialValue.RawValue));

                foreach (var l in RenderInternalCode())
                {
                    yield return(l);
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Return the code for this statement.
        /// </summary>
        /// <returns></returns>
        public override System.Collections.Generic.IEnumerable <string> CodeItUp()
        {
            if (Statements.Any())
            {
                //
                // First, convert the keys into an array. We do this because everything is based
                // on index variables.
                //

                yield return(string.Format("for ({0} {1} = {2}.begin(); {1} != {2}.end(); {1}++)", _groupIndex.Type.AsCPPType(), _groupIndex.RawValue, _mapOfGroups.RawValue));

                foreach (var l in RenderInternalCode())
                {
                    yield return(l);
                }
            }
        }
Ejemplo n.º 9
0
            public IfBlockConditionSegment(Expression conditionStatement, IEnumerable <ICodeBlock> statements)
            {
                if (conditionStatement == null)
                {
                    throw new ArgumentNullException("conditionStatement");
                }
                if (statements == null)
                {
                    throw new ArgumentNullException("statements");
                }

                Statements = statements.ToList().AsReadOnly();
                if (Statements.Any(s => s == null))
                {
                    throw new ArgumentException("Null reference encountered in statements set");
                }
                Condition = conditionStatement;
            }
Ejemplo n.º 10
0
        /// <summary>
        /// Emit the code for this test statement
        /// </summary>
        /// <returns></returns>
        public override IEnumerable <string> CodeItUp()
        {
            ///
            /// If no statements, then we can optimize away!
            ///

            if (Statements.Any())
            {
                yield return(string.Format("{0}++;", Counter.RawValue));

                yield return("if (" + Counter.RawValue + " " + ComparisonCodeTranslation[Comparison] + " " + Limit.RawValue + ")");

                foreach (var l in RenderInternalCode())
                {
                    yield return(l);
                }
            }
        }
Ejemplo n.º 11
0
        // =======================================================================================
        // CLASS INITIALISATION
        // =======================================================================================
        public AbstractFunctionBlock(
            bool isPublic,
            bool isDefault,
            bool hasReturnValue,
            NameToken name,
            IEnumerable <Parameter> parameters,
            IEnumerable <ICodeBlock> statements)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (!isPublic && isDefault)
            {
                throw new ArgumentException("Can not be default AND private");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (statements == null)
            {
                throw new ArgumentNullException("statements");
            }

            Parameters = parameters.ToList().AsReadOnly();
            if (Parameters.Any(p => p == null))
            {
                throw new ArgumentException("Null reference encountered in parameters set");
            }
            Statements = statements.ToList().AsReadOnly();
            if (Statements.Any(s => s == null))
            {
                throw new ArgumentException("Null reference encountered in Statements set");
            }

            IsPublic       = isPublic;
            IsDefault      = isDefault;
            HasReturnValue = hasReturnValue;
            Name           = name;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Generate the code.
        /// </summary>
        /// <returns></returns>
        public override System.Collections.Generic.IEnumerable <string> CodeItUp()
        {
            if (Statements.Any())
            {
                yield return(string.Format("for(int {0} = 0; {0} < {1}.size(); {0}++)", index1.RawValue, arrayRecord.RawValue));

                yield return("{");

                yield return(string.Format("  for(int {0} = {1}+1; {0} < {2}.size(); {0}++)", index2.RawValue, index1.RawValue, arrayRecord.RawValue));

                yield return("  {");

                foreach (var l in RenderInternalCode())
                {
                    yield return("    " + l);
                }
                yield return("  }");

                yield return("}");
            }
        }
Ejemplo n.º 13
0
        public IAnswer SelectAllConcepts(
            Func <StatementT, IConcept> resultConceptSelector,
            Func <QuestionT, IConcept> titleConceptSelector,
            String titleConceptCaption,
            Func <ILanguage, String> answerFormat,
            Func <IEnumerable <IConcept>, IEnumerable <IConcept> > conceptsFilter = null)
        {
            ProcessChildrenIfNeed();

            if (Statements.Any())
            {
                if (conceptsFilter == null)
                {
                    conceptsFilter = concepts => concepts;
                }

                var resultConcepts = conceptsFilter(Statements.Select(resultConceptSelector)).ToList();

                var format = new UnstructuredContainer(new FormattedText(
                                                           language => answerFormat(Context.Language),
                                                           new Dictionary <String, IKnowledge>
                {
                    { titleConceptCaption, titleConceptSelector(Context.Question) },
                })).AppendBulletsList(resultConcepts.Enumerate());

                var answer = new ConceptsAnswer(
                    resultConcepts,
                    format,
                    new Explanation(Statements.OfType <IStatement>()));

                answer.Explanation.Expand(AdditionalTransitives);

                return(answer);
            }
            else
            {
                return(Answer.CreateUnknown());
            }
        }
Ejemplo n.º 14
0
        // =======================================================================================
        // CLASS INITIALISATION
        // =======================================================================================
        /// <summary>
        /// It is valid to have a null conditionStatement in VBScript - in case the isPreCondition and doUntil constructor arguments are of no consequence
        /// </summary>
        public DoBlock(Expression conditionIfAny, bool isPreCondition, bool doUntil, bool supportsExit, IEnumerable <ICodeBlock> statements, int lineIndexOfStartOfConstruct)
        {
            if (statements == null)
            {
                throw new ArgumentNullException("statements");
            }
            if (lineIndexOfStartOfConstruct < 0)
            {
                throw new ArgumentOutOfRangeException("Must be zero or greater", "lineIndexOfStartOfConstruct");
            }

            ConditionIfAny     = conditionIfAny;
            IsPreCondition     = isPreCondition;
            IsDoWhileCondition = !doUntil;
            SupportsExit       = supportsExit;
            Statements         = statements.ToList().AsReadOnly();
            if (Statements.Any(s => s == null))
            {
                throw new ArgumentException("Null reference encountered in statements set");
            }
            LineIndexOfStartOfConstruct = lineIndexOfStartOfConstruct;
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Return the code for this if statement.
        /// </summary>
        /// <returns></returns>
        public override IEnumerable <string> CodeItUp()
        {
            ///
            /// If there are no held statements, then we can optimize away the
            /// if statement!
            ///

            if (Statements.Any() && TestExpression.RawValue != "false")
            {
                ///
                /// Now, emit the if statement and work from there
                ///

                if (TestExpression.RawValue != "true")
                {
                    yield return("if (" + TestExpression.RawValue + ")");
                }
                foreach (var l in RenderInternalCode())
                {
                    yield return(l);
                }
            }
        }
Ejemplo n.º 16
0
        public override async ValueTask <Completion> WriteToAsync(TextWriter writer, TextEncoder encoder, TemplateContext context)
        {
            if (!context.AmbientValues.TryGetValue("Services", out var servicesValue))
            {
                throw new ArgumentException("Services missing while invoking 'helper'");
            }

            var services = servicesValue as IServiceProvider;

            var viewContextAccessor = services.GetRequiredService <ViewContextAccessor>();
            var viewContext         = viewContextAccessor.ViewContext;

            var arguments = (FilterArguments)(await _arguments.EvaluateAsync(context)).ToObjectValue();
            var helper    = _helper ?? arguments["helper_name"].Or(arguments.At(0)).ToStringValue();

            var factory = services.GetRequiredService <LiquidTagHelperFactory>();

            if (_activator == null)
            {
                lock (this)
                {
                    if (_activator == null)
                    {
                        _activator = factory.GetActivator(helper, arguments.Names);
                    }
                }
            }

            if (_activator == LiquidTagHelperActivator.None)
            {
                return(Completion.Normal);
            }

            var tagHelper = factory.CreateTagHelper(_activator, (ViewContext)viewContext,
                                                    arguments, out var contextAttributes, out var outputAttributes);

            var content = new StringWriter();

            if (Statements?.Any() ?? false)
            {
                Completion completion = Completion.Break;
                for (var index = 0; index < Statements.Count; index++)
                {
                    completion = await Statements[index].WriteToAsync(content, encoder, context);

                    if (completion != Completion.Normal)
                    {
                        return(completion);
                    }
                }
            }

            var tagHelperContext = new TagHelperContext(contextAttributes,
                                                        new Dictionary <object, object>(), Guid.NewGuid().ToString("N"));

            var tagHelperOutput = new TagHelperOutput(helper, outputAttributes, (_, e)
                                                      => Task.FromResult(new DefaultTagHelperContent().AppendHtml(content.ToString())));

            tagHelperOutput.Content.AppendHtml(content.ToString());
            await tagHelper.ProcessAsync(tagHelperContext, tagHelperOutput);

            tagHelperOutput.WriteTo(writer, HtmlEncoder.Default);

            return(Completion.Normal);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Generate the code to sort and play back.
        /// </summary>
        /// <returns></returns>
        public override System.Collections.Generic.IEnumerable <string> CodeItUp()
        {
            if (Statements.Any())
            {
                // Use the first map index guy to run the sort - though it really doesn't matter which
                // one we use.
                var first = _mapRecords.First();

                yield return(string.Format("{0} {1};", first.sortValueTypeArray.AsCPPType(), first.tempListingName));

                yield return(string.Format("for({0}::const_iterator i_itr = {1}.begin(); i_itr != {1}.end(); i_itr++) {{", first.mapRecords.Type.AsCPPType(), first.mapRecords.RawValue));

                yield return(string.Format("  {0}.push_back(i_itr->first);", first.tempListingName));

                yield return(string.Format("}}"));

                yield return(string.Format("sort({0}.begin(), {0}.end());", first.tempListingName));

                if (_sortAscending)
                {
                    yield return(string.Format("for (int i_index = 0; i_index < {0}.size(); i_index++) {{", first.tempListingName));
                }
                else
                {
                    yield return(string.Format("for (int i_index = {0}.size()-1; i_index >= 0; i_index--) {{", first.tempListingName));
                }

                // Next, for each of the arrays we are moving through, we need to generate a temp variable. Create a temp
                // var to make access below simpler.
                foreach (var saver in _mapRecords)
                {
                    var subListType = saver.mapRecords.Type.GetGenericArguments()[1];
                    yield return(string.Format("  const {0} &sublist{3}({1}[{2}.at(i_index)]);", subListType.AsCPPType(), saver.mapRecords.RawValue, first.tempListingName, saver.sequence));
                }

                //
                // Now, loop over the sublist...
                //

                yield return(string.Format("  for (unsigned int i_sindex = 0; i_sindex < sublist{0}.size(); i_sindex++) {{", first.sequence));

                //
                // The value of the sequence is used by everyone, so we need to pop it out here.
                //

                foreach (var saver in _mapRecords)
                {
                    yield return(string.Format("    const {0} {1} = sublist{2}.at(i_sindex);", saver.indexVariable.Type.AsCPPType(), saver.indexVariable.RawValue, saver.sequence));
                }

                //
                // Render the code in the inner loop
                //

                foreach (var l in RenderInternalCode())
                {
                    yield return("      " + l);
                }

                //
                // And clean up!
                //

                yield return("  }");

                yield return("}");
            }
        }
Ejemplo n.º 18
0
        public override async Task <Completion> WriteToAsync(TextWriter writer, TextEncoder encoder, TemplateContext context)
        {
            if (!context.AmbientValues.TryGetValue("Services", out var servicesValue))
            {
                throw new ArgumentException("Services missing while invoking 'helper'");
            }

            var services = servicesValue as IServiceProvider;

            if (!context.AmbientValues.TryGetValue("ViewContext", out var viewContext))
            {
                throw new ArgumentException("ViewContext missing while invoking 'helper'");
            }

            var arguments = (FilterArguments)(await _arguments.EvaluateAsync(context)).ToObjectValue();

            var helper = _helper ?? arguments.At(0).ToStringValue();
            var tagHelperSharedState = services.GetRequiredService <TagHelperSharedState>();

            if (tagHelperSharedState.TagHelperDescriptors == null)
            {
                lock (tagHelperSharedState)
                {
                    if (tagHelperSharedState.TagHelperDescriptors == null)
                    {
                        var razorEngine      = services.GetRequiredService <RazorEngine>();
                        var tagHelperFeature = razorEngine.Features.OfType <ITagHelperFeature>().FirstOrDefault();
                        tagHelperSharedState.TagHelperDescriptors = tagHelperFeature.GetDescriptors().ToList();
                    }
                }
            }

            if (_descriptor == null)
            {
                lock (this)
                {
                    var descriptors = tagHelperSharedState.TagHelperDescriptors
                                      .Where(d => d.TagMatchingRules.Any(rule => ((rule.TagName == "*") ||
                                                                                  rule.TagName == helper) && rule.Attributes.All(attr => arguments.Names.Any(name =>
                    {
                        if (String.Equals(name, attr.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            return(true);
                        }

                        name = name.Replace("_", "-");

                        if (attr.Name.StartsWith(AspPrefix) && String.Equals(name,
                                                                             attr.Name.Substring(AspPrefix.Length), StringComparison.OrdinalIgnoreCase))
                        {
                            return(true);
                        }

                        if (String.Equals(name, attr.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            return(true);
                        }

                        return(false);
                    }))));

                    _descriptor = descriptors.FirstOrDefault();

                    if (_descriptor == null)
                    {
                        return(Completion.Normal);
                    }
                }
            }

            var tagHelperType = Type.GetType(_descriptor.Name + ", " + _descriptor.AssemblyName);

            var _tagHelperActivator = _tagHelperActivators.GetOrAdd(tagHelperType, key =>
            {
                var genericFactory = typeof(ReusableTagHelperFactory <>).MakeGenericType(key);
                var factoryMethod  = genericFactory.GetMethod("CreateTagHelper");

                return(Delegate.CreateDelegate(typeof(Func <ITagHelperFactory, ViewContext, ITagHelper>), factoryMethod) as Func <ITagHelperFactory, ViewContext, ITagHelper>);
            });

            var tagHelperFactory = services.GetRequiredService <ITagHelperFactory>();
            var tagHelper        = _tagHelperActivator(tagHelperFactory, (ViewContext)viewContext);

            var attributes = new TagHelperAttributeList();

            foreach (var name in arguments.Names)
            {
                var propertyName = LiquidViewFilters.LowerKebabToPascalCase(name);

                var found = false;
                foreach (var attribute in _descriptor.BoundAttributes)
                {
                    if (propertyName == attribute.GetPropertyName())
                    {
                        found = true;

                        var setter = _tagHelperSetters.GetOrAdd(attribute.DisplayName, key =>
                        {
                            var propertyInfo   = tagHelperType.GetProperty(propertyName);
                            var propertySetter = propertyInfo.GetSetMethod();

                            var invokeType     = typeof(Action <,>).MakeGenericType(tagHelperType, propertyInfo.PropertyType);
                            var setterDelegate = Delegate.CreateDelegate(invokeType, propertySetter);

                            Action <ITagHelper, FluidValue> result = (h, v) =>
                            {
                                object value = null;

                                if (attribute.IsEnum)
                                {
                                    value = Enum.Parse(propertyInfo.PropertyType, v.ToStringValue());
                                }
                                else if (attribute.IsStringProperty)
                                {
                                    value = v.ToStringValue();
                                }
                                else if (propertyInfo.PropertyType == typeof(Boolean))
                                {
                                    value = Convert.ToBoolean(v.ToStringValue());
                                }
                                else
                                {
                                    value = v.ToObjectValue();
                                }

                                setterDelegate.DynamicInvoke(new[] { h, value });
                            };

                            return(result);
                        });

                        try
                        {
                            setter(tagHelper, arguments[name]);
                        }
                        catch (ArgumentException e)
                        {
                            throw new ArgumentException("Incorrect value type assigned to a tag.", name, e);
                        }

                        break;
                    }
                }

                if (!found)
                {
                    attributes.Add(new TagHelperAttribute(name.Replace("_", "-"), arguments[name].ToObjectValue()));
                }
            }

            var content = new StringWriter();

            if (Statements?.Any() ?? false)
            {
                Completion completion = Completion.Break;
                for (var index = 0; index < Statements.Count; index++)
                {
                    completion = await Statements[index].WriteToAsync(content, encoder, context);

                    if (completion != Completion.Normal)
                    {
                        return(completion);
                    }
                }
            }

            var tagHelperContext = new TagHelperContext(attributes,
                                                        new Dictionary <object, object>(), Guid.NewGuid().ToString("N"));

            var tagHelperOutput = new TagHelperOutput(helper, attributes, (_, e)
                                                      => Task.FromResult(new DefaultTagHelperContent().AppendHtml(content.ToString())));

            tagHelperOutput.Content.AppendHtml(content.ToString());
            await tagHelper.ProcessAsync(tagHelperContext, tagHelperOutput);

            tagHelperOutput.WriteTo(writer, HtmlEncoder.Default);

            return(Completion.Normal);
        }
Ejemplo n.º 19
0
 /// <summary>
 /// True if the list has at least one statement.
 /// </summary>
 /// <returns></returns>
 public bool Any()
 {
     return(Statements.Any());
 }
Ejemplo n.º 20
0
 public bool IsEmpty() => !Statements.Any();