public bool Load(Queue<Token> tokens, Type tokenizerType,TemplateGroup group)
 {
     _parameterMap = new Dictionary<string, string>();
     Token t = tokens.Dequeue();
     Match m = _functionReg.Match(t.Content);
     if ((_parameters == null) || (_parameters.Length == 0))
     {
         Queue<Token> toks = new Queue<Token>();
         toks.Enqueue(new Token(m.Groups[4].Value.Trim(),TokenType.COMPONENT));
         _it = ComponentExtractor.ExtractComponent(toks, tokenizerType, group);
         if (_it is ParameterComponent)
         {
             _it = null;
             _parameterMap.Add("it", m.Groups[4].Value.Trim());
         }
     }
     else
     {
         int x = 5;
         foreach (string str in _parameters)
         {
             _parameterMap.Add(str, m.Groups[x].Value.Trim());
             x += 3;
         }
     }
     return true;
 }
 public bool Load(Queue<Token> tokens, Type tokenizerType,TemplateGroup group)
 {
     _val = tokens.Dequeue().Content;
     _val = _val.Substring(1);
     _val = _val.Substring(0, _val.Length);
     return true;
 }
 public override bool Load(Queue<Token> tokens, Type tokenizerType,TemplateGroup group)
 {
     Token t = tokens.Dequeue();
     Match m;
     if (regAlternateFormat.IsMatch(t.Content))
     {
         m = regAlternateFormat.Match(t.Content);
         _variableName = m.Groups[1].Value;
         _entryName = m.Groups[2].Value;
         string tmp = t.Content.Substring(t.Content.IndexOf("|", m.Groups[2].Index) + 1);
         tmp = tmp.Substring(0, tmp.Length - 1);
         Tokenizer tok = (Tokenizer)tokenizerType.GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { tmp});
         _children = tok.TokenizeStream(group);
     }
     else
     {
         m = regVariableExtractor.Match(t.Content);
         _entryName = m.Groups[1].Value;
         _variableName = m.Groups[2].Value;
         if (regVarValueExtracor.IsMatch(_entryName))
             _entryName = regVarValueExtracor.Match(_entryName).Groups[2].Value;
         if (regListValueExtracor.IsMatch(_variableName))
             _variableName = regListValueExtracor.Match(_variableName).Groups[2].Value;
         while ((tokens.Count>0)&&!regEndFor.IsMatch(tokens.Peek().Content))
             _children.Add(ComponentExtractor.ExtractComponent(tokens, tokenizerType, group));
         if (tokens.Count > 0)
             tokens.Dequeue();
     }
     _entryName = _entryName.Trim();
     _variableName = _variableName.Trim();
     return true;
 }
Пример #4
0
 public override bool Load(Queue<Token> tokens, Type tokenizerType, TemplateGroup group)
 {
     Token t = tokens.Dequeue();
     string tmp = _reg.Match(t.Content).Groups[2].ToString();
     Tokenizer tok = (Tokenizer)tokenizerType.GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { tmp });
     _val = tok.TokenizeStream(group)[0];
     return true;
 }
        public bool Load(Queue<Token> tokens, Type tokenizerType,TemplateGroup group)
		{
			_variableName = tokens.Dequeue().Content;
			if (_variableName.Contains(";"))
			{
				_seperator = _variableName.Substring(_variableName.IndexOf(";")+1);
				_variableName = _variableName.Substring(0,_variableName.IndexOf(";"));
				_seperator = _seperator.Substring(_seperator.IndexOf("\"")+1);
				_seperator = _seperator.Substring(0,_seperator.IndexOf("\""));
			}
			return true;
		}
Пример #6
0
 public override bool Load(Queue<Token> tokens, Type tokenizerType, TemplateGroup group)
 {
     Token t = tokens.Dequeue();
     Match m = _reg.Match(t.Content);
     Tokenizer tok = (Tokenizer)tokenizerType.GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { m.Groups[2].Value });
     _eval = tok.TokenizeStream(group)[0];
     tok = (Tokenizer)tokenizerType.GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { m.Groups[4].Value });
     _search = tok.TokenizeStream(group)[0];
     tok = (Tokenizer)tokenizerType.GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { m.Groups[6].Value });
     _replace = tok.TokenizeStream(group)[0];
     return true;
 }
Пример #7
0
 public override bool Load(Queue<Org.Reddragonit.Stringtemplate.Tokenizers.Token> tokens, Type tokenizerType, TemplateGroup group)
 {
     Token t = tokens.Dequeue();
     Match m = _reg.Match(t.Content);
     _variable = m.Groups[2].Value;
     _format = m.Groups[4].Value;
     if (_format.StartsWith("\"") || _format.StartsWith("'"))
         _format = _format.Substring(1);
     if (_format.EndsWith("\"") || _format.EndsWith("'"))
         _format = _format.Substring(0, _format.Length - 1);
     _variable = (_variable.StartsWith("$") && _variable.EndsWith("$") ? _variable.Substring(1, _variable.Length - 2) : _variable);
     _format = (_format.StartsWith("$") && _format.EndsWith("$") ? _format.Substring(1, _format.Length - 2) : _format);
     return true;
 }
Пример #8
0
 public bool Load(Queue<Token> tokens, Type tokenizerType,TemplateGroup group)
 {
     Token curToken = tokens.Dequeue();
     Queue<Token> tmp = new Queue<Token>();
     tmp.Enqueue(new Token(regIf.Match(curToken.Content).Groups[2].Value, TokenType.COMPONENT));
     IComponent curCondition = ComponentExtractor.ExtractComponent(tmp, tokenizerType, group);
     List<IComponent> curChildren = new List<IComponent>();
     while ((tokens.Count>0)&&!regEndIf.IsMatch(tokens.Peek().Content))
     {
         if (regIf.IsMatch(tokens.Peek().Content))
         {
             IFComponent ifc = new IFComponent();
             ifc.Load(tokens, tokenizerType, group);
             curChildren.Add(ifc);
         }
         else
         {
             curToken = tokens.Peek();
             if (regElseIf.IsMatch(curToken.Content))
             {
                 _statements.Add(new IfStatement(curCondition, curChildren));
                 curChildren = new List<IComponent>();
                 curToken = tokens.Dequeue();
                 tmp.Clear();
                 tmp.Enqueue(new Token(regElseIf.Match(curToken.Content).Groups[2].Value, TokenType.COMPONENT));
                 curCondition = ComponentExtractor.ExtractComponent(tmp, tokenizerType, group);
             }
             else if (regElse.IsMatch(curToken.Content))
             {
                 _statements.Add(new IfStatement(curCondition, curChildren));
                 curChildren = new List<IComponent>();
                 curToken = tokens.Dequeue();
                 tmp.Clear();
                 tmp.Enqueue(new Token("true", TokenType.TEXT));
                 curCondition = ComponentExtractor.ExtractComponent(tmp, tokenizerType, group);
             }
             else
                 curChildren.Add(ComponentExtractor.ExtractComponent(tokens, tokenizerType, group));
         }
     }
     _statements.Add(new IfStatement(curCondition, curChildren));
     if (tokens.Count != 0)
         tokens.Dequeue();
     return true;
 }
 public SubTemplateComponent(string GroupName,string FunctionName,List<IComponent> Components,string[] Parameters,TemplateGroup group ) {
     _groupName = GroupName;
     _functionName = FunctionName;
     _components = Components;
     _parameters = Parameters;
     string reg = "^((" + GroupName + "/)";
     if ((_parameters == null) || (_parameters.Length == 0))
         reg += "|((.+):)";
     reg+=")?"+_functionName+"\\(";
     if ((_parameters != null) && (_parameters.Length > 0))
     {
         foreach (string str in _parameters)
         {
             reg += "(\\s*(" + str + "\\s*=\\s*)?([^\\(]+)),";
         }
         reg = reg.Substring(0, reg.Length - 1);
     }
     reg += "\\)$";
     _functionReg = new Regex(reg, RegexOptions.Compiled | RegexOptions.ECMAScript);
     _group = group;
 }
		public static IComponent ExtractComponent(Queue<Tokenizers.Token> tokens,Type tokenizerType,TemplateGroup group)
		{
            IComponent ret = null;
            if (tokens.Peek().Type == Tokenizers.TokenType.TEXT)
            {
                ret = new GenericComponent();
                ret.Load(tokens,tokenizerType,group);
                return ret;
            }
			//mut.WaitOne();
			foreach (IComponent comp in _components)
			{
				if (comp.CanLoad(tokens.Peek()))
				{
                    ret = comp.NewInstance();
					ret.Load(tokens,tokenizerType,group);
					break;
				}
			}
			//mut.ReleaseMutex();
            if ((group != null)&&(ret==null))
            {
                foreach (IComponent comp in group.Components)
                {
                    if (comp.CanLoad(tokens.Peek()))
                    {
                        ret = comp.NewInstance();
                        ret.Load(tokens, tokenizerType, group);
                        break;
                    }
                }
            }
            if (ret == null)
            {
                ret = new GenericComponent();
                ret.Load(tokens,tokenizerType,group);
                return ret;
            }
			return ret;
		}
Пример #11
0
 // Constructors
 public TemplateModeChangedEventArgs(TemplateGroup newTemplateGroup)
 {
 }
Пример #12
0
 public virtual void DefineImplicitlyDefinedTemplates(TemplateGroup group)
 {
     if (ImplicitlyDefinedTemplates != null)
     {
         foreach (CompiledTemplate sub in ImplicitlyDefinedTemplates)
         {
             group.RawDefineTemplate(sub.Name, sub, sub.TemplateDefStartToken);
             sub.DefineImplicitlyDefinedTemplates(group);
         }
     }
 }
Пример #13
0
 public static void Display(TemplateGroup templateGroup)
 {
     Display(templateGroup, null);
 }
Пример #14
0
        public virtual void DefineArgumentDefaultValueTemplates(TemplateGroup group)
        {
            if (FormalArguments == null)
                return;

            foreach (FormalArgument fa in FormalArguments)
            {
                if (fa.DefaultValueToken != null)
                {
                    switch (fa.DefaultValueToken.Type)
                    {
                    case GroupParser.ANONYMOUS_TEMPLATE:
                        string argSTname = fa.Name + "_default_value";
                        TemplateCompiler c2 = new TemplateCompiler(group);
                        string defArgTemplate = Utility.Strip(fa.DefaultValueToken.Text, 1);
                        fa.CompiledDefaultValue = c2.Compile(group.FileName, argSTname, null, defArgTemplate, fa.DefaultValueToken);
                        fa.CompiledDefaultValue.Name = argSTname;
                        fa.CompiledDefaultValue.DefineImplicitlyDefinedTemplates(group);
                        break;

                    case GroupParser.STRING:
                        fa.DefaultValue = Utility.Strip(fa.DefaultValueToken.Text, 1);
                        break;

                    case GroupParser.LBRACK:
                        fa.DefaultValue = new object[0];
                        break;

                    case GroupParser.TRUE:
                    case GroupParser.FALSE:
                        fa.DefaultValue = fa.DefaultValueToken.Type == GroupParser.TRUE;
                        break;

                    default:
                        throw new NotSupportedException("Unexpected default value token type.");
                    }
                }
            }
        }
Пример #15
0
 public List<IComponent> TokenizeStream(TemplateGroup group)
 {
     _chunks = new Queue<Token>();
     _curChunk = "";
     _index = 0;
     Next();
     while (_curChar != EOF)
     {
         if ((_curChar == EscapeChar)&&(_nextChar==TokenChar))
         {
             Next();
             Consume();
         }
         else if (_curChar == TokenChar)
         {
             if (_curChunk.Length > 0)
             {
                 AddCurrentChunk(TokenType.TEXT);
             }
             Next();
             while ((_curChar != TokenChar)&&(_lastChar!=EscapeChar)&&(_curChar!=EOF))
             {
                 if ((_curChar == '(') || (_curChar == '{') || (_curChar == '['))
                     ConsumeBracket(_curChar);
                 else if ((_curChar == EscapeChar) && (_nextChar == TokenChar))
                 {
                     Next();
                     Consume();
                 }
                 else
                     Consume();
             }
             if (_curChar == TokenChar)
                 Next();
             _curChunk = _curChunk.Trim();
             AddCurrentChunk(TokenType.COMPONENT);
         }
         else
             Consume();
     }
     if (_curChunk.Length > 0)
         AddCurrentChunk(TokenType.TEXT);
     List<IComponent> ret = new List<IComponent>();
     while (_chunks.Count > 0)
     {
     	System.Diagnostics.Debug.WriteLine("Analyzing chunk: "+_chunks.Peek().Content);
         ret.Add(ComponentExtractor.ExtractComponent(_chunks,this.GetType(),group));
     }
     return ret;
 }
 public override void ImportTemplates(TemplateGroup g)
 {
     base.ImportTemplates(g);
 }
Пример #17
0
        internal static List <TemplateResult> CollectTemplateMatchInfo(InstantiateCommandArgs args, IEngineEnvironmentSettings environmentSettings, TemplatePackageManager templatePackageManager, TemplateGroup templateGroup)
        {
            List <TemplateResult> matchInfos = new List <TemplateResult>();

            foreach (CliTemplateInfo template in templateGroup.Templates)
            {
                if (ReparseForTemplate(args, environmentSettings, templatePackageManager, templateGroup, template)
                    is (TemplateCommand command, ParseResult parseResult))
                {
                    matchInfos.Add(TemplateResult.FromParseResult(command, parseResult));
                }
            }
            return(matchInfos);
        }
Пример #18
0
 // Methods
 public int Add(TemplateGroup group)
 {
 }
Пример #19
0
 public void Remove(TemplateGroup group)
 {
 }
Пример #20
0
 public void Insert(int index, TemplateGroup group)
 {
 }
Пример #21
0
 public int IndexOf(TemplateGroup group)
 {
 }
Пример #22
0
 public bool Contains(TemplateGroup group)
 {
 }
Пример #23
0
        /// <summary>
        /// Create command for instantiation of specific template.
        /// </summary>
        /// <exception cref="InvalidTemplateParametersException">when <paramref name="template"/> has invalid template parameters.</exception>
        public TemplateCommand(
            BaseCommand instantiateCommand,
            IEngineEnvironmentSettings environmentSettings,
            TemplatePackageManager templatePackageManager,
            TemplateGroup templateGroup,
            CliTemplateInfo template,
            bool buildDefaultLanguageValidation = false)
            : base(
                templateGroup.ShortNames[0],
                template.Name + Environment.NewLine + template.Description)
        {
            _instantiateCommand     = instantiateCommand;
            _environmentSettings    = environmentSettings;
            _templatePackageManager = templatePackageManager;
            _templateGroup          = templateGroup;
            _template = template;
            foreach (var item in templateGroup.ShortNames.Skip(1))
            {
                AddAlias(item);
            }

            this.AddOption(OutputOption);
            this.AddOption(NameOption);
            this.AddOption(DryRunOption);
            this.AddOption(ForceOption);
            this.AddOption(NoUpdateCheckOption);

            string?templateLanguage = template.GetLanguage();
            string?defaultLanguage  = environmentSettings.GetDefaultLanguage();

            if (!string.IsNullOrWhiteSpace(templateLanguage))
            {
                LanguageOption             = SharedOptionsFactory.CreateLanguageOption();
                LanguageOption.Description = SymbolStrings.TemplateCommand_Option_Language;
                LanguageOption.FromAmongCaseInsensitive(new[] { templateLanguage });

                if (!string.IsNullOrWhiteSpace(defaultLanguage) &&
                    buildDefaultLanguageValidation)
                {
                    LanguageOption.SetDefaultValue(defaultLanguage);
                    LanguageOption.AddValidator(optionResult =>
                    {
                        var value = optionResult.GetValueOrDefault <string>();
                        if (value != template.GetLanguage())
                        {
                            optionResult.ErrorMessage = "Languages don't match";
                        }
                    }
                                                );
                }
                this.AddOption(LanguageOption);
            }

            string?templateType = template.GetTemplateType();

            if (!string.IsNullOrWhiteSpace(templateType))
            {
                TypeOption             = SharedOptionsFactory.CreateTypeOption();
                TypeOption.Description = SymbolStrings.TemplateCommand_Option_Type;
                TypeOption.FromAmongCaseInsensitive(new[] { templateType });
                this.AddOption(TypeOption);
            }

            if (template.BaselineInfo.Any(b => !string.IsNullOrWhiteSpace(b.Key)))
            {
                BaselineOption             = SharedOptionsFactory.CreateBaselineOption();
                BaselineOption.Description = SymbolStrings.TemplateCommand_Option_Baseline;
                BaselineOption.FromAmongCaseInsensitive(template.BaselineInfo.Select(b => b.Key).Where(b => !string.IsNullOrWhiteSpace(b)).ToArray());
                this.AddOption(BaselineOption);
            }

            if (HasRunScriptPostActionDefined(template))
            {
                AllowScriptsOption = new Option <AllowRunScripts>("--allow-scripts")
                {
                    Description = SymbolStrings.TemplateCommand_Option_AllowScripts,
                    Arity       = new ArgumentArity(1, 1)
                };
                AllowScriptsOption.SetDefaultValue(AllowRunScripts.Prompt);
                this.AddOption(AllowScriptsOption);
            }

            AddTemplateOptionsToCommand(template);
        }
Пример #24
0
 public override bool Load(Queue<Org.Reddragonit.Stringtemplate.Tokenizers.Token> tokens, Type tokenizerType, TemplateGroup group)
 {
     Token t = tokens.Dequeue();
     val = _reg.Match(t.Content).Groups[2].ToString();
     return true;
 }
 private static void Unbind(TemplateGroup group)
 {
     group.Listener = ErrorManager.DefaultErrorListener;
 }
Пример #26
0
 public List <TemplateGroup> GetGrouping()
 {
     return(TemplateGroup.GetTemplates(this));
 }
		public bool Load(Queue<Token> tokens, Type tokenizerType, TemplateGroup @group)
		{
			Token t = tokens.Dequeue();
			_val = (Values)Enum.Parse(typeof(Values),t.Content);
			return true;
		}
 // Methods
 public int Add(TemplateGroup group)
 {
 }
Пример #29
0
 public SettingNode(TemplateGroup item)
 {
     Text = item.Name;
     Tag  = item;
 }
 public bool Contains(TemplateGroup group)
 {
 }
Пример #31
0
        public TemplateCompiler(TemplateGroup group)
        {
            if (group == null)
                throw new ArgumentNullException("group");

            _group = group;
        }
 public void CopyTo(TemplateGroup[] array, int index)
 {
 }
Пример #33
0
        public OpenDocumentRendering(IDictionary <string, object> model, byte[] manifestFile, IDictionary <string, byte[]> imageByName, TemplateGroup contentTemplateGroup, TemplateGroup stylesTemplateGroup, Dictionary <string, byte[]> fileByFileName)
        {
            this.model                = model;
            this.manifestFile         = manifestFile;
            this.ContentTemplateGroup = contentTemplateGroup;
            this.StylesTemplateGroup  = stylesTemplateGroup;
            this.fileByFileName       = fileByFileName;

            this.images = imageByName?.Select(v => new Image {
                Name = v.Key, Contents = v.Value
            }).ToArray() ?? new Image[0];
        }
 public int IndexOf(TemplateGroup group)
 {
 }
Пример #35
0
        public virtual void DefineArgumentDefaultValueTemplates(TemplateGroup group)
        {
            if (FormalArguments == null)
                return;

            foreach (FormalArgument fa in FormalArguments)
            {
                if (fa.DefaultValueToken != null)
                {
                    if (fa.DefaultValueToken.Type == GroupParser.ANONYMOUS_TEMPLATE)
                    {
                        string argSTname = fa.Name + "_default_value";
                        TemplateCompiler c2 = new TemplateCompiler(group);
                        string defArgTemplate = Utility.Strip(fa.DefaultValueToken.Text, 1);
                        fa.CompiledDefaultValue = c2.Compile(group.FileName, argSTname, null, defArgTemplate, fa.DefaultValueToken);
                        fa.CompiledDefaultValue.Name = argSTname;
                        fa.CompiledDefaultValue.DefineImplicitlyDefinedTemplates(group);
                    }
                    else if (fa.DefaultValueToken.Type == GroupParser.STRING)
                    {
                        fa.DefaultValue = Utility.Strip(fa.DefaultValueToken.Text, 1);
                    }
                    else
                    {
                        // true or false
                        fa.DefaultValue = fa.DefaultValueToken.Type == GroupParser.TRUE;
                    }
                }
            }
        }
 public void Insert(int index, TemplateGroup group)
 {
 }
Пример #37
0
		public bool Load(Queue<Token> tokens, Type tokenizerType,TemplateGroup group)
		{
			Token t = tokens.Dequeue();
			Queue<Token> toks = new Queue<Token>();
			Match m;
			if (regSimpleStyle.IsMatch(t.Content)){
				m = regSimpleStyle.Match(t.Content);
				toks.Enqueue(new Token(m.Groups[1].Value.Trim(), TokenType.COMPONENT));
				_left = ComponentExtractor.ExtractComponent(toks,tokenizerType,group);
				toks.Clear();
                switch (m.Groups[2].Value.ToUpper())
                {
                    case "NE":
                        _type = CompareType.NOT_EQUAL;
                        break;
                    case "GT":
                        _type = CompareType.GREATER_THAN;
                        break;
                    case "GE":
                        _type = CompareType.GREATER_THAN_OR_EQUAL_TO;
                        break;
                    case "LT":
                        _type = CompareType.LESS_THAN;
                        break;
                    case "LE":
                        _type = CompareType.LESS_THAN_OR_EQUAL_TO;
                        break;
                    case "ST":
                        _type = CompareType.SIMILAR_TO;
                        break;
                    case "NS":
                        _type = CompareType.NOT_SIMILAR_TO;
                        break;
                }
                if (m.Groups[11].Value.Trim().StartsWith("'")||m.Groups[11].Value.Trim().StartsWith("\""))
                    toks.Enqueue(new Token(m.Groups[11].Value.Trim().Substring(1,m.Groups[11].Value.Trim().Length-2), TokenType.TEXT));
                else
				    toks.Enqueue(new Token(m.Groups[11].Value.Trim(),TokenType.COMPONENT));
				_right = ComponentExtractor.ExtractComponent(toks,tokenizerType,group);
			}else{
				m = regFunctionStyle.Match(t.Content);
                switch (m.Groups[1].Value.ToUpper())
                {
                    case "NOTEQUAL":
                        _type = CompareType.NOT_EQUAL;
                        break;
                    case "GREATERTHAN":
                        _type = CompareType.GREATER_THAN;
                        break;
                    case "GREATERTHANOREQUALTO":
                        _type = CompareType.GREATER_THAN_OR_EQUAL_TO;
                        break;
                    case "LESSTHAN":
                        _type = CompareType.LESS_THAN;
                        break;
                    case "LESSTHANOREQUALTO":
                        _type = CompareType.LESS_THAN_OR_EQUAL_TO;
                        break;
                    case "SIMILARTO":
                        _type = CompareType.SIMILAR_TO;
                        break;
                    case "NOTSIMILARTO":
                        _type = CompareType.NOT_SIMILAR_TO;
                        break;
                }
				toks.Enqueue(new Token(m.Groups[12].Value,TokenType.COMPONENT));
                _left = ComponentExtractor.ExtractComponent(toks, tokenizerType, group);
				toks.Clear();
                if (m.Groups[13].Value.Trim().StartsWith("'") || m.Groups[13].Value.Trim().StartsWith("\""))
                    toks.Enqueue(new Token(m.Groups[12].Value.Trim().Substring(1, m.Groups[13].Value.Trim().Length - 2), TokenType.TEXT));
                else
                    toks.Enqueue(new Token(m.Groups[13].Value.Trim(), TokenType.COMPONENT));
                _right = ComponentExtractor.ExtractComponent(toks, tokenizerType, group);
			}
			return true;
		}
 public void Remove(TemplateGroup group)
 {
 }
Пример #39
0
 public bool Load(Queue<Token> tokens, Type tokenizerType,TemplateGroup group)
 {
     _data = tokens.Dequeue().Content;
     return true;
 }
Пример #40
0
        static int RunStGen(StGenOptions opts)
        {
            Console.WriteLine("Generate snippets (using StringTemplate)");

            Console.WriteLine("Source: {0}", opts.InputFile);
            Console.WriteLine("Template: {0}", opts.Template);
            Console.WriteLine("OutputFile: {0}", opts.OutputFile);

            if (opts.InputFile == null || opts.Template == null || opts.OutputFile == null)
            {
                Console.WriteLine("Error. needs Source, Template and OutputFile.");
                return(-1);
            }

            string inputFileEncoding  = opts.InputFileEncoding ?? Encoding.Default.WebName;
            string outputFileEncoding = opts.OutputFileEncoding ?? Encoding.Default.WebName;
            string templateEncoding   = opts.TemplateEncoding ?? Encoding.Default.WebName;

            Console.WriteLine("inputFileEncoding: {0}", inputFileEncoding);
            Console.WriteLine("outputFileEncoding: {0}", outputFileEncoding);
            Console.WriteLine("templateEncoding: {0}", templateEncoding);

            try
            {
                // read an input file
                List <Dictionary <string, object> > records = null;
                using (StreamReader stReader = new StreamReader(
                           opts.InputFile,
                           Encoding.GetEncoding(inputFileEncoding)))
                {
                    using (CsvReader csvReader = new CsvReader(stReader))
                    {
                        // convert IEnumerable<dynamic> to List<Dictionary<string, object>>
                        records = csvReader.GetRecords <dynamic>()
                                  .Select(
                            x => ((ExpandoObject)x)
                            .ToDictionary(xx => xx.Key, xx => xx.Value))
                                  .ToList();

                        // remove elements of dictionary if element's value is "".
                        records = records.Select(
                            x => x.Where(xx => xx.Value != null && xx.Value.ToString() != "")
                            .ToDictionary(xx => xx.Key, xx => xx.Value)
                            ).ToList();
                    }
                }

                if (records == null)
                {
                    Console.WriteLine("Error. failed to read an input file.");
                    return(-1);
                }

                // read a template file
                string templateStr = "";
                using (StreamReader stReader = new StreamReader(
                           opts.Template,
                           Encoding.GetEncoding(templateEncoding)))
                {
                    templateStr = stReader.ReadToEnd();
                }

                // create template object
                Template      template = null;
                TemplateGroup tg       = null;

                if (!string.IsNullOrEmpty(opts.GetInstanceOf))
                {
                    // template group
                    if (!string.IsNullOrEmpty(opts.DelimiterStartChar) &&
                        !string.IsNullOrEmpty(opts.DelimiterStopChar))
                    {
                        tg = new TemplateGroupString(
                            "[string]",
                            templateStr,
                            opts.DelimiterStartChar[0],
                            opts.DelimiterStopChar[0]);
                    }
                    else
                    {
                        tg = new TemplateGroupString(templateStr);
                    }

                    template = tg.GetInstanceOf(opts.GetInstanceOf);
                }
                else
                {
                    // template
                    template = new Template(templateStr);
                }


                // output file(s)
                if (opts.AllRecordsAs != null)
                {
                    // if option AllRecordsAs is specified, it outputs only one file.

                    template.Add(opts.AllRecordsAs, records);

                    string outputfile = opts.OutputFile;

                    using (StreamWriter writer = new StreamWriter(
                               outputfile,
                               false,
                               Encoding.GetEncoding(outputFileEncoding)))
                    {
                        writer.Write(template.Render());
                    }
                }
                else
                {
                    // if option AllRecordsAs is note specified, it outputs each files par record.

                    foreach (Dictionary <string, object> record in records)
                    {
                        Template tempOutputFile = new Template(opts.OutputFile);

                        if (opts.RecordAs != null)
                        {
                            Console.WriteLine("{0}:{1}", opts.RecordAs, record);
                            template.Add(opts.RecordAs, record);
                            tempOutputFile.Add(opts.RecordAs, record);
                        }
                        else
                        {
                            foreach (var kv in record.ToList())
                            {
                                Console.WriteLine("{0}:{1}", kv.Key, kv.Value);
                                string key   = $"{kv.Key}";
                                object value = kv.Value;
                                template.Add(key, value);
                                tempOutputFile.Add(key, value);
                            }
                        }

                        Console.WriteLine($"content:{template.Render()}");
                        Console.WriteLine($"outputFile:{tempOutputFile.Render()}");

                        string outputfile = tempOutputFile.Render();

                        using (StreamWriter writer = new StreamWriter(
                                   outputfile,
                                   false,
                                   Encoding.GetEncoding(outputFileEncoding)))
                        {
                            writer.Write(template.Render());
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return(-1);
            }

            return(0);
        }
Пример #41
0
 public OptionNode(TemplateGroup item)
 {
     Text = item.Name;
     Tag  = item;
 }
Пример #42
0
 public EditTemplateGroup(TemplateGroup group)
 {
     InitializeComponent();
     _group        = group;
     _templateList = group.TemplateGroupMembers.Select(a => a.Template).ToList();
 }
Пример #43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Template"/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 public Template(string name)
 {
     this.Name  = name;
     this.group = new TemplateGroupFile($"{Directory.GetCurrentDirectory()}/{this.Name}");
 }
Пример #44
0
 public TemplateProxyFactory(TemplateGroup ignoreGroup)
 {
     _ignoreGroup = ignoreGroup;
 }
 public abstract bool Load(Queue<Token> tokens, Type tokenizerType,TemplateGroup group);
Пример #46
0
        protected override void Initialize()
        {
            ReturnHyperLink.NavigateUrl = String.Format("TemplateGroupDetail.aspx?file={0}", TemplateGroupFileName);
            //通过模板别名和是否详细模板读取
            if (FileAlias != null && IsDetail != null && TemplateGroupFileName != null)
            {
                //读取模板别名
                TemplateGroup tg = TemplateHelper.GetTemplateGroup(TemplateGroupFileName);
                foreach (TemplateGroup.Item it in tg.Items)
                {
                    if (it.Alias == FileAlias && it.IsDetailTemplate.ToString() == IsDetail)
                    {
                        DeleteItemAliasTextBox.Text = AliasTextBox.Text = AliasWordsTextBox.Text = it.Alias;
                        We7Helper.SetDropdownList(IsDetailTemplateDropDownList, it.IsDetailTemplate ? Boolean.TrueString : Boolean.FalseString);
                        DeleteItemIsDetailTextBox.Text = it.IsDetailTemplate ? Boolean.TrueString : Boolean.FalseString;
                        FileName           = it.Template;
                        AliasPanel.Visible = true;
                    }
                }
            }
            //通过模板文件名读取
            if (AscxFile != null && TemplateGroupFileName != null)
            {
                FileName           = AscxFile;
                AliasPanel.Visible = false;
            }
            if (FileNameAlias != null && FileNameAlias != "")
            {
                FileName = FileNameAlias;
            }
            if (FileName != null && FileName != "" && TemplateGroupFileName != null)
            {
                Template t = TemplateHelper.GetTemplate(FileName + ".xml", Path.GetFileNameWithoutExtension(TemplateGroupFileName));
                if (t != null)
                {
                    NameTextBox.Text         = t.Name;
                    DescriptionTextBox.Text  = t.Description;
                    CreatedLabel.Text        = t.Created.ToString();
                    FileNameTextBox.Text     = t.FileName;
                    FileNameTextBox.ReadOnly = true;
                    We7Helper.SetDropdownList(TypeList, t.IsSubTemplateText);
                    CodeDropDownList.SelectedValue = t.IsCode ? Boolean.TrueString : Boolean.FalseString;
                    if (t.IsSubTemplate)
                    {
                        ComposeHyperLink.NavigateUrl = String.Format("Compose.aspx?file={0}&folder={1}&&templateSub=sub", t.FileName, Path.GetFileNameWithoutExtension(TemplateGroupFileName));
                        AliasPanel.Visible           = false;
                    }
                    else
                    {
                        ComposeHyperLink.NavigateUrl = String.Format("Compose.aspx?file={0}&folder={1}", t.FileName, Path.GetFileNameWithoutExtension(TemplateGroupFileName));
                        AliasPanel.Visible           = true;
                    }
                    TitleLabel.Text   = "编辑模板文件";
                    SummaryLabel.Text = String.Format("修改模板文件 {0}", t.FileName);
                    //TypeList.Enabled = false;
                    ComposeHyperLink.Enabled = true;
                }
            }
            else if (FileName == null || FileName == "" && TemplateGroupFileName != null)
            {
                DateTime now = DateTime.Now;

                ComposeHyperLink.NavigateUrl = String.Format("Compose.aspx?file={0}&folder={1}", FileAlias, Path.GetFileNameWithoutExtension(TemplateGroupFileName));
                ComposeHyperLink.Enabled     = true;
            }
            else
            {
                Messages.ShowError("Url信息不完整。");
                ComposeHyperLink.NavigateUrl = SaveHyperLink.NavigateUrl = "";
            }
        }
Пример #47
0
 public OutputModelWalker(AntlrTool tool, TemplateGroup templates)
 {
     this.tool      = tool;
     this.templates = templates;
 }
Пример #48
0
        /// <summary>
        /// Provides the error string to use for the invalid parameters collection
        /// </summary>
        /// <param name="invalidParameterList">the invalid parameters collection to prepare output for</param>
        /// <param name="templateGroup">the template group to use to get more information about parameters. Optional - if not provided the possible value for the parameters won't be included to the output.</param>
        /// <returns>the error string for the output</returns>
        public static string InvalidParameterListToString(IEnumerable <InvalidParameterInfo> invalidParameterList, TemplateGroup templateGroup = null)
        {
            if (!invalidParameterList.Any())
            {
                return(string.Empty);
            }

            StringBuilder invalidParamsErrorText = new StringBuilder(LocalizableStrings.InvalidTemplateParameterValues);
            const int     padWidth = 3;

            invalidParamsErrorText.AppendLine();
            foreach (InvalidParameterInfo invalidParam in invalidParameterList)
            {
                if (invalidParam.ErrorKind == Kind.InvalidParameterName)
                {
                    invalidParamsErrorText.AppendLine(invalidParam.InputFormat);
                    invalidParamsErrorText.Append(' ', padWidth).AppendLine(string.Format(LocalizableStrings.InvalidParameterNameDetail, invalidParam.InputFormat));
                }
                else if (invalidParam.ErrorKind == Kind.AmbiguousParameterValue)
                {
                    invalidParamsErrorText.AppendLine(invalidParam.InputFormat + ' ' + invalidParam.SpecifiedValue);
                    string header = string.Format(LocalizableStrings.AmbiguousParameterDetail, invalidParam.InputFormat, invalidParam.SpecifiedValue);
                    if (templateGroup != null)
                    {
                        DisplayValidValues(invalidParamsErrorText, header, templateGroup.GetAmbiguousValuesForChoiceParameter(invalidParam.Canonical, invalidParam.SpecifiedValue), padWidth);
                    }
                    else
                    {
                        invalidParamsErrorText.Append(' ', padWidth).AppendLine(header);
                    }
                }
                else if (invalidParam.ErrorKind == Kind.InvalidParameterValue)
                {
                    invalidParamsErrorText.AppendLine(invalidParam.InputFormat + ' ' + invalidParam.SpecifiedValue);
                    string header = string.Format(LocalizableStrings.InvalidParameterDetail, invalidParam.InputFormat, invalidParam.SpecifiedValue);
                    if (templateGroup != null)
                    {
                        DisplayValidValues(invalidParamsErrorText, header, templateGroup.GetValidValuesForChoiceParameter(invalidParam.Canonical), padWidth);
                    }
                    else
                    {
                        invalidParamsErrorText.Append(' ', padWidth).AppendLine(header);
                    }
                }
                else
                {
                    invalidParamsErrorText.AppendLine(invalidParam.InputFormat + ' ' + invalidParam.SpecifiedValue);
                    invalidParamsErrorText.Append(' ', padWidth).AppendLine(string.Format(LocalizableStrings.InvalidParameterDefault, invalidParam.InputFormat, invalidParam.SpecifiedValue));
                }
            }
            return(invalidParamsErrorText.ToString());
        }
Пример #49
0
        public virtual void BuildLeftRecursiveRuleFunction(LeftRecursiveRule r, LeftRecursiveRuleFunction function)
        {
            BuildNormalRuleFunction(r, function);

            // now inject code to start alts
            AbstractTarget target           = @delegate.GetTarget();
            TemplateGroup  codegenTemplates = target.GetTemplates();

            // pick out alt(s) for primaries
            CodeBlockForOuterMostAlt outerAlt        = (CodeBlockForOuterMostAlt)function.code[0];
            IList <CodeBlockForAlt>  primaryAltsCode = new List <CodeBlockForAlt>();
            SrcOp primaryStuff = outerAlt.ops[0];

            if (primaryStuff is Choice)
            {
                Choice primaryAltBlock = (Choice)primaryStuff;
                foreach (var alt in primaryAltBlock.alts)
                {
                    primaryAltsCode.Add(alt);
                }
            }
            else
            { // just a single alt I guess; no block
                primaryAltsCode.Add((CodeBlockForAlt)primaryStuff);
            }

            // pick out alt(s) for op alts
            StarBlock               opAltStarBlock   = (StarBlock)outerAlt.ops[1];
            CodeBlockForAlt         altForOpAltBlock = opAltStarBlock.alts[0];
            IList <CodeBlockForAlt> opAltsCode       = new List <CodeBlockForAlt>();
            SrcOp opStuff = altForOpAltBlock.ops[0];

            if (opStuff is AltBlock)
            {
                AltBlock opAltBlock = (AltBlock)opStuff;
                foreach (var alt in opAltBlock.alts)
                {
                    opAltsCode.Add(alt);
                }
            }
            else
            { // just a single alt I guess; no block
                opAltsCode.Add((CodeBlockForAlt)opStuff);
            }

            // Insert code in front of each primary alt to create specialized context if there was a label
            for (int i = 0; i < primaryAltsCode.Count; i++)
            {
                LeftRecursiveRuleAltInfo altInfo = r.recPrimaryAlts[i];
                if (altInfo.altLabel == null)
                {
                    continue;
                }
                Template altActionST = codegenTemplates.GetInstanceOf("recRuleReplaceContext");
                altActionST.Add("ctxName", Utils.Capitalize(altInfo.altLabel));
                AltLabelStructDecl ctx = null;
                if (altInfo.altLabel != null)
                {
                    function.altLabelCtxs.TryGetValue(altInfo.altLabel, out ctx);
                }
                Action          altAction = new Action(@delegate, ctx, altActionST);
                CodeBlockForAlt alt       = primaryAltsCode[i];
                alt.InsertOp(0, altAction);
            }

            // Insert code to set ctx.stop after primary block and before op * loop
            Template setStopTokenAST    = codegenTemplates.GetInstanceOf("recRuleSetStopToken");
            Action   setStopTokenAction = new Action(@delegate, function.ruleCtx, setStopTokenAST);

            outerAlt.InsertOp(1, setStopTokenAction);

            // Insert code to set _prevctx at start of * loop
            Template setPrevCtx       = codegenTemplates.GetInstanceOf("recRuleSetPrevCtx");
            Action   setPrevCtxAction = new Action(@delegate, function.ruleCtx, setPrevCtx);

            opAltStarBlock.AddIterationOp(setPrevCtxAction);

            // Insert code in front of each op alt to create specialized context if there was an alt label
            for (int i = 0; i < opAltsCode.Count; i++)
            {
                Template altActionST;
                LeftRecursiveRuleAltInfo altInfo = r.recOpAlts.GetElement(i);
                string templateName;
                if (altInfo.altLabel != null)
                {
                    templateName = "recRuleLabeledAltStartAction";
                    altActionST  = codegenTemplates.GetInstanceOf(templateName);
                    altActionST.Add("currentAltLabel", altInfo.altLabel);
                }
                else
                {
                    templateName = "recRuleAltStartAction";
                    altActionST  = codegenTemplates.GetInstanceOf(templateName);
                    altActionST.Add("ctxName", Utils.Capitalize(r.name));
                }
                altActionST.Add("ruleName", r.name);
                // add label of any LR ref we deleted
                altActionST.Add("label", altInfo.leftRecursiveRuleRefLabel);
                if (altActionST.impl.FormalArguments.Any(x => x.Name == "isListLabel"))
                {
                    altActionST.Add("isListLabel", altInfo.isListLabel);
                }
                else if (altInfo.isListLabel)
                {
                    @delegate.GetGenerator().tool.errMgr.ToolError(ErrorType.CODE_TEMPLATE_ARG_ISSUE, templateName, "isListLabel");
                }
                AltLabelStructDecl ctx = null;
                if (altInfo.altLabel != null)
                {
                    function.altLabelCtxs.TryGetValue(altInfo.altLabel, out ctx);
                }
                Action          altAction = new Action(@delegate, ctx, altActionST);
                CodeBlockForAlt alt       = opAltsCode[i];
                alt.InsertOp(0, altAction);
            }
        }
Пример #50
0
 public void CreateTemplateGroup(TemplateGroup group)
 {
     _appInfo.Context.TemplateGroups.Add(group);
     _appInfo.Context.SaveChanges();
 }
Пример #51
0
        private static void HandleNoMatchOnTemplateBaseOptions(IEnumerable <TemplateResult> matchInfos, InstantiateCommandArgs args, TemplateGroup templateGroup)
        {
            Option <string> languageOption = SharedOptionsFactory.CreateLanguageOption();
            Option <string> typeOption     = SharedOptionsFactory.CreateTypeOption();
            Option <string> baselineOption = SharedOptionsFactory.CreateBaselineOption();

            Command reparseCommand = new Command("reparse-only")
            {
                languageOption,
                typeOption,
                baselineOption,
                new Argument <string[]>("rem-args")
                {
                    Arity = new ArgumentArity(0, 999)
                }
            };

            ParseResult result = ParserFactory.CreateParser(reparseCommand).Parse(args.RemainingArguments ?? Array.Empty <string>());
            string      baseInputParameters = $"'{args.ShortName}'";

            foreach (var option in new[] { languageOption, typeOption, baselineOption })
            {
                if (result.FindResultFor(option) is { } optionResult&& optionResult.Token is { } token)
                {
                    baseInputParameters = baseInputParameters + $", {token.Value}='{optionResult.GetValueOrDefault<string>()}'";
                }
            }

            Reporter.Error.WriteLine(string.Format(LocalizableStrings.NoTemplatesMatchingInputParameters, baseInputParameters).Bold().Red());
            foreach (var option in new[]
            {
                new { Option = languageOption, Condition = matchInfos.All(mi => !mi.IsLanguageMatch), AllowedValues = templateGroup.Languages },
                new { Option = typeOption, Condition = matchInfos.All(mi => !mi.IsTypeMatch), AllowedValues = templateGroup.Types },
                new { Option = baselineOption, Condition = matchInfos.All(mi => !mi.IsBaselineMatch), AllowedValues = (IReadOnlyList <string?>)templateGroup.Baselines },
            })
            {
                if (option.Condition && result.FindResultFor(option.Option) is { } optionResult&& optionResult.Token is { } token)
                {
                    string allowedValues = string.Join(", ", option.AllowedValues.Select(l => $"'{l}'").OrderBy(l => l, StringComparer.OrdinalIgnoreCase));
                    Reporter.Error.WriteLine(string.Format(LocalizableStrings.TemplateOptions_Error_AllowedValuesForOptionList, token.Value, allowedValues));
                }
            }

            Reporter.Error.WriteLine();

            Reporter.Error.WriteLine(LocalizableStrings.ListTemplatesCommand);

            Reporter.Error.WriteCommand(
                Example
                .For <NewCommand>(args.ParseResult)
                .WithSubcommand <ListCommand>());

            Reporter.Error.WriteLine(LocalizableStrings.SearchTemplatesCommand);
            Reporter.Error.WriteCommand(
                Example
                .For <NewCommand>(args.ParseResult)
                .WithSubcommand <SearchCommand>()
                .WithArgument(SearchCommand.NameArgument, args.ShortName ?? string.Empty));
            Reporter.Error.WriteLine();
        }
Пример #52
0
 public void AddToTemplateGroup(TemplateGroup templateGroup)
 {
     base.AddObject("TemplateGroup", templateGroup);
 }
 public bool Load(Queue<Token> tokens, Type tokenizerType,TemplateGroup group)
 {
     Match m = _reg.Match(tokens.Dequeue().Content);
     _variableName = m.Groups[1].Value;
     _variableType = Utility.LocateType(m.Groups[2].Value.Replace("[]",""));
     if (_variableType==null)
         _variableType=Utility.LocateType("System."+m.Groups[2].Value.Replace("[]", ""));
     _isArray = m.Groups[2].Value.Contains("[]");
     if (_variableType == null)
         return false;
     _constructor = m.Groups[3].Value.ToUpper().Trim()=="NEW";
     int y = 0;
     foreach (Group g in m.Groups)
     {
         System.Diagnostics.Debug.WriteLine(y.ToString() + ":" + g.Value);
         y++;
     }
     _constructorCall = m.Groups[4].Value;
     if (!_constructor)
         _staticCall = m.Groups[6].Value.Length > 0;
     string variables = m.Groups[7].Value;
     if (variables.EndsWith(")") || variables.EndsWith("}"))
         variables = variables.Substring(0, variables.Length - 1);
     string tmp = "";
     Tokenizer tok = null;
     if (_isArray || _constructor || _staticCall)
     {
         char[] chars = variables.ToCharArray();
         for (int x = 0; x < chars.Length; x++)
         {
             if (chars[x] == ',')
             {
                 tok = (Tokenizer)tokenizerType.GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { tmp });
                 if (_components == null)
                     _components = tok.TokenizeStream(group);
                 else
                     _components.AddRange(tok.TokenizeStream(group).ToArray());
                 tmp = "";
             }
             else if ((chars[x] == '\'') || (chars[x] == '"'))
             {
                 tmp = processQuote(chars, ref x);
             }
             else
                 tmp += chars[x].ToString();
         }
         if (tmp.Length > 0)
         {
             tok = (Tokenizer)tokenizerType.GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { tmp });
             if (_components == null)
                 _components = tok.TokenizeStream(group);
             else
                 _components.AddRange(tok.TokenizeStream(group).ToArray());
         }
     }
     else
     {
         if ((variables.StartsWith("\"") || variables.StartsWith("'"))&&(variables.EndsWith("\"") || variables.EndsWith("'")))
             variables = variables.Substring(1,variables.Length-2);
         tok = (Tokenizer)tokenizerType.GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { variables });
         _components = tok.TokenizeStream(group);
     }
     foreach (IComponent ic in _components)
     {
         System.Diagnostics.Debug.WriteLine(ic.ToString());
     }
     return true;
 }
Пример #54
0
 public static TemplateGroup CreateTemplateGroup(int id)
 {
     TemplateGroup templateGroup = new TemplateGroup();
     templateGroup.ID = id;
     return templateGroup;
 }
 // Constructors
 public TemplateModeChangedEventArgs(TemplateGroup newTemplateGroup)
 {
 }
Пример #56
0
        private static string Render(TemplateGroup templateGroup, string templateName)
        {
            var template = templateGroup.GetInstanceOf(templateName);

            return(template?.Render());
        }