1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-07-03 07:05:24 +02:00

[220446] Added and preprocessor for tutorial excercises.

This commit is contained in:
Pawel Piech 2008-02-26 20:02:06 +00:00
parent 398f01e873
commit e8d462f047
8 changed files with 586 additions and 4 deletions

View file

@ -3,5 +3,6 @@
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="src" path="src_ant"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View file

@ -1,4 +1,4 @@
#Thu Jun 07 11:07:55 PDT 2007
#Fri Feb 22 09:41:13 PST 2008
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
@ -33,7 +33,7 @@ org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=warning
org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning
org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
org.eclipse.jdt.core.compiler.problem.nullReference=ignore
org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
@ -41,6 +41,7 @@ org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warnin
org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore
org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
@ -53,13 +54,17 @@ org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeUncheckedExceptions=disabled
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
org.eclipse.jdt.core.compiler.problem.unusedImport=error
org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
org.eclipse.jdt.core.compiler.source=1.5

View file

@ -12,7 +12,7 @@ Require-Bundle: org.eclipse.ui,
org.eclipse.debug.ui,
org.eclipse.dd.dsf,
org.eclipse.ui,
org.eclipse.dd.dsf.ui
org.eclipse.dd.dsf.ui,
org.apache.ant;bundle-version="1.7.0";resolution:=optional
Eclipse-LazyStart: true
Bundle-RequiredExecutionEnvironment: J2SE-1.5

View file

@ -0,0 +1,51 @@
<?xml version="1.0"?>
<!-- ======================================================================
Copyright (c) 2005, 2008 IBM Corporation and others.\
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
Contributors:
IBM Corporation - initial API and implementation
EclipseCon
Debug Tutorial Exercises
====================================================================== -->
<project name="EclipseCon" default="generateAll">
<description>
Debug Tutorial Exercises
</description>
<taskdef name="preprocess" classname="org.eclipse.dd.examples.ant.tasks.PreProcessor" classpath="../bin" />
<property name="workspace" location="c:\eclipse-dev\dev-3.4" />
<property name="srcBase" location="${workspace}/org.eclipse.dd.examples.dsf/src_preprocess" />
<property name="destBase" location="${workspace}/org.eclipse.dd.examples.dsf/src" />
<!-- =================================
target: generateAll
================================= -->
<target name="generateAll" description="--> Debug Tutorial Exercises">
<!-- = = = = = = = = = = = = = = = = =
macrodef: process
= = = = = = = = = = = = = = = = = -->
<macrodef name="process">
<attribute name="packagedir"/>
<attribute name="symbols"/>
<sequential>
<delete dir="@{destBase}/${packagedir}/excercise"/>
<delete dir="@{destBase}/${packagedir}/answer"/>
<mkdir dir="@{destBase}/${packagedir}/excercise"/>
<mkdir dir="@{destBase}/${packagedir}/answer"/>
<preprocess destdir="@{destBase}/${packagedir}/excercise" symbols="@{symbols}">
<fileset dir="@{destBase}/${packagedir}"/>
</preprocess>
</sequential>
</macrodef>
<process packagedir="${srcBase}/org/eclipse/dd/examples/dsf/requestmonitor" symbols="request_monitors_ex1"/>
</target>
</project>

View file

@ -0,0 +1,40 @@
/*******************************************************************************
* Copyright (c) 2008 Wind River Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.examples.dsf.requestmonitor;
import java.util.concurrent.Executor;
import org.eclipse.dd.dsf.concurrent.DataRequestMonitor;
import org.eclipse.dd.dsf.concurrent.ImmediateExecutor;
/**
* Example of using a DataRequestMonitor to retrieve a result from an
* asynchronous method.
*/
public class Async2Plus2 {
public static void main(String[] args) {
Executor executor = ImmediateExecutor.getInstance();
DataRequestMonitor<Integer> rm =
new DataRequestMonitor<Integer>(executor, null) {
@Override
protected void handleCompleted() {
System.out.println("2 + 2 = " + getData());
}
};
asyncAdd(2, 2, rm);
}
static void asyncAdd(int value1, int value2, DataRequestMonitor<Integer> rm) {
rm.setData(value1 + value2);
rm.done();
}
}

View file

@ -0,0 +1,134 @@
/*******************************************************************************
* Copyright (c) 2008 Wind River Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.examples.dsf.requestmonitor;
import java.util.Arrays;
import java.util.concurrent.Executor;
import org.eclipse.dd.dsf.concurrent.CountingRequestMonitor;
import org.eclipse.dd.dsf.concurrent.DataRequestMonitor;
import org.eclipse.dd.dsf.concurrent.ImmediateExecutor;
import org.eclipse.dd.dsf.concurrent.RequestMonitor;
/**
* Example of using a CountingRequestMonitor to wait for multiple
* asynchronous calls to complete.
*/
public class AsyncQuicksort {
static Executor fgExecutor = ImmediateExecutor.getInstance();
public static void main(String[] args) {
final int[] array = {5, 7, 8, 3, 2, 1, 9, 5, 4};
System.out.println("To sort: " + Arrays.toString(array));
asyncQuicksort(
array, 0, array.length - 1,
new RequestMonitor(fgExecutor, null) {
@Override
protected void handleCompleted() {
System.out.println("Sorted: " + Arrays.toString(array));
}
});
}
static void asyncQuicksort(final int[] array, final int left,
final int right, final RequestMonitor rm)
{
if (right > left) {
int pivot = left;
//#ifdef request_monitors_ex2
//# // TODO: Request Monitors Exercise 2 - Convert partition to an async. method.
//# int newPivot = partition(array, left, right, pivot);
//# int newPivot = getData();
//# printArray(array, left, right, newPivot);
//#
//# CountingRequestMonitor countingRm = new CountingRequestMonitor(fgExecutor, rm);
//# asyncQuicksort(array, left, newPivot - 1, countingRm);
//# asyncQuicksort(array, newPivot + 1, right, countingRm);
//# countingRm.setDoneCount(2);
//#else
asyncPartition(
array, left, right, pivot,
new DataRequestMonitor<Integer>(fgExecutor, rm) {
@Override
protected void handleCompleted() {
int newPivot = getData();
printArray(array, left, right, newPivot);
CountingRequestMonitor countingRm = new CountingRequestMonitor(fgExecutor, rm);
asyncQuicksort(array, left, newPivot - 1, countingRm);
asyncQuicksort(array, newPivot + 1, right, countingRm);
countingRm.setDoneCount(2);
}
});
//#endif
} else {
rm.done();
}
}
//#ifdef request_monitors_ex2
//# // TODO: Request Monitors Exercise 2 - Convert partition to an async. method.
//# static int partition(int[] array, int left, int right, int pivot)
//#else
static void asyncPartition(int[] array, int left, int right, int pivot, DataRequestMonitor<Integer> rm)
//#endif
{
int pivotValue = array[pivot];
array[pivot] = array[right];
array[right] = pivotValue;
int store = left;
for (int i = left; i < right; i++) {
if (array[i] <= pivotValue) {
int tmp = array[store];
array[store] = array[i];
array[i] = tmp;
store++;
}
}
array[right] = array[store];
array[store] = pivotValue;
//#ifdef request_monitors_ex2
//# // TODO: Request Monitors Exercise 2 - Convert partition to an async. method.
//# return store;
//#else
rm.setData(store);
rm.done();
//#endif
}
static void printArray(int[] array, int left, int right, int pivot) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < array.length; i++ ) {
if (i == left) {
buffer.append('>');
} else if (i == pivot) {
buffer.append('-');
} else {
buffer.append(' ');
}
buffer.append(array[i]);
if (i == right) {
buffer.append('<');
} else if (i == pivot) {
buffer.append('-');
} else {
buffer.append(' ');
}
}
System.out.println(buffer);
}
}

View file

@ -0,0 +1,292 @@
/*******************************************************************************
* Copyright (c) 2005, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Bjorn Freeman-Benson - initial API and implementation
*******************************************************************************/
package org.eclipse.dd.examples.ant.tasks;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.util.FileUtils;
/**
* Java preprocessor for code examples. Used to export source code for
* example plug-ins with parts of code missing/inserted etc., for
* various exercises.
* <p>
* The preprocessor looks for #ifdef statements in java comments, and is
* run with a set of symbols. For example:
* <pre>
* //#ifdef ex1
* ... code to insert when 'ex1' symbol is on
* //#else
* ... code to insert when not 'ex1'
* //#endif
* </pre>
* </p>
*/
public class PreProcessor extends Task {
private Vector fFileSets = new Vector();
private File fDestDir = null;
private Set fSymbols = new HashSet();
private FileUtils fUtils = FileUtils.getFileUtils();
// possible states
private static final int STATE_OUTSIDE_CONDITION = 0;
private static final int STATE_TRUE_CONDITION = 1;
private static final int STATE_FALSE_CONDITION = 2;
private static final int STATE_POST_TRUE_CONDITION = 3;
// matchers
private Matcher IF_DEF_MATCHER = Pattern.compile("#ifdef\\s+\\w+").matcher("");
private Matcher ELSE_IF_MATCHER = Pattern.compile("#elseif\\s+\\w+").matcher("");
private Matcher ELSE_MATCHER = Pattern.compile("#else$|#else\\W+").matcher("");
private Matcher END_MATCHER = Pattern.compile("#endif").matcher("");
/**
* Constructs a new preprocessor task
*/
public PreProcessor() {
}
/**
* Adds a set of files to process.
*
* @param set a set of files to process
*/
public void addFileset(FileSet set) {
fFileSets.addElement(set);
}
/**
* Sets the destination directory for processed files.
*
* @param destDir destination directory for processed files
*/
public void setDestdir(File destDir) {
fDestDir = destDir;
}
/**
* Sets the symbols that are "on" for the preprocessing.
*
* @param symbols symbols that are "on" for the preprocessing
*/
public void setSymbols(String symbols) {
String[] strings = symbols.split(",");
for (int i = 0; i < strings.length; i++) {
String string = strings[i].trim();
if (string.length() > 0) {
fSymbols.add(string);
}
}
}
public void execute() throws BuildException {
if (fSymbols.size() == 0) {
throw new BuildException("No symbols specified for preprocessor");
}
if (fFileSets.isEmpty()) {
throw new BuildException("No filesets specified for processing");
}
if (!fDestDir.exists()) {
throw new BuildException("destdir does not exist: " + fDestDir.getAbsolutePath());
}
StringBuffer buf = new StringBuffer("Symbols: ");
String[] symbols = (String[]) fSymbols.toArray(new String[fSymbols.size()]);
for (int i = 0; i < symbols.length; i++) {
String symbol = symbols[i];
buf.append(symbol);
if(i < (symbols.length -1)) {
buf.append(", ");
}
}
log(buf.toString());
Iterator fileSets = fFileSets.iterator();
while (fileSets.hasNext()) {
FileSet fileSet = (FileSet) fileSets.next();
DirectoryScanner scanner = fileSet.getDirectoryScanner(getProject());
String[] includedFiles = scanner.getIncludedFiles();
File baseDir = fileSet.getDir(getProject());
for (int i = 0; i < includedFiles.length; i++) {
String fileName = includedFiles[i];
processFile(baseDir, fileName, fDestDir);
}
}
}
/**
* Process the file
* @param baseDir base directory source file is relative to
* @param fileName source file name
* @param destDir root destination directory
*/
private void processFile(File baseDir, String fileName, File destDir) throws BuildException {
File destFile = new File(destDir, fileName);
File srcFile = new File(baseDir, fileName);
File dir = destFile.getParentFile();
if (!dir.exists()) {
dir.mkdirs();
}
String contents = null;
if (fileName.endsWith(".java")) {
contents = preProcessFile(srcFile, "//#");
} else if (fileName.equals("plugin.xml")) {
contents = preProcessFile(srcFile, null);
}
if (contents == null) {
// no change, just copy file
try {
fUtils.copyFile(srcFile, destFile);
} catch (IOException e) {
throw new BuildException(e);
}
} else {
// write new file
FileWriter writer;
try {
writer = new FileWriter(destFile);
writer.write(contents);
writer.close();
} catch (IOException e) {
throw new BuildException(e);
}
}
}
/**
* Preprocesses a file
*
* @param srcFile the file to process
* @param strip chars to stip off lines in a true condition, or <code>null</code>
* @return
*/
public String preProcessFile(File srcFile, String strip) {
try {
FileReader fileReader = new FileReader(srcFile);
BufferedReader reader = new BufferedReader(fileReader);
StringBuffer buffer = new StringBuffer();
String line = reader.readLine();
String activeSymbol = null;
int state = STATE_OUTSIDE_CONDITION;
boolean changed = false;
while (line != null) {
boolean ifdef = IF_DEF_MATCHER.reset(line).find();
boolean elseif = ELSE_IF_MATCHER.reset(line).find();
boolean elze = ELSE_MATCHER.reset(line).find();
boolean endif = END_MATCHER.reset(line).find();
boolean commandLine = ifdef || elseif || elze || endif;
boolean written = false;
switch (state) {
case STATE_OUTSIDE_CONDITION:
if (ifdef) {
String condition = line.substring(IF_DEF_MATCHER.start(), IF_DEF_MATCHER.end());
String[] strings = condition.split("\\s+");
activeSymbol = strings[1].trim();
if (fSymbols.contains(activeSymbol)) {
state = STATE_TRUE_CONDITION;
} else {
state = STATE_FALSE_CONDITION;
}
} else if (elseif) {
throw new BuildException("#elseif encountered without corresponding #ifdef");
} else if (elze) {
throw new BuildException("#else encountered without corresponding #ifdef (" + srcFile.getPath() + ")");
} else if (endif) {
throw new BuildException("#endif encountered without corresponding #ifdef");
}
break;
case STATE_TRUE_CONDITION:
if (elze || elseif) {
state = STATE_POST_TRUE_CONDITION;
break;
} else if (endif) {
state = STATE_OUTSIDE_CONDITION;
break;
} else if (ifdef) {
throw new BuildException("illegal nested #ifdef");
}
case STATE_FALSE_CONDITION:
if (elseif) {
String condition = line.substring(ELSE_IF_MATCHER.start(), ELSE_IF_MATCHER.end());
String[] strings = condition.split("\\s+");
activeSymbol = strings[1].trim();
if (fSymbols.contains(activeSymbol)) {
state = STATE_TRUE_CONDITION;
} else {
state = STATE_FALSE_CONDITION;
}
} else if (elze) {
state = STATE_TRUE_CONDITION;
break;
} else if (endif) {
state = STATE_OUTSIDE_CONDITION;
break;
} else if (ifdef) {
throw new BuildException("illegal nested #ifdef");
}
case STATE_POST_TRUE_CONDITION:
if (endif) {
state = STATE_OUTSIDE_CONDITION;
break;
} else if (ifdef) {
throw new BuildException("illegal nested #ifdef");
}
}
if (!commandLine) {
if (state == STATE_OUTSIDE_CONDITION || state == STATE_TRUE_CONDITION) {
if (state == STATE_TRUE_CONDITION && strip != null) {
if (line.startsWith(strip)) {
line = line.substring(strip.length());
}
}
buffer.append(line);
buffer.append("\n");
written = true;
}
}
changed = changed || !written;
line = reader.readLine();
}
if (!changed) {
return null;
}
return buffer.toString();
} catch (IOException e) {
throw new BuildException(e);
}
}
public static void main(String[] args) {
PreProcessor processor = new PreProcessor();
processor.setSymbols("ex2");
String string = processor.preProcessFile(new File("c:\\eclipse3.1\\dev\\example.debug.core\\src\\example\\debug\\core\\launcher\\PDALaunchDelegate.java"), "//#");
//String string = processor.preProcessFile(new File("c:\\eclipse3.1\\dev\\example.debug.core\\plugin.xml"), null);
System.out.println(string);
}
}

View file

@ -0,0 +1,59 @@
/*******************************************************************************
* Copyright (c) 2008 Wind River Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
//#ifdef request_monitors_ex1
//#package org.eclipse.dd.examples.dsf.requestmonitor.excercise;
//#else
package org.eclipse.dd.examples.dsf.requestmonitor.answer;
//#endif
import java.util.concurrent.Executor;
import org.eclipse.dd.dsf.concurrent.ImmediateExecutor;
import org.eclipse.dd.dsf.concurrent.RequestMonitor;
/**
* "Hello world" example which uses an asynchronous method to print out
* the result.
* <p>
* The main method uses an immediate executor, which executes runnables
* as soon as they are submitted, in creating its request monitor.
*
*/
public class AsyncHelloWorld {
public static void main(String[] args) {
Executor executor = ImmediateExecutor.getInstance();
RequestMonitor rm = new RequestMonitor(executor, null);
asyncHelloWorld(rm);
}
static void asyncHelloWorld(RequestMonitor rm) {
System.out.println("Hello world");
//#ifdef request_monitors_ex1
//# // TODO: Request Monitors Exercise 1 - Call a second async.
//# // "Hello world 2" method.
//# rm.done();
//#else
RequestMonitor rm2 = new RequestMonitor(ImmediateExecutor.getInstance(), rm);
asyncHelloWorld2(rm2);
//#endif
}
//#ifdef request_monitors_ex1
//# // TODO: Request Monitors Exercise 1 - Add a second async.
//# // "Hello world 2" method.
//#else
static void asyncHelloWorld2(RequestMonitor rm) {
System.out.println("Hello world 2");
rm.done();
}
//#endif
}