aboutsummaryrefslogtreecommitdiff
path: root/velocity-engine-core/src/main/java/org/apache/velocity/runtime/directive/Macro.java
blob: 973c3358294233a0bc978b46f239de44d2840353 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package org.apache.velocity.runtime.directive;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.TemplateInitException;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.parser.ParseException;
import org.apache.velocity.runtime.parser.Token;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.runtime.parser.node.ParserTreeConstants;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

/**
 *  Macro implements the macro definition directive of VTL.
 *
 *  example:
 *
 *  #macro( isnull $i )
 *     #if( $i )
 *         $i
 *      #end
 *  #end
 *
 *  This object is used at parse time to mainly process and register the
 *  macro.  It is used inline in the parser when processing a directive.
 *
 * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
 * @author <a href="hps@intermeta.de">Henning P. Schmiedehausen</a>
 * @version $Id$
 */
public class Macro extends Directive
{
    private static  boolean debugMode = false;

    /**
     * Return name of this directive.
     * @return The name of this directive.
     */
    @Override
    public String getName()
    {
        return "macro";
    }

    /**
     * Return type of this directive.
     * @return The type of this directive.
     */
    @Override
    public int getType()
    {
        return BLOCK;
    }

    /**
     * Since this class does no processing of content,
     * there is never a need for an internal scope.
     */
    @Override
    public boolean isScopeProvided()
    {
        return false;
    }

    /**
     *   render() doesn't do anything in the final output rendering.
     *   There is no output from a #macro() directive.
     * @param context
     * @param writer
     * @param node
     * @return True if the directive rendered successfully.
     * @throws IOException
     */
    @Override
    public boolean render(InternalContextAdapter context,
                          Writer writer, Node node)
        throws IOException
    {
        /*
         *  do nothing: We never render.  The VelocimacroProxy object does that
         */

        return true;
    }

    /**
     * @see org.apache.velocity.runtime.directive.Directive#init(org.apache.velocity.runtime.RuntimeServices, org.apache.velocity.context.InternalContextAdapter, org.apache.velocity.runtime.parser.node.Node)
     */
    @Override
    public void init(RuntimeServices rs, InternalContextAdapter context,
                     Node node)
       throws TemplateInitException
    {
        super.init(rs, context, node);


        // Add this macro to the VelocimacroManager now that it has been initialized.
        List<MacroArg> macroArgs = getArgArray(node, rsvc);
        int numArgs = node.jjtGetNumChildren();
        rsvc.addVelocimacro(macroArgs.get(0).name, node.jjtGetChild(numArgs - 1),
            macroArgs, node.getTemplate());
    }

    /**
     * Check the argument types of a macro call, called by the parser to do validation
     */
    @Override
    public void checkArgs(ArrayList<Integer> argtypes, Token t, String templateName)
        throws ParseException
    {
        if (argtypes.size() < 1)
        {
            throw new MacroParseException("A macro definition requires at least a macro name"
                , templateName, t);
        }

        /*
         *  lets make sure that the first arg is an ASTWord
         */
        if(argtypes.get(0) != ParserTreeConstants.JJTWORD)
        {
            throw new MacroParseException("Macro argument 1"
                    + " must be a token without surrounding \' or \""
                    , templateName, t);
        }


        // We use this to flag if the default arguments are out of order. such as
        // #macro($a $b=1 $c).  We enforce that all default parameters must be
        // specified consecutively, and at the end of the argument list.
        boolean consecutive = false;

        // All arguments other then the first must be either a reference
        // or a directiveassign followed by a reference in the case a default
        // value is specified.
        for (int argPos = 1; argPos < argtypes.size(); argPos++)
        {
            if (argtypes.get(argPos) == ParserTreeConstants.JJTDIRECTIVEASSIGN)
            {
               // Absorb next argument type since parser enforces that these are in
               // pairs, and we don't need to check the type of the second
               // arg because it is done by the parser.
               argPos++;
               consecutive = true;
            }
            else if (argtypes.get(argPos) != ParserTreeConstants.JJTREFERENCE)
            {
                throw new MacroParseException("Macro argument " + (argPos + 1)
                  + " must be a reference", templateName, t);
            }
            else if (consecutive)
            {
                // We have already found a default parameter e.g.; $x = 2, but
                // the next parameter was not a reference.
                throw new MacroParseException("Macro non-default argument follows a default argument at "
                  , templateName, t);
            }
        }
    }

    /**
     * Creates an array containing the literal text from the macro
     * argument(s) (including the macro's name as the first arg).
     *
     * @param node The parse node from which to grok the argument
     * list.  It's expected to include the block node tree (for the
     * macro body).
     * @param rsvc For debugging purposes only.
     * @return array of arguments
     */
    private static List<MacroArg> getArgArray(Node node, RuntimeServices rsvc)
    {
        /*
         * Get the number of arguments for the macro, excluding the
         * last child node which is the block tree containing the
         * macro body.
         */
        int numArgs = node.jjtGetNumChildren();
        numArgs--;  // avoid the block tree...

        ArrayList<MacroArg> macroArgs = new ArrayList<>();

        for (int i = 0; i < numArgs; i++)
        {
            Node curnode = node.jjtGetChild(i);
            MacroArg macroArg = new MacroArg();
            if (curnode.getType() == ParserTreeConstants.JJTDIRECTIVEASSIGN)
            {
                // This is an argument with a default value
            	macroArg.name = curnode.getFirstTokenImage();

                // Inforced by the parser there will be an argument here.
                i++;
                curnode = node.jjtGetChild(i);
                macroArg.defaultVal = curnode;
            }
            else
            {
                // An argument without a default value
               	macroArg.name = curnode.getFirstTokenImage();
            }

            // trim off the leading $ for the args after the macro name.
            // saves everyone else from having to do it
            if (i > 0 && macroArg.name.startsWith(String.valueOf(rsvc.getParserConfiguration().getDollarChar())))
            {
                macroArg.name = macroArg.name.substring(1);
            }

            macroArgs.add(macroArg);
        }

        if (debugMode)
        {
            StringBuilder msg = new StringBuilder("Macro.getArgArray(): nbrArgs=");
            msg.append(numArgs).append(": ");
            macroToString(msg, macroArgs, rsvc);
            rsvc.getLog("macro").debug(msg.toString());
        }

        return macroArgs;
    }

    /**
     * MacroArgs holds the information for a single argument in a
     * macro definition.  The arguments for a macro are passed around as a
     * list of these objects.
     */
    public static class MacroArg
    {
       /**
        * Name of the argument with '$' stripped off
        */
        public String name = null;

        /**
         * If the argument was given a default value, then this contains
         * the base of the AST tree of the value. Otherwise it is null.
         */
        public Node defaultVal = null;
    }

    /**
     * For debugging purposes.  Formats the arguments from
     * <code>argArray</code> and appends them to <code>buf</code>.
     *
     * @param buf A StringBuilder. If null, a new StringBuilder is allocated.
     * @param macroArgs  Array of macro arguments, containing the
     *        #macro() arguments and default values.  the 0th is the name.
     * @return A StringBuilder containing the formatted arguments. If a StringBuilder
     *         has passed in as buf, this method returns it.
     * @since 1.5
     */
    public static StringBuilder macroToString(final StringBuilder buf, List<MacroArg> macroArgs, RuntimeServices rsvc)
    {
        StringBuilder ret = (buf == null) ? new StringBuilder() : buf;

        ret.append(rsvc.getParserConfiguration().getHashChar()).append(macroArgs.get(0).name).append("( ");
        for (MacroArg marg : macroArgs)
        {
            ret.append(rsvc.getParserConfiguration().getDollarChar()).append(marg.name);
            if (marg.defaultVal != null)
            {
              ret.append("=").append(marg.defaultVal);
            }
            ret.append(' ');
        }
        ret.append(" )");
        return ret;
    }
    
}