1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-04-29 19:45:01 +02:00
Removed warnings from parser source tree.  
	Removed preliminary task tags support to clean up parser interfaces and implementation.   
	Added preliminary IProblem support to 

UI
	Updated parser clients to use new IProblem strategy.  

TESTS
	Updated parser clients to use new IProblem strategy.
This commit is contained in:
John Camelon 2003-11-05 18:15:21 +00:00
parent b3b6f231c6
commit 56c76eb3e7
51 changed files with 1147 additions and 2438 deletions

View file

@ -1,3 +1,6 @@
2003-11-05 John Camelon
Updated parser clients to use new IProblem strategy.
2003-10-28 Andrew Niefer
Added testBug44510() to CompleteParseASTTest
Added testBug44925() to CompleteParseASTTest

View file

@ -122,8 +122,7 @@ public class ASTFailedTests extends BaseASTTest
catch (IOException ioe)
{
}
Iterator declarations = parse(code.toString()).getDeclarations();
assertFalse( "Should be 2 declarations, not 0", declarations.hasNext() );
assertCodeFailsParse(code.toString());
}
public void testBug39694() throws Exception
{

View file

@ -40,7 +40,7 @@ public class BaseScannerTest extends TestCase {
protected void initializeScanner( String input, ParserMode mode )
{
scanner= ParserFactory.createScanner( new StringReader(input),"TEXT", new ScannerInfo(), mode, ParserLanguage.CPP, callback );
scanner= ParserFactory.createScanner( new StringReader(input),"TEXT", new ScannerInfo(), mode, ParserLanguage.CPP, new NullSourceElementRequestor( mode ) );
}
@ -205,7 +205,6 @@ public class BaseScannerTest extends TestCase {
public static final boolean verbose = false;
protected NullSourceElementRequestor callback = new NullSourceElementRequestor();
/**
* @param string

View file

@ -1,5 +1,7 @@
package org.eclipse.cdt.core.parser.tests;
import java.util.EmptyStackException;
import junit.framework.TestCase;
import org.eclipse.cdt.core.parser.ScannerException;
@ -135,7 +137,7 @@ public class BranchTrackerTest extends TestCase {
assertFalse( bt.poundendif() );
assertTrue( bt.poundendif() );
assertEquals(0, bt.getDepth());
} catch (ScannerException se) {
} catch (EmptyStackException se) {
fail("Unexpected Scanner exception thrown");
}
}
@ -191,7 +193,7 @@ public class BranchTrackerTest extends TestCase {
}
catch( ScannerException se )
catch( EmptyStackException se )
{
fail( "Exception" );
}

View file

@ -498,13 +498,18 @@ public class CompleteParseBaseTest extends TestCase
}
List problems = new ArrayList();
public Iterator getProblems() {
return problems.iterator();
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ISourceElementRequestor#acceptProblem(org.eclipse.cdt.core.parser.IProblem)
*/
public void acceptProblem(IProblem problem)
public boolean acceptProblem(IProblem problem)
{
// TODO Auto-generated method stub
problems.add( problem );
return true;
}
/* (non-Javadoc)

View file

@ -1667,7 +1667,7 @@ public class QuickParseASTTests extends BaseASTTest
code.write(" const char di_str glue(<, :)glue(:, >) = str(%:%:<::><%%>%:);\n");
code.write(" /* Check the glue macro actually pastes, and that the spelling of\n");
code.write(" all digraphs is preserved. */\n");
code.write(" if (glue(str, cmp) (di_str, \"%:%:<::><%%>%:\"))\n");
code.write(" if (glue(strc, mp) (di_str, \"%:%:<::><%%>%:\"))\n");
code.write(" err (\"Digraph spelling not preserved!\");\n");
code.write(" return 0;\n");
code.write("glue (%, >) /* } */\n");

View file

@ -6,6 +6,7 @@ import java.util.List;
import org.eclipse.cdt.core.parser.EndOfFile;
import org.eclipse.cdt.core.parser.IMacroDescriptor;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.IToken;
import org.eclipse.cdt.core.parser.ParserMode;
import org.eclipse.cdt.core.parser.ScannerException;
@ -693,7 +694,7 @@ public class ScannerTestCase extends BaseScannerTest
catch (ScannerException se)
{
validateBalance(1);
assertTrue(se.getMessage().equals("#error Correct!"));
assertEquals( se.getProblem().getID(), IProblem.PREPROCESSOR_POUND_ERROR);
}
catch (Exception e)
{
@ -1270,33 +1271,33 @@ public class ScannerTestCase extends BaseScannerTest
try{
validateEOF();
} catch ( ScannerException e ){
assertTrue( e.getErrorCode() == ScannerException.ErrorCode.UNBOUNDED_STRING);
assertTrue( e.getProblem().getID() == IProblem.PREPROCESSOR_INVALID_DIRECTIVE );
}
initializeScanner( "#include <foo.h" );
try{
validateEOF();
} catch ( ScannerException e ){
assertTrue( e.getErrorCode() == ScannerException.ErrorCode.INVALID_PREPROCESSOR_DIRECTIVE);
assertTrue( e.getProblem().getID() == IProblem.PREPROCESSOR_INVALID_DIRECTIVE);
}
initializeScanner( "#define FOO(A" );
try{
validateEOF();
} catch( ScannerException e ){
assertTrue( e.getErrorCode() == ScannerException.ErrorCode.MALFORMED_MACRO_DEFN );
assertTrue( e.getProblem().getID() == IProblem.PREPROCESSOR_INVALID_MACRO_DEFN );
}
initializeScanner( "#define FOO(A \\ B" );
try{
validateEOF();
} catch( ScannerException e ){
assertTrue( e.getErrorCode() == ScannerException.ErrorCode.MALFORMED_MACRO_DEFN );
assertTrue( e.getProblem().getID() == IProblem.PREPROCESSOR_INVALID_MACRO_DEFN);
}
initializeScanner( "#define FOO(A,\\\nB) 1\n FOO(foo" );
try{
validateInteger("1");
} catch( ScannerException e ){
assertTrue( e.getErrorCode() == ScannerException.ErrorCode.MACRO_USAGE_ERROR );
assertTrue( e.getProblem().getID() == IProblem.PREPROCESSOR_MACRO_USAGE_ERROR);
}
}
@ -1355,19 +1356,6 @@ public class ScannerTestCase extends BaseScannerTest
validateIdentifier("FooBar");
validateEOF();
try {
initializeScanner( "Foo\\Bar" );
validateIdentifier("Foo");
validateIdentifier("Bar");
validateEOF();
} catch (ScannerException se) {
// if Scanner.throwExceptionOnBadCharacterRead == true
// we might end up with valid ScannerException "Invalid character ..."
// for '\'
assertTrue(se.getErrorCode() == ScannerException.ErrorCode.BAD_CHARACTER );
}
}
public void testBug36701A() throws Exception
@ -1483,7 +1471,7 @@ public class ScannerTestCase extends BaseScannerTest
}
catch( ScannerException se )
{
assertEquals( se.getErrorCode(), ScannerException.ErrorCode.ATTEMPTED_REDEFINITION );
assertTrue( se.getProblem().getID() == IProblem.PREPROCESSOR_INVALID_MACRO_REDEFN);
}
}

View file

@ -17,8 +17,10 @@ package org.eclipse.cdt.internal.core.search.indexing;
import java.util.LinkedList;
import org.eclipse.cdt.core.parser.DefaultProblemHandler;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.ISourceElementRequestor;
import org.eclipse.cdt.core.parser.ParserMode;
import org.eclipse.cdt.core.parser.ast.IASTASMDefinition;
import org.eclipse.cdt.core.parser.ast.IASTAbstractTypeSpecifierDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTClassReference;
@ -82,9 +84,8 @@ public class SourceIndexerRequestor implements ISourceElementRequestor, IIndexCo
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ISourceElementRequestor#acceptProblem(org.eclipse.cdt.core.parser.IProblem)
*/
public void acceptProblem(IProblem problem) {
// TODO Auto-generated method stub
public boolean acceptProblem(IProblem problem) {
return DefaultProblemHandler.ruleOnProblem( problem, ParserMode.COMPLETE_PARSE );
}
/* (non-Javadoc)

View file

@ -1,3 +1,8 @@
2003-11-05 John Camelon
Removed warnings from parser source tree.
Removed preliminary task tags support to clean up parser interfaces and implementation.
Added preliminary IProblem support to
2003-11-03 John Camelon
Added in preliminary interface for code completion mode.

View file

@ -0,0 +1,50 @@
/**********************************************************************
* Copyright (c) 2002,2003 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Rational Software - Initial API and implementation
***********************************************************************/
package org.eclipse.cdt.core.parser;
/**
* @author jcamelon
*
*/
public class DefaultProblemHandler
{
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.IProblemHandler#ruleOnProblem(org.eclipse.cdt.core.parser.IProblem)
*/
public static boolean ruleOnProblem( IProblem p, ParserMode mode )
{
if( p == null ) return true;
if( p.checkCategory( IProblem.SCANNER_RELATED ) || p.checkCategory( IProblem.PREPROCESSOR_RELATED ))
{
switch( p.getID() )
{
case IProblem.PREPROCESSOR_INVALID_DIRECTIVE:
return false;
case IProblem.PREPROCESSOR_POUND_ERROR:
case IProblem.PREPROCESSOR_UNBALANCE_CONDITION:
case IProblem.PREPROCESSOR_INVALID_MACRO_DEFN:
case IProblem.PREPROCESSOR_MACRO_USAGE_ERROR:
case IProblem.PREPROCESSOR_MACRO_PASTING_ERROR:
case IProblem.PREPROCESSOR_CONDITIONAL_EVAL_ERROR:
case IProblem.SCANNER_UNEXPECTED_EOF:
case IProblem.PREPROCESSOR_INVALID_MACRO_REDEFN:
if( mode == ParserMode.COMPLETE_PARSE )
return false;
default:
return true;
}
}
return true;
}
}

View file

@ -10,6 +10,8 @@
*******************************************************************************/
package org.eclipse.cdt.core.parser;
import java.util.Map;
/**
* Description of a C/C++ problem, as detected by the translation or some of the underlying
* technology reusing it.
@ -21,13 +23,8 @@ package org.eclipse.cdt.core.parser;
* as constants on this interface. </li>
* </ul>
*/
public interface IProblem extends ISourceElementCallbackDelegate {
/**
* Answer back the original arguments recorded into the problem.
* @return the original arguments recorded into the problem
*/
String[] getArguments();
public interface IProblem
{
/**
* Returns the problem id
@ -43,6 +40,16 @@ public interface IProblem extends ISourceElementCallbackDelegate {
*/
String getMessage();
/**
* Return to the client a map between parameter names and values.
*
* The keys and values are all Strings.
*
*
* @return a map between parameter names and values.
*/
Map getArguments();
/**
* Answer the file name in which the problem was found.
*
@ -60,7 +67,7 @@ public interface IProblem extends ISourceElementCallbackDelegate {
/**
* Answer the line number in source where the problem begins.
*
* @return the line number in source where the problem begins
* @return the line number in source where the problem begins, or -1 if unknown
*/
int getSourceLineNumber();
@ -86,27 +93,14 @@ public interface IProblem extends ISourceElementCallbackDelegate {
boolean isWarning();
/**
* Set the end position of the problem (inclusive), or -1 if unknown.
* Used for shifting problem positions.
*
* @param sourceEnd the given end position
* Unknown Numeric Value for line numbers and offsets; use this constant
*/
void setSourceEnd(int sourceEnd);
public final static int INT_VALUE_NOT_PROVIDED = -1;
/**
* Set the line number in source where the problem begins.
*
* @param lineNumber the given line number
* Unknown filename sentinel value
*/
void setSourceLineNumber(int lineNumber);
/**
* Set the start position of the problem (inclusive), or -1 if unknown.
* Used for shifting problem positions.
*
* @param the given start position
*/
void setSourceStart(int sourceStart);
public final static String FILENAME_NOT_PROVIDED = "<unknown>";
/**
* Problem Categories
@ -119,30 +113,237 @@ public interface IProblem extends ISourceElementCallbackDelegate {
* When a problem is tagged as Internal, it means that no change other than a local source code change
* can fix the corresponding problem.
*/
int TypeRelated = 0x01000000;
int FieldRelated = 0x02000000;
int MethodRelated = 0x04000000;
int ConstructorRelated = 0x08000000;
int ImportRelated = 0x10000000;
int Internal = 0x20000000;
int Syntax = 0x40000000;
/**
* IProblem relates to a valid error on the Scanner
*/
public final static int SCANNER_RELATED = 0x01000000;
/**
* IProblem relates to a valid error on the preprocessor
*/
public final static int PREPROCESSOR_RELATED = 0x02000000;
/**
* IProblem relates to a valid syntax error in the parser
*/
public final static int SYNTAX_RELATED = 0x04000000;
/**
* IProblem relates to a valid semantical error in the parser
*/
public final static int SEMANTICS_RELATED = 0x08000000;
/**
* IProblem relates to an implementation of design limitation
*/
public final static int INTERNAL_RELATED = 0x10000000;
/**
* Check the parameter bitmask against an IProblem's ID to broadly segregate the
* types of problems.
*
* @param bitmask
* @return true if ( (id & bitmask ) != 0 )
*/
public boolean checkCategory(int bitmask);
/**
* Mask to use in order to filter out the category portion of the problem ID.
*/
int IgnoreCategoriesMask = 0xFFFFFF;
public final static int IGNORE_CATEGORIES_MASK = 0xFFFFFF;
/**
* Below are listed all available problem attributes. The JavaDoc for each problem ID indicates
* when they should be contributed to creating a problem of that type.
*/
// Preprocessor IProblem attributes
/**
* The text that follows a #error preprocessor directive
*/
public final static String A_PREPROC_POUND_ERROR = "#error text";
/**
* The filename that failed somehow in an preprocessor include directive
*/
public final static String A_PREPROC_INCLUDE_FILENAME = "include file";
/**
* A preprocessor macro name
*/
public final static String A_PREPROC_MACRO_NAME = "macro name";
/**
* A preprocessor conditional that could not be evaluated
*
* #if X + Y == Z <== that one, if X, Y or Z are not defined
* #endif
*/
public final static String A_PREPROC_CONDITION = "preprocessor condition";
/**
* A preprocessor directive that could not be interpretted
*
* e.g. #blah
*/
public final static String A_PREPROC_UNKNOWN_DIRECTIVE = "bad preprocessor directive";
/**
* The preprocessor conditional statement that caused an unbalanced mismatch.
*
* #if X
* #else
* #else <=== that one
* #endif
*/
public final static String A_PREPROC_CONDITIONAL_MISMATCH = "conditional mismatch";
/**
* The Bad character encountered in scanner
*/
public static final String A_SCANNER_BADCHAR = null;
/**
* Below are listed all available problem IDs. Note that this list could be augmented in the future,
* as new features are added to the C/C++ core implementation.
*/
/*
* Scanner Problems
*/
/**
* Bad character encountered by Scanner.
* Required attributes: A_SCANNER_BADCHAR
* @see #A_SCANNER_BADCHAR
*/
public final static int SCANNER_BAD_CHARACTER = SCANNER_RELATED | 0x001;
/**
* Unbounded literal string encountered by Scanner.
* Required attributes: none.
*/
public final static int SCANNER_UNBOUNDED_STRING = SCANNER_RELATED | 0x002;
/**
* Invalid escape sequence encountered by Scanner.
* Required attributes: none.
*/
public final static int SCANNER_INVALID_ESCAPECHAR = SCANNER_RELATED | 0x003;
/**
* Bad floating point encountered by Scanner.
* Required attributes: none.
*/
public final static int SCANNER_BAD_FLOATING_POINT = SCANNER_RELATED | 0x004;
/**
* Bad hexidecimal encountered by Scanner.
* Required attributes: none.
*/
public final static int SCANNER_BAD_HEX_FORMAT = SCANNER_RELATED | 0x005;
/**
* Unexpected EOF encountered by Scanner.
* Required attributes: none.
*/
public final static int SCANNER_UNEXPECTED_EOF = SCANNER_RELATED | 0x006;
/*
* Preprocessor Problems
*/
/**
* #error encountered by Preprocessor.
* Required attributes: A_PREPROC_POUND_ERROR
* @see #A_PREPROC_POUND_ERROR
*/
public final static int PREPROCESSOR_POUND_ERROR = PREPROCESSOR_RELATED | 0x001;
/**
* Inclusion not found by Preprocessor.
* Required attributes: A_PREPROC_INCLUDE_FILENAME
* @see #A_PREPROC_INCLUDE_FILENAME
*/
public final static int PREPROCESSOR_INCLUSION_NOT_FOUND = PREPROCESSOR_RELATED | 0x002;
/**
* Macro definition not found by Preprocessor.
* Required attributes: A_PREPROC_MACRO_NAME
* @see #A_PREPROC_MACRO_NAME
*/
public final static int PREPROCESSOR_DEFINITION_NOT_FOUND = PREPROCESSOR_RELATED | 0x003;
/**
* Preprocessor conditionals seem unbalanced.
* Required attributes: A_PREPROC_CONDITIONAL_MISMATCH
* @see #A_PREPROC_CONDITIONAL_MISMATCH
*/
public final static int PREPROCESSOR_UNBALANCE_CONDITION = PREPROCESSOR_RELATED | 0x004;
/**
* Invalid format to Macro definition.
* Required attributes: A_PREPROC_MACRO_NAME
* @see #A_PREPROC_MACRO_NAME
*/
public final static int PREPROCESSOR_INVALID_MACRO_DEFN = PREPROCESSOR_RELATED | 0x005;
/**
* Invalid or unknown preprocessor directive encountered by Preprocessor.
* Required attributes: A_PREPROC_UNKNOWN_DIRECTIVE
* @see #A_PREPROC_UNKNOWN_DIRECTIVE
*/
public final static int PREPROCESSOR_INVALID_DIRECTIVE = PREPROCESSOR_RELATED | 0x006;
/**
* Invalid macro redefinition encountered by Preprocessor.
* Required attributes: A_PREPROC_MACRO_NAME
* @see #A_PREPROC_MACRO_NAME
*/
public final static int PREPROCESSOR_INVALID_MACRO_REDEFN = PREPROCESSOR_RELATED | 0x007;
/**
* Preprocessor Conditional cannot not be evaluated due.
* Required attributes: A_PREPROC_CONDITION
* @see #A_PREPROC_CONDITION
*/
public final static int PREPROCESSOR_CONDITIONAL_EVAL_ERROR = PREPROCESSOR_RELATED | 0x008;
/**
* Invalid macro usage encountered by Preprocessor.
* Required attributes: A_PREPROC_MACRO_NAME
* @see #A_PREPROC_MACRO_NAME
*/
public final static int PREPROCESSOR_MACRO_USAGE_ERROR = PREPROCESSOR_RELATED | 0x009;
/**
* Invalid Macro Pasting encountered by Preprocessor.
* Required attributes: A_PREPROC_MACRO_NAME
* @see #A_PREPROC_MACRO_NAME
*/
public final static int PREPROCESSOR_MACRO_PASTING_ERROR = PREPROCESSOR_RELATED | 0x00A;
/**
* Circular inclusion encountered by Preprocessor.
* Required attributes: A_PREPROC_INCLUDE_FILENAME
* @see #A_PREPROC_INCLUDE_FILENAME
*/
public final static int PREPROCESSOR_CIRCULAR_INCLUSION = PREPROCESSOR_RELATED | 0x00B;
/*
* Parser Syntactic Problems
*/
/*
* Parser Semantic Problems
*/
/**
* ID reserved for referencing an internal error inside the CCorePlugin implementation which
* may be surfaced as a problem associated with the translation unit which caused it to occur.
*/
int Unclassified = 0;
// detected task
int Task = Internal + 450;
public final static int UNCLASSIFIED_ERROR = 0;
}

View file

@ -1,27 +0,0 @@
/*
* Created on 25-Jun-2003
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package org.eclipse.cdt.core.parser;
/**
* @author vmozgin
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public interface IProblemReporter {
public ITranslationOptions getOptions();
public abstract void task(
String tag,
String message,
String priority,
int start,
int end,
int line,
ITranslationResult result);
}

View file

@ -1,21 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.parser;
/**
* Implementors are valid translation contexts from which we can
* escape in case of error:
* For example: method, type or translation unit.
*/
public interface IReferenceContext {
ITranslationResult translationResult();
}

View file

@ -23,8 +23,6 @@ public interface IScanner {
public IToken nextToken() throws ScannerException, EndOfFile;
public IToken nextToken( boolean next ) throws ScannerException, EndOfFile;
public void setLanguage( ParserLanguage value );
public int getCount();
public int getDepth();
@ -32,7 +30,6 @@ public interface IScanner {
public void setTokenizingMacroReplacementList(boolean b);
public void setThrowExceptionOnBadCharacterRead( boolean throwOnBad );
public void onParseEnd();
/**
* @param i
* @return

View file

@ -48,7 +48,7 @@ import org.eclipse.cdt.core.parser.ast.IASTVariableReference;
*/
public interface ISourceElementRequestor {
public void acceptProblem( IProblem problem );
public boolean acceptProblem( IProblem problem );
public void acceptMacro( IASTMacro macro );
public void acceptVariable( IASTVariable variable );

View file

@ -1,35 +0,0 @@
/*
* Created on 25-Jun-2003
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package org.eclipse.cdt.core.parser;
import java.util.Map;
/**
* @author vmozgin
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public interface ITranslationOptions {
/**
* Option IDs
*/
public static final String OPTION_TaskTags
= "org.eclipse.cdt.core.translation.taskTags"; //$NON-NLS-1$
public static final String OPTION_TaskPriorities
= "org.eclipse.cdt.core.translation.taskPriorities"; //$NON-NLS-1$
/**
* Initializing the compiler options with external settings
*/
public abstract void initialize(Map settings);
public abstract char[][] getTaskTags();
public abstract char[][] getTaskPriorities();
}

View file

@ -1,65 +0,0 @@
/*
* Created on 25-Jun-2003
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package org.eclipse.cdt.core.parser;
//import org.eclipse.cdt.core.model.ITranslationUnit;
/**
* @author vmozgin
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public interface ITranslationResult {
public abstract IProblem[] getAllProblems();
/**
* Answer the initial translation unit corresponding to the present translation result
*/
// public abstract ITranslationUnit getTranslationUnit();
/**
* Answer the initial file name
*/
public abstract char[] getFileName();
/**
* Answer the errors encountered during translation.
*/
public abstract IProblem[] getErrors();
/**
* Answer the problems (errors and warnings) encountered during translation.
*
* It is intended to be used only once all problems have been detected,
* and makes sure the problems slot as the exact size of the number of
* problems.
*/
public abstract IProblem[] getProblems();
/**
* Answer the tasks (TO-DO, ...) encountered during translation.
*
* It is intended to be used only once all problems have been detected,
* and makes sure the problems slot as the exact size of the number of
* problems.
*/
public abstract IProblem[] getTasks();
public abstract boolean hasErrors();
public abstract boolean hasProblems();
public abstract boolean hasSyntaxError();
public abstract boolean hasTasks();
public abstract boolean hasWarnings();
public abstract void record(IProblem newProblem, IReferenceContext referenceContext);
public abstract ITranslationResult tagAsAccepted();
}

View file

@ -11,22 +11,16 @@
package org.eclipse.cdt.core.parser;
import java.io.Reader;
import java.util.Map;
import org.eclipse.cdt.core.parser.ast.IASTFactory;
import org.eclipse.cdt.internal.core.parser.DefaultErrorHandlingPolicies;
import org.eclipse.cdt.internal.core.parser.LineOffsetReconciler;
import org.eclipse.cdt.internal.core.parser.NullSourceElementRequestor;
import org.eclipse.cdt.internal.core.parser.Parser;
import org.eclipse.cdt.internal.core.parser.Preprocessor;
import org.eclipse.cdt.internal.core.parser.QuickParseCallback;
import org.eclipse.cdt.internal.core.parser.Scanner;
import org.eclipse.cdt.internal.core.parser.TranslationOptions;
import org.eclipse.cdt.internal.core.parser.TranslationResult;
import org.eclipse.cdt.internal.core.parser.ast.complete.CompleteParseASTFactory;
import org.eclipse.cdt.internal.core.parser.ast.quick.QuickParseASTFactory;
import org.eclipse.cdt.internal.core.parser.problem.DefaultProblemFactory;
import org.eclipse.cdt.internal.core.parser.problem.ProblemReporter;
/**
@ -44,40 +38,25 @@ public class ParserFactory {
}
public static IParser createParser( IScanner scanner, ISourceElementRequestor callback, ParserMode mode, ParserLanguage language )
{
return createParser(scanner, callback, mode, language, null, null);
}
public static IParser createParser( IScanner scanner, ISourceElementRequestor callback, ParserMode mode, ParserLanguage language, IProblemReporter problemReporter, ITranslationResult unitResult )
{
ParserMode ourMode = ( (mode == null )? ParserMode.COMPLETE_PARSE : mode );
ISourceElementRequestor ourCallback = (( callback == null) ? new NullSourceElementRequestor() : callback );
return new Parser( scanner, ourCallback, ourMode, language, problemReporter, unitResult );
return new Parser( scanner, ourCallback, ourMode, language );
}
public static IScanner createScanner( Reader input, String fileName, IScannerInfo config, ParserMode mode, ParserLanguage language, ISourceElementRequestor requestor )
{
return createScanner(input, fileName, config, mode, language, requestor, null, null);
}
public static IScanner createScanner( Reader input, String fileName, IScannerInfo config, ParserMode mode, ParserLanguage language, ISourceElementRequestor requestor, IProblemReporter problemReporter, ITranslationResult unitResult )
{
ParserMode ourMode = ( (mode == null )? ParserMode.COMPLETE_PARSE : mode );
ISourceElementRequestor ourRequestor = (( requestor == null) ? new NullSourceElementRequestor() : requestor );
IScanner s = new Scanner( input, fileName, config, problemReporter, unitResult, ourRequestor, ourMode, language );
IScanner s = new Scanner( input, fileName, config, ourRequestor, ourMode, language );
return s;
}
public static IPreprocessor createPreprocessor( Reader input, String fileName, IScannerInfo info, ParserMode mode, ParserLanguage language, ISourceElementRequestor requestor )
{
return createPreprocessor(input, fileName, info, mode, language, requestor, null, null);
}
public static IPreprocessor createPreprocessor( Reader input, String fileName, IScannerInfo info, ParserMode mode, ParserLanguage language, ISourceElementRequestor requestor, IProblemReporter problemReporter, ITranslationResult unitResult )
{
ParserMode ourMode = ( (mode == null )? ParserMode.COMPLETE_PARSE : mode );
ISourceElementRequestor ourRequestor = (( requestor == null) ? new NullSourceElementRequestor() : requestor );
IPreprocessor s = new Preprocessor( input, fileName, info, ourRequestor, problemReporter, unitResult, ourMode, language );
IPreprocessor s = new Preprocessor( input, fileName, info, ourRequestor, ourMode, language );
return s;
}
@ -86,25 +65,9 @@ public class ParserFactory {
return new LineOffsetReconciler( input );
}
public static IProblemReporter createProblemReporter( Map options )
{
ITranslationOptions cOptions = new TranslationOptions(options);
IProblemReporter problemReporter = new ProblemReporter(
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
cOptions,
new DefaultProblemFactory()
);
return problemReporter;
}
public static ITranslationResult createTranslationResult( String fileName/*ITranslationUnit tu*/ )
{
return new TranslationResult( fileName /* tu */ );
}
public static IQuickParseCallback createQuickParseCallback()
{
return new QuickParseCallback();
}
}

View file

@ -10,169 +10,21 @@
******************************************************************************/
package org.eclipse.cdt.core.parser;
import java.util.HashMap;
import java.util.Map;
public class ScannerException extends Exception {
private final String info;
private final String fileName;
private final int offset;
private final static int OFFSET_NOT_PROVIDED = -1;
private final ErrorCode code;
private final IProblem problem;
public static class ErrorCode extends Enum
public ScannerException( IProblem p )
{
public static final ErrorCode POUND_ERROR = new ErrorCode( 0 );
public static final ErrorCode INCLUSION_NOT_FOUND = new ErrorCode( 1 );
public static final ErrorCode DEFINITION_NOT_FOUND = new ErrorCode( 2 );
public static final ErrorCode UNBALANCED_CONDITIONALS = new ErrorCode( 3 );
public static final ErrorCode MALFORMED_MACRO_DEFN = new ErrorCode( 4 );
public static final ErrorCode UNBOUNDED_STRING = new ErrorCode( 5 );
public static final ErrorCode BAD_FLOATING_POINT = new ErrorCode( 6 );
public static final ErrorCode BAD_HEXIDECIMAL_FORMAT = new ErrorCode( 7 );
public static final ErrorCode INVALID_PREPROCESSOR_DIRECTIVE = new ErrorCode( 8 );
public static final ErrorCode ATTEMPTED_REDEFINITION = new ErrorCode( 9 );
public static final ErrorCode INVALID_ESCAPE_CHARACTER_SEQUENCE = new ErrorCode( 11 );
public static final ErrorCode EXPRESSION_EVALUATION_ERROR = new ErrorCode( 12 );
public static final ErrorCode UNEXPECTED_EOF = new ErrorCode(13);
public static final ErrorCode MACRO_USAGE_ERROR = new ErrorCode( 14 );
public static final ErrorCode MACRO_PASTING_ERROR = new ErrorCode( 15 );
public static final ErrorCode CIRCULAR_INCLUSION = new ErrorCode( 16 );
public static final ErrorCode BAD_CHARACTER = new ErrorCode( 17 );
/**
* @param enumValue
*/
protected ErrorCode(int enumValue)
{
super(enumValue);
}
public boolean hasInfo()
{
if( this == ErrorCode.UNBALANCED_CONDITIONALS ||
this == ErrorCode.UNBOUNDED_STRING ||
this == ErrorCode.BAD_FLOATING_POINT ||
this == ErrorCode.BAD_HEXIDECIMAL_FORMAT ||
this == ErrorCode.INVALID_PREPROCESSOR_DIRECTIVE ||
this == ErrorCode.UNEXPECTED_EOF ||
this == ErrorCode.MACRO_PASTING_ERROR )
return false;
return true;
}
public boolean hasOffsetInfo()
{
if( this == INCLUSION_NOT_FOUND || this == POUND_ERROR )
return false;
return true;
}
/**
* @param mode
* @return
*/
public boolean isSeriousError(ParserMode mode)
{
if(this == ErrorCode.INVALID_PREPROCESSOR_DIRECTIVE)
return true;
if( mode == ParserMode.COMPLETE_PARSE )
if( this == ErrorCode.POUND_ERROR ||
this == ErrorCode.UNBALANCED_CONDITIONALS ||
this == ErrorCode.MALFORMED_MACRO_DEFN ||
this == ErrorCode.UNEXPECTED_EOF ||
this == ErrorCode.MACRO_USAGE_ERROR ||
this == ErrorCode.MACRO_PASTING_ERROR ||
this == ErrorCode.EXPRESSION_EVALUATION_ERROR )
return true;
return false;
}
}
public ScannerException( ErrorCode code )
{
this( code, "", "UNKNOWN", OFFSET_NOT_PROVIDED );
}
public ScannerException( ErrorCode code, String info )
{
this( code, info, "UNKNOWN", OFFSET_NOT_PROVIDED );
}
public ScannerException( ErrorCode code, String fileName, int offset )
{
this( code, "", fileName, offset );
}
static Map errorMessages = new HashMap();
static {
errorMessages.put( ErrorCode.POUND_ERROR, "#error " );
errorMessages.put( ErrorCode.INCLUSION_NOT_FOUND, "Inclusion not found: " );
errorMessages.put( ErrorCode.DEFINITION_NOT_FOUND, "Definition not found: " );
errorMessages.put( ErrorCode.MALFORMED_MACRO_DEFN, "Macro definition malformed: " );
errorMessages.put( ErrorCode.ATTEMPTED_REDEFINITION, "" );
errorMessages.put( ErrorCode.INVALID_ESCAPE_CHARACTER_SEQUENCE, "" );
errorMessages.put( ErrorCode.EXPRESSION_EVALUATION_ERROR, "" );
errorMessages.put( ErrorCode.MACRO_USAGE_ERROR, "" );
errorMessages.put( ErrorCode.CIRCULAR_INCLUSION, "" );
errorMessages.put( ErrorCode.UNBALANCED_CONDITIONALS , "Conditionals unbalanced " );
errorMessages.put( ErrorCode.UNBOUNDED_STRING, "Unbounded string " );
errorMessages.put( ErrorCode.BAD_FLOATING_POINT, "Invalid floating point format " );
errorMessages.put( ErrorCode.BAD_HEXIDECIMAL_FORMAT, "Invalid hexidecimal format " );
errorMessages.put( ErrorCode.INVALID_PREPROCESSOR_DIRECTIVE, "Invalid preprocessor directive format " );
errorMessages.put( ErrorCode.UNEXPECTED_EOF, "Unexpected End Of File " );
errorMessages.put( ErrorCode.MACRO_PASTING_ERROR, "Invalid use of macro pasting " );
errorMessages.put( ErrorCode.BAD_CHARACTER, "Bad character sequence encountered:");
}
public ScannerException( ErrorCode code, String info, String fileName, int offset )
{
this.code = code;
this.info = info;
this.fileName = fileName;
this.offset = offset;
}
/**
* @return
*/
public ErrorCode getErrorCode()
{
return code;
}
public String getMessage()
{
StringBuffer buff = new StringBuffer();
String errorMessage = (String)errorMessages.get( getErrorCode() );
if( errorMessage == null ) return "";
buff.append( errorMessage );
if( getErrorCode().hasInfo() )
buff.append( info );
if( getErrorCode().hasOffsetInfo() )
{
buff.append( "from file: ");
buff.append( fileName );
buff.append( " offset @ ");
buff.append( offset );
}
return buff.toString();
}
public boolean isSeriousError( ParserMode mode )
{
return getErrorCode().isSeriousError( mode );
problem = p;
}
/**
* @return
*/
public String getInfoString()
public IProblem getProblem()
{
return info;
return problem;
}
}

View file

@ -26,6 +26,7 @@ public interface IASTFactory
int startingOffset,
int nameOffset,
int nameEndOffset, int endingOffset) ;
public IASTInclusion createInclusion(
String name,
String fileName,
@ -33,19 +34,23 @@ public interface IASTFactory
int startingOffset,
int nameOffset,
int nameEndOffset, int endingOffset) ;
public IASTUsingDirective createUsingDirective(
IASTScope scope,
ITokenDuple duple, int startingOffset, int endingOffset)
throws ASTSemanticException;
public IASTUsingDeclaration createUsingDeclaration(
IASTScope scope,
boolean isTypeName,
ITokenDuple name, int startingOffset, int endingOffset) throws ASTSemanticException;
public IASTASMDefinition createASMDefinition(
IASTScope scope,
String assembly,
int first,
int last);
public IASTNamespaceDefinition createNamespaceDefinition(
IASTScope scope,
String identifier,
@ -61,9 +66,11 @@ public interface IASTFactory
int nameEndOffset, int endOffset ) throws ASTSemanticException;
public IASTCompilationUnit createCompilationUnit() ;
public IASTLinkageSpecification createLinkageSpecification(
IASTScope scope,
String spec, int startingOffset) ;
public IASTClassSpecifier createClassSpecifier(
IASTScope scope,
ITokenDuple name,
@ -72,6 +79,7 @@ public interface IASTFactory
ASTAccessVisibility access,
int startingOffset,
int nameOffset, int nameEndOffset) throws ASTSemanticException;
/**
* @param astClassSpec
* @param isVirtual
@ -83,20 +91,24 @@ public interface IASTFactory
boolean isVirtual,
ASTAccessVisibility visibility,
ITokenDuple parentClassName) throws ASTSemanticException;
public IASTElaboratedTypeSpecifier createElaboratedTypeSpecifier(
IASTScope scope,
ASTClassKind elaboratedClassKind,
ITokenDuple typeName,
int startingOffset, int endOffset, boolean isForewardDecl) throws ASTSemanticException;
public IASTEnumerationSpecifier createEnumerationSpecifier(
IASTScope scope,
String name,
int startingOffset, int nameOffset, int nameEndOffset) throws ASTSemanticException;
public void addEnumerator(
IASTEnumerationSpecifier enumeration,
String string,
int startingOffset,
int nameOffset, int nameEndOffset, int endingOffset, IASTExpression initialValue)throws ASTSemanticException;
public IASTExpression createExpression(
IASTScope scope,
IASTExpression.Kind kind,
@ -105,24 +117,31 @@ public interface IASTFactory
IASTExpression thirdExpression,
IASTTypeId typeId,
ITokenDuple idExpression, String literal, IASTNewExpressionDescriptor newDescriptor) throws ASTSemanticException;
public IASTExpression.IASTNewExpressionDescriptor createNewDescriptor(List newPlacementExpressions,List newTypeIdExpressions,List newInitializerExpressions);
public IASTInitializerClause createInitializerClause(
IASTScope scope,
IASTInitializerClause.Kind kind,
IASTExpression assignmentExpression, List initializerClauses, List designators) ;
public IASTExceptionSpecification createExceptionSpecification(IASTScope scope, List typeIds) throws ASTSemanticException;
/**
* @param exp
*/
public IASTArrayModifier createArrayModifier(IASTExpression exp) ;
/**
* @param duple
* @param expressionList
* @return
*/
public IASTConstructorMemberInitializer createConstructorMemberInitializer(
IASTScope scope,
ITokenDuple duple, IASTExpression expressionList) throws ASTSemanticException;
public IASTSimpleTypeSpecifier createSimpleTypeSpecifier(
IASTScope scope,
IASTSimpleTypeSpecifier.Type kind,
@ -131,6 +150,7 @@ public interface IASTFactory
boolean isLong,
boolean isSigned,
boolean isUnsigned, boolean isTypename, boolean isComplex, boolean isImaginary) throws ASTSemanticException;
public IASTFunction createFunction(
IASTScope scope,
ITokenDuple name,
@ -149,11 +169,14 @@ public interface IASTFactory
boolean isVirtual,
boolean isExplicit,
boolean isPureVirtual, List constructorChain, boolean isDefinition, boolean hasFunctionTryBlock ) throws ASTSemanticException;
public IASTAbstractDeclaration createAbstractDeclaration(
boolean isConst,
boolean isVolatile,
IASTTypeSpecifier typeSpecifier,
List pointerOperators, List arrayModifiers, List parameters, ASTPointerOperator pointerOperator);
public IASTMethod createMethod(
IASTScope scope,
String name,
@ -210,6 +233,4 @@ public interface IASTFactory
* @param astClassSpecifier
*/
public void signalEndOfClassSpecifier(IASTClassSpecifier astClassSpecifier);
}

View file

@ -0,0 +1,66 @@
/**********************************************************************
* Copyright (c) 2002,2003 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Rational Software - Initial API and implementation
***********************************************************************/
package org.eclipse.cdt.internal.core.parser;
import java.util.Map;
import org.eclipse.cdt.core.parser.IProblem;
/**
* @author jcamelon
*
*/
public abstract class BaseProblemFactory {
protected final static String PROBLEM = "IProblem : ";
protected final static String IN_FILE = " in file: ";
protected final static String ON_LINE = " on line: ";
public abstract String createMessage(int id, Map arguments, int lineNumber, char[] fileName );
public IProblem createProblem(int id, int start, int end, int line, char[] file, String message, Map arguments, boolean warn, boolean error) {
return new Problem( id, start, end, line, file, message, arguments, warn, error);
}
public boolean checkBitmask( int id, int bitmask )
{
return ( id & bitmask ) != 0;
}
protected IProblem createInternalProblem( int id, int start, int end, int line, char [] file, Map arguments, boolean warn, boolean error )
{
return createProblem( id, start, end, line, file, createInternalMessage( id, arguments, line, file), arguments, warn, error );
}
/**
* @param id
* @param arguments
* @param line
* @param file
* @return
*/
private String createInternalMessage(int id, Map arguments, int line, char[] file)
{
if( checkBitmask( id, IProblem.INTERNAL_RELATED ))
{
StringBuffer buffer = new StringBuffer();
switch( id )
{
}
return buffer.toString();
}
return null;
}
}

View file

@ -3,8 +3,6 @@ package org.eclipse.cdt.internal.core.parser;
import java.util.EmptyStackException;
import java.util.Stack;
import org.eclipse.cdt.core.parser.ScannerException;
/**
* @author jcamelon
*
@ -65,7 +63,7 @@ public class BranchTracker {
}
}
public boolean poundelif( boolean taken ) throws ScannerException
public boolean poundelif( boolean taken ) throws EmptyStackException
{
if( ignore != IGNORE_SENTINEL && ignore < branches.size() )
{
@ -79,14 +77,7 @@ public class BranchTracker {
// --> ignore >= branches.size()
// check the branch queue to see whether or not the branch has already been taken
Boolean branchAlreadyTaken;
try
{
branchAlreadyTaken = (Boolean) branches.peek();
}
catch( EmptyStackException ese )
{
throw new ScannerException( ScannerException.ErrorCode.UNBALANCED_CONDITIONALS );
}
if( ignore == IGNORE_SENTINEL )
{
@ -119,7 +110,7 @@ public class BranchTracker {
return false;
}
public boolean poundelse() throws ScannerException
public boolean poundelse() throws EmptyStackException
{
if( ignore != IGNORE_SENTINEL && ignore < branches.size() )
{
@ -129,14 +120,7 @@ public class BranchTracker {
}
Boolean branchAlreadyTaken;
try
{
branchAlreadyTaken = (Boolean) branches.peek();
}
catch( EmptyStackException ese )
{
throw new ScannerException( ScannerException.ErrorCode.UNBALANCED_CONDITIONALS );
}
if( ignore == IGNORE_SENTINEL )
{

View file

@ -0,0 +1,37 @@
/**********************************************************************
* Copyright (c) 2002,2003 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Rational Software - Initial API and implementation
***********************************************************************/
package org.eclipse.cdt.internal.core.parser;
/**
* @author jcamelon
*
*/
public class ContextException extends Exception
{
private final int id;
/**
* @param i
*/
public ContextException(int i)
{
id = i;
}
/**
* @return
*/
public int getId()
{
return id;
}
}

View file

@ -18,8 +18,8 @@ import java.util.LinkedList;
import java.util.Set;
import java.util.Stack;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.ISourceElementRequestor;
import org.eclipse.cdt.core.parser.ScannerException;
import org.eclipse.cdt.core.parser.ast.IASTInclusion;
import org.eclipse.cdt.internal.core.model.IDebugLogConstants;
import org.eclipse.cdt.internal.core.model.Util;
@ -36,11 +36,11 @@ public class ContextStack {
super();
}
public void updateContext(Reader reader, String filename, int type, IASTInclusion inclusion, ISourceElementRequestor requestor) throws ScannerException {
public void updateContext(Reader reader, String filename, int type, IASTInclusion inclusion, ISourceElementRequestor requestor) throws ContextException {
updateContext(reader, filename, type, inclusion, requestor, -1, -1);
}
public void updateContext(Reader reader, String filename, int type, IASTInclusion inclusion, ISourceElementRequestor requestor, int macroOffset, int macroLength) throws ScannerException
public void updateContext(Reader reader, String filename, int type, IASTInclusion inclusion, ISourceElementRequestor requestor, int macroOffset, int macroLength) throws ContextException
{
int startLine = 1;
@ -61,18 +61,18 @@ public class ContextStack {
push( context, requestor );
}
protected void push( IScannerContext context, ISourceElementRequestor requestor ) throws ScannerException
protected void push( IScannerContext context, ISourceElementRequestor requestor ) throws ContextException
{
if( context.getKind() == IScannerContext.INCLUSION )
{
if( !inclusions.add( context.getFilename() ) )
throw new ScannerException( ScannerException.ErrorCode.CIRCULAR_INCLUSION, context.getFilename() );
throw new ContextException( IProblem.PREPROCESSOR_CIRCULAR_INCLUSION );
context.getExtension().enterScope( requestor );
} else if( context.getKind() == IScannerContext.MACROEXPANSION )
{
if( !defines.add( context.getFilename() ) )
throw new ScannerException( ScannerException.ErrorCode.MALFORMED_MACRO_DEFN, context.getFilename() );
throw new ContextException( IProblem.PREPROCESSOR_INVALID_MACRO_DEFN );
}
if( currentContext != null )
contextStack.push(currentContext);
@ -109,7 +109,7 @@ public class ContextStack {
return true;
}
public void undoRollback( IScannerContext undoTo, ISourceElementRequestor requestor ) throws ScannerException {
public void undoRollback( IScannerContext undoTo, ISourceElementRequestor requestor ) throws ContextException {
if( currentContext == undoTo ){
return;
}
@ -159,4 +159,33 @@ public class ContextStack {
return topContext;
}
public IScannerContext getMostRelevantFileContext()
{
if( currentContext != null )
{
if( currentContext.getKind() == IScannerContext.TOP ) return currentContext;
if( currentContext.getKind() == IScannerContext.INCLUSION ) return currentContext;
}
IScannerContext context = null;
for( int i = contextStack.size() - 1; i >= 0; --i )
{
context = (IScannerContext)contextStack.get(i);
if( context.getKind() == IScannerContext.INCLUSION || context.getKind() == IScannerContext.TOP )
break;
if( i == 0 ) context = null;
}
return context;
}
public int getCurrentLineNumber()
{
return getMostRelevantFileContext() != null ? getMostRelevantFileContext().getLine() : -1;
}
public int getTopFileLineNumber()
{
return topContext.getLine();
}
}

View file

@ -1,78 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.parser;
public class DefaultErrorHandlingPolicies {
/**
* Accumulate all problems, then exit without proceeding.
*
* Typically, the #proceedWithProblems(Problem[]) should
* show the problems.
*
*/
public static IErrorHandlingPolicy exitAfterAllProblems() {
return new IErrorHandlingPolicy() {
public boolean stopOnFirstError() {
return false;
}
public boolean proceedOnErrors(){
return false;
}
};
}
/**
* Exit without proceeding on the first problem wich appears
* to be an error.
*
*/
public static IErrorHandlingPolicy exitOnFirstError() {
return new IErrorHandlingPolicy() {
public boolean stopOnFirstError() {
return true;
}
public boolean proceedOnErrors(){
return false;
}
};
}
/**
* Proceed on the first error met.
*
*/
public static IErrorHandlingPolicy proceedOnFirstError() {
return new IErrorHandlingPolicy() {
public boolean stopOnFirstError() {
return true;
}
public boolean proceedOnErrors(){
return true;
}
};
}
/**
* Accumulate all problems, then proceed with them.
*
*/
public static IErrorHandlingPolicy proceedWithAllProblems() {
return new IErrorHandlingPolicy() {
public boolean stopOnFirstError() {
return false;
}
public boolean proceedOnErrors(){
return true;
}
};
}
}

View file

@ -1,28 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.parser;
/**
* Handler policy is responsible to answer the 2 following
* questions:
* 1. should the handler stop on first problem which appears
* to be a real error (that is, not a warning),
* 2. should it proceed once it has gathered all problems
*
* The intent is that one can supply its own policy to implement
* some interactive error handling strategy where some UI would
* display problems and ask user if he wants to proceed or not.
*/
public interface IErrorHandlingPolicy {
boolean proceedOnErrors();
boolean stopOnFirstError();
}

View file

@ -1,41 +1,26 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
/**********************************************************************
* Copyright (c) 2002,2003 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
* IBM Rational Software - Initial API and implementation
***********************************************************************/
package org.eclipse.cdt.internal.core.parser;
import java.util.Locale;
import java.util.Map;
import org.eclipse.cdt.core.parser.IProblem;
/**
* Factory used during translation to build the actual problems
* which are handed back in the translation result.
* @author jcamelon
*
* This allows sharing the internal problem representation with the environment.
*
* Note: The factory is responsible for computing and storing a localized error message.
*/
public interface IProblemFactory {
IProblem createProblem(
char[] originatingFileName,
int problemId,
String[] problemArguments,
String[] messageArguments, // shorter versions of the problemArguments
int severity,
int startPosition,
int endPosition,
int lineNumber);
public IProblem createProblem( int id, int start, int end, int line, char [] file, Map arguments, boolean warn, boolean error );
public String [] getRequiredAttributesForId( int id );
Locale getLocale();
String getLocalizedMessage(int problemId, String[] messageArguments);
}

View file

@ -23,6 +23,7 @@ import org.eclipse.cdt.core.parser.IOffsetDuple;
public class LineOffsetReconciler implements ILineOffsetReconciler
{
private Reader ourReader;
int currentOffset = 0;
/**
* @param input
*/
@ -36,11 +37,14 @@ public class LineOffsetReconciler implements ILineOffsetReconciler
*/
public int getLineNumberForOffset(int offset)
{
if( offset < currentOffset )
resetReader();
int lineNumber = 1;
for( int i = 0; i < offset; ++i )
for( int i = currentOffset; i < offset; ++i )
{
int c = getChar();
if( c == -1 )
return -1;
if( c == '\n' )
++lineNumber;
}
@ -53,11 +57,11 @@ public class LineOffsetReconciler implements ILineOffsetReconciler
try
{
c = ourReader.read();
++currentOffset;
}
catch (IOException e)
{
throw new Error( "Could not read");
return -1;
}
return c;
}
@ -66,6 +70,7 @@ public class LineOffsetReconciler implements ILineOffsetReconciler
try
{
ourReader.reset();
currentOffset = 0;
}
catch (IOException e)
{

View file

@ -1,7 +1,9 @@
package org.eclipse.cdt.internal.core.parser;
import org.eclipse.cdt.core.parser.DefaultProblemHandler;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.ISourceElementRequestor;
import org.eclipse.cdt.core.parser.ParserMode;
import org.eclipse.cdt.core.parser.ast.IASTASMDefinition;
import org.eclipse.cdt.core.parser.ast.IASTAbstractTypeSpecifierDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTClassReference;
@ -37,14 +39,22 @@ import org.eclipse.cdt.core.parser.ast.IASTVariableReference;
public class NullSourceElementRequestor implements ISourceElementRequestor
{
private ParserMode mode = ParserMode.COMPLETE_PARSE;
public NullSourceElementRequestor()
{
}
public NullSourceElementRequestor( ParserMode mode )
{
this.mode = mode;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ISourceElementRequestor#acceptProblem(org.eclipse.cdt.core.parser.IProblem)
*/
public void acceptProblem(IProblem problem)
public boolean acceptProblem(IProblem problem)
{
// TODO Auto-generated method stub
return DefaultProblemHandler.ruleOnProblem( problem, mode );
}
/* (non-Javadoc)

View file

@ -18,12 +18,10 @@ import org.eclipse.cdt.core.ICLogConstants;
import org.eclipse.cdt.core.parser.Backtrack;
import org.eclipse.cdt.core.parser.EndOfFile;
import org.eclipse.cdt.core.parser.IParser;
import org.eclipse.cdt.core.parser.IProblemReporter;
import org.eclipse.cdt.core.parser.IScanner;
import org.eclipse.cdt.core.parser.ISourceElementRequestor;
import org.eclipse.cdt.core.parser.IToken;
import org.eclipse.cdt.core.parser.ITokenDuple;
import org.eclipse.cdt.core.parser.ITranslationResult;
import org.eclipse.cdt.core.parser.ParserFactory;
import org.eclipse.cdt.core.parser.ParserLanguage;
import org.eclipse.cdt.core.parser.ParserMode;
@ -88,8 +86,6 @@ public class Parser implements IParser
private ISourceElementRequestor requestor = null;
// new callback mechanism
private IASTFactory astFactory = null; // ast factory
private IProblemReporter problemReporter = null;
private ITranslationResult unitResult = null;
/**
* This is the single entry point for setting parsePassed to
* false, and also making note what token offset we failed upon.
@ -123,13 +119,9 @@ public class Parser implements IParser
IScanner scanner,
ISourceElementRequestor callback,
ParserMode mode,
ParserLanguage language,
IProblemReporter problemReporter,
ITranslationResult unitResult)
ParserLanguage language )
{
this.scanner = scanner;
this.problemReporter = problemReporter;
this.unitResult = unitResult;
requestor = callback;
this.mode = mode;
this.language = language;
@ -145,7 +137,6 @@ public class Parser implements IParser
{
long startTime = System.currentTimeMillis();
translationUnit();
onParseEnd();
// For the debuglog to take place, you have to call
// Util.setDebugging(true);
// Or set debug to true in the core plugin preference
@ -158,10 +149,7 @@ public class Parser implements IParser
+ (parsePassed ? "" : " - parse failure"), IDebugLogConstants.PARSER);
return parsePassed;
}
public void onParseEnd()
{
scanner.onParseEnd();
}
/**
* This is the top-level entry point into the ANSI C++ grammar.
*
@ -5156,11 +5144,7 @@ public class Parser implements IParser
{
Util.debugLog( "ScannerException thrown : " + e.getMessage(), IDebugLogConstants.PARSER );
org.eclipse.cdt.internal.core.model.Util.log(e, "Scanner Exception: " + e.getMessage() , ICLogConstants.CDT); //$NON-NLS-1$h
if( e.isSeriousError(mode) )
{
failParse();
throw endOfFile;
}
return fetchToken();
}
}
@ -5262,8 +5246,6 @@ public class Parser implements IParser
public void setLanguage( ParserLanguage l )
{
language = l;
if (scanner != null)
scanner.setLanguage( l );
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.parser.IParser#getLastErrorOffset()

View file

@ -15,10 +15,8 @@ import java.io.Reader;
import org.eclipse.cdt.core.ICLogConstants;
import org.eclipse.cdt.core.parser.EndOfFile;
import org.eclipse.cdt.core.parser.IPreprocessor;
import org.eclipse.cdt.core.parser.IProblemReporter;
import org.eclipse.cdt.core.parser.IScannerInfo;
import org.eclipse.cdt.core.parser.ISourceElementRequestor;
import org.eclipse.cdt.core.parser.ITranslationResult;
import org.eclipse.cdt.core.parser.ParserLanguage;
import org.eclipse.cdt.core.parser.ParserMode;
import org.eclipse.cdt.core.parser.ScannerException;
@ -35,8 +33,8 @@ public class Preprocessor extends Scanner implements IPreprocessor {
* @param filename
* @param defns
*/
public Preprocessor(Reader reader, String filename, IScannerInfo info, ISourceElementRequestor requestor, IProblemReporter problemReporter, ITranslationResult unitResult, ParserMode mode, ParserLanguage language ) {
super(reader, filename, info, problemReporter, unitResult, requestor, mode, language );
public Preprocessor(Reader reader, String filename, IScannerInfo info, ISourceElementRequestor requestor, ParserMode mode, ParserLanguage language ) {
super(reader, filename, info, requestor, mode, language );
}
public void process()

View file

@ -0,0 +1,118 @@
/**********************************************************************
* Copyright (c) 2002,2003 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Rational Software - Initial API and implementation
***********************************************************************/
package org.eclipse.cdt.internal.core.parser;
import java.util.Map;
import org.eclipse.cdt.core.parser.IProblem;
/**
* @author jcamelon
*
*/
public class Problem implements IProblem {
private final Map arguments;
private final int id;
private final int sourceStart;
private final int sourceEnd;
private final int lineNumber;
private final boolean isError;
private final boolean isWarning;
private final char[] originatingFileName;
private final String message;
public Problem( int id, int start, int end, int line, char [] file, String message, Map arguments, boolean warn, boolean error )
{
this.id = id;
this.sourceStart = start;
this.sourceEnd = end;
this.lineNumber = line;
this.originatingFileName = file;
this.message = message;
this.arguments = arguments;
this.isWarning = warn;
this.isError = error;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.IProblem#getID()
*/
public int getID() {
return id;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.IProblem#getOriginatingFileName()
*/
public char[] getOriginatingFileName() {
return originatingFileName;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.IProblem#getSourceEnd()
*/
public int getSourceEnd() {
return sourceEnd;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.IProblem#getSourceLineNumber()
*/
public int getSourceLineNumber() {
return lineNumber;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.IProblem#getSourceStart()
*/
public int getSourceStart() {
return sourceStart;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.IProblem#isError()
*/
public boolean isError() {
return isError;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.IProblem#isWarning()
*/
public boolean isWarning() {
return isWarning;
}
public String getMessage()
{
return message;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.IProblem#checkCategory(int)
*/
public boolean checkCategory(int bitmask) {
return ((id & bitmask) != 0 );
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.IProblem#getArguments()
*/
public Map getArguments() {
return arguments;
}
}

View file

@ -0,0 +1,228 @@
/**********************************************************************
* Copyright (c) 2002,2003 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Rational Software - Initial API and implementation
***********************************************************************/
package org.eclipse.cdt.internal.core.parser;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.cdt.core.parser.IProblem;
/**
* @author jcamelon
*
*/
public class ScannerProblemFactory extends BaseProblemFactory implements IProblemFactory
{
protected static Map errorMessages = new HashMap();
static {
errorMessages.put(
new Integer(IProblem.PREPROCESSOR_POUND_ERROR),
"#error encountered with text: ");
errorMessages.put(
new Integer(IProblem.PREPROCESSOR_INCLUSION_NOT_FOUND),
"Preprocessor Inclusion not found: ");
errorMessages.put(
new Integer(IProblem.PREPROCESSOR_DEFINITION_NOT_FOUND),
"Macro definition not found: ");
errorMessages.put(
new Integer(IProblem.PREPROCESSOR_INVALID_MACRO_DEFN),
"Macro definition malformed for macro: ");
errorMessages.put(
new Integer(IProblem.PREPROCESSOR_INVALID_MACRO_REDEFN),
"Invalid macro redefinition for macro : ");
errorMessages.put(
new Integer(IProblem.PREPROCESSOR_UNBALANCE_CONDITION),
"Preprocessor Conditionals unbalanced : ");
errorMessages.put(
new Integer(IProblem.PREPROCESSOR_CONDITIONAL_EVAL_ERROR),
"Expression Evaluation error for condition : ");
errorMessages.put(
new Integer(IProblem.PREPROCESSOR_MACRO_USAGE_ERROR),
"Macro usage error for macro :");
errorMessages.put(
new Integer(IProblem.PREPROCESSOR_CIRCULAR_INCLUSION),
"Circular inclusion for file : ");
errorMessages.put(
new Integer(IProblem.PREPROCESSOR_INVALID_DIRECTIVE),
"Invalid preprocessor directive : ");
errorMessages.put(
new Integer(IProblem.PREPROCESSOR_MACRO_PASTING_ERROR),
"Invalid use of macro pasting in macro : ");
errorMessages.put(
new Integer(IProblem.SCANNER_INVALID_ESCAPECHAR),
"Invalid escape character encountered ");
errorMessages.put(
new Integer(IProblem.SCANNER_UNBOUNDED_STRING),
"Unbounded string encountered ");
errorMessages.put(
new Integer(IProblem.SCANNER_BAD_FLOATING_POINT),
"Invalid floating point format encountered ");
errorMessages.put(
new Integer(IProblem.SCANNER_BAD_HEX_FORMAT),
"Invalid hexidecimal format encountered ");
errorMessages.put(
new Integer(IProblem.SCANNER_UNEXPECTED_EOF),
"Unexpected End Of File encountered ");
errorMessages.put(
new Integer(IProblem.SCANNER_BAD_CHARACTER),
"Bad character sequence encountered : ");
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.parser.BaseProblemFactory#createMessage()
*/
public String createMessage(int id, Map arguments, int lineNumber, char[] fileName)
{
StringBuffer buffer = new StringBuffer();
buffer.append(PROBLEM);
buffer.append(errorMessages.get(new Integer(id)));
switch (id)
{
case IProblem.PREPROCESSOR_POUND_ERROR :
buffer.append(arguments.get(IProblem.A_PREPROC_POUND_ERROR));
break;
case IProblem.PREPROCESSOR_INCLUSION_NOT_FOUND :
buffer.append(arguments.get(IProblem.A_PREPROC_INCLUDE_FILENAME));
break;
case IProblem.PREPROCESSOR_DEFINITION_NOT_FOUND :
buffer.append(arguments.get(IProblem.A_PREPROC_MACRO_NAME));
break;
case IProblem.PREPROCESSOR_UNBALANCE_CONDITION :
buffer.append(arguments.get(IProblem.A_PREPROC_CONDITIONAL_MISMATCH));
break;
case IProblem.PREPROCESSOR_INVALID_MACRO_DEFN :
buffer.append(arguments.get(IProblem.A_PREPROC_MACRO_NAME));
break;
case IProblem.PREPROCESSOR_INVALID_DIRECTIVE :
buffer.append(arguments.get(IProblem.A_PREPROC_UNKNOWN_DIRECTIVE));
break;
case IProblem.PREPROCESSOR_INVALID_MACRO_REDEFN :
buffer.append(arguments.get(IProblem.A_PREPROC_MACRO_NAME));
break;
case IProblem.PREPROCESSOR_CONDITIONAL_EVAL_ERROR :
buffer.append(arguments.get(IProblem.A_PREPROC_CONDITION));
break;
case IProblem.PREPROCESSOR_MACRO_USAGE_ERROR :
buffer.append(arguments.get(IProblem.A_PREPROC_MACRO_NAME));
break;
case IProblem.PREPROCESSOR_MACRO_PASTING_ERROR :
buffer.append(arguments.get(IProblem.A_PREPROC_MACRO_NAME));
break;
case IProblem.PREPROCESSOR_CIRCULAR_INCLUSION :
buffer.append(arguments.get(IProblem.A_PREPROC_INCLUDE_FILENAME));
break;
case IProblem.SCANNER_BAD_CHARACTER :
buffer.append( arguments.get(IProblem.A_SCANNER_BADCHAR));
break;
case IProblem.SCANNER_UNBOUNDED_STRING :
case IProblem.SCANNER_INVALID_ESCAPECHAR :
case IProblem.SCANNER_BAD_FLOATING_POINT :
case IProblem.SCANNER_BAD_HEX_FORMAT :
case IProblem.SCANNER_UNEXPECTED_EOF :
break;
default :
return null;
}
buffer.append( IN_FILE );
buffer.append(fileName);
buffer.append( ON_LINE );
buffer.append(lineNumber);
return buffer.toString();
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.parser.IProblemFactory#createProblem(int, int, int, int, char[], java.lang.String, boolean, boolean)
*/
public IProblem createProblem(
int id,
int start,
int end,
int line,
char[] file,
Map arguments,
boolean warn,
boolean error)
{
if( checkBitmask( id, IProblem.INTERNAL_RELATED ) )
return createInternalProblem( id, start, end, line, file, arguments, warn, error );
if ( checkBitmask( id, IProblem.SCANNER_RELATED ) ||
checkBitmask( id, IProblem.PREPROCESSOR_RELATED ) )
return super.createProblem(
id,
start,
end,
line,
file,
createMessage(id, arguments, line, file),
arguments,
warn,
error);
return null;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.parser.IProblemFactory#getRequiredAttributesForId(int)
*/
public String[] getRequiredAttributesForId(int id)
{
String [] result = new String[1];
switch (id)
{
case IProblem.PREPROCESSOR_POUND_ERROR :
result[0] = IProblem.A_PREPROC_POUND_ERROR;
break;
case IProblem.PREPROCESSOR_INCLUSION_NOT_FOUND :
result[0] = IProblem.A_PREPROC_INCLUDE_FILENAME;
break;
case IProblem.PREPROCESSOR_DEFINITION_NOT_FOUND :
result[0] = IProblem.A_PREPROC_MACRO_NAME;
break;
case IProblem.PREPROCESSOR_UNBALANCE_CONDITION :
result[0] = IProblem.A_PREPROC_CONDITIONAL_MISMATCH;
break;
case IProblem.PREPROCESSOR_INVALID_MACRO_DEFN :
result[0] = IProblem.A_PREPROC_MACRO_NAME;
break;
case IProblem.PREPROCESSOR_INVALID_DIRECTIVE :
result[0] = IProblem.A_PREPROC_UNKNOWN_DIRECTIVE;
break;
case IProblem.PREPROCESSOR_INVALID_MACRO_REDEFN :
result[0] = IProblem.A_PREPROC_MACRO_NAME;
break;
case IProblem.PREPROCESSOR_CONDITIONAL_EVAL_ERROR :
result[0] = IProblem.A_PREPROC_CONDITION;
break;
case IProblem.PREPROCESSOR_MACRO_USAGE_ERROR :
result[0] = IProblem.A_PREPROC_MACRO_NAME;
break;
case IProblem.PREPROCESSOR_MACRO_PASTING_ERROR :
result[0] = IProblem.A_PREPROC_MACRO_NAME;
break;
case IProblem.PREPROCESSOR_CIRCULAR_INCLUSION :
result[0] = IProblem.A_PREPROC_INCLUDE_FILENAME;
break;
case IProblem.SCANNER_BAD_CHARACTER :
result[0] = IProblem.A_SCANNER_BADCHAR;
break;
case IProblem.SCANNER_UNBOUNDED_STRING :
case IProblem.SCANNER_INVALID_ESCAPECHAR :
case IProblem.SCANNER_BAD_FLOATING_POINT :
case IProblem.SCANNER_BAD_HEX_FORMAT :
case IProblem.SCANNER_UNEXPECTED_EOF :
break;
}
return result;
}
}

View file

@ -1,136 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.parser;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import org.eclipse.cdt.core.parser.ITranslationOptions;
public class TranslationOptions implements ITranslationOptions {
// tags used to recognize tasks in comments
private char[][] taskTags = null;
// priorities of tasks in comments
private char[][] taskPriorities = null;
public TranslationOptions(Map settings) {
initialize(settings);
}
/**
* Initializing the translation options with external settings
*/
public void initialize(Map settings){
if (settings == null) return;
// filter out related options
Iterator entries = settings.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry)entries.next();
Object oKey = entry.getKey();
Object oValue = entry.getValue();
if (!(oKey instanceof String)) continue;
if (!(oValue instanceof String)) continue;
String optionID = (String) oKey;
String optionValue = (String) oValue;
// Unpack task tags
if (optionID.equals(OPTION_TaskTags)) {
if (optionValue.length() == 0) {
this.taskTags = null;
} else {
StringTokenizer tokenizer = new StringTokenizer(optionValue, ",");
this.taskTags = new char[tokenizer.countTokens()][];
int i = 0;
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken().trim();
this.taskTags[i] = token.toCharArray();
i++;
}
}
continue;
}
// Unpack task priorities
if (optionID.equals(OPTION_TaskPriorities)){
if (optionValue.length() == 0) {
this.taskPriorities = null;
} else {
StringTokenizer tokenizer = new StringTokenizer(optionValue, ",");
this.taskPriorities = new char[tokenizer.countTokens()][];
int i = 0;
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken().trim();
this.taskPriorities[i] = token.toCharArray();
i++;
}
}
continue;
}
}
}
public void setTaskTags(char[][] taskTags) {
this.taskTags = taskTags;
}
public char[][] getTaskTags() {
return taskTags;
}
public void setTaskPriorities(char[][] taskPriorities) {
this.taskPriorities = taskPriorities;
}
public char[][] getTaskPriorities() {
return taskPriorities;
}
public String toString() {
StringBuffer buf = new StringBuffer("TranslationOptions:"); //$NON-NLS-1$
String result = "";
if (this.taskTags != null) {
for (int i=0; i<this.taskTags.length; i++) {
result += this.taskTags.toString();
if (i<this.taskTags.length-1) result += ",";
}
}
buf.append("\n-task tags: " + result); //$NON-NLS-1$
result = "";
if (this.taskPriorities != null) {
for (int i=0; i<this.taskPriorities.length; i++) {
result += this.taskPriorities.toString();
if (i<this.taskPriorities.length-1) result += ",";
}
}
buf.append("\n-task priorities : " + result); //$NON-NLS-1$
return buf.toString();
}
}

View file

@ -1,388 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.parser;
/**
* A translation result consists of all information returned during translation for
* a translation unit. This includes:
* <ul>
* <li> the translation unit that was processed
* <li> any problems (errors, warnings, tasks etc.) produced
* </ul>
*/
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.IReferenceContext;
import org.eclipse.cdt.core.parser.ITranslationResult;
//import org.eclipse.cdt.core.model.ITranslationUnit;
public class TranslationResult implements ITranslationResult {
public IProblem problems[];
public IProblem tasks[];
public int problemCount;
public int taskCount;
// public ITranslationUnit translationUnit;
private int maxProblemPerUnit;
public int unitIndex, totalUnitsKnown;
public boolean hasBeenAccepted = false;
public char[] fileName;
public TranslationResult(
char[] fileName,
int unitIndex,
int totalUnitsKnown,
int maxProblemPerUnit){
this.fileName = fileName;
this.unitIndex = unitIndex;
this.totalUnitsKnown = totalUnitsKnown;
this.maxProblemPerUnit = maxProblemPerUnit;
}
public static final int DEFAULT_MAX_PROBLEMS_PER_UNIT = 100;
/*
public TranslationResult(
ITranslationUnit translationUnit) {
this(translationUnit, 1, 1, DEFAULT_MAX_PROBLEMS_PER_UNIT);
}
*/
public TranslationResult(
String fileName) {
this(fileName.toCharArray(), 1, 1, DEFAULT_MAX_PROBLEMS_PER_UNIT);
}
/*
public TranslationResult(
ITranslationUnit translationUnit,
int unitIndex,
int totalUnitsKnown,
int maxProblemPerUnit){
this.fileName = translationUnit.getPath().lastSegment().toCharArray();
this.translationUnit = translationUnit;
this.unitIndex = unitIndex;
this.totalUnitsKnown = totalUnitsKnown;
this.maxProblemPerUnit = maxProblemPerUnit;
}
*/
private int computePriority(IProblem problem) {
// early problems first
int priority = 100000 - problem.getSourceLineNumber();
return priority;
}
public IProblem[] getAllProblems() {
IProblem[] problems = this.getProblems();
int problemCount = problems != null ? problems.length : 0;
IProblem[] tasks = this.getTasks();
int taskCount = tasks != null ? tasks.length : 0;
if (taskCount == 0) {
return problems;
}
if (problemCount == 0) {
return tasks;
}
int totalNumberOfProblem = problemCount + taskCount;
IProblem[] allProblems = new IProblem[totalNumberOfProblem];
int allProblemIndex = 0;
int taskIndex = 0;
int problemIndex = 0;
while (taskIndex + problemIndex < totalNumberOfProblem) {
IProblem nextTask = null;
IProblem nextProblem = null;
if (taskIndex < taskCount) {
nextTask = tasks[taskIndex];
}
if (problemIndex < problemCount) {
nextProblem = problems[problemIndex];
}
// select the next problem
IProblem currentProblem = null;
if (nextProblem != null) {
if (nextTask != null) {
if (nextProblem.getSourceStart() < nextTask.getSourceStart()) {
currentProblem = nextProblem;
problemIndex++;
} else {
currentProblem = nextTask;
taskIndex++;
}
} else {
currentProblem = nextProblem;
problemIndex++;
}
} else {
if (nextTask != null) {
currentProblem = nextTask;
taskIndex++;
}
}
allProblems[allProblemIndex++] = currentProblem;
}
return allProblems;
}
/**
* Answer the initial translation unit corresponding to the present translation result
*/
// public ITranslationUnit getTranslationUnit() {
// return translationUnit;
// }
/**
* Answer the initial file name
*/
public char[] getFileName() {
return fileName;
}
/**
* Answer the errors encountered during translation.
*/
public IProblem[] getErrors() {
IProblem[] problems = getProblems();
int errorCount = 0;
for (int i = 0; i < this.problemCount; i++) {
if (problems[i].isError()) errorCount++;
}
if (errorCount == this.problemCount) return problems;
IProblem[] errors = new IProblem[errorCount];
int index = 0;
for (int i = 0; i < this.problemCount; i++) {
if (problems[i].isError()) errors[index++] = problems[i];
}
return errors;
}
/**
* Answer the problems (errors and warnings) encountered during translation.
*
* This is not a compiler internal API - it has side-effects !
* It is intended to be used only once all problems have been detected,
* and makes sure the problems slot as the exact size of the number of
* problems.
*/
public IProblem[] getProblems() {
// Re-adjust the size of the problems if necessary.
if (problems != null) {
if (this.problemCount != problems.length) {
System.arraycopy(problems, 0, (problems = new IProblem[problemCount]), 0, problemCount);
}
if (this.maxProblemPerUnit > 0 && this.problemCount > this.maxProblemPerUnit){
quickPrioritize(problems, 0, problemCount - 1);
this.problemCount = this.maxProblemPerUnit;
System.arraycopy(problems, 0, (problems = new IProblem[problemCount]), 0, problemCount);
}
// Sort problems per source positions.
quickSort(problems, 0, problems.length-1);
}
return problems;
}
/**
* Answer the tasks (TO-DO, ...) encountered during translation.
*
* This is not a compiler internal API - it has side-effects !
* It is intended to be used only once all problems have been detected,
* and makes sure the problems slot as the exact size of the number of
* problems.
*/
public IProblem[] getTasks() {
// Re-adjust the size of the tasks if necessary.
if (this.tasks != null) {
if (this.taskCount != this.tasks.length) {
System.arraycopy(this.tasks, 0, (this.tasks = new IProblem[this.taskCount]), 0, this.taskCount);
}
quickSort(tasks, 0, tasks.length-1);
}
return this.tasks;
}
public boolean hasErrors() {
if (problems != null)
for (int i = 0; i < problemCount; i++) {
if (problems[i].isError())
return true;
}
return false;
}
public boolean hasProblems() {
return problemCount != 0;
}
public boolean hasSyntaxError(){
if (problems != null)
for (int i = 0; i < problemCount; i++) {
IProblem problem = problems[i];
if ((problem.getID() & IProblem.Syntax) != 0 && problem.isError())
return true;
}
return false;
}
public boolean hasTasks() {
return this.taskCount != 0;
}
public boolean hasWarnings() {
if (problems != null)
for (int i = 0; i < problemCount; i++) {
if (problems[i].isWarning())
return true;
}
return false;
}
private static void quickSort(IProblem[] list, int left, int right) {
if (left >= right) return;
// sort the problems by their source start position... starting with 0
int original_left = left;
int original_right = right;
int mid = list[(left + right) / 2].getSourceStart();
do {
while (list[left].getSourceStart() < mid)
left++;
while (mid < list[right].getSourceStart())
right--;
if (left <= right) {
IProblem tmp = list[left];
list[left] = list[right];
list[right] = tmp;
left++;
right--;
}
} while (left <= right);
if (original_left < right)
quickSort(list, original_left, right);
if (left < original_right)
quickSort(list, left, original_right);
}
private void quickPrioritize(IProblem[] list, int left, int right) {
if (left >= right) return;
// sort the problems by their priority... starting with the highest priority
int original_left = left;
int original_right = right;
int mid = computePriority(list[(left + right) / 2]);
do {
while (computePriority(list[right]) < mid)
right--;
while (mid < computePriority(list[left]))
left++;
if (left <= right) {
IProblem tmp = list[left];
list[left] = list[right];
list[right] = tmp;
left++;
right--;
}
} while (left <= right);
if (original_left < right)
quickPrioritize(list, original_left, right);
if (left < original_right)
quickPrioritize(list, left, original_right);
}
public void record(IProblem newProblem, IReferenceContext referenceContext) {
if (newProblem.getID() == IProblem.Task) {
recordTask(newProblem);
return;
}
if (problemCount == 0) {
problems = new IProblem[5];
} else if (problemCount == problems.length) {
System.arraycopy(problems, 0, (problems = new IProblem[problemCount * 2]), 0, problemCount);
}
problems[problemCount++] = newProblem;
}
private void recordTask(IProblem newProblem) {
if (this.taskCount == 0) {
this.tasks = new IProblem[5];
} else if (this.taskCount == this.tasks.length) {
System.arraycopy(this.tasks, 0, (this.tasks = new IProblem[this.taskCount * 2]), 0, this.taskCount);
}
this.tasks[this.taskCount++] = newProblem;
}
public ITranslationResult tagAsAccepted() {
this.hasBeenAccepted = true;
return this;
}
public String toString() {
StringBuffer buffer = new StringBuffer();
if (this.fileName != null){
buffer.append("Filename : ").append(this.fileName).append('\n'); //$NON-NLS-1$
}
if (problems != null){
buffer.append(this.problemCount).append(" PROBLEM(s) detected \n"); //$NON-NLS-1$//$NON-NLS-2$
for (int i = 0; i < this.problemCount; i++){
buffer.append("\t - ").append(this.problems[i]).append('\n'); //$NON-NLS-1$
}
} else {
buffer.append("No PROBLEM\n"); //$NON-NLS-1$
}
return buffer.toString();
}
}

View file

@ -1,279 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.parser.problem;
//import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.ISourceElementRequestor;
public class DefaultProblem implements IProblem {
private char[] fileName;
private int id;
private int startPosition, endPosition, line;
private int severity;
private String[] arguments;
private String message;
public DefaultProblem(
char[] originatingFileName,
String message,
int id,
String[] stringArguments,
int severity,
int startPosition,
int endPosition,
int line) {
this.fileName = originatingFileName;
this.message = message;
this.id = id;
this.arguments = stringArguments;
this.severity = severity;
this.startPosition = startPosition;
this.endPosition = endPosition;
this.line = line;
}
public String errorReportSource(char[] source) {
//extra from the source the innacurate token
//and "highlight" it using some underneath ^^^^^
//put some context around too.
//this code assumes that the font used in the console is fixed size
//sanity .....
if ((startPosition > endPosition)
|| ((startPosition <= 0) && (endPosition <= 0)))
return "\n!! no source information available !!";
final char SPACE = '\u0020';
final char MARK = '^';
final char TAB = '\t';
//char[] source = translationUnit.getContents();
//the next code tries to underline the token.....
//it assumes (for a good display) that token source does not
//contain any \r \n. This is false on statements !
//(the code still works but the display is not optimal !)
//compute the how-much-char we are displaying around the inaccurate token
int begin = startPosition >= source.length ? source.length - 1 : startPosition;
int relativeStart = 0;
int end = endPosition >= source.length ? source.length - 1 : endPosition;
int relativeEnd = 0;
label : for (relativeStart = 0;; relativeStart++) {
if (begin == 0)
break label;
if ((source[begin - 1] == '\n') || (source[begin - 1] == '\r'))
break label;
begin--;
}
label : for (relativeEnd = 0;; relativeEnd++) {
if ((end + 1) >= source.length)
break label;
if ((source[end + 1] == '\r') || (source[end + 1] == '\n')) {
break label;
}
end++;
}
//extract the message form the source
char[] extract = new char[end - begin + 1];
System.arraycopy(source, begin, extract, 0, extract.length);
char c;
//remove all SPACE and TAB that begin the error message...
int trimLeftIndex = 0;
while (((c = extract[trimLeftIndex++]) == TAB) || (c == SPACE)) {
};
System.arraycopy(
extract,
trimLeftIndex - 1,
extract = new char[extract.length - trimLeftIndex + 1],
0,
extract.length);
relativeStart -= trimLeftIndex;
//buffer spaces and tabs in order to reach the error position
int pos = 0;
char[] underneath = new char[extract.length]; // can't be bigger
for (int i = 0; i <= relativeStart; i++) {
if (extract[i] == TAB) {
underneath[pos++] = TAB;
} else {
underneath[pos++] = SPACE;
}
}
//mark the error position
for (int i = startPosition;
i <= (endPosition >= source.length ? source.length - 1 : endPosition);
i++)
underneath[pos++] = MARK;
//resize underneathto remove 'null' chars
System.arraycopy(underneath, 0, underneath = new char[pos], 0, pos);
return " at line" + String.valueOf(line)
+ "\n\t" + new String(extract) + "\n\t" + new String(underneath); //$NON-NLS-2$ //$NON-NLS-1$
}
/**
* Answer back the original arguments recorded into the problem.
* @return java.lang.String[]
*/
public String[] getArguments() {
return arguments;
}
/**
* Answer the type of problem.
* @see org.eclipse.cdt.core.parser.IProblem#getID()
* @return int
*/
public int getID() {
return id;
}
/**
* Answer a localized, human-readable message string which describes the problem.
* @return java.lang.String
*/
public String getMessage() {
return message;
}
/**
* Answer the file name in which the problem was found.
* @return char[]
*/
public char[] getOriginatingFileName() {
return fileName;
}
/**
* Answer the end position of the problem (inclusive), or -1 if unknown.
* @return int
*/
public int getSourceEnd() {
return endPosition;
}
/**
* Answer the line number in source where the problem begins.
* @return int
*/
public int getSourceLineNumber() {
return line;
}
/**
* Answer the start position of the problem (inclusive), or -1 if unknown.
* @return int
*/
public int getSourceStart() {
return startPosition;
}
/*
* Helper method: checks the severity to see if the Error bit is set.
* @return boolean
*/
public boolean isError() {
return (severity & IProblemSeverities.Error) != 0;
}
/*
* Helper method: checks the severity to see if the Warning bit is set.
* @return boolean
*/
public boolean isWarning() {
return (severity & IProblemSeverities.Warning) == 0;
}
/**
* Set the end position of the problem (inclusive), or -1 if unknown.
*
* Used for shifting problem positions.
* @param sourceEnd the new value of the sourceEnd of the receiver
*/
public void setSourceEnd(int sourceEnd) {
endPosition = sourceEnd;
}
/**
* Set the line number in source where the problem begins.
* @param lineNumber the new value of the line number of the receiver
*/
public void setSourceLineNumber(int lineNumber) {
line = lineNumber;
}
/**
* Set the start position of the problem (inclusive), or -1 if unknown.
*
* Used for shifting problem positions.
* @param sourceStart the new value of the source start position of the receiver
*/
public void setSourceStart(int sourceStart) {
startPosition = sourceStart;
}
public String toString() {
String s = "Pb(" + (id & IgnoreCategoriesMask) + ") "; //$NON-NLS-1$ //$NON-NLS-2$
if (message != null) {
s += message;
} else {
if (arguments != null)
for (int i = 0; i < arguments.length; i++)
s += " " + arguments[i]; //$NON-NLS-1$
}
return s;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ISourceElementCallbackDelegate#acceptElement(org.eclipse.cdt.core.parser.ISourceElementRequestor)
*/
public void acceptElement(ISourceElementRequestor requestor)
{
try
{
requestor.acceptProblem( this );
}
catch (Exception e)
{
// do nothing
}
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ISourceElementCallbackDelegate#enterScope(org.eclipse.cdt.core.parser.ISourceElementRequestor)
*/
public void enterScope(ISourceElementRequestor requestor)
{
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ISourceElementCallbackDelegate#exitScope(org.eclipse.cdt.core.parser.ISourceElementRequestor)
*/
public void exitScope(ISourceElementRequestor requestor)
{
}
}

View file

@ -1,169 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.parser.problem;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.internal.core.parser.IProblemFactory;
public class DefaultProblemFactory implements IProblemFactory {
public String[] messageTemplates;
private Locale locale;
private static String[] DEFAULT_LOCALE_TEMPLATES;
private final static char[] DOUBLE_QUOTES = "''".toCharArray(); //$NON-NLS-1$
private final static char[] SINGLE_QUOTE = "'".toCharArray(); //$NON-NLS-1$
/**
* @param loc the locale used to get the right message
*/
public DefaultProblemFactory(Locale loc) {
this.locale = loc;
if (Locale.getDefault().equals(loc)){
if (DEFAULT_LOCALE_TEMPLATES == null){
DEFAULT_LOCALE_TEMPLATES = loadMessageTemplates(loc);
}
this.messageTemplates = DEFAULT_LOCALE_TEMPLATES;
} else {
this.messageTemplates = loadMessageTemplates(loc);
}
}
/**
* Answer a new IProblem created according to the parameters value
* <ul>
* <li>originatingFileName the name of the file name from which the problem is originated
* <li>problemId the problem id
* <li>problemArguments the fully qualified arguments recorded inside the problem
* <li>messageArguments the arguments needed to set the error message (shorter names than problemArguments ones)
* <li>severity the severity of the problem
* <li>startPosition the starting position of the problem
* <li>endPosition the end position of the problem
* <li>lineNumber the line on which the problem occured
* </ul>
* @param originatingFileName char[]
* @param problemId int
* @param arguments String[]
* @param severity int
* @param startPosition int
* @param endPosition int
* @param lineNumber int
* @return org.eclipse.cdt.core.parser.IProblem
*/
public IProblem createProblem(
char[] originatingFileName,
int problemId,
String[] problemArguments,
String[] messageArguments,
int severity,
int startPosition,
int endPosition,
int lineNumber) {
return new DefaultProblem(
originatingFileName,
this.getLocalizedMessage(problemId, messageArguments),
problemId,
problemArguments,
severity,
startPosition,
endPosition,
lineNumber);
}
/**
* Answer the locale used to retrieve the error messages
* @return java.util.Locale
*/
public Locale getLocale() {
return locale;
}
public final String getLocalizedMessage(int id, String[] problemArguments) {
StringBuffer output = new StringBuffer(80);
String message =
messageTemplates[(id & IProblem.IgnoreCategoriesMask)];
if (message == null) {
return "Unable to retrieve the error message for problem id: " //$NON-NLS-1$
+ (id & IProblem.IgnoreCategoriesMask)
+ ". Check translation resources."; //$NON-NLS-1$
}
// for compatibility with MessageFormat which eliminates double quotes in original message
message = message.replace('\"', '\'');
int length = message.length();
int start = -1, end = length;
while (true) {
if ((end = message.indexOf('{', start)) > -1) {
output.append(message.substring(start + 1, end));
if ((start = message.indexOf('}', end)) > -1) {
try {
output.append(
problemArguments[Integer.parseInt(message.substring(end + 1, start))]);
} catch (NumberFormatException nfe) {
output.append(message.substring(end + 1, start + 1));
} catch (ArrayIndexOutOfBoundsException e) {
return "Corrupted translation resources for problem id: " //$NON-NLS-1$
+ (id & IProblem.IgnoreCategoriesMask)
+ ". Check translation resources."; //$NON-NLS-1$
}
} else {
output.append(message.substring(end, length));
break;
}
} else {
output.append(message.substring(start + 1, length));
break;
}
}
return output.toString();
}
/**
* @param problem org.eclipse.cdt.core.parser.IProblem
* @return String
*/
public final String localizedMessage(IProblem problem) {
return getLocalizedMessage(problem.getID(), problem.getArguments());
}
/**
* This method initializes the MessageTemplates class variable according
* to the current Locale.
*/
public static String[] loadMessageTemplates(Locale loc) {
ResourceBundle bundle = null;
String bundleName = "org.eclipse.cdt.internal.core.parser.problem.messages"; //$NON-NLS-1$
try {
bundle = ResourceBundle.getBundle(bundleName, loc);
} catch(MissingResourceException e) {
System.out.println("Missing resource : " + bundleName.replace('.', '/') + ".properties for locale " + loc); //$NON-NLS-1$//$NON-NLS-2$
throw e;
}
String[] templates = new String[500];
for (int i = 0, max = templates.length; i < max; i++) {
try {
templates[i] = bundle.getString(String.valueOf(i));
} catch (MissingResourceException e) {
// available ID
}
}
return templates;
}
public DefaultProblemFactory() {
this(Locale.getDefault());
}
}

View file

@ -1,21 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.parser.problem;
public interface IProblemSeverities {
final int Ignore = -1;
final int Error = 0x00001;
final int Warning = 0x00002;
final int Task = 0x10000; // when bit is set: the problem is a task
}

View file

@ -1,157 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.parser.problem;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.IReferenceContext;
import org.eclipse.cdt.core.parser.ITranslationOptions;
import org.eclipse.cdt.core.parser.ITranslationResult;
import org.eclipse.cdt.internal.core.parser.IErrorHandlingPolicy;
import org.eclipse.cdt.internal.core.parser.IProblemFactory;
/*
* Translation problem handler, responsible to determine whether
* a problem is actually a warning or an error (or a task); also will
* decide whether the translation task can be processed further or not.
*
* Behavior : will request its current policy if need to stop on
* first error, and if should proceed (persist) with problems.
*/
public class ProblemHandler {
public final static String[] NoArgument = new String[0];
final public IErrorHandlingPolicy policy;
public final IProblemFactory problemFactory;
private final ITranslationOptions options;
/**
* Problem handler can be supplied with a policy to specify
* its behavior in error handling. Also see static methods for
* built-in policies.
*
*/
public ProblemHandler(IErrorHandlingPolicy policy, ITranslationOptions options, IProblemFactory problemFactory) {
this.policy = policy;
this.problemFactory = problemFactory;
this.options = options;
}
/**
* Given the current configuration, answers which category the problem
* falls into:
* Error | Warning | Ignore | Task
*/
public int computeSeverity(int problemId) {
if (problemId == IProblem.Task) return IProblemSeverities.Task;
// by default all problems are errors
return IProblemSeverities.Error;
}
public IProblem createProblem(
char[] fileName,
int problemId,
String[] problemArguments,
String[] messageArguments,
int severity,
int problemStartPosition,
int problemEndPosition,
int lineNumber,
IReferenceContext referenceContext,
ITranslationResult unitResult) {
return problemFactory.createProblem(
fileName,
problemId,
problemArguments,
messageArguments,
severity,
problemStartPosition,
problemEndPosition,
lineNumber);
}
public void handle(
int problemId,
String[] problemArguments,
String[] messageArguments,
int severity,
int problemStartPosition,
int problemEndPosition,
int line,
IReferenceContext referenceContext,
ITranslationResult unitResult) {
if (severity == IProblemSeverities.Ignore)
return;
IProblem problem =
this.createProblem(
unitResult.getFileName(),
problemId,
problemArguments,
messageArguments,
severity,
problemStartPosition,
problemEndPosition,
line >= 0
? line
: 1,
referenceContext,
unitResult);
if (problem == null) return; // problem couldn't be created, ignore
this.record(problem, unitResult, referenceContext);
}
/**
* Standard problem handling API, the actual severity (warning/error/ignore) is deducted
* from the problem ID and the current translation options.
*/
public void handle(
int problemId,
String[] problemArguments,
String[] messageArguments,
int problemStartPosition,
int problemEndPosition,
int line,
IReferenceContext referenceContext,
ITranslationResult unitResult) {
this.handle(
problemId,
problemArguments,
messageArguments,
this.computeSeverity(problemId), // severity inferred using the ID
problemStartPosition,
problemEndPosition,
line,
referenceContext,
unitResult);
}
public void record(IProblem problem, ITranslationResult unitResult, IReferenceContext referenceContext) {
unitResult.record(problem, referenceContext);
}
public ITranslationOptions getOptions() {
return options;
}
}

View file

@ -1,110 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.parser.problem;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.IProblemReporter;
import org.eclipse.cdt.core.parser.IReferenceContext;
import org.eclipse.cdt.core.parser.ITranslationOptions;
import org.eclipse.cdt.core.parser.ITranslationResult;
import org.eclipse.cdt.internal.core.parser.IErrorHandlingPolicy;
import org.eclipse.cdt.internal.core.parser.IProblemFactory;
public class ProblemReporter extends ProblemHandler implements IProblemReporter {
public IReferenceContext referenceContext = null;
public ProblemReporter(IErrorHandlingPolicy policy, ITranslationOptions options, IProblemFactory problemFactory) {
super(policy, options, problemFactory);
}
public void task(String tag, String message, String priority, int start, int end, int line, ITranslationResult result){
this.handle(
IProblem.Task,
new String[] { tag, message, priority/*secret argument that is not surfaced in getMessage()*/},
new String[] { tag, message, priority/*secret argument that is not surfaced in getMessage()*/},
start,
end,
line,
result);
}
// use this private API when the translation unit result can be found through the
// reference context. Otherwise, use the other API taking a problem and a translation result
// as arguments
private void handle(
int problemId,
String[] problemArguments,
String[] messageArguments,
int problemStartPosition,
int problemEndPosition,
int line){
this.handle(
problemId,
problemArguments,
messageArguments,
problemStartPosition,
problemEndPosition,
line,
referenceContext,
referenceContext == null ? null : referenceContext.translationResult());
referenceContext = null;
}
// use this private API when the translation unit result can be found through the
// reference context. Otherwise, use the other API taking a problem and a translation result
// as arguments
private void handle(
int problemId,
String[] problemArguments,
String[] messageArguments,
int severity,
int problemStartPosition,
int problemEndPosition,
int line){
this.handle(
problemId,
problemArguments,
messageArguments,
severity,
problemStartPosition,
problemEndPosition,
referenceContext,
referenceContext == null ? null : referenceContext.translationResult());
referenceContext = null;
}
// use this private API when the translation unit result cannot be found through the
// reference context.
private void handle(
int problemId,
String[] problemArguments,
String[] messageArguments,
int problemStartPosition,
int problemEndPosition,
int line,
ITranslationResult unitResult){
this.handle(
problemId,
problemArguments,
messageArguments,
problemStartPosition,
problemEndPosition,
line,
referenceContext,
unitResult);
referenceContext = null;
}
}

View file

@ -1,14 +0,0 @@
###############################################################################
# Copyright (c) 2000, 2003 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Common Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/cpl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
0 = {0}
# Task message: {taskTag} {taskMessage}
450 = {0} {1}

View file

@ -14,7 +14,6 @@ import java.util.Iterator;
import java.util.NoSuchElementException;
import org.eclipse.cdt.internal.core.parser.ast.complete.ASTSymbol;
import org.eclipse.cdt.internal.core.parser.pst.ISymbolASTExtension.ExtensionException;
/**
* @author jcamelon

View file

@ -16,7 +16,6 @@ import java.util.List;
import java.util.NoSuchElementException;
import org.eclipse.cdt.internal.core.parser.ast.complete.ASTSymbol;
import org.eclipse.cdt.internal.core.parser.pst.ISymbolASTExtension.ExtensionException;
/**
* @author jcamelon

View file

@ -14,8 +14,6 @@ import java.util.Iterator;
import java.util.NoSuchElementException;
import org.eclipse.cdt.internal.core.parser.ast.complete.ASTSymbol;
import org.eclipse.cdt.internal.core.parser.pst.ISymbolASTExtension.ExtensionException;
/**
* @author jcamelon

View file

@ -20,6 +20,7 @@ import java.util.LinkedList;
import org.eclipse.cdt.core.parser.EndOfFile;
import org.eclipse.cdt.core.parser.IParser;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.IQuickParseCallback;
import org.eclipse.cdt.core.parser.IScanner;
import org.eclipse.cdt.core.parser.IToken;
@ -46,6 +47,7 @@ import org.eclipse.cdt.internal.core.index.IEntryResult;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.index.impl.BlocksIndexInput;
import org.eclipse.cdt.internal.core.index.impl.IndexInput;
import org.eclipse.cdt.internal.core.parser.NullSourceElementRequestor;
import org.eclipse.cdt.internal.core.parser.ScannerInfo;
import org.eclipse.cdt.internal.core.search.IIndexSearchRequestor;
import org.eclipse.cdt.internal.core.search.indexing.IIndexConstants;
@ -62,6 +64,21 @@ public abstract class CSearchPattern implements ICSearchConstants, ICSearchPatte
public static final int ACCURATE_MATCH = 2;
public static final int INACCURATE_MATCH = 3;
protected static class Requestor extends NullSourceElementRequestor
{
public Requestor( ParserMode mode )
{
super( mode );
}
public boolean acceptProblem( IProblem problem )
{
if( problem.getID() == IProblem.SCANNER_BAD_CHARACTER ) return false;
return super.acceptProblem( problem );
}
}
private static Requestor callback = new Requestor( ParserMode.COMPLETE_PARSE );
/**
* @param matchMode
* @param caseSensitive
@ -154,7 +171,7 @@ public abstract class CSearchPattern implements ICSearchConstants, ICSearchPatte
return orPattern;
}
IScanner scanner = ParserFactory.createScanner( new StringReader( patternString ), "TEXT", new ScannerInfo(), ParserMode.QUICK_PARSE, ParserLanguage.CPP, null );
IScanner scanner = ParserFactory.createScanner( new StringReader( patternString ), "TEXT", new ScannerInfo(), ParserMode.QUICK_PARSE, ParserLanguage.CPP, callback );
LinkedList list = scanForNames( scanner, null );
char [] name = (char []) list.removeLast();
@ -212,7 +229,7 @@ public abstract class CSearchPattern implements ICSearchConstants, ICSearchPatte
return orPattern;
}
IScanner scanner = ParserFactory.createScanner( new StringReader( patternString ), "TEXT", new ScannerInfo(), ParserMode.QUICK_PARSE, ParserLanguage.CPP, null );
IScanner scanner = ParserFactory.createScanner( new StringReader( patternString ), "TEXT", new ScannerInfo(), ParserMode.QUICK_PARSE, ParserLanguage.CPP, callback );
LinkedList list = scanForNames( scanner, null );
char [] name = (char []) list.removeLast();
@ -242,7 +259,7 @@ public abstract class CSearchPattern implements ICSearchConstants, ICSearchPatte
String paramString = ( index == -1 ) ? "" : patternString.substring( index );
String nameString = ( index == -1 ) ? patternString : patternString.substring( 0, index );
IScanner scanner = ParserFactory.createScanner( new StringReader( nameString ), "TEXT", new ScannerInfo(), ParserMode.QUICK_PARSE, ParserLanguage.CPP, null );
IScanner scanner = ParserFactory.createScanner( new StringReader( nameString ), "TEXT", new ScannerInfo(), ParserMode.QUICK_PARSE, ParserLanguage.CPP, callback );
LinkedList names = scanForNames( scanner, null );
@ -289,7 +306,7 @@ public abstract class CSearchPattern implements ICSearchConstants, ICSearchPatte
// return orPattern;
// }
IScanner scanner = ParserFactory.createScanner( new StringReader( patternString ), "TEXT", new ScannerInfo(), ParserMode.QUICK_PARSE, ParserLanguage.CPP, null );
IScanner scanner = ParserFactory.createScanner( new StringReader( patternString ), "TEXT", new ScannerInfo(), ParserMode.QUICK_PARSE, ParserLanguage.CPP, callback );
IToken token = null;
ASTClassKind kind = null;
@ -342,7 +359,7 @@ public abstract class CSearchPattern implements ICSearchConstants, ICSearchPatte
String functionString = "void f " + paramString + ";";
IScanner scanner = ParserFactory.createScanner( new StringReader( functionString ), "TEXT", new ScannerInfo(), ParserMode.QUICK_PARSE, ParserLanguage.CPP, null );
IScanner scanner = ParserFactory.createScanner( new StringReader( functionString ), "TEXT", new ScannerInfo(), ParserMode.QUICK_PARSE, ParserLanguage.CPP, callback );
IQuickParseCallback callback = ParserFactory.createQuickParseCallback();
IParser parser = ParserFactory.createParser( scanner, callback, ParserMode.QUICK_PARSE, ParserLanguage.CPP );
@ -484,8 +501,8 @@ public abstract class CSearchPattern implements ICSearchConstants, ICSearchPatte
try{
token = scanner.nextToken();
} catch ( ScannerException e ){
if( e.getErrorCode() == ScannerException.ErrorCode.BAD_CHARACTER ){
//TODO : This may not //, it could be another bad character
if( e.getProblem().getID() == IProblem.SCANNER_BAD_CHARACTER ){
//TODO : This may not be \\, it could be another bad character
if( !encounteredWild && !lastTokenWasOperator ) name += " ";
name += "\\";
encounteredWild = true;

View file

@ -26,6 +26,7 @@ import java.util.LinkedList;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.parser.DefaultProblemHandler;
import org.eclipse.cdt.core.parser.IParser;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.IScanner;
@ -113,7 +114,7 @@ public class MatchLocator implements ISourceElementRequestor, ICSearchConstants
progressMonitor = monitor;
}
public void acceptProblem(IProblem problem) { }
public boolean acceptProblem(IProblem problem) { return DefaultProblemHandler.ruleOnProblem(problem, ParserMode.COMPLETE_PARSE ); }
public void acceptUsingDirective(IASTUsingDirective usageDirective) { }
public void acceptUsingDeclaration(IASTUsingDeclaration usageDeclaration) { }
public void acceptASMDefinition(IASTASMDefinition asmDefinition) { }

View file

@ -1,132 +0,0 @@
package org.eclipse.cdt.core;
/**********************************************************************
* Copyright (c) 2002,2003 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Rational Software - Initial API and implementation
***********************************************************************/
import java.util.HashSet;
import java.util.Iterator;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.model.ICModelMarker;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.parser.ITranslationResult;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
public class CTaskTagsReconciler {
private static CTaskTagsReconciler instance = null;
private CTaskTagsReconciler() {
}
public static CTaskTagsReconciler getInstance() {
if (instance == null) {
instance = new CTaskTagsReconciler();
}
return instance;
}
public void acceptResult(ITranslationUnit translationUnit, ITranslationResult result) {
try {
updateTasksFor(translationUnit, result); // record tasks
} catch (CoreException e) {
System.out.println("Exception while accepting parse results");
e.printStackTrace();
}
}
protected void updateTasksFor(ITranslationUnit sourceFile, ITranslationResult result) throws CoreException {
IProblem[] tasks = result.getTasks();
storeTasksFor(sourceFile, tasks);
}
protected void storeTasksFor(ITranslationUnit sourceFile, IProblem[] tasks) throws CoreException {
if (sourceFile == null) return;
if (tasks == null) tasks = new IProblem[0];
IResource resource = sourceFile.getResource();
IMarker[] existingTaskMarkers = resource.findMarkers(ICModelMarker.TASK_MARKER, false, IResource.DEPTH_ONE);
HashSet taskSet = new HashSet();
if (existingTaskMarkers != null)
for (int i=0; i<existingTaskMarkers.length; i++)
taskSet.add(existingTaskMarkers[i]);
taskLoop:
for (int i = 0, l = tasks.length; i < l; i++) {
IProblem task = tasks[i];
if (task.getID() == IProblem.Task) {
int priority = IMarker.PRIORITY_NORMAL;
String compilerPriority = task.getArguments()[2];
if (CCorePlugin.TRANSLATION_TASK_PRIORITY_HIGH.equals(compilerPriority))
priority = IMarker.PRIORITY_HIGH;
else if (CCorePlugin.TRANSLATION_TASK_PRIORITY_LOW.equals(compilerPriority))
priority = IMarker.PRIORITY_LOW;
/*
* Try to find matching markers and don't put in duplicates
*/
if ((existingTaskMarkers != null) && (existingTaskMarkers.length > 0)) {
for (int j = 0; j < existingTaskMarkers.length; j++) {
if (
(((Integer) existingTaskMarkers[j].getAttribute(IMarker.LINE_NUMBER)).intValue() == task.getSourceLineNumber())
&& (((Integer) existingTaskMarkers[j].getAttribute(IMarker.PRIORITY)).intValue() == priority)
&& (((Integer) existingTaskMarkers[j].getAttribute(IMarker.CHAR_START)).intValue() == task.getSourceStart())
&& (((Integer) existingTaskMarkers[j].getAttribute(IMarker.CHAR_END)).intValue() == task.getSourceEnd()+1)
&& (((String) existingTaskMarkers[j].getAttribute(IMarker.MESSAGE)).equals(task.getMessage()))
) {
taskSet.remove(existingTaskMarkers[j]);
continue taskLoop;
}
}
}
IMarker marker = resource.createMarker(ICModelMarker.TASK_MARKER);
marker.setAttributes(
new String[] {
IMarker.MESSAGE,
IMarker.PRIORITY,
IMarker.DONE,
IMarker.CHAR_START,
IMarker.CHAR_END,
IMarker.LINE_NUMBER,
IMarker.USER_EDITABLE,
},
new Object[] {
task.getMessage(),
new Integer(priority),
new Boolean(false),
new Integer(task.getSourceStart()),
new Integer(task.getSourceEnd() + 1),
new Integer(task.getSourceLineNumber()),
new Boolean(false),
});
}
}
// Remove all obsolete markers
Iterator setI = taskSet.iterator();
while (setI.hasNext()) {
IMarker marker = (IMarker)setI.next();
marker.delete();
}
}
}

View file

@ -1,3 +1,6 @@
2003-11-05 John Camelon
Updated parser clients to use new IProblem strategy.
2003-10-28 Andrew Niefer
fix bug 44337 : Disabling of "definition" not making sense in Search dialog
fix bug 44947 : Navigate from Outline: Enumeration type not pre-populated

View file

@ -234,11 +234,12 @@ public class CParseTreeBuilder extends SourceElementRequestorAdapter {
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ISourceElementRequestor#acceptProblem(org.eclipse.cdt.core.parser.IProblem)
*/
public void acceptProblem(IProblem problem) {
public boolean acceptProblem(IProblem problem) {
int problemId = problem.getID();
if (problem.isError() && ((problemId & IProblem.Syntax) != 0)) {
if (problem.isError() && ((problemId & IProblem.SYNTAX_RELATED) != 0)) {
throw new ParseError();
}
return true;
}
/* (non-Javadoc)

View file

@ -11,8 +11,10 @@
package org.eclipse.cdt.internal.ui.compare;
import org.eclipse.cdt.core.parser.DefaultProblemHandler;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.ISourceElementRequestor;
import org.eclipse.cdt.core.parser.ParserMode;
import org.eclipse.cdt.core.parser.ast.IASTASMDefinition;
import org.eclipse.cdt.core.parser.ast.IASTAbstractTypeSpecifierDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTClassReference;
@ -136,7 +138,8 @@ public class SourceElementRequestorAdapter implements ISourceElementRequestor {
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ISourceElementRequestor#acceptProblem(org.eclipse.cdt.core.parser.IProblem)
*/
public void acceptProblem(IProblem problem) {
public boolean acceptProblem(IProblem problem) {
return DefaultProblemHandler.ruleOnProblem( problem, ParserMode.QUICK_PARSE );
}
/* (non-Javadoc)