Search in sources :

Example 1 with BuildException

use of org.eclipse.cdt.managedbuilder.core.BuildException in project linuxtools by eclipse.

the class CProjectBuildHelpers method isOptionCheckedInCDTTool.

/**
 * <h1>Check if an option is set</h1>
 * Same as {@link #isOptionCheckedInCDT(IProject project, String optionIDString) isOptionChecked_inCDT },
 * except you specify tool name manually. <br>
 *
 * (e.g you need to check something that's not supported in the implementation above.
 * @param project         the IProject project which will be read to check if it is c or cpp
 * @param optionIDString  for example <code> gnu.cpp.compiler.option.debugging.codecov </code>
 * @param toolSuperClassId  superclass id of the parent tool. see {@link #helperGetToolSuperClassId helper_GetToolSuperClassId}
 * @return                true if the option is set
 */
private static boolean isOptionCheckedInCDTTool(IProject project, String optionIDString, String toolSuperClassId) {
    IConfiguration activeConf = helperGetActiveConfiguration(project);
    // Get Compiler tool.
    ITool gccCompileriTool = helperGetGccCompilerToolBySuperClass(toolSuperClassId, activeConf);
    // (Get immutable option: This is like a 'template' that we will use to get the actual option)
    IOption optionTemplate = gccCompileriTool.getOptionById(optionIDString);
    // Check that we got a good option.
    if (optionTemplate == null) {
        MessageDialogSyncedRunnable.openErrorSyncedRunnable(ProfilingMessages.errorTitle, ProfilingMessages.errorGetOptionTemplate);
        return false;
    }
    // (Now we acquire the actual option from which we can read the value)
    try {
        IOption mutableOptionToSet = gccCompileriTool.getOptionToSet(optionTemplate, false);
        return (boolean) mutableOptionToSet.getValue();
    } catch (BuildException e) {
        // This is reached if the template that was provided was bad.
        MessageDialogSyncedRunnable.openErrorSyncedRunnable(ProfilingMessages.errorTitle, ProfilingMessages.errorGetOptionForWriting);
    }
    return false;
}
Also used : IOption(org.eclipse.cdt.managedbuilder.core.IOption) BuildException(org.eclipse.cdt.managedbuilder.core.BuildException) IConfiguration(org.eclipse.cdt.managedbuilder.core.IConfiguration) ITool(org.eclipse.cdt.managedbuilder.core.ITool)

Example 2 with BuildException

use of org.eclipse.cdt.managedbuilder.core.BuildException in project arduino-eclipse-plugin by Sloeber.

the class ArduinoGnuMakefileGenerator method addRuleForSource.

/**
 * Create a rule for this source file. We create a pattern rule if possible.
 * This is an example of a pattern rule:
 * <relative_path>/%.<outputExtension>: ../<relative_path>/%.
 * <inputExtension>
 *
 * @echo Building file: $<
 * @echo Invoking tool xxx
 * @echo <tool> <flags> <output_flag><output_prefix>$@ $<
 * @<tool> <flags> <output_flag><output_prefix>$@ $< && \ echo -n
 *         $(@:%.o=%.d) ' <relative_path>/' >> $(@:%.o=%.d) && \ <tool> -P
 *         -MM -MG <flags> $< >> $(@:%.o=%.d)
 * @echo Finished building: $<
 * @echo ' ' Note that the macros all come from the build model and are
 *       resolved to a real command before writing to the module makefile,
 *       so a real command might look something like: source1/%.o:
 *       ../source1/%.cpp
 * @echo Building file: $<
 * @echo Invoking tool xxx
 * @echo g++ -g -O2 -c -I/cygdrive/c/eclipse/workspace/Project/headers -o$@
 *       $< @g++ -g -O2 -c -I/cygdrive/c/eclipse/workspace/Project/headers
 *       -o$@ $< && \ echo -n $(@:%.o=%.d) ' source1/' >> $(@:%.o=%.d) && \
 *       g++ -P -MM -MG -g -O2 -c
 *       -I/cygdrive/c/eclipse/workspace/Project/headers $< >> $(@:%.o=%.d)
 * @echo Finished building: $<
 * @echo ' '
 * @param relativePath
 *            top build output directory relative path of the current output
 *            directory
 * @param buffer
 *            buffer to populate with the build rule
 * @param resource
 *            the source file for this invocation of the tool
 * @param sourceLocation
 *            the full path of the source
 * @param rcInfo
 *            the IResourceInfo associated with this file or null
 * @param generatedSource
 *            <code>true</code> if the resource is a generated output
 * @param enumeratedOutputs
 *            vector of the filenames that are the output of this rule
 */
@SuppressWarnings("null")
protected void addRuleForSource(String relativePath, StringBuffer buffer, IResource resource, IPath sourceLocation, IResourceInfo rcInfo, boolean generatedSource, List<IPath> generatedDepFiles, List<IPath> enumeratedOutputs) {
    String fileName = sourceLocation.removeFileExtension().lastSegment();
    String inputExtension = sourceLocation.getFileExtension();
    String outputExtension = null;
    ITool tool = null;
    if (rcInfo instanceof IFileInfo) {
        IFileInfo fi = (IFileInfo) rcInfo;
        ITool[] tools = fi.getToolsToInvoke();
        if (tools != null && tools.length > 0) {
            tool = tools[0];
        }
    } else {
        IFolderInfo foInfo = (IFolderInfo) rcInfo;
        tool = foInfo.getToolFromInputExtension(inputExtension);
    }
    ToolInfoHolder h = getToolInfo(rcInfo.getPath());
    if (tool != null)
        outputExtension = tool.getOutputExtension(inputExtension);
    if (outputExtension == null)
        outputExtension = EMPTY_STRING;
    // Get the dependency generator information for this tool and file
    // extension
    IManagedDependencyGenerator oldDepGen = null;
    IManagedDependencyGenerator2 depGen = null;
    IManagedDependencyInfo depInfo = null;
    IManagedDependencyCommands depCommands = null;
    IManagedDependencyPreBuild depPreBuild = null;
    IPath[] depFiles = null;
    boolean doDepGen = false;
    {
        IManagedDependencyGeneratorType t = null;
        if (tool != null)
            t = tool.getDependencyGeneratorForExtension(inputExtension);
        if (t != null) {
            int calcType = t.getCalculatorType();
            if (calcType <= IManagedDependencyGeneratorType.TYPE_OLD_TYPE_LIMIT) {
                oldDepGen = (IManagedDependencyGenerator) t;
                doDepGen = (calcType == IManagedDependencyGeneratorType.TYPE_COMMAND);
                if (doDepGen) {
                    IPath depFile = Path.fromOSString(relativePath + fileName + DOT + DEP_EXT);
                    getDependencyMakefiles(h).add(depFile);
                    generatedDepFiles.add(depFile);
                }
            } else {
                depGen = (IManagedDependencyGenerator2) t;
                doDepGen = (calcType == IManagedDependencyGeneratorType.TYPE_BUILD_COMMANDS);
                IBuildObject buildContext = rcInfo;
                depInfo = depGen.getDependencySourceInfo(resource.getProjectRelativePath(), resource, buildContext, tool, getBuildWorkingDir());
                if (calcType == IManagedDependencyGeneratorType.TYPE_BUILD_COMMANDS) {
                    depCommands = (IManagedDependencyCommands) depInfo;
                    depFiles = depCommands.getDependencyFiles();
                } else if (calcType == IManagedDependencyGeneratorType.TYPE_PREBUILD_COMMANDS) {
                    depPreBuild = (IManagedDependencyPreBuild) depInfo;
                    depFiles = depPreBuild.getDependencyFiles();
                }
                if (depFiles != null) {
                    for (IPath depFile : depFiles) {
                        getDependencyMakefiles(h).add(depFile);
                        generatedDepFiles.add(depFile);
                    }
                }
            }
        }
    }
    // Figure out the output paths
    String optDotExt = EMPTY_STRING;
    if (outputExtension.length() > 0)
        optDotExt = DOT + outputExtension;
    List<IPath> ruleOutputs = new ArrayList<>();
    List<IPath> enumeratedPrimaryOutputs = new ArrayList<>();
    List<IPath> enumeratedSecondaryOutputs = new ArrayList<>();
    // JABA
    this.usedOutType = tool.getPrimaryOutputType();
    calculateOutputsForSource(tool, relativePath, resource, sourceLocation, ruleOutputs, enumeratedPrimaryOutputs, enumeratedSecondaryOutputs);
    enumeratedOutputs.addAll(enumeratedPrimaryOutputs);
    enumeratedOutputs.addAll(enumeratedSecondaryOutputs);
    String primaryOutputName = null;
    if (enumeratedPrimaryOutputs.size() > 0) {
        primaryOutputName = escapeWhitespaces(enumeratedPrimaryOutputs.get(0).toOSString());
    } else {
        primaryOutputName = escapeWhitespaces(relativePath + fileName + optDotExt);
    }
    String otherPrimaryOutputs = EMPTY_STRING;
    for (int i = 1; i < enumeratedPrimaryOutputs.size(); i++) {
        otherPrimaryOutputs += WHITESPACE + escapeWhitespaces(enumeratedPrimaryOutputs.get(i).toOSString());
    }
    // Output file location needed for the file-specific build macros
    IPath outputLocation = Path.fromOSString(primaryOutputName);
    if (!outputLocation.isAbsolute()) {
        outputLocation = getPathForResource(this.project).append(getBuildWorkingDir()).append(primaryOutputName);
    }
    // A separate rule is needed for the resource in the case where explicit
    // file-specific macros
    // are referenced, or if the resource contains special characters in its
    // path (e.g., whitespace)
    /*
		 * fix for 137674 We only need an explicit rule if one of the following
		 * is true: - The resource is linked, and its full path to its real
		 * location contains special characters - The resource is not linked,
		 * but its project relative path contains special characters
		 */
    boolean resourceNameRequiresExplicitRule = (resource.isLinked() && containsSpecialCharacters(sourceLocation.toOSString())) || (!resource.isLinked() && containsSpecialCharacters(resource.getProjectRelativePath().toOSString()));
    boolean needExplicitRuleForFile = resourceNameRequiresExplicitRule || BuildMacroProvider.getReferencedExplitFileMacros(tool).length > 0 || BuildMacroProvider.getReferencedExplitFileMacros(tool.getToolCommand(), IBuildMacroProvider.CONTEXT_FILE, new FileContextData(sourceLocation, outputLocation, null, tool)).length > 0;
    // Get and resolve the command
    String cmd = tool.getToolCommand();
    try {
        String resolvedCommand = null;
        if (!needExplicitRuleForFile) {
            resolvedCommand = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(cmd, EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE, new FileContextData(sourceLocation, outputLocation, null, tool));
        } else {
            // if we need an explicit rule then don't use any builder
            // variables, resolve everything
            // to explicit strings
            resolvedCommand = ManagedBuildManager.getBuildMacroProvider().resolveValue(cmd, EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE, new FileContextData(sourceLocation, outputLocation, null, tool));
        }
        if ((resolvedCommand = resolvedCommand.trim()).length() > 0)
            cmd = resolvedCommand;
    } catch (BuildMacroException e) {
    /* JABA is not going to write this code */
    }
    String defaultOutputName = EMPTY_STRING;
    String primaryDependencyName = EMPTY_STRING;
    String patternPrimaryDependencyName = EMPTY_STRING;
    String home = (generatedSource) ? DOT : ROOT;
    String resourcePath = null;
    boolean patternRule = true;
    boolean isItLinked = false;
    if (resource.isLinked(IResource.CHECK_ANCESTORS)) {
        // it IS linked, so use the actual location
        isItLinked = true;
        resourcePath = sourceLocation.toOSString();
        // Need a hardcoded rule, not a pattern rule, as a linked file
        // can reside in any path
        defaultOutputName = escapeWhitespaces(relativePath + fileName + optDotExt);
        primaryDependencyName = escapeWhitespaces(resourcePath);
        patternRule = false;
    } else {
        // Use the relative path (not really needed to store per se but in
        // the future someone may want this)
        resourcePath = relativePath;
        // The rule and command to add to the makefile
        if (rcInfo instanceof IFileInfo || needExplicitRuleForFile) {
            // Need a hardcoded rule, not a pattern rule
            defaultOutputName = escapeWhitespaces(resourcePath + fileName + optDotExt);
            patternRule = false;
        } else {
            defaultOutputName = relativePath + WILDCARD + optDotExt;
        }
        primaryDependencyName = escapeWhitespaces(home + FILE_SEPARATOR + resourcePath + fileName + DOT + inputExtension);
        patternPrimaryDependencyName = home + FILE_SEPARATOR + resourcePath + WILDCARD + DOT + inputExtension;
    }
    // end fix for PR 70491
    // If the tool specifies a dependency calculator of
    // TYPE_BUILD_COMMANDS,
    // ask whether
    // the dependency commands are "generic" (i.e., we can use a pattern
    // rule)
    boolean needExplicitDependencyCommands = false;
    if (depCommands != null) {
        needExplicitDependencyCommands = !depCommands.areCommandsGeneric();
    }
    // things
    if (patternRule) {
        patternRule = false;
        // Make sure that at least one of the rule outputs contains a %.
        for (int i = 0; i < ruleOutputs.size(); i++) {
            String ruleOutput = ruleOutputs.get(i).toOSString();
            if (ruleOutput.indexOf('%') >= 0) {
                patternRule = true;
                break;
            }
        }
        if (patternRule) {
            patternRule = !needExplicitDependencyCommands;
        }
    }
    // Begin building the rule for this source file
    String buildRule = EMPTY_STRING;
    if (patternRule) {
        if (ruleOutputs.size() == 0) {
            buildRule += defaultOutputName;
        } else {
            boolean first = true;
            for (int i = 0; i < ruleOutputs.size(); i++) {
                String ruleOutput = ruleOutputs.get(i).toOSString();
                if (ruleOutput.indexOf('%') >= 0) {
                    if (first) {
                        first = false;
                    } else {
                        buildRule += WHITESPACE;
                    }
                    buildRule += ruleOutput;
                }
            }
        }
    } else {
        buildRule += primaryOutputName;
    }
    String buildRuleDependencies = primaryDependencyName;
    String patternBuildRuleDependencies = patternPrimaryDependencyName;
    // Other additional inputs
    // Get any additional dependencies specified for the tool in other
    // InputType elements and AdditionalInput elements
    IPath[] addlDepPaths = tool.getAdditionalDependencies();
    for (IPath addlDepPath : addlDepPaths) {
        // Translate the path from project relative to build directory
        // relative
        IPath addlPath = addlDepPath;
        if (!(addlPath.toString().startsWith("$("))) {
            if (!addlPath.isAbsolute()) {
                IPath tempPath = this.project.getLocation().append(new Path(ensureUnquoted(addlPath.toString())));
                if (tempPath != null) {
                    addlPath = ManagedBuildManager.calculateRelativePath(getTopBuildDir(), tempPath);
                }
            }
        }
        String suitablePath = ensurePathIsGNUMakeTargetRuleCompatibleSyntax(addlPath.toOSString());
        buildRuleDependencies += WHITESPACE + suitablePath;
        patternBuildRuleDependencies += WHITESPACE + suitablePath;
    }
    buildRule += COLON + WHITESPACE + (patternRule ? patternBuildRuleDependencies : buildRuleDependencies);
    // it or the commands to build the file
    if (getRuleList().contains(buildRule)) {
    // TODO: Should we assert that this is a pattern rule?
    } else {
        getRuleList().add(buildRule);
        // Echo starting message
        buffer.append(buildRule + NEWLINE);
        buffer.append(TAB + AT + escapedEcho(MESSAGE_START_FILE + WHITESPACE + IN_MACRO));
        buffer.append(TAB + AT + escapedEcho(tool.getAnnouncement()));
        // there are any pre-tool commands.
        if (depCommands != null) {
            String[] preToolCommands = depCommands.getPreToolDependencyCommands();
            if (preToolCommands != null && preToolCommands.length > 0) {
                for (String preCmd : preToolCommands) {
                    try {
                        String resolvedCommand;
                        IBuildMacroProvider provider = ManagedBuildManager.getBuildMacroProvider();
                        if (!needExplicitRuleForFile) {
                            resolvedCommand = provider.resolveValueToMakefileFormat(preCmd, EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE, new FileContextData(sourceLocation, outputLocation, null, tool));
                        } else {
                            // if we need an explicit rule then don't use
                            // any builder
                            // variables, resolve everything to explicit
                            // strings
                            resolvedCommand = provider.resolveValue(preCmd, EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE, new FileContextData(sourceLocation, outputLocation, null, tool));
                        }
                        if (resolvedCommand != null)
                            buffer.append(resolvedCommand).append(NEWLINE);
                    } catch (BuildMacroException e) {
                    /* JABA is not going to write this code */
                    }
                }
            }
        }
        // Generate the command line
        Vector<String> inputs = new Vector<>();
        inputs.add(IN_MACRO);
        // Other additional inputs
        // Get any additional dependencies specified for the tool in other
        // InputType elements and AdditionalInput elements
        IPath[] addlInputPaths = getAdditionalResourcesForSource(tool);
        for (IPath addlInputPath : addlInputPaths) {
            // Translate the path from project relative to build directory
            // relative
            IPath addlPath = addlInputPath;
            if (!(addlPath.toString().startsWith("$("))) {
                if (!addlPath.isAbsolute()) {
                    IPath tempPath = getPathForResource(this.project).append(addlPath);
                    if (tempPath != null) {
                        addlPath = ManagedBuildManager.calculateRelativePath(getTopBuildDir(), tempPath);
                    }
                }
            }
            inputs.add(addlPath.toOSString());
        }
        String[] inputStrings = inputs.toArray(new String[inputs.size()]);
        String[] flags = null;
        // Get the tool command line options
        try {
            flags = tool.getToolCommandFlags(sourceLocation, outputLocation);
        } catch (BuildException ex) {
            // TODO add some routines to catch this
            flags = EMPTY_STRING_ARRAY;
        }
        // it wants added to the command line
        if (depCommands != null) {
            flags = addDependencyOptions(depCommands, flags);
        }
        IManagedCommandLineInfo cmdLInfo = null;
        String outflag = null;
        String outputPrefix = null;
        if (rcInfo instanceof IFileInfo || needExplicitRuleForFile || needExplicitDependencyCommands) {
            outflag = tool.getOutputFlag();
            outputPrefix = tool.getOutputPrefix();
            // Call the command line generator
            IManagedCommandLineGenerator cmdLGen = tool.getCommandLineGenerator();
            cmdLInfo = cmdLGen.generateCommandLineInfo(tool, cmd, flags, outflag, outputPrefix, OUT_MACRO + otherPrimaryOutputs, inputStrings, tool.getCommandLinePattern());
        } else {
            // config.getOutputFlag(outputExtension);
            outflag = tool.getOutputFlag();
            // config.getOutputPrefix(outputExtension);
            outputPrefix = tool.getOutputPrefix();
            // Call the command line generator
            cmdLInfo = generateToolCommandLineInfo(tool, inputExtension, flags, outflag, outputPrefix, OUT_MACRO + otherPrimaryOutputs, inputStrings, sourceLocation, outputLocation);
        }
        // The command to build
        String buildCmd;
        if (cmdLInfo != null) {
            buildCmd = cmdLInfo.getCommandLine();
        } else {
            StringBuffer buildFlags = new StringBuffer();
            for (String flag : flags) {
                if (flag != null) {
                    buildFlags.append(flag).append(WHITESPACE);
                }
            }
            buildCmd = cmd + WHITESPACE + buildFlags.toString().trim() + WHITESPACE + outflag + WHITESPACE + outputPrefix + OUT_MACRO + otherPrimaryOutputs + WHITESPACE + IN_MACRO;
        }
        // generated
        try {
            String resolvedCommand;
            IBuildMacroProvider provider = ManagedBuildManager.getBuildMacroProvider();
            if (!needExplicitRuleForFile) {
                resolvedCommand = provider.resolveValueToMakefileFormat(buildCmd, EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE, new FileContextData(sourceLocation, outputLocation, null, tool));
            } else {
                // if we need an explicit rule then don't use any builder
                // variables, resolve everything to explicit strings
                resolvedCommand = provider.resolveValue(buildCmd, EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE, new FileContextData(sourceLocation, outputLocation, null, tool));
            }
            if ((resolvedCommand = resolvedCommand.trim()).length() > 0)
                buildCmd = resolvedCommand;
        } catch (BuildMacroException e) {
        /* JABA is not going to write this code */
        }
        // buffer.append(TAB).append(AT).append(escapedEcho(buildCmd));
        // buffer.append(TAB).append(AT).append(buildCmd);
        buffer.append(TAB).append(buildCmd);
        // Determine if there are any dependencies to calculate
        if (doDepGen) {
            // Get the dependency rule out of the generator
            String[] depCmds = null;
            if (oldDepGen != null) {
                depCmds = new String[1];
                depCmds[0] = oldDepGen.getDependencyCommand(resource, ManagedBuildManager.getBuildInfo(this.project));
            } else {
                if (depCommands != null) {
                    depCmds = depCommands.getPostToolDependencyCommands();
                }
            }
            if (depCmds != null) {
                for (String depCmd : depCmds) {
                    // Resolve any macros in the dep command after it has
                    // been generated.
                    // Note: do not trim the result because it will strip
                    // out necessary tab characters.
                    buffer.append(WHITESPACE).append(LOGICAL_AND).append(WHITESPACE).append(LINEBREAK);
                    try {
                        if (!needExplicitRuleForFile) {
                            depCmd = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(depCmd, EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE, new FileContextData(sourceLocation, outputLocation, null, tool));
                        } else {
                            depCmd = ManagedBuildManager.getBuildMacroProvider().resolveValue(depCmd, EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE, new FileContextData(sourceLocation, outputLocation, null, tool));
                        }
                    } catch (BuildMacroException e) {
                    /* JABA is not going to do this */
                    }
                    buffer.append(depCmd);
                }
            }
        }
        // Echo finished message
        buffer.append(NEWLINE);
        buffer.append(TAB + AT + escapedEcho(MESSAGE_FINISH_FILE + WHITESPACE + IN_MACRO));
        buffer.append(TAB + AT + ECHO_BLANK_LINE + NEWLINE);
    }
    // Determine if there are calculated dependencies
    IPath[] addlDeps = null;
    IPath[] addlTargets = null;
    String calculatedDependencies = null;
    boolean addedDepLines = false;
    String depLine;
    if (oldDepGen != null && oldDepGen.getCalculatorType() != IManagedDependencyGeneratorType.TYPE_COMMAND) {
        addlDeps = oldCalculateDependenciesForSource(oldDepGen, tool, relativePath, resource);
    } else {
        if (depGen != null && depGen.getCalculatorType() == IManagedDependencyGeneratorType.TYPE_CUSTOM) {
            if (depInfo instanceof IManagedDependencyCalculator) {
                IManagedDependencyCalculator depCalculator = (IManagedDependencyCalculator) depInfo;
                addlDeps = calculateDependenciesForSource(depCalculator);
                addlTargets = depCalculator.getAdditionalTargets();
            }
        }
    }
    if (addlDeps != null && addlDeps.length > 0) {
        calculatedDependencies = new String();
        for (IPath addlDep : addlDeps) {
            calculatedDependencies += WHITESPACE + escapeWhitespaces(addlDep.toOSString());
        }
    }
    if (calculatedDependencies != null) {
        depLine = primaryOutputName + COLON + calculatedDependencies + NEWLINE;
        if (!getDepLineList().contains(depLine)) {
            getDepLineList().add(depLine);
            addedDepLines = true;
            buffer.append(depLine);
        }
    }
    // Add any additional outputs here using dependency lines
    Vector<IPath> addlOutputs = new Vector<>();
    if (enumeratedPrimaryOutputs.size() > 1) {
        // output
        for (int i = 1; i < enumeratedPrimaryOutputs.size(); i++) addlOutputs.add(enumeratedPrimaryOutputs.get(i));
    }
    addlOutputs.addAll(enumeratedSecondaryOutputs);
    if (addlTargets != null) {
        for (IPath addlTarget : addlTargets) addlOutputs.add(addlTarget);
    }
    for (int i = 0; i < addlOutputs.size(); i++) {
        depLine = escapeWhitespaces(addlOutputs.get(i).toOSString()) + COLON + WHITESPACE + primaryOutputName;
        if (calculatedDependencies != null)
            depLine += calculatedDependencies;
        depLine += NEWLINE;
        if (!getDepLineList().contains(depLine)) {
            getDepLineList().add(depLine);
            addedDepLines = true;
            buffer.append(depLine);
        }
    }
    if (addedDepLines) {
        buffer.append(NEWLINE);
    }
    // get the rule to build the dependency file
    if (depPreBuild != null && depFiles != null) {
        addedDepLines = false;
        String[] preBuildCommands = depPreBuild.getDependencyCommands();
        if (preBuildCommands != null) {
            depLine = "";
            // Can we use a pattern rule?
            patternRule = !isItLinked && !needExplicitRuleForFile && depPreBuild.areCommandsGeneric();
            // Begin building the rule
            for (int i = 0; i < depFiles.length; i++) {
                if (i > 0)
                    depLine += WHITESPACE;
                if (patternRule) {
                    optDotExt = EMPTY_STRING;
                    String depExt = depFiles[i].getFileExtension();
                    if (depExt != null && depExt.length() > 0)
                        optDotExt = DOT + depExt;
                    depLine += escapeWhitespaces(relativePath + WILDCARD + optDotExt);
                } else {
                    depLine += escapeWhitespaces((depFiles[i]).toOSString());
                }
            }
            depLine += COLON + WHITESPACE + (patternRule ? patternBuildRuleDependencies : buildRuleDependencies);
            if (!getDepRuleList().contains(depLine)) {
                getDepRuleList().add(depLine);
                addedDepLines = true;
                buffer.append(depLine + NEWLINE);
                buffer.append(TAB + AT + escapedEcho(MESSAGE_START_DEPENDENCY + WHITESPACE + OUT_MACRO));
                for (String preBuildCommand : preBuildCommands) {
                    depLine = preBuildCommand;
                    // Resolve macros
                    try {
                        if (!needExplicitRuleForFile) {
                            depLine = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(depLine, EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE, new FileContextData(sourceLocation, outputLocation, null, tool));
                        } else {
                            depLine = ManagedBuildManager.getBuildMacroProvider().resolveValue(depLine, EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE, new FileContextData(sourceLocation, outputLocation, null, tool));
                        }
                    } catch (BuildMacroException e) {
                    // JABA is not going to write this code
                    }
                    // buffer.append(TAB + AT + escapedEcho(depLine));
                    // buffer.append(TAB + AT + depLine + NEWLINE);
                    buffer.append(TAB + depLine + NEWLINE);
                }
            }
            if (addedDepLines) {
                buffer.append(TAB + AT + ECHO_BLANK_LINE + NEWLINE);
            }
        }
    }
}
Also used : IManagedDependencyCalculator(org.eclipse.cdt.managedbuilder.makegen.IManagedDependencyCalculator) ArrayList(java.util.ArrayList) IFolderInfo(org.eclipse.cdt.managedbuilder.core.IFolderInfo) IManagedDependencyGeneratorType(org.eclipse.cdt.managedbuilder.makegen.IManagedDependencyGeneratorType) IBuildObject(org.eclipse.cdt.managedbuilder.core.IBuildObject) BuildMacroException(org.eclipse.cdt.managedbuilder.macros.BuildMacroException) IManagedDependencyGenerator2(org.eclipse.cdt.managedbuilder.makegen.IManagedDependencyGenerator2) IManagedDependencyCommands(org.eclipse.cdt.managedbuilder.makegen.IManagedDependencyCommands) IBuildMacroProvider(org.eclipse.cdt.managedbuilder.macros.IBuildMacroProvider) Vector(java.util.Vector) IPath(org.eclipse.core.runtime.IPath) Path(org.eclipse.core.runtime.Path) IManagedDependencyGenerator(org.eclipse.cdt.managedbuilder.makegen.IManagedDependencyGenerator) IPath(org.eclipse.core.runtime.IPath) IManagedCommandLineGenerator(org.eclipse.cdt.managedbuilder.core.IManagedCommandLineGenerator) FileContextData(org.eclipse.cdt.managedbuilder.internal.macros.FileContextData) IManagedDependencyInfo(org.eclipse.cdt.managedbuilder.makegen.IManagedDependencyInfo) ITool(org.eclipse.cdt.managedbuilder.core.ITool) IFileInfo(org.eclipse.cdt.managedbuilder.core.IFileInfo) IManagedCommandLineInfo(org.eclipse.cdt.managedbuilder.core.IManagedCommandLineInfo) IManagedDependencyPreBuild(org.eclipse.cdt.managedbuilder.makegen.IManagedDependencyPreBuild) BuildException(org.eclipse.cdt.managedbuilder.core.BuildException)

Example 3 with BuildException

use of org.eclipse.cdt.managedbuilder.core.BuildException in project arduino-eclipse-plugin by Sloeber.

the class ArduinoGnuMakefileGenerator method addRuleForTool.

/**
 * Create the rule
 *
 * @param buffer
 *            Buffer to add makefile rules to
 * @param bTargetTool
 *            True if this is the target tool
 * @param targetName
 *            If this is the "targetTool", the target file name, else
 *            <code>null</code>
 * @param targetExt
 *            If this is the "targetTool", the target file extension, else
 *            <code>null</code>
 * @param outputVarsAdditionsList
 *            list to add needed build output variables to
 * @param managedProjectOutputs
 *            Other projects in the workspace that this project depends upon
 * @param bEmitPostBuildStepCall
 *            Emit post-build step invocation
 */
protected boolean addRuleForTool(ITool tool, StringBuffer buffer, boolean bTargetTool, String targetName, String targetExt, List<String> outputVarsAdditionsList, List<String> managedProjectOutputs, boolean bEmitPostBuildStepCall) {
    // Get the tool's inputs and outputs
    List<String> inputs = new ArrayList<>();
    List<String> dependencies = new ArrayList<>();
    List<String> outputs = new ArrayList<>();
    List<String> enumeratedPrimaryOutputs = new ArrayList<>();
    List<String> enumeratedSecondaryOutputs = new ArrayList<>();
    List<String> outputVariables = new ArrayList<>();
    List<String> additionalTargets = new ArrayList<>();
    String outputPrefix = EMPTY_STRING;
    if (!getToolInputsOutputs(tool, inputs, dependencies, outputs, enumeratedPrimaryOutputs, enumeratedSecondaryOutputs, outputVariables, additionalTargets, bTargetTool, managedProjectOutputs)) {
        return false;
    }
    // primary output
    if (enumeratedPrimaryOutputs.size() == 0) {
        enumeratedPrimaryOutputs = enumeratedSecondaryOutputs;
        enumeratedSecondaryOutputs.clear();
    }
    // Add the output variables for this tool to our list
    outputVarsAdditionsList.addAll(outputVariables);
    // Create the build rule
    String buildRule = EMPTY_STRING;
    String outflag = tool.getOutputFlag();
    String primaryOutputs = EMPTY_STRING;
    String primaryOutputsQuoted = EMPTY_STRING;
    boolean first = true;
    for (int i = 0; i < enumeratedPrimaryOutputs.size(); i++) {
        String output = enumeratedPrimaryOutputs.get(i);
        if (!first) {
            primaryOutputs += WHITESPACE;
            primaryOutputsQuoted += WHITESPACE;
        }
        first = false;
        primaryOutputs += new Path(output).toOSString();
        primaryOutputsQuoted += ensurePathIsGNUMakeTargetRuleCompatibleSyntax(new Path(output).toOSString());
    }
    buildRule += (primaryOutputsQuoted + COLON + WHITESPACE);
    first = true;
    String calculatedDependencies = EMPTY_STRING;
    for (int i = 0; i < dependencies.size(); i++) {
        String input = dependencies.get(i);
        if (!first)
            calculatedDependencies += WHITESPACE;
        first = false;
        calculatedDependencies += input;
    }
    buildRule += calculatedDependencies;
    // We can't have duplicates in a makefile
    if (getRuleList().contains(buildRule)) {
    /* JABA is not going to write this code */
    } else {
        getRuleList().add(buildRule);
        buffer.append(buildRule + NEWLINE);
        if (bTargetTool) {
            buffer.append(TAB + AT + escapedEcho(MESSAGE_START_BUILD + WHITESPACE + OUT_MACRO));
        }
        buffer.append(TAB + AT + escapedEcho(tool.getAnnouncement()));
        // Get the command line for this tool invocation
        String[] flags;
        try {
            flags = tool.getToolCommandFlags(null, null);
        } catch (BuildException ex) {
            // TODO report error
            flags = EMPTY_STRING_ARRAY;
        }
        String command = tool.getToolCommand();
        try {
            // try to resolve the build macros in the tool command
            String resolvedCommand = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(command, EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE, new FileContextData(null, null, null, tool));
            if ((resolvedCommand = resolvedCommand.trim()).length() > 0)
                command = resolvedCommand;
        } catch (BuildMacroException e) {
        /* JABA is not going to write this code */
        }
        String[] cmdInputs = inputs.toArray(new String[inputs.size()]);
        IManagedCommandLineGenerator gen = tool.getCommandLineGenerator();
        IManagedCommandLineInfo cmdLInfo = gen.generateCommandLineInfo(tool, command, flags, outflag, outputPrefix, primaryOutputs, cmdInputs, tool.getCommandLinePattern());
        // The command to build
        String buildCmd = null;
        if (cmdLInfo == null) {
            String toolFlags;
            try {
                toolFlags = tool.getToolCommandFlagsString(null, null);
            } catch (BuildException ex) {
                // TODO report error
                toolFlags = EMPTY_STRING;
            }
            buildCmd = command + WHITESPACE + toolFlags + WHITESPACE + outflag + WHITESPACE + outputPrefix + primaryOutputs + WHITESPACE + IN_MACRO;
        } else
            buildCmd = cmdLInfo.getCommandLine();
        // generated
        try {
            String resolvedCommand = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(buildCmd, EMPTY_STRING, WHITESPACE, IBuildMacroProvider.CONTEXT_FILE, new FileContextData(null, null, null, tool));
            if ((resolvedCommand = resolvedCommand.trim()).length() > 0)
                buildCmd = resolvedCommand;
        } catch (BuildMacroException e) {
        /* JABA is not going to write this code */
        }
        // buffer.append(TAB).append(AT).append(escapedEcho(buildCmd));
        // buffer.append(TAB).append(AT).append(buildCmd);
        buffer.append(TAB).append(buildCmd);
        // TODO
        // NOTE WELL: Dependency file generation is not handled for this
        // type of Tool
        // Echo finished message
        buffer.append(NEWLINE);
        buffer.append(TAB + AT + escapedEcho((bTargetTool ? MESSAGE_FINISH_BUILD : MESSAGE_FINISH_FILE) + WHITESPACE + OUT_MACRO));
        buffer.append(TAB + AT + ECHO_BLANK_LINE);
        // the makefile originally
        if (bEmitPostBuildStepCall) {
            buffer.append(TAB + MAKE + WHITESPACE + NO_PRINT_DIR + WHITESPACE + POSTBUILD + NEWLINE + NEWLINE);
        } else {
            // Just emit a blank line
            buffer.append(NEWLINE);
        }
    }
    // commands
    if (enumeratedSecondaryOutputs.size() > 0 || additionalTargets.size() > 0) {
        String primaryOutput = enumeratedPrimaryOutputs.get(0);
        List<String> addlOutputs = new ArrayList<>();
        addlOutputs.addAll(enumeratedSecondaryOutputs);
        addlOutputs.addAll(additionalTargets);
        for (int i = 0; i < addlOutputs.size(); i++) {
            String output = addlOutputs.get(i);
            String depLine = output + COLON + WHITESPACE + primaryOutput + WHITESPACE + calculatedDependencies + NEWLINE;
            if (!getDepLineList().contains(depLine)) {
                getDepLineList().add(depLine);
                buffer.append(depLine);
            }
        }
        buffer.append(NEWLINE);
    }
    return true;
}
Also used : IPath(org.eclipse.core.runtime.IPath) Path(org.eclipse.core.runtime.Path) IManagedCommandLineGenerator(org.eclipse.cdt.managedbuilder.core.IManagedCommandLineGenerator) BuildMacroException(org.eclipse.cdt.managedbuilder.macros.BuildMacroException) IManagedCommandLineInfo(org.eclipse.cdt.managedbuilder.core.IManagedCommandLineInfo) ArrayList(java.util.ArrayList) FileContextData(org.eclipse.cdt.managedbuilder.internal.macros.FileContextData) BuildException(org.eclipse.cdt.managedbuilder.core.BuildException)

Example 4 with BuildException

use of org.eclipse.cdt.managedbuilder.core.BuildException in project arduino-eclipse-plugin by Sloeber.

the class ArduinoManagedBuildGnuToolInfo method calculateOutputs.

/*
	 * The priorities for determining the names of the outputs of a tool are: 1.
	 * If the tool is the build target and primary output, use artifact name &
	 * extension 2. If an option is specified, use the value of the option 3. If
	 * a nameProvider is specified, call it 4. If outputNames is specified, use
	 * it 5. Use the name pattern to generate a transformation macro so that the
	 * source names can be transformed into the target names using the built-in
	 * string substitution functions of <code>make</code>.
	 *
	 * NOTE: If an option is not specified and this is not the primary output
	 * type, the outputs from the type are not added to the command line
	 */
public boolean calculateOutputs(ArduinoGnuMakefileGenerator makeGen, IConfiguration config, HashSet<String> handledInputExtensions, boolean lastChance) {
    boolean done = true;
    Vector<String> myCommandOutputs = new Vector<>();
    Vector<String> myEnumeratedPrimaryOutputs = new Vector<>();
    Vector<String> myEnumeratedSecondaryOutputs = new Vector<>();
    HashMap<String, List<IPath>> myOutputMacros = new HashMap<>();
    // The next two fields are used together
    Vector<String> myBuildVars = new Vector<>();
    Vector<Vector<String>> myBuildVarsValues = new Vector<>();
    // Get the outputs for this tool invocation
    IOutputType[] outTypes = this.tool.getOutputTypes();
    if (outTypes != null && outTypes.length > 0) {
        for (int i = 0; i < outTypes.length; i++) {
            Vector<String> typeEnumeratedOutputs = new Vector<>();
            IOutputType type = outTypes[i];
            String outputPrefix = type.getOutputPrefix();
            if (config != null) {
                try {
                    outputPrefix = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(// $NON-NLS-1$
                    outputPrefix, // $NON-NLS-1$
                    "", // $NON-NLS-1$
                    " ", IBuildMacroProvider.CONTEXT_CONFIGURATION, config);
                } catch (BuildMacroException e) {
                // JABA is not going to add
                // code
                }
            }
            String variable = type.getBuildVariable();
            boolean multOfType = type.getMultipleOfType();
            boolean primaryOutput = (type == this.tool.getPrimaryOutputType());
            IOption option = this.tool.getOptionBySuperClassId(type.getOptionId());
            IManagedOutputNameProvider nameProvider = type.getNameProvider();
            String[] outputNames = type.getOutputNames();
            // use artifact name & extension
            if (this.bIsTargetTool && primaryOutput) {
                String outputName = outputPrefix + this.targetName;
                if (this.targetExt.length() > 0) {
                    outputName += (DOT + this.targetExt);
                }
                myCommandOutputs.add(outputName);
                typeEnumeratedOutputs.add(outputName);
            // But this doesn't use any output macro...
            } else // 2. If an option is specified, use the value of the option
            if (option != null) {
                try {
                    List<String> outputs = new ArrayList<>();
                    int optType = option.getValueType();
                    if (optType == IOption.STRING) {
                        outputs.add(outputPrefix + option.getStringValue());
                    } else if (optType == IOption.STRING_LIST || optType == IOption.LIBRARIES || optType == IOption.OBJECTS || optType == IOption.INCLUDE_FILES || optType == IOption.LIBRARY_PATHS || optType == IOption.LIBRARY_FILES || optType == IOption.MACRO_FILES) {
                        @SuppressWarnings("unchecked") List<String> value = (List<String>) option.getValue();
                        outputs = value;
                        this.tool.filterValues(optType, outputs);
                        // Add outputPrefix to each if necessary
                        if (outputPrefix.length() > 0) {
                            for (int j = 0; j < outputs.size(); j++) {
                                outputs.set(j, outputPrefix + outputs.get(j));
                            }
                        }
                    }
                    for (int j = 0; j < outputs.size(); j++) {
                        String outputName = outputs.get(j);
                        try {
                            // try to resolve the build macros in the output
                            // names
                            String resolved = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(// $NON-NLS-1$
                            outputName, // $NON-NLS-1$
                            "", // $NON-NLS-1$
                            " ", IBuildMacroProvider.CONTEXT_OPTION, new OptionContextData(option, this.tool));
                            if ((resolved = resolved.trim()).length() > 0)
                                outputs.set(j, resolved);
                        } catch (BuildMacroException e) {
                        // JABA is not
                        // going to add
                        // code
                        }
                    }
                    // NO - myCommandOutputs.addAll(outputs);
                    typeEnumeratedOutputs.addAll(outputs);
                    if (variable.length() > 0) {
                        List<IPath> outputPaths = new ArrayList<>();
                        for (int j = 0; j < outputs.size(); j++) {
                            outputPaths.add(Path.fromOSString(outputs.get(j)));
                        }
                        if (myOutputMacros.containsKey(variable)) {
                            List<IPath> currList = myOutputMacros.get(variable);
                            currList.addAll(outputPaths);
                            myOutputMacros.put(variable, currList);
                        } else {
                            myOutputMacros.put(variable, outputPaths);
                        }
                    }
                } catch (BuildException ex) {
                // JABA is not going to add
                // code
                }
            } else // 3. If a nameProvider is specified, call it
            if (nameProvider != null) {
                // The inputs must have been calculated before we can do
                // this
                IPath[] outNames = null;
                if (!this.inputsCalculated) {
                    done = false;
                } else {
                    Vector<String> inputs = getEnumeratedInputs();
                    IPath[] inputPaths = new IPath[inputs.size()];
                    for (int j = 0; j < inputPaths.length; j++) {
                        inputPaths[j] = Path.fromOSString(inputs.get(j));
                    }
                    // if (inputPaths.length == 0) {
                    try {
                        IManagedOutputNameProviderJaba newNameProvider = (IManagedOutputNameProviderJaba) nameProvider;
                        outNames = newNameProvider.getOutputNames(this.project, config, this.tool, inputPaths);
                    } catch (Exception e) {
                        // The provided class is not a
                        // IManagedOutputNameProviderJaba class;
                        Common.log(new Status(IStatus.ERROR, Const.CORE_PLUGIN_ID, "The provided class is not of type IManagedOutputNameProviderJaba", // $NON-NLS-1$
                        e));
                    }
                    // JABA end of insertion
                    if (outNames != null) {
                        for (int j = 0; j < outNames.length; j++) {
                            String outputName = outNames[j].toOSString();
                            try {
                                // try to resolve the build macros in the
                                // output names
                                String resolved = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(// $NON-NLS-1$
                                outputName, // $NON-NLS-1$
                                "", // $NON-NLS-1$
                                " ", IBuildMacroProvider.CONTEXT_CONFIGURATION, config);
                                if ((resolved = resolved.trim()).length() > 0) {
                                    outputName = resolved;
                                    outNames[j] = Path.fromOSString(resolved);
                                }
                            } catch (BuildMacroException e) {
                            // JABA is not
                            // going to add
                            // code
                            }
                            if (primaryOutput) {
                                myCommandOutputs.add(outputName);
                            }
                            typeEnumeratedOutputs.add(outputName);
                        }
                    }
                }
                if (variable.length() > 0 && outNames != null) {
                    if (myOutputMacros.containsKey(variable)) {
                        List<IPath> currList = myOutputMacros.get(variable);
                        currList.addAll(Arrays.asList(outNames));
                        myOutputMacros.put(variable, currList);
                    } else {
                        myOutputMacros.put(variable, new ArrayList<>(Arrays.asList(outNames)));
                    }
                }
            } else // 4. If outputNames is specified, use it
            if (outputNames != null) {
                if (outputNames.length > 0) {
                    for (int j = 0; j < outputNames.length; j++) {
                        String outputName = outputNames[j];
                        try {
                            // try to resolve the build macros in the output
                            // names
                            String resolved = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(// $NON-NLS-1$
                            outputName, // $NON-NLS-1$
                            "", // $NON-NLS-1$
                            " ", IBuildMacroProvider.CONTEXT_OPTION, new OptionContextData(option, this.tool));
                            if ((resolved = resolved.trim()).length() > 0)
                                outputNames[j] = resolved;
                        } catch (BuildMacroException e) {
                        // JABA is not
                        // going to add
                        // code
                        }
                    }
                    List<String> namesList = Arrays.asList(outputNames);
                    if (primaryOutput) {
                        myCommandOutputs.addAll(namesList);
                    }
                    typeEnumeratedOutputs.addAll(namesList);
                    if (variable.length() > 0) {
                        List<IPath> outputPaths = new ArrayList<>();
                        for (int j = 0; j < namesList.size(); j++) {
                            outputPaths.add(Path.fromOSString(namesList.get(j)));
                        }
                        if (myOutputMacros.containsKey(variable)) {
                            List<IPath> currList = myOutputMacros.get(variable);
                            currList.addAll(outputPaths);
                            myOutputMacros.put(variable, currList);
                        } else {
                            myOutputMacros.put(variable, outputPaths);
                        }
                    }
                }
            } else {
                // <code>make</code>.
                if (multOfType) {
                    // This case is not handled - a nameProvider or
                    // outputNames must be specified
                    List<String> errList = new ArrayList<>();
                    // $NON-NLS-1$
                    errList.add(ManagedMakeMessages.getResourceString("MakefileGenerator.error.no.nameprovider"));
                    myCommandOutputs.addAll(errList);
                } else {
                    String namePattern = type.getNamePattern();
                    if (namePattern == null || namePattern.length() == 0) {
                        namePattern = outputPrefix + IManagedBuilderMakefileGenerator.WILDCARD;
                        String outExt = (type.getOutputExtensions(this.tool))[0];
                        if (outExt != null && outExt.length() > 0) {
                            namePattern += DOT + outExt;
                        }
                    } else if (outputPrefix.length() > 0) {
                        namePattern = outputPrefix + namePattern;
                    }
                    // this
                    if (!this.inputsCalculated) {
                        done = false;
                    } else {
                        Vector<String> inputs = getEnumeratedInputs();
                        String fileName;
                        if (inputs.size() > 0) {
                            // Get the input file name
                            fileName = (Path.fromOSString(inputs.get(0))).removeFileExtension().lastSegment();
                            // the raw macro name.
                            if (fileName.startsWith("$(") && fileName.endsWith(")")) {
                                // $NON-NLS-1$ //$NON-NLS-2$
                                fileName = fileName.substring(2, fileName.length() - 1);
                            }
                        } else {
                            // $NON-NLS-1$
                            fileName = "default";
                        }
                        // Replace the % with the file name
                        if (primaryOutput) {
                            // $NON-NLS-1$
                            myCommandOutputs.add(namePattern.replaceAll("%", fileName));
                        }
                        // $NON-NLS-1$
                        typeEnumeratedOutputs.add(namePattern.replaceAll("%", fileName));
                        if (variable.length() > 0) {
                            List<IPath> outputs = new ArrayList<>();
                            outputs.add(Path.fromOSString(fileName));
                            if (myOutputMacros.containsKey(variable)) {
                                List<IPath> currList = myOutputMacros.get(variable);
                                currList.addAll(outputs);
                                myOutputMacros.put(variable, currList);
                            } else {
                                myOutputMacros.put(variable, outputs);
                            }
                        }
                    }
                }
            }
            if (variable.length() > 0) {
                myBuildVars.add(variable);
                myBuildVarsValues.add(typeEnumeratedOutputs);
            }
            if (primaryOutput) {
                myEnumeratedPrimaryOutputs.addAll(typeEnumeratedOutputs);
            } else {
                myEnumeratedSecondaryOutputs.addAll(typeEnumeratedOutputs);
            }
        }
    } else {
        if (this.bIsTargetTool) {
            String outputPrefix = this.tool.getOutputPrefix();
            String outputName = outputPrefix + this.targetName;
            if (this.targetExt.length() > 0) {
                outputName += (DOT + this.targetExt);
            }
            myCommandOutputs.add(outputName);
            myEnumeratedPrimaryOutputs.add(outputName);
        } else {
        // For support of pre-CDT 3.0 integrations.
        // NOTE WELL: This only supports the case of a single
        // "target tool"
        // that consumes exactly all of the object files, $OBJS,
        // produced
        // by other tools in the build and produces a single output
        }
    }
    // Add the output macros of this tool to the buildOutVars map
    Set<Entry<String, List<IPath>>> entrySet = myOutputMacros.entrySet();
    for (Entry<String, List<IPath>> entry : entrySet) {
        String macroName = entry.getKey();
        List<IPath> newMacroValue = entry.getValue();
        Map<String, List<IPath>> map = makeGen.getBuildOutputVars();
        if (map.containsKey(macroName)) {
            List<IPath> macroValue = map.get(macroName);
            macroValue.addAll(newMacroValue);
            map.put(macroName, macroValue);
        } else {
            map.put(macroName, newMacroValue);
        }
    }
    this.outputVariablesCalculated = true;
    if (done) {
        this.commandOutputs.addAll(myCommandOutputs);
        this.enumeratedPrimaryOutputs.addAll(myEnumeratedPrimaryOutputs);
        this.enumeratedSecondaryOutputs.addAll(myEnumeratedSecondaryOutputs);
        this.outputVariables.addAll(myOutputMacros.keySet());
        this.outputsCalculated = true;
        for (int i = 0; i < myBuildVars.size(); i++) {
            makeGen.addMacroAdditionFiles(makeGen.getTopBuildOutputVars(), myBuildVars.get(i), myBuildVarsValues.get(i));
        }
        return true;
    }
    return false;
}
Also used : HashMap(java.util.HashMap) IOption(org.eclipse.cdt.managedbuilder.core.IOption) Entry(java.util.Map.Entry) BuildMacroException(org.eclipse.cdt.managedbuilder.macros.BuildMacroException) ArrayList(java.util.ArrayList) List(java.util.List) Vector(java.util.Vector) IOutputType(org.eclipse.cdt.managedbuilder.core.IOutputType) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) OptionContextData(org.eclipse.cdt.managedbuilder.internal.macros.OptionContextData) IPath(org.eclipse.core.runtime.IPath) BuildException(org.eclipse.cdt.managedbuilder.core.BuildException) BuildMacroException(org.eclipse.cdt.managedbuilder.macros.BuildMacroException) IManagedOutputNameProvider(org.eclipse.cdt.managedbuilder.core.IManagedOutputNameProvider) BuildException(org.eclipse.cdt.managedbuilder.core.BuildException)

Example 5 with BuildException

use of org.eclipse.cdt.managedbuilder.core.BuildException in project arduino-eclipse-plugin by Sloeber.

the class ArduinoManagedBuildGnuToolInfo method calculateInputs.

/*
	 * Other Methods
	 */
public boolean calculateInputs(ArduinoGnuMakefileGenerator makeGen, IConfiguration config, IResource[] projResources, ToolInfoHolder h, boolean lastChance) {
    // Get the inputs for this tool invocation
    // Note that command inputs that are also dependencies are also added to
    // the command dependencies list
    /*
		 * The priorities for determining the names of the inputs of a tool are:
		 * 1. If an option is specified, use the value of the option. 2. If a
		 * build variable is specified, use the files that have been added to
		 * the build variable as the output(s) of other build steps. 3. Use the
		 * file extensions and the resources in the project
		 */
    boolean done = true;
    // Inputs for the
    Vector<String> myCommandInputs = new Vector<>();
    // tool command
    // line
    // Dependencies
    Vector<String> myCommandDependencies = new Vector<>();
    // for the
    // make
    // rule
    // Complete
    Vector<String> myEnumeratedInputs = new Vector<>();
    // list of
    // individual
    // inputs
    IInputType[] inTypes = this.tool.getInputTypes();
    if (inTypes != null && inTypes.length > 0) {
        for (IInputType type : inTypes) {
            // Inputs
            Vector<String> itCommandInputs = new Vector<>();
            // for
            // the
            // tool
            // command
            // line
            // for
            // this
            // input-type
            // Dependencies
            Vector<String> itCommandDependencies = new Vector<>();
            // for
            // the
            // make
            // rule
            // for
            // this
            // input-type
            // Complete
            Vector<String> itEnumeratedInputs = new Vector<>();
            // list
            // of
            // individual
            // inputs
            // for
            // this
            // input-type
            String variable = type.getBuildVariable();
            boolean primaryInput = type.getPrimaryInput();
            boolean useFileExts = false;
            IOption option = this.tool.getOptionBySuperClassId(type.getOptionId());
            IOption assignToOption = this.tool.getOptionBySuperClassId(type.getAssignToOptionId());
            // Option?
            if (option != null) {
                try {
                    List<String> inputs = new ArrayList<>();
                    int optType = option.getValueType();
                    if (optType == IOption.STRING) {
                        inputs.add(option.getStringValue());
                    } else if (optType == IOption.STRING_LIST || optType == IOption.LIBRARIES || optType == IOption.OBJECTS || optType == IOption.INCLUDE_FILES || optType == IOption.LIBRARY_PATHS || optType == IOption.LIBRARY_FILES || optType == IOption.MACRO_FILES) {
                        @SuppressWarnings("unchecked") List<String> valueList = (List<String>) option.getValue();
                        inputs = valueList;
                        this.tool.filterValues(optType, inputs);
                        this.tool.filterValues(optType, inputs);
                    }
                    for (int j = 0; j < inputs.size(); j++) {
                        String inputName = inputs.get(j);
                        try {
                            // try to resolve the build macros in the output
                            // names
                            String resolved = null;
                            // TODO: support other special characters
                            if (// $NON-NLS-1$
                            inputName.indexOf(" ") != -1) {
                                // resolve to string
                                resolved = // $NON-NLS-1$
                                ManagedBuildManager.getBuildMacroProvider().resolveValue(// $NON-NLS-1$
                                inputName, // $NON-NLS-1$
                                "", // $NON-NLS-1$
                                " ", IBuildMacroProvider.CONTEXT_OPTION, new OptionContextData(option, this.tool));
                            } else {
                                // resolve to makefile variable format
                                resolved = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(// $NON-NLS-1$
                                inputName, // $NON-NLS-1$
                                "", // $NON-NLS-1$
                                " ", IBuildMacroProvider.CONTEXT_OPTION, new OptionContextData(option, this.tool));
                            }
                            if ((resolved = resolved.trim()).length() > 0)
                                inputName = resolved;
                        } catch (BuildMacroException e) {
                        // JABA is not
                        // going to add
                        // code
                        }
                        if (primaryInput) {
                            itCommandDependencies.add(j, inputName);
                        } else {
                            itCommandDependencies.add(inputName);
                        }
                    // NO - itCommandInputs.add(inputName);
                    // NO - itEnumeratedInputs.add(inputName);
                    }
                } catch (BuildException ex) {
                // JABA is not going to add
                // code
                }
            } else {
                // Build Variable?
                if (variable.length() > 0) {
                    // $NON-NLS-1$ //$NON-NLS-2$
                    String cmdVariable = variable = "$(" + variable + ")";
                    itCommandInputs.add(cmdVariable);
                    if (primaryInput) {
                        itCommandDependencies.add(0, cmdVariable);
                    } else {
                        itCommandDependencies.add(cmdVariable);
                    }
                    // If there is an output variable with the same name,
                    // get
                    // the files associated with it.
                    List<String> outMacroList = makeGen.getBuildVariableList(h, variable, ArduinoGnuMakefileGenerator.PROJECT_RELATIVE, null, true);
                    if (outMacroList != null) {
                        itEnumeratedInputs.addAll(outMacroList);
                    } else {
                        // extensions below
                        if (lastChance) {
                            useFileExts = true;
                        } else {
                            done = false;
                            break;
                        }
                    }
                }
                // Use file extensions
                if (variable.length() == 0 || useFileExts) {
                    // if (type.getMultipleOfType()) {
                    // Calculate EnumeratedInputs using the file extensions
                    // and the resources in the project
                    // Note: This is only correct for tools with
                    // multipleOfType == true, but for other tools
                    // it gives us an input resource for generating default
                    // names
                    // Determine the set of source input macros to use
                    HashSet<String> handledInputExtensions = new HashSet<>();
                    String[] exts = type.getSourceExtensions(this.tool);
                    if (projResources != null) {
                        for (IResource rc : projResources) {
                            if (rc.getType() == IResource.FILE) {
                                String fileExt = rc.getFileExtension();
                                // fix for NPE, bugzilla 99483
                                if (fileExt == null) {
                                    // $NON-NLS-1$
                                    fileExt = "";
                                }
                                for (int k = 0; k < exts.length; k++) {
                                    if (fileExt.equals(exts[k])) {
                                        if (!useFileExts) {
                                            if (!handledInputExtensions.contains(fileExt)) {
                                                handledInputExtensions.add(fileExt);
                                                String buildMacro = // $NON-NLS-1$
                                                "$(" + makeGen.getSourceMacroName(fileExt).toString() + // $NON-NLS-1$
                                                ")";
                                                itCommandInputs.add(buildMacro);
                                                if (primaryInput) {
                                                    itCommandDependencies.add(0, buildMacro);
                                                } else {
                                                    itCommandDependencies.add(buildMacro);
                                                }
                                            }
                                        }
                                        if (type.getMultipleOfType() || itEnumeratedInputs.size() == 0) {
                                            // Add a path that is relative
                                            // to the project directory
                                            itEnumeratedInputs.add(rc.getProjectRelativePath().toOSString());
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                // }
                }
            }
            // Get any additional inputs specified in the manifest file or
            // the project file
            IAdditionalInput[] addlInputs = type.getAdditionalInputs();
            if (addlInputs != null) {
                for (int j = 0; j < addlInputs.length; j++) {
                    IAdditionalInput addlInput = addlInputs[j];
                    int kind = addlInput.getKind();
                    if (kind == IAdditionalInput.KIND_ADDITIONAL_INPUT || kind == IAdditionalInput.KIND_ADDITIONAL_INPUT_DEPENDENCY) {
                        String[] paths = addlInput.getPaths();
                        if (paths != null) {
                            for (int k = 0; k < paths.length; k++) {
                                String path = paths[k];
                                itEnumeratedInputs.add(path);
                                // to build directory relative
                                if (!(path.startsWith("$("))) {
                                    // $NON-NLS-1$
                                    IResource addlResource = this.project.getFile(path);
                                    if (addlResource != null) {
                                        IPath addlPath = addlResource.getLocation();
                                        if (addlPath != null) {
                                            path = ManagedBuildManager.calculateRelativePath(makeGen.getTopBuildDir(), addlPath).toOSString();
                                        }
                                    }
                                }
                                itCommandInputs.add(path);
                            }
                        }
                    }
                }
            }
            // input(s) as the value of that option
            if (assignToOption != null && option == null) {
                try {
                    int optType = assignToOption.getValueType();
                    if (optType == IOption.STRING) {
                        // $NON-NLS-1$
                        String optVal = "";
                        for (int j = 0; j < itCommandInputs.size(); j++) {
                            if (j != 0) {
                                // $NON-NLS-1$
                                optVal += " ";
                            }
                            optVal += itCommandInputs.get(j);
                        }
                        ManagedBuildManager.setOption(config, this.tool, assignToOption, optVal);
                    } else if (optType == IOption.STRING_LIST || optType == IOption.LIBRARIES || optType == IOption.OBJECTS || optType == IOption.INCLUDE_FILES || optType == IOption.LIBRARY_PATHS || optType == IOption.LIBRARY_FILES || optType == IOption.MACRO_FILES) {
                        // TODO: do we need to do anything with undefs here?
                        // Mote that when using the enumerated inputs, the
                        // path(s) must be translated from project relative
                        // to top build directory relative
                        String[] paths = new String[itEnumeratedInputs.size()];
                        for (int j = 0; j < itEnumeratedInputs.size(); j++) {
                            paths[j] = itEnumeratedInputs.get(j);
                            IResource enumResource = this.project.getFile(paths[j]);
                            if (enumResource != null) {
                                IPath enumPath = enumResource.getLocation();
                                if (enumPath != null) {
                                    paths[j] = ManagedBuildManager.calculateRelativePath(makeGen.getTopBuildDir(), enumPath).toOSString();
                                }
                            }
                        }
                        ManagedBuildManager.setOption(config, this.tool, assignToOption, paths);
                    } else if (optType == IOption.BOOLEAN) {
                        if (itEnumeratedInputs.size() > 0) {
                            ManagedBuildManager.setOption(config, this.tool, assignToOption, true);
                        } else {
                            ManagedBuildManager.setOption(config, this.tool, assignToOption, false);
                        }
                    } else if (optType == IOption.ENUMERATED || optType == IOption.TREE) {
                        if (itCommandInputs.size() > 0) {
                            ManagedBuildManager.setOption(config, this.tool, assignToOption, itCommandInputs.firstElement());
                        }
                    }
                    itCommandInputs.removeAllElements();
                // itEnumeratedInputs.removeAllElements();
                } catch (BuildException ex) {
                // JABA is not going to add
                // code
                }
            }
            myCommandInputs.addAll(itCommandInputs);
            myCommandDependencies.addAll(itCommandDependencies);
            myEnumeratedInputs.addAll(itEnumeratedInputs);
        }
    } else {
        // For support of pre-CDT 3.0 integrations.
        if (this.bIsTargetTool) {
            // NOTE WELL: This only supports the case of a single
            // "target tool"
            // with the following characteristics:
            // 1. The tool consumes exactly all of the object files produced
            // by other tools in the build and produces a single output
            // 2. The target name comes from the configuration artifact name
            // The rule looks like:
            // <targ_prefix><target>.<extension>: $(OBJS) <refd_project_1
            // ... refd_project_n>
            // $NON-NLS-1$
            myCommandInputs.add("$(OBJS)");
            // $NON-NLS-1$
            myCommandInputs.add("$(USER_OBJS)");
            // $NON-NLS-1$
            myCommandInputs.add("$(LIBS)");
        } else {
        // Rule will be generated by addRuleForSource
        }
    }
    if (done) {
        this.commandInputs.addAll(myCommandInputs);
        this.commandDependencies.addAll(0, myCommandDependencies);
        this.enumeratedInputs.addAll(myEnumeratedInputs);
        this.inputsCalculated = true;
        return true;
    }
    return false;
}
Also used : OptionContextData(org.eclipse.cdt.managedbuilder.internal.macros.OptionContextData) IPath(org.eclipse.core.runtime.IPath) IOption(org.eclipse.cdt.managedbuilder.core.IOption) ArrayList(java.util.ArrayList) IAdditionalInput(org.eclipse.cdt.managedbuilder.core.IAdditionalInput) BuildMacroException(org.eclipse.cdt.managedbuilder.macros.BuildMacroException) IInputType(org.eclipse.cdt.managedbuilder.core.IInputType) ArrayList(java.util.ArrayList) List(java.util.List) BuildException(org.eclipse.cdt.managedbuilder.core.BuildException) Vector(java.util.Vector) IResource(org.eclipse.core.resources.IResource) HashSet(java.util.HashSet)

Aggregations

BuildException (org.eclipse.cdt.managedbuilder.core.BuildException)14 IOption (org.eclipse.cdt.managedbuilder.core.IOption)10 ArrayList (java.util.ArrayList)8 ITool (org.eclipse.cdt.managedbuilder.core.ITool)7 IPath (org.eclipse.core.runtime.IPath)7 CoreException (org.eclipse.core.runtime.CoreException)6 IStatus (org.eclipse.core.runtime.IStatus)6 Status (org.eclipse.core.runtime.Status)6 BuildMacroException (org.eclipse.cdt.managedbuilder.macros.BuildMacroException)5 IConfiguration (org.eclipse.cdt.managedbuilder.core.IConfiguration)4 List (java.util.List)3 Vector (java.util.Vector)3 IManagedCommandLineGenerator (org.eclipse.cdt.managedbuilder.core.IManagedCommandLineGenerator)3 IManagedCommandLineInfo (org.eclipse.cdt.managedbuilder.core.IManagedCommandLineInfo)3 FileContextData (org.eclipse.cdt.managedbuilder.internal.macros.FileContextData)3 IResource (org.eclipse.core.resources.IResource)3 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 ICProjectDescription (org.eclipse.cdt.core.settings.model.ICProjectDescription)2 IInputType (org.eclipse.cdt.managedbuilder.core.IInputType)2