cpreprocessorwrapper.java

来自「plugin for eclipse」· Java 代码 · 共 283 行

JAVA
283
字号
package isis.anp.preprocessor;

import isis.anp.common.ParserConfiguration;
import isis.commons.exec.Executor;
import isis.commons.fs.SearchPath;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;



/*
 * Created on Apr 15, 2005
 */

/**
 * Java wrapper for the GNU C preprocessor.
 * @author sallai
 */
public class CPreprocessorWrapper {

	// presistently store the effective macros in an imacros file
    private String macrosFile = null;
    
    // configuration (search path, defines, etc)
    private ParserConfiguration parserConfig;
	
//	public CPreprocessorWrapper(String tosDir, PlatformProfile platformProfile, SensorBoardProfile sensorBoardProfile, SearchPath userSearchPathList) throws IOException {
//		this.platformProfile = platformProfile;
//		// set up search path
//		searchPathList = (SearchPath) userSearchPathList.clone();
//		searchPathList.addAllWithPrefix(sensorBoardProfile.getSearchPathList(), tosDir+"/");
//		searchPathList.addAllWithPrefix(platformProfile.getSearchPathList(), tosDir+"/");
//		searchPathList.addAllWithPrefix(SearchPath.load("parser/config/syspath.properties"),tosDir+"/");
//	}	

	public CPreprocessorWrapper(ParserConfiguration parserConfig) {
		this.setParserConfig(parserConfig);
	}	
	
	
    public SearchPath getSearchPathList() {
        return getParserConfig().getSearchPath();
    }

    public void addDefine(String name, String value) {
        if (value == null)
            value = "";
        getParserConfig().getDefines().put(name, value);
    }


    
    public InputStream preprocess(String inputFile)
            throws PreprocessorException {

        String outputFileName = getTempDir() + "/preprocessed_" + System.currentTimeMillis()
                + "_" + baseName(inputFile);
        String stdErrRedirectFileName = getTempDir() + "/preprocessor_STDERR_"
                + System.currentTimeMillis() + "_" + baseName(inputFile);
        String stdOutRedirectFileName = getTempDir() + "/preprocessor_STDOUT_"
                + System.currentTimeMillis() + "_" + baseName(inputFile);
        
        try {

        	// create STDERR and STDOUT streams
            FileOutputStream stdErrRedirectOutputStream = new FileOutputStream(
                    stdErrRedirectFileName);
            FileOutputStream stdOutRedirectOutputStream = new FileOutputStream(
                    stdOutRedirectFileName);

            // compose command line
            ArrayList cmdLine;
            
            if (macrosFile == null) {
            	cmdLine = getCmdLine(inputFile, outputFileName, null,
                		false, true, true, true, true);
            } else {
            	cmdLine = getCmdLine(inputFile, outputFileName, macrosFile,
                      false, true, true, false, true);
            }

            // execute preprocessor
            int exitVal = Executor.exec(null, stdErrRedirectOutputStream, stdOutRedirectOutputStream, (String[])(cmdLine.toArray(new String[0])), null, null);

            // close STDERR and STDOUT streams
            stdErrRedirectOutputStream.close();
            stdOutRedirectOutputStream.close();
            
            
            // if there was something on stdErr, create an exception out of
            // it...
            BufferedReader isr = new BufferedReader(new InputStreamReader(
                    new FileInputStream(stdErrRedirectFileName)));
            StringBuffer errors = new StringBuffer();
            String line = null;
            while ((line = isr.readLine()) != null) {
                errors.append(line);
                errors.append('\n');
            }
            isr.close();
// TODO: we need to distinguish between warnings and errors...            
//            if (errors.length() > 0) {
//                throw new PreprocessorException(
//                        "Errors occured while preprocessing:\n"
//                                + errors.toString());
//            }

            // if exit value is nonzero, we throw an exception
            if (exitVal != 0) {
                throw new PreprocessorException(
                        "Preprocessor exited with exit value " + exitVal
                                + " Errors:" + errors.toString());
            }

            // preprocessing of a header was successful: use output as an imacros file from
            // now on
            if(inputFile.matches(".*\\.[hH]")) {
//            	System.out.println("Header file: "+inputFile);
            	macrosFile = outputFileName;
            }

            // create an input stream from the preprocessor output
            return new BufferedInputStream(new FileInputStream(outputFileName));
        }

        catch (FileNotFoundException fnfe) {
            throw new PreprocessorException("Cannot create temporary file: "
                    + fnfe.getMessage());
        }
        catch (InterruptedException ie) {
            throw new PreprocessorException("Preprocessor interrupted: "
                    + ie.getMessage());
        } catch (IOException ioe) {
            throw new PreprocessorException("Cannot execute preprocessor: "
                    + ioe.getMessage());
        }

    }

    /**
     * Assemble the command line.
     * @param inputFile the input file
     * @param outputFile the output file
     * @param imacrosFile the imacros file
     * @param discardComments 
     * @param outputDefines
     * @param outputPreprocessed
     * @param enableWarnings
     * @param includeStdInc
     * @return command line as an array of strings
     * @throws IOException
     */
    private ArrayList getCmdLine(String inputFile, String outputFile,
            String imacrosFile, boolean discardComments, boolean outputDefines,
            boolean outputPreprocessed, boolean enableWarnings,
            boolean includeStdInc) throws IOException {
        ArrayList cmdLine = new ArrayList();

        cmdLine.add(parserConfig.getCppExecutable());
        cmdLine.addAll(parserConfig.getCppOptions());

        if (getSearchPathList() != null) {
            Iterator iter = getSearchPathList().iterator();
            while (iter.hasNext()) {
                String path = (String) iter.next();
                cmdLine.add("-I" + path);
            }
        }

        if (getDefines() != null) {
            Iterator iter = getDefines().keySet().iterator();
            while (iter.hasNext()) {
            	StringBuffer param = new StringBuffer();
                String define = (String) iter.next();
                param.append("-D");
                param.append(define);
                String value = (String) getDefines().get(define);
                if (!value.equals("")) {
                    param.append("=");
                    param.append(value);
                }
                cmdLine.add(param.toString());
            }
        }

        if (outputDefines) {
            if (outputPreprocessed) {
                cmdLine.add("-dD");
            } else {
                cmdLine.add("-dM");
            }
        } else {
            if (!outputPreprocessed) {
                // nothing to output: return
                return null;
            }
        }

        if (!discardComments) {
            cmdLine.add("-C");
        }

        if (!enableWarnings) {
            cmdLine.add("-w");
        }

        if (imacrosFile != null) {
            cmdLine.add("-imacros");
            cmdLine.add(imacrosFile);
        }

        if (!includeStdInc) {
            cmdLine.add("-nostdinc");
        }

        if (inputFile != null) {
            cmdLine.add(inputFile);
        } else {
            cmdLine.add("-");
        }

        if (outputFile != null) {
            cmdLine.add(outputFile);
        } else {
            cmdLine.add("-");
        }

        return cmdLine;
    }
        
    private String baseName(String fn) {
        int lastSlashPos = fn.lastIndexOf("/");
        int lastBackSlashPos = fn.lastIndexOf("\\");

        if (lastSlashPos > lastBackSlashPos) {
            return fn.substring(lastSlashPos + 1, fn.length());
        } else {
            return fn.substring(lastBackSlashPos + 1, fn.length());
        }
    }

	public String getTempDir() {
		return parserConfig.getTempDir();
	}

	public void setTempDir(String tempDir) {
		getParserConfig().setTempDir(tempDir);
	}


	/**
	 * @return Returns the parserConfig.
	 */
	public ParserConfiguration getParserConfig() {
		return parserConfig;
	}


	/**
	 * @param parserConfig The parserConfig to set.
	 */
	public void setParserConfig(ParserConfiguration parserConfig) {
		this.parserConfig = parserConfig;
	}


	/* (non-Javadoc)
	 * @see parser.common.ParserConfiguration#getDefines()
	 */
	public Map getDefines() {
		return parserConfig.getDefines();
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?