コード例 #1
0
        /** Compile full template with unknown formal args. */
        public virtual CompiledTemplate Compile(string name, string template)
        {
            CompiledTemplate code = Compile(null, name, null, template, null);

            code.HasFormalArgs = false;
            return(code);
        }
コード例 #2
0
ファイル: CompiledTemplate.cs プロジェクト: ymf1/webgrease
        public virtual void AddImplicitlyDefinedTemplate(CompiledTemplate sub)
        {
            if (implicitlyDefinedTemplates == null)
            {
                implicitlyDefinedTemplates = new List <CompiledTemplate>();
            }

            implicitlyDefinedTemplates.Add(sub);
        }
コード例 #3
0
        /** Compile full template with respect to a list of formal args. */
        public virtual CompiledTemplate Compile(string srcName, string name, List <FormalArgument> args, string template, IToken templateToken)
        {
            ANTLRStringStream @is = new ANTLRStringStream(template);

            @is.name = srcName != null ? srcName : name;
            TemplateLexer     lexer  = new TemplateLexer(ErrorManager, @is, templateToken, DelimiterStartChar, DelimiterStopChar);
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            TemplateParser    p      = new TemplateParser(tokens, ErrorManager, templateToken);

            TemplateParser.templateAndEOF_return r = null;
            try
            {
                r = p.templateAndEOF();
            }
            catch (RecognitionException re)
            {
                ReportMessageAndThrowTemplateException(tokens, templateToken, p, re);
                return(null);
            }

            if (p.NumberOfSyntaxErrors > 0 || r.Tree == null)
            {
                CompiledTemplate impl = new CompiledTemplate();
                impl.DefineFormalArguments(args);
                return(impl);
            }

            //System.out.println(((CommonTree)r.getTree()).toStringTree());
            CommonTreeNodeStream nodes = new CommonTreeNodeStream(r.Tree);

            nodes.TokenStream = tokens;
            CodeGenerator gen = new CodeGenerator(nodes, this, name, template, templateToken);

            CompiledTemplate impl2 = null;

            try
            {
                impl2             = gen.template(name, args);
                impl2.NativeGroup = Group;
                impl2.template    = template;
                // only save tree/token stream when debugging
                if (Group.Debug)
                {
                    impl2.ast = (CommonTree)r.Tree;
                    impl2.ast.SetUnknownTokenBoundaries();
                    impl2.tokens = tokens;
                }
            }
            catch (RecognitionException re)
            {
                ErrorManager.InternalError(null, "bad tree structure", re);
            }

            return(impl2);
        }
コード例 #4
0
        /// <summary>
        /// Cloning the <see cref="CompiledTemplate"/> for a <see cref="StringTemplate.Template"/> instance allows
        /// <see cref="StringTemplate.Template.Add"/> to be called safely during interpretation for templates that do
        /// not contain formal arguments.
        /// </summary>
        /// <returns>
        /// A copy of the current <see cref="CompiledTemplate"/> instance. The copy is a shallow copy, with the
        /// exception of the <see cref="_formalArguments"/> field which is also cloned.
        /// </returns>
        public CompiledTemplate Clone()
        {
            CompiledTemplate clone = (CompiledTemplate)MemberwiseClone();

            if (_formalArguments != null)
            {
                _formalArguments = new List <FormalArgument>(_formalArguments);
            }

            return(clone);
        }
コード例 #5
0
        public static CompiledTemplate DefineBlankRegion(CompiledTemplate outermostImpl, string name)
        {
            string           outermostTemplateName = outermostImpl.name;
            string           mangled = TemplateGroup.GetMangledRegionName(outermostTemplateName, name);
            CompiledTemplate blank   = new CompiledTemplate();

            blank.isRegion      = true;
            blank.regionDefType = Template.RegionType.Implicit;
            blank.name          = mangled;
            outermostImpl.AddImplicitlyDefinedTemplate(blank);
            return(blank);
        }
コード例 #6
0
        public virtual void AddImplicitlyDefinedTemplate(CompiledTemplate sub)
        {
            sub.Prefix = this.Prefix;
            if (sub.Name[0] != '/')
            {
                sub.Name = sub.Prefix + sub.Name;
            }

            if (implicitlyDefinedTemplates == null)
            {
                implicitlyDefinedTemplates = new List <CompiledTemplate>();
            }

            implicitlyDefinedTemplates.Add(sub);
        }
コード例 #7
0
        public static CompiledTemplate DefineBlankRegion(CompiledTemplate outermostImpl, IToken nameToken)
        {
            if (outermostImpl == null)
            {
                throw new ArgumentNullException("outermostImpl");
            }
            if (nameToken == null)
            {
                throw new ArgumentNullException("nameToken");
            }

            string           outermostTemplateName = outermostImpl.Name;
            string           mangled = TemplateGroup.GetMangledRegionName(outermostTemplateName, nameToken.Text);
            CompiledTemplate blank   = new CompiledTemplate();

            blank.IsRegion = true;
            blank.TemplateDefStartToken = nameToken;
            blank.RegionDefType         = Template.RegionType.Implicit;
            blank.Name = mangled;
            outermostImpl.AddImplicitlyDefinedTemplate(blank);
            return(blank);
        }
コード例 #8
0
 public TemplateInformation(IToken nameToken, IToken templateToken, CompiledTemplate template)
     : this(null, nameToken, templateToken, template)
 {
 }
コード例 #9
0
ファイル: TemplateGroup.cs プロジェクト: mahanteshck/antlrcs
        public virtual Template CreateStringTemplate(CompiledTemplate impl)
        {
            Template st = new Template(this);
            st.impl = impl;
            if (impl.FormalArguments != null)
            {
                st.locals = new object[impl.FormalArguments.Count];
                for (int i = 0; i < st.locals.Length; i++)
                    st.locals[i] = Template.EmptyAttribute;
            }

            return st;
        }
コード例 #10
0
 public override Template CreateStringTemplate(Antlr4.StringTemplate.Compiler.CompiledTemplate impl)
 {
     return(base.CreateStringTemplate(impl));
 }
コード例 #11
0
        /** Compile full template with respect to a list of formal args. */
        public virtual CompiledTemplate Compile(string srcName, string name, List<FormalArgument> args, string template, IToken templateToken)
        {
            ANTLRStringStream @is = new ANTLRStringStream(template, srcName);
            @is.name = srcName != null ? srcName : name;
            TemplateLexer lexer = null;
            if (templateToken != null && templateToken.Type == GroupParser.BIGSTRING_NO_NL)
            {
                lexer = new TemplateLexerNoNewlines(ErrorManager, @is, templateToken, DelimiterStartChar, DelimiterStopChar);
            }
            else
            {
                lexer = new TemplateLexer(ErrorManager, @is, templateToken, DelimiterStartChar, DelimiterStopChar);
            }

            CommonTokenStream tokens = new CommonTokenStream(lexer);
            TemplateParser p = new TemplateParser(tokens, ErrorManager, templateToken);
            IAstRuleReturnScope<CommonTree> r = null;
            try
            {
                r = p.templateAndEOF();
            }
            catch (RecognitionException re)
            {
                ReportMessageAndThrowTemplateException(tokens, templateToken, p, re);
                return null;
            }

            if (p.NumberOfSyntaxErrors > 0 || r.Tree == null)
            {
                CompiledTemplate impl = new CompiledTemplate();
                impl.DefineFormalArguments(args);
                return impl;
            }

            //System.out.println(((CommonTree)r.getTree()).toStringTree());
            CommonTreeNodeStream nodes = new CommonTreeNodeStream(r.Tree);
            nodes.TokenStream = tokens;
            CodeGenerator gen = new CodeGenerator(nodes, this, name, template, templateToken);

            CompiledTemplate impl2 = null;
            try
            {
                impl2 = gen.template(name, args);
                impl2.NativeGroup = Group;
                impl2.Template = template;
                impl2.Ast = r.Tree;
                impl2.Ast.SetUnknownTokenBoundaries();
                impl2.Tokens = tokens;
            }
            catch (RecognitionException re)
            {
                ErrorManager.InternalError(null, "bad tree structure", re);
            }

            return impl2;
        }
コード例 #12
0
        public virtual void AddImplicitlyDefinedTemplate(CompiledTemplate sub)
        {
            sub.Prefix = this.Prefix;
            if (sub.Name[0] != '/')
                sub.Name = sub.Prefix + sub.Name;

            if (implicitlyDefinedTemplates == null)
                implicitlyDefinedTemplates = new List<CompiledTemplate>();

            implicitlyDefinedTemplates.Add(sub);
        }
コード例 #13
0
ファイル: TemplateGroup.cs プロジェクト: mahanteshck/antlrcs
        public virtual void RawDefineTemplate(string name, CompiledTemplate code, IToken defT)
        {
            CompiledTemplate prev;
            templates.TryGetValue(name, out prev);
            if (prev != null)
            {
                if (!prev.IsRegion)
                {
                    ErrorManager.CompiletimeError(ErrorType.TEMPLATE_REDEFINITION, null, defT);
                    return;
                }

                /* If this region was previously defined, the following actions should be taken:
                 *
                 *      Previous type   Current type   Result   Applied     Reason
                 *      -------------   ------------   ------   -------     ------
                 *      Implicit        Implicit       Success  Previous    A rule may make multiple implicit references to the same region.
                 *                                                          Keeping either has the same semantics, so the existing one is
                 *                                                          used for slightly less overhead.
                 *      Implicit        Explicit       Success  Current     A region with previous implicit references is now being explicitly
                 *                                                          defined.
                 *      Implicit        Embedded       Success  Current     A region with previous implicit references is now being defined
                 *                                                          with an embedded region.
                 *      Explicit        Implicit       Success  Previous    An explicitly defined region is now being implicitly referenced.
                 *                                                          Make sure to keep the previous explicit definition as the actual
                 *                                                          definition.
                 *      Explicit        Explicit       Error    Previous    Multiple explicit definitions exist for the same region (template
                 *                                                          redefinition error). Give an error and use the previous one.
                 *      Explicit        Embedded       Warning  Previous    An explicit region definition already exists for the current
                 *                                                          embedded region definition. The explicit definition overrides the
                 *                                                          embedded definition and a warning is given since the embedded
                 *                                                          definition is hidden.
                 *      Embedded        Implicit       Success  Previous    A region with an embedded definition is now being implicitly
                 *                                                          referenced. The embedded definition should be used.
                 *      Embedded        Explicit       Warning  Current     A region with an embedded definition is now being explicitly
                 *                                                          defined. The explicit definition overrides the embedded
                 *                                                          definition and a warning is given since the embedded definition
                 *                                                          is hidden.
                 *      Embedded        Embedded       Error    Previous    Multiple embedded definitions of the same region were given in a
                 *                                                          template. Give an error and use the previous one.
                 */

                // handle the Explicit/Explicit and Embedded/Embedded error cases
                if (code.RegionDefType != Template.RegionType.Implicit && code.RegionDefType == prev.RegionDefType)
                {
                    if (code.RegionDefType == Template.RegionType.Embedded)
                        ErrorManager.CompiletimeError(ErrorType.EMBEDDED_REGION_REDEFINITION, null, defT, GetUnmangledTemplateName(name));
                    else
                        ErrorManager.CompiletimeError(ErrorType.REGION_REDEFINITION, null, defT, GetUnmangledTemplateName(name));

                    // keep the previous one
                    return;
                }
                // handle the Explicit/Embedded and Embedded/Explicit warning cases
                else if ((code.RegionDefType == Template.RegionType.Embedded && prev.RegionDefType == Template.RegionType.Explicit)
                    || (code.RegionDefType == Template.RegionType.Explicit && prev.RegionDefType == Template.RegionType.Embedded))
                {
                    // TODO: can we make this a warning?
                    ErrorManager.CompiletimeError(ErrorType.HIDDEN_EMBEDDED_REGION_DEFINITION, null, defT, GetUnmangledTemplateName(name));
                    // keep the previous one only if that's the explicit definition
                    if (prev.RegionDefType == Template.RegionType.Explicit)
                        return;
                }
                // else if the current definition type is implicit, keep the previous one
                else if (code.RegionDefType == Template.RegionType.Implicit)
                {
                    return;
                }
            }

            code.NativeGroup = this;
            code.TemplateDefStartToken = defT;
            templates[name] = code;
        }
コード例 #14
0
ファイル: TemplateGroup.cs プロジェクト: mahanteshck/antlrcs
        /** differentiate so we can avoid having creation events for regions,
         *  map operations, and other "new ST" events used during interp.
         */
        public Template CreateStringTemplateInternally(CompiledTemplate impl)
        {
            Template template = CreateStringTemplate(impl);
            if (TrackCreationEvents && template.DebugState != null)
            {
                // toss it out
                template.DebugState.NewTemplateEvent = null;
            }

            return template;
        }
コード例 #15
0
 public TemplateInformation(string enclosingTemplateName, IToken nameToken, IToken templateToken, CompiledTemplate template)
 {
     this._enclosingTemplateName = enclosingTemplateName;
     this._nameToken = nameToken;
     this._templateToken = templateToken;
     this._template = template;
 }
コード例 #16
0
ファイル: Interpreter.cs プロジェクト: mahanteshck/antlrcs
        /** Set any default argument values that were not set by the
         *  invoking template or by setAttribute directly.  Note
         *  that the default values may be templates.
         *
         *  The evaluation context is the template enclosing invokedST.
         */
        protected virtual void SetDefaultArguments(TemplateFrame frame)
        {
            Template invokedST = frame.Template;
            if (invokedST.impl.FormalArguments == null || invokedST.impl.NumberOfArgsWithDefaultValues == 0)
                return;

            foreach (FormalArgument arg in invokedST.impl.FormalArguments)
            {
                // if no value for attribute and default arg, inject default arg into self
                if (invokedST.locals[arg.Index] != Template.EmptyAttribute || arg.DefaultValueToken == null)
                    continue;

                if (arg.DefaultValueToken.Type == GroupParser.ANONYMOUS_TEMPLATE)
                {
                    CompiledTemplate code = arg.CompiledDefaultValue;
                    if (code == null)
                        code = new CompiledTemplate();

                    Template defaultArgST = group.CreateStringTemplateInternally(code);
                    // default arg template must see other args so it's enclosing
                    // instance is the template we are invoking.
                    defaultArgST.Group = group;
                    // If default arg is template with single expression
                    // wrapped in parens, x={<(...)>}, then eval to string
                    // rather than setting x to the template for later
                    // eval.
                    string defArgTemplate = arg.DefaultValueToken.Text;
                    if (defArgTemplate.StartsWith("{" + group.DelimiterStartChar + "(")
                        && defArgTemplate.EndsWith(")" + group.DelimiterStopChar + "}"))
                    {
                        invokedST.RawSetAttribute(arg.Name, ToString(new TemplateFrame(defaultArgST, frame), defaultArgST));
                    }
                    else
                    {
                        invokedST.RawSetAttribute(arg.Name, defaultArgST);
                    }
                }
                else
                {
                    invokedST.RawSetAttribute(arg.Name, arg.DefaultValue);
                }
            }
        }
コード例 #17
0
 public override void RawDefineTemplate(string name, Antlr4.StringTemplate.Compiler.CompiledTemplate code, Antlr.Runtime.IToken defT)
 {
     base.RawDefineTemplate(name, code, defT);
 }
コード例 #18
0
        public static CompiledTemplate DefineBlankRegion(CompiledTemplate outermostImpl, IToken nameToken)
        {
            if (outermostImpl == null)
                throw new ArgumentNullException("outermostImpl");
            if (nameToken == null)
                throw new ArgumentNullException("nameToken");

            string outermostTemplateName = outermostImpl.Name;
            string mangled = TemplateGroup.GetMangledRegionName(outermostTemplateName, nameToken.Text);
            CompiledTemplate blank = new CompiledTemplate();
            blank.IsRegion = true;
            blank.TemplateDefStartToken = nameToken;
            blank.RegionDefType = Template.RegionType.Implicit;
            blank.Name = mangled;
            outermostImpl.AddImplicitlyDefinedTemplate(blank);
            return blank;
        }
コード例 #19
0
 public BytecodeDisassembler(CompiledTemplate code)
 {
     this.code = code;
 }
コード例 #20
0
 public BytecodeDisassembler(CompiledTemplate code)
 {
     this.code = code;
 }
コード例 #21
0
ファイル: TemplateGroup.cs プロジェクト: mahanteshck/antlrcs
        private object CreateGroupObject(BinaryReader reader, int key, Dictionary<int, object> objects)
        {
            var comparer = ObjectReferenceEqualityComparer<object>.Default;

            int typeKey = reader.ReadInt32();
            if (typeKey == 0)
            {
                // this is a string
                return reader.ReadString();
            }

            string typeName = (string)objects[typeKey];
            if (typeName == typeof(bool).FullName)
            {
                return reader.ReadBoolean();
            }
            else if (typeName == typeof(TemplateToken).FullName || typeName == typeof(CommonToken).FullName)
            {
                int channel = reader.ReadInt32();
                int charPositionInLine = reader.ReadInt32();
                int line = reader.ReadInt32();
                int startIndex = reader.ReadInt32();
                int stopIndex = reader.ReadInt32();
                string text = reader.ReadString();
                int tokenIndex = reader.ReadInt32();
                int type = reader.ReadInt32();
                CommonToken token = new CommonToken(type, text)
                {
                    Channel = channel,
                    CharPositionInLine = charPositionInLine,
                    Line = line,
                    StartIndex = startIndex,
                    StopIndex = stopIndex,
                    TokenIndex = tokenIndex,
                };

                return token;
            }
            else if (typeName == typeof(CompiledTemplate).FullName)
            {
                CompiledTemplate compiledTemplate = new CompiledTemplate();
                compiledTemplate.Name = reader.ReadString();
                compiledTemplate.Prefix = reader.ReadString();
                compiledTemplate.Template = reader.ReadString();
                int templateDefStartTokenObject = reader.ReadInt32();
                compiledTemplate.HasFormalArgs = reader.ReadBoolean();
                int nativeGroupObject = reader.ReadInt32();
                compiledTemplate.IsRegion = reader.ReadBoolean();
                compiledTemplate.RegionDefType = (Template.RegionType)reader.ReadInt32();
                compiledTemplate.IsAnonSubtemplate = reader.ReadBoolean();

                int formalArgsLength = reader.ReadInt32();
                if (formalArgsLength > 0)
                {
                    for (int i = 0; i < formalArgsLength; i++)
                    {
                        int formalArgObject = reader.ReadInt32();
                    }
                }

                int stringsLength = reader.ReadInt32();
                if (stringsLength >= 0)
                {
                    compiledTemplate.strings = new string[stringsLength];
                    for (int i = 0; i < stringsLength; i++)
                        compiledTemplate.strings[i] = reader.ReadString();
                }

                int instrsLength = reader.ReadInt32();
                if (instrsLength >= 0)
                    compiledTemplate.instrs = reader.ReadBytes(instrsLength);

                compiledTemplate.codeSize = reader.ReadInt32();

                int sourceMapLength = reader.ReadInt32();
                if (sourceMapLength >= 0)
                {
                    compiledTemplate.sourceMap = new Interval[sourceMapLength];
                    for (int i = 0; i < sourceMapLength; i++)
                    {
                        int start = reader.ReadInt32();
                        int length = reader.ReadInt32();
                        if (length >= 0)
                            compiledTemplate.sourceMap[i] = new Interval(start, length);
                    }
                }

                return compiledTemplate;
            }
            else if (typeName == typeof(FormalArgument).FullName)
            {
                string name = reader.ReadString();
                int index = reader.ReadInt32();
                IToken defaultValueToken = (IToken)objects[reader.ReadInt32()];
                int defaultValueObject = reader.ReadInt32();
                int compiledDefaultValue = reader.ReadInt32();

                FormalArgument formalArgument = new FormalArgument(name, defaultValueToken);
                formalArgument.Index = index;

                return formalArgument;
            }
            else if (typeName == typeof(Template).FullName)
            {
                int implObject = reader.ReadInt32();

                int localsCount = reader.ReadInt32();
                for (int i = 0; i < localsCount; i++)
                {
                    int localObject = reader.ReadInt32();
                }

                int groupObject = reader.ReadInt32();

                TemplateGroup group = this;
                Template template = new Template(group);
                return template;
            }
            else if (typeName == typeof(TemplateGroupFile).FullName)
            {
                bool isDefaultGroup = reader.ReadBoolean();
                if (!isDefaultGroup)
                    return this;
                else
                    throw new NotSupportedException();
            }
            else if (typeName == typeof(TemplateGroup).FullName)
            {
                bool isDefaultGroup = reader.ReadBoolean();
                if (isDefaultGroup)
                    return TemplateGroup.DefaultGroup;
                else
                    throw new NotSupportedException();
            }
            else
            {
                throw new NotImplementedException();
            }
        }
コード例 #22
-1
        internal TemplateInformation GetTemplateInformation(CompiledTemplate template)
        {
            Contract.Requires<ArgumentNullException>(template != null, "template");
            Contract.Requires<ArgumentException>(template.NativeGroup == this);
            Contract.Ensures(Contract.Result<TemplateInformation>() != null);

            return _compiledTemplateInformation[template];
        }