aboutsummaryrefslogtreecommitdiffstats
path: root/framework/src/ant/apache-ant-1.9.6/src/main/org/apache/tools/ant/taskdefs/optional/javacc/JJTree.java
blob: f5d126eed0dd5c57fcc33754fdc676f54917dd54 (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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/*
 *  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.
 *
 */

package org.apache.tools.ant.taskdefs.optional.javacc;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Execute;
import org.apache.tools.ant.taskdefs.LogStreamHandler;
import org.apache.tools.ant.types.Commandline;
import org.apache.tools.ant.types.CommandlineJava;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.util.JavaEnvUtils;

/**
 * Runs the JJTree compiler compiler.
 *
 */
public class JJTree extends Task {

    // keys to optional attributes
    private static final String OUTPUT_FILE       = "OUTPUT_FILE";
    private static final String BUILD_NODE_FILES  = "BUILD_NODE_FILES";
    private static final String MULTI             = "MULTI";
    private static final String NODE_DEFAULT_VOID = "NODE_DEFAULT_VOID";
    private static final String NODE_FACTORY      = "NODE_FACTORY";
    private static final String NODE_SCOPE_HOOK   = "NODE_SCOPE_HOOK";
    private static final String NODE_USES_PARSER  = "NODE_USES_PARSER";
    private static final String STATIC            = "STATIC";
    private static final String VISITOR           = "VISITOR";

    private static final String NODE_PACKAGE      = "NODE_PACKAGE";
    private static final String VISITOR_EXCEPTION = "VISITOR_EXCEPTION";
    private static final String NODE_PREFIX       = "NODE_PREFIX";

    private final Hashtable optionalAttrs = new Hashtable();

    private String outputFile = null;

    private static final String DEFAULT_SUFFIX = ".jj";

    // required attributes
    private File outputDirectory = null;
    private File targetFile      = null;
    private File javaccHome      = null;

    private CommandlineJava cmdl = new CommandlineJava();

    private String maxMemory = null;

    /**
     * Sets the BUILD_NODE_FILES grammar option.
     * @param buildNodeFiles a <code>boolean</code> value.
     */
    public void setBuildnodefiles(boolean buildNodeFiles) {
        optionalAttrs.put(BUILD_NODE_FILES, buildNodeFiles ? Boolean.TRUE : Boolean.FALSE);
    }

    /**
     * Sets the MULTI grammar option.
     * @param multi a <code>boolean</code> value.
     */
    public void setMulti(boolean multi) {
        optionalAttrs.put(MULTI, multi ? Boolean.TRUE : Boolean.FALSE);
    }

    /**
     * Sets the NODE_DEFAULT_VOID grammar option.
     * @param nodeDefaultVoid a <code>boolean</code> value.
     */
    public void setNodedefaultvoid(boolean nodeDefaultVoid) {
        optionalAttrs.put(NODE_DEFAULT_VOID, nodeDefaultVoid ? Boolean.TRUE : Boolean.FALSE);
    }

    /**
     * Sets the NODE_FACTORY grammar option.
     * @param nodeFactory a <code>boolean</code> value.
     */
    public void setNodefactory(boolean nodeFactory) {
        optionalAttrs.put(NODE_FACTORY, nodeFactory ? Boolean.TRUE : Boolean.FALSE);
    }

    /**
     * Sets the NODE_SCOPE_HOOK grammar option.
     * @param nodeScopeHook a <code>boolean</code> value.
     */
    public void setNodescopehook(boolean nodeScopeHook) {
        optionalAttrs.put(NODE_SCOPE_HOOK, nodeScopeHook ? Boolean.TRUE : Boolean.FALSE);
    }

    /**
     * Sets the NODE_USES_PARSER grammar option.
     * @param nodeUsesParser a <code>boolean</code> value.
     */
    public void setNodeusesparser(boolean nodeUsesParser) {
        optionalAttrs.put(NODE_USES_PARSER, nodeUsesParser ? Boolean.TRUE : Boolean.FALSE);
    }

    /**
     * Sets the STATIC grammar option.
     * @param staticParser a <code>boolean</code> value.
     */
    public void setStatic(boolean staticParser) {
        optionalAttrs.put(STATIC, staticParser ? Boolean.TRUE : Boolean.FALSE);
    }

    /**
     * Sets the VISITOR grammar option.
     * @param visitor a <code>boolean</code> value.
     */
    public void setVisitor(boolean visitor) {
        optionalAttrs.put(VISITOR, visitor ? Boolean.TRUE : Boolean.FALSE);
    }

    /**
     * Sets the NODE_PACKAGE grammar option.
     * @param nodePackage the option to use.
     */
    public void setNodepackage(String nodePackage) {
        optionalAttrs.put(NODE_PACKAGE, nodePackage);
    }

    /**
     * Sets the VISITOR_EXCEPTION grammar option.
     * @param visitorException the option to use.
     */
    public void setVisitorException(String visitorException) {
        optionalAttrs.put(VISITOR_EXCEPTION, visitorException);
    }

    /**
     * Sets the NODE_PREFIX grammar option.
     * @param nodePrefix the option to use.
     */
    public void setNodeprefix(String nodePrefix) {
        optionalAttrs.put(NODE_PREFIX, nodePrefix);
    }

    /**
     * The directory to write the generated JavaCC grammar and node files to.
     * If not set, the files are written to the directory
     * containing the grammar file.
     * @param outputDirectory the output directory.
     */
    public void setOutputdirectory(File outputDirectory) {
        this.outputDirectory = outputDirectory;
    }

    /**
     * The outputfile to write the generated JavaCC grammar file to.
     * If not set, the file is written with the same name as
     * the JJTree grammar file with a suffix .jj.
     * @param outputFile the output file name.
     */
    public void setOutputfile(String outputFile) {
        this.outputFile = outputFile;
    }

    /**
     * The jjtree grammar file to process.
     * @param targetFile the grammar file.
     */
    public void setTarget(File targetFile) {
        this.targetFile = targetFile;
    }

    /**
     * The directory containing the JavaCC distribution.
     * @param javaccHome the directory containing JavaCC.
     */
    public void setJavacchome(File javaccHome) {
        this.javaccHome = javaccHome;
    }

    /**
     * Corresponds -Xmx.
     *
     * @param max max memory parameter.
     * @since Ant 1.8.3
     */
    public void setMaxmemory(String max) {
        maxMemory = max;
    }

    /**
     * Constructor
     */
    public JJTree() {
        cmdl.setVm(JavaEnvUtils.getJreExecutable("java"));
    }

    /**
     * Run the task.
     * @throws BuildException on error.
     */
    public void execute() throws BuildException {

        // load command line with optional attributes
        Enumeration iter = optionalAttrs.keys();
        while (iter.hasMoreElements()) {
            String name  = (String) iter.nextElement();
            Object value = optionalAttrs.get(name);
            cmdl.createArgument().setValue("-" + name + ":" + value.toString());
        }

        if (targetFile == null || !targetFile.isFile()) {
            throw new BuildException("Invalid target: " + targetFile);
        }

        File javaFile = null;

        // use the directory containing the target as the output directory
        if (outputDirectory == null) {
            // convert backslashes to slashes, otherwise jjtree will
            // put this as comments and this seems to confuse javacc
            cmdl.createArgument().setValue("-OUTPUT_DIRECTORY:"
                                           + getDefaultOutputDirectory());

            javaFile = new File(createOutputFileName(targetFile, outputFile,
                                                     null));
        } else {
            if (!outputDirectory.isDirectory()) {
                throw new BuildException("'outputdirectory' " + outputDirectory
                                         + " is not a directory.");
            }

            // convert backslashes to slashes, otherwise jjtree will
            // put this as comments and this seems to confuse javacc
            cmdl.createArgument().setValue("-OUTPUT_DIRECTORY:"
                                           + outputDirectory.getAbsolutePath()
                                             .replace('\\', '/'));

            javaFile = new File(createOutputFileName(targetFile, outputFile,
                                                     outputDirectory
                                                     .getPath()));
        }

        if (javaFile.exists()
            && targetFile.lastModified() < javaFile.lastModified()) {
            log("Target is already built - skipping (" + targetFile + ")",
                Project.MSG_VERBOSE);
            return;
        }

        if (outputFile != null) {
            cmdl.createArgument().setValue("-" + OUTPUT_FILE + ":"
                                           + outputFile.replace('\\', '/'));
        }

        cmdl.createArgument().setValue(targetFile.getAbsolutePath());

        final Path classpath = cmdl.createClasspath(getProject());
        final File javaccJar = JavaCC.getArchiveFile(javaccHome);
        classpath.createPathElement().setPath(javaccJar.getAbsolutePath());
        classpath.addJavaRuntime();

        cmdl.setClassname(JavaCC.getMainClass(classpath,
                                              JavaCC.TASKDEF_TYPE_JJTREE));

        cmdl.setMaxmemory(maxMemory);
        final Commandline.Argument arg = cmdl.createVmArgument();
        arg.setValue("-Dinstall.root=" + javaccHome.getAbsolutePath());

        final Execute process =
            new Execute(new LogStreamHandler(this,
                                             Project.MSG_INFO,
                                             Project.MSG_INFO),
                        null);
        log(cmdl.describeCommand(), Project.MSG_VERBOSE);
        process.setCommandline(cmdl.getCommandline());

        try {
            if (process.execute() != 0) {
                throw new BuildException("JJTree failed.");
            }
        } catch (IOException e) {
            throw new BuildException("Failed to launch JJTree", e);
        }
    }

    private String createOutputFileName(File destFile, String optionalOutputFile,
                                        String outputDir) {
        optionalOutputFile = validateOutputFile(optionalOutputFile,
                                                outputDir);
        String jjtreeFile = destFile.getAbsolutePath().replace('\\', '/');

        if ((optionalOutputFile == null) || optionalOutputFile.equals("")) {
            int filePos = jjtreeFile.lastIndexOf("/");

            if (filePos >= 0) {
                jjtreeFile = jjtreeFile.substring(filePos + 1);
            }

            int suffixPos = jjtreeFile.lastIndexOf('.');

            if (suffixPos == -1) {
                optionalOutputFile = jjtreeFile + DEFAULT_SUFFIX;
            } else {
                String currentSuffix = jjtreeFile.substring(suffixPos);

                if (currentSuffix.equals(DEFAULT_SUFFIX)) {
                    optionalOutputFile = jjtreeFile + DEFAULT_SUFFIX;
                } else {
                    optionalOutputFile = jjtreeFile.substring(0, suffixPos)
                        + DEFAULT_SUFFIX;
                }
            }
        }

        if ((outputDir == null) || outputDir.equals("")) {
            outputDir = getDefaultOutputDirectory();
        }

        return (outputDir + "/" + optionalOutputFile).replace('\\', '/');
    }

    /**
     * When running JJTree from an Ant taskdesk the -OUTPUT_DIRECTORY must
     * always be set. But when -OUTPUT_DIRECTORY is set, -OUTPUT_FILE is
     * handled as if relative of this -OUTPUT_DIRECTORY. Thus when the
     * -OUTPUT_FILE is absolute or contains a drive letter we have a problem.
     *
     * @param destFile
     * @param outputDir
     * @return validation file, relative if possible; <tt>null</tt> if not set
     * @throws BuildException
     */
    private String validateOutputFile(String destFile,
                                      String outputDir)
        throws BuildException {
        if (destFile == null) {
            return null;
        }

        if ((outputDir == null)
            && (destFile.startsWith("/") || destFile.startsWith("\\"))) {
            String relativeOutputFile = makeOutputFileRelative(destFile);
            setOutputfile(relativeOutputFile);

            return relativeOutputFile;
        }

        String root = getRoot(new File(destFile)).getAbsolutePath();

        if ((root.length() > 1)
            && destFile.startsWith(root.substring(0, root.length() - 1))) {
            throw new BuildException("Drive letter in 'outputfile' not "
                                     + "supported: " + destFile);
        }

        return destFile;
    }

    private String makeOutputFileRelative(String destFile) {
        StringBuffer relativePath = new StringBuffer();
        String defaultOutputDirectory = getDefaultOutputDirectory();
        int nextPos = defaultOutputDirectory.indexOf('/');
        int startPos = nextPos + 1;

        while (startPos > -1 && startPos < defaultOutputDirectory.length()) {
            relativePath.append("/..");
            nextPos = defaultOutputDirectory.indexOf('/', startPos);

            if (nextPos == -1) {
                startPos = nextPos;
            } else {
                startPos = nextPos + 1;
            }
        }

        relativePath.append(destFile);

        return relativePath.toString();
    }

    private String getDefaultOutputDirectory() {
        return getProject().getBaseDir().getAbsolutePath().replace('\\', '/');
    }

    /**
     * Determine root directory for a given file.
     *
     * @param file
     * @return file's root directory
     */
    private File getRoot(File file) {
        File root = file.getAbsoluteFile();

        while (root.getParent() != null) {
            root = root.getParentFile();
        }

        return root;
    }
}