mirror of https://github.com/icsharpcode/ILSpy.git
92 changed files with 0 additions and 49227 deletions
@ -1,314 +0,0 @@
@@ -1,314 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
|
||||
namespace NRefactoryASTGenerator.Ast |
||||
{ |
||||
[CustomImplementation] |
||||
abstract class Expression : AbstractNode, INullable {} |
||||
|
||||
[CustomImplementation] |
||||
class PrimitiveExpression : Expression {} |
||||
|
||||
enum ParameterModifiers { In } |
||||
|
||||
class ParameterDeclarationExpression : Expression { |
||||
List<AttributeSection> attributes; |
||||
[QuestionMarkDefault] |
||||
string parameterName; |
||||
TypeReference typeReference; |
||||
ParameterModifiers paramModifier; |
||||
Expression defaultValue; |
||||
|
||||
public ParameterDeclarationExpression(TypeReference typeReference, string parameterName) {} |
||||
public ParameterDeclarationExpression(TypeReference typeReference, string parameterName, ParameterModifiers paramModifier) {} |
||||
public ParameterDeclarationExpression(TypeReference typeReference, string parameterName, ParameterModifiers paramModifier, Expression defaultValue) {} |
||||
} |
||||
|
||||
class NamedArgumentExpression : Expression { |
||||
string name; |
||||
Expression expression; |
||||
|
||||
public NamedArgumentExpression(string name, Expression expression) {} |
||||
} |
||||
|
||||
[IncludeBoolProperty("IsAnonymousType", "return createType.IsNull || string.IsNullOrEmpty(createType.Type);")] |
||||
class ObjectCreateExpression : Expression { |
||||
TypeReference createType; |
||||
List<Expression> parameters; |
||||
CollectionInitializerExpression objectInitializer; |
||||
|
||||
public ObjectCreateExpression(TypeReference createType, List<Expression> parameters) {} |
||||
} |
||||
|
||||
[IncludeBoolProperty("IsImplicitlyTyped", "return createType.IsNull || string.IsNullOrEmpty(createType.Type);")] |
||||
class ArrayCreateExpression : Expression { |
||||
TypeReference createType; |
||||
List<Expression> arguments; |
||||
CollectionInitializerExpression arrayInitializer; |
||||
|
||||
public ArrayCreateExpression(TypeReference createType) {} |
||||
public ArrayCreateExpression(TypeReference createType, List<Expression> arguments) {} |
||||
public ArrayCreateExpression(TypeReference createType, CollectionInitializerExpression arrayInitializer) {} |
||||
} |
||||
|
||||
[ImplementNullable(NullableImplementation.Shadow)] |
||||
class CollectionInitializerExpression : Expression { |
||||
List<Expression> createExpressions; |
||||
|
||||
public CollectionInitializerExpression() {} |
||||
public CollectionInitializerExpression(List<Expression> createExpressions) {} |
||||
} |
||||
|
||||
enum AssignmentOperatorType {} |
||||
|
||||
class AssignmentExpression : Expression { |
||||
Expression left; |
||||
AssignmentOperatorType op; |
||||
Expression right; |
||||
|
||||
public AssignmentExpression(Expression left, AssignmentOperatorType op, Expression right) {} |
||||
} |
||||
|
||||
class BaseReferenceExpression : Expression {} |
||||
|
||||
enum BinaryOperatorType {} |
||||
|
||||
class BinaryOperatorExpression : Expression |
||||
{ |
||||
Expression left; |
||||
BinaryOperatorType op; |
||||
Expression right; |
||||
|
||||
public BinaryOperatorExpression(Expression left, BinaryOperatorType op, Expression right) {} |
||||
} |
||||
|
||||
enum CastType {} |
||||
|
||||
class CastExpression : Expression |
||||
{ |
||||
TypeReference castTo; |
||||
Expression expression; |
||||
CastType castType; |
||||
|
||||
public CastExpression(TypeReference castTo) {} |
||||
public CastExpression(TypeReference castTo, Expression expression, CastType castType) {} |
||||
} |
||||
|
||||
[IncludeMember("[Obsolete] public string FieldName { get { return MemberName; } set { MemberName = value; } }")]
|
||||
class MemberReferenceExpression : Expression |
||||
{ |
||||
Expression targetObject; |
||||
string memberName; |
||||
List<TypeReference> typeArguments; |
||||
|
||||
public MemberReferenceExpression(Expression targetObject, string memberName) {} |
||||
} |
||||
|
||||
class PointerReferenceExpression : Expression { |
||||
Expression targetObject; |
||||
string identifier; |
||||
List<TypeReference> typeArguments; |
||||
|
||||
public PointerReferenceExpression(Expression targetObject, string identifier) {} |
||||
} |
||||
|
||||
class IdentifierExpression : Expression { |
||||
string identifier; |
||||
List<TypeReference> typeArguments; |
||||
|
||||
public IdentifierExpression(string identifier) {} |
||||
} |
||||
|
||||
class InvocationExpression : Expression { |
||||
Expression targetObject; |
||||
List<Expression> arguments; |
||||
|
||||
public InvocationExpression(Expression targetObject) {} |
||||
public InvocationExpression(Expression targetObject, List<Expression> arguments) {} |
||||
} |
||||
|
||||
class ParenthesizedExpression : Expression { |
||||
Expression expression; |
||||
|
||||
public ParenthesizedExpression(Expression expression) {} |
||||
} |
||||
|
||||
class ThisReferenceExpression : Expression {} |
||||
|
||||
class TypeOfExpression : Expression { |
||||
TypeReference typeReference; |
||||
|
||||
public TypeOfExpression(TypeReference typeReference) {} |
||||
} |
||||
|
||||
[IncludeMember("public TypeReferenceExpression(string typeName) : this(new TypeReference(typeName)) {}")] |
||||
class TypeReferenceExpression : Expression { |
||||
TypeReference typeReference; |
||||
|
||||
public TypeReferenceExpression(TypeReference typeReference) {} |
||||
} |
||||
|
||||
enum UnaryOperatorType {} |
||||
|
||||
class UnaryOperatorExpression : Expression { |
||||
UnaryOperatorType op; |
||||
Expression expression; |
||||
|
||||
public UnaryOperatorExpression(UnaryOperatorType op) {} |
||||
public UnaryOperatorExpression(Expression expression, UnaryOperatorType op) {} |
||||
} |
||||
|
||||
class AnonymousMethodExpression : Expression { |
||||
List<ParameterDeclarationExpression> parameters; |
||||
BlockStatement body; |
||||
bool hasParameterList; |
||||
} |
||||
|
||||
class LambdaExpression : Expression { |
||||
List<ParameterDeclarationExpression> parameters; |
||||
BlockStatement statementBody; |
||||
Expression expressionBody; |
||||
} |
||||
|
||||
class CheckedExpression : Expression { |
||||
Expression expression; |
||||
|
||||
public CheckedExpression(Expression expression) {} |
||||
} |
||||
|
||||
class ConditionalExpression : Expression { |
||||
Expression condition; |
||||
Expression trueExpression; |
||||
Expression falseExpression; |
||||
|
||||
public ConditionalExpression(Expression condition, Expression trueExpression, Expression falseExpression) {} |
||||
} |
||||
|
||||
class DefaultValueExpression : Expression { |
||||
TypeReference typeReference; |
||||
|
||||
public DefaultValueExpression(TypeReference typeReference) {} |
||||
} |
||||
|
||||
enum FieldDirection {} |
||||
|
||||
class DirectionExpression : Expression { |
||||
FieldDirection fieldDirection; |
||||
Expression expression; |
||||
|
||||
public DirectionExpression(FieldDirection fieldDirection, Expression expression) {} |
||||
} |
||||
|
||||
class IndexerExpression : Expression { |
||||
Expression targetObject; |
||||
List<Expression> indexes; |
||||
|
||||
public IndexerExpression(Expression targetObject, List<Expression> indexes) {} |
||||
} |
||||
|
||||
class SizeOfExpression : Expression { |
||||
TypeReference typeReference; |
||||
|
||||
public SizeOfExpression(TypeReference typeReference) {} |
||||
} |
||||
|
||||
class StackAllocExpression : Expression { |
||||
TypeReference typeReference; |
||||
Expression expression; |
||||
|
||||
public StackAllocExpression(TypeReference typeReference, Expression expression) {} |
||||
} |
||||
|
||||
class UncheckedExpression : Expression { |
||||
Expression expression; |
||||
|
||||
public UncheckedExpression(Expression expression) {} |
||||
} |
||||
|
||||
class AddressOfExpression : Expression { |
||||
Expression expression; |
||||
|
||||
public AddressOfExpression(Expression expression) {} |
||||
} |
||||
|
||||
class ClassReferenceExpression : Expression {} |
||||
|
||||
class TypeOfIsExpression : Expression { |
||||
Expression expression; |
||||
TypeReference typeReference; |
||||
|
||||
public TypeOfIsExpression(Expression expression, TypeReference typeReference) {} |
||||
} |
||||
|
||||
[ImplementNullable(NullableImplementation.Shadow)] |
||||
class QueryExpression : Expression { |
||||
QueryExpressionFromClause fromClause; |
||||
List<QueryExpressionClause> fromLetWhereClauses; |
||||
List<QueryExpressionOrdering> orderings; |
||||
QueryExpressionClause selectOrGroupClause; |
||||
QueryExpressionIntoClause intoClause; |
||||
} |
||||
|
||||
[ImplementNullable] |
||||
abstract class QueryExpressionClause : AbstractNode, INullable { } |
||||
|
||||
class QueryExpressionWhereClause : QueryExpressionClause { |
||||
Expression condition; |
||||
} |
||||
|
||||
class QueryExpressionLetClause : QueryExpressionClause { |
||||
[QuestionMarkDefault] |
||||
string identifier; |
||||
Expression expression; |
||||
} |
||||
|
||||
abstract class QueryExpressionFromOrJoinClause : QueryExpressionClause { |
||||
TypeReference type; |
||||
[QuestionMarkDefault] |
||||
string identifier; |
||||
Expression inExpression; |
||||
} |
||||
|
||||
[ImplementNullable(NullableImplementation.Shadow)] |
||||
class QueryExpressionFromClause : QueryExpressionFromOrJoinClause { } |
||||
|
||||
class QueryExpressionJoinClause : QueryExpressionFromOrJoinClause { |
||||
Expression onExpression; |
||||
Expression equalsExpression; |
||||
|
||||
string intoIdentifier; |
||||
} |
||||
|
||||
class QueryExpressionOrdering : AbstractNode { |
||||
Expression criteria; |
||||
QueryExpressionOrderingDirection direction; |
||||
} |
||||
|
||||
enum QueryExpressionOrderingDirection { |
||||
None, Ascending, Descending |
||||
} |
||||
|
||||
class QueryExpressionSelectClause : QueryExpressionClause { |
||||
Expression projection; |
||||
} |
||||
|
||||
class QueryExpressionGroupClause : QueryExpressionClause { |
||||
Expression projection; |
||||
Expression groupBy; |
||||
} |
||||
|
||||
[ImplementNullable(NullableImplementation.Shadow)] |
||||
class QueryExpressionIntoClause : QueryExpressionClause { |
||||
[QuestionMarkDefault] |
||||
string intoIdentifier; |
||||
|
||||
QueryExpression continuedQuery; |
||||
} |
||||
} |
@ -1,95 +0,0 @@
@@ -1,95 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
|
||||
namespace NRefactoryASTGenerator.Ast |
||||
{ |
||||
[CustomImplementation, HasChildren] |
||||
class CompilationUnit : AbstractNode {} |
||||
|
||||
[HasChildren] |
||||
class NamespaceDeclaration : AbstractNode |
||||
{ |
||||
string name; |
||||
|
||||
public NamespaceDeclaration(string name) {} |
||||
} |
||||
|
||||
class TemplateDefinition : AttributedNode |
||||
{ |
||||
[QuestionMarkDefault] |
||||
string name; |
||||
List<TypeReference> bases; |
||||
|
||||
public TemplateDefinition(string name, List<AttributeSection> attributes) : base(attributes) {} |
||||
} |
||||
|
||||
class DelegateDeclaration : AttributedNode |
||||
{ |
||||
[QuestionMarkDefault] |
||||
string name; |
||||
TypeReference returnType; |
||||
List<ParameterDeclarationExpression> parameters; |
||||
List<TemplateDefinition> templates; |
||||
|
||||
public DelegateDeclaration(Modifiers modifier, List<AttributeSection> attributes) : base(modifier, attributes) {} |
||||
} |
||||
|
||||
enum ClassType { Class } |
||||
|
||||
[HasChildren] |
||||
class TypeDeclaration : AttributedNode |
||||
{ |
||||
// Children of Struct: FieldDeclaration, MethodDeclaration, EventDeclaration, ConstructorDeclaration,
|
||||
// OperatorDeclaration, TypeDeclaration, IndexerDeclaration, PropertyDeclaration, in VB: DeclareDeclaration
|
||||
// Childrean of class: children of struct, DestructorDeclaration
|
||||
// Children of Interface: MethodDeclaration, PropertyDeclaration, IndexerDeclaration, EventDeclaration, in VB: TypeDeclaration(Enum) too
|
||||
// Children of Enum: FieldDeclaration
|
||||
string name; |
||||
ClassType type; |
||||
List<TypeReference> baseTypes; |
||||
List<TemplateDefinition> templates; |
||||
Location bodyStartLocation; |
||||
|
||||
public TypeDeclaration(Modifiers modifier, List<AttributeSection> attributes) : base(modifier, attributes) {} |
||||
} |
||||
|
||||
[IncludeBoolProperty("IsAlias", "return !alias.IsNull;")] |
||||
class Using : AbstractNode |
||||
{ |
||||
[QuestionMarkDefault] |
||||
string name; |
||||
TypeReference alias; |
||||
|
||||
public Using(string name) {} |
||||
public Using(string name, TypeReference alias) {} |
||||
} |
||||
|
||||
[IncludeMember("public UsingDeclaration(string @namespace) : this(@namespace, null) {}")] |
||||
[IncludeMember("public UsingDeclaration(string @namespace, TypeReference alias) {" + |
||||
" usings = new List<Using>(1);" + |
||||
" usings.Add(new Using(@namespace, alias)); " + |
||||
"}")] |
||||
class UsingDeclaration : AbstractNode |
||||
{ |
||||
List<Using> usings; |
||||
|
||||
public UsingDeclaration(List<Using> usings) {} |
||||
} |
||||
|
||||
enum OptionType { None } |
||||
|
||||
class OptionDeclaration : AbstractNode |
||||
{ |
||||
OptionType optionType; |
||||
bool optionValue; |
||||
|
||||
public OptionDeclaration(OptionType optionType, bool optionValue) {} |
||||
} |
||||
} |
@ -1,72 +0,0 @@
@@ -1,72 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
|
||||
namespace NRefactoryASTGenerator.Ast |
||||
{ |
||||
interface INode {} |
||||
interface INullable {} |
||||
struct Location {} |
||||
|
||||
enum Modifiers { None } |
||||
|
||||
[CustomImplementation] |
||||
abstract class AbstractNode : INode {} |
||||
|
||||
abstract class AttributedNode : AbstractNode |
||||
{ |
||||
List<AttributeSection> attributes; |
||||
Modifiers modifier; |
||||
|
||||
public AttributedNode() {} |
||||
public AttributedNode(List<AttributeSection> attributes) {} |
||||
public AttributedNode(Modifiers modifier, List<AttributeSection> attributes) {} |
||||
} |
||||
|
||||
abstract class ParametrizedNode : AttributedNode |
||||
{ |
||||
string name; |
||||
List<ParameterDeclarationExpression> parameters; |
||||
|
||||
public ParametrizedNode() {} |
||||
|
||||
public ParametrizedNode(Modifiers modifier, List<AttributeSection> attributes, |
||||
string name, List<ParameterDeclarationExpression> parameters) |
||||
: base(modifier, attributes) |
||||
{} |
||||
} |
||||
|
||||
[CustomImplementation] |
||||
class TypeReference : AbstractNode |
||||
{ |
||||
List<TypeReference> genericTypes; |
||||
} |
||||
|
||||
[CustomImplementation] |
||||
class InnerClassTypeReference : TypeReference |
||||
{ |
||||
TypeReference baseType; |
||||
} |
||||
|
||||
class AttributeSection : AbstractNode, INullable |
||||
{ |
||||
string attributeTarget; |
||||
List<Attribute> attributes; |
||||
} |
||||
|
||||
class Attribute : AbstractNode |
||||
{ |
||||
string name; |
||||
List<Expression> positionalArguments; |
||||
List<NamedArgumentExpression> namedArguments; |
||||
|
||||
public Attribute() {} |
||||
public Attribute(string name, List<Expression> positionalArguments, List<NamedArgumentExpression> namedArguments) {} |
||||
} |
||||
} |
@ -1,314 +0,0 @@
@@ -1,314 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
|
||||
namespace NRefactoryASTGenerator.Ast |
||||
{ |
||||
[CustomImplementation] |
||||
abstract class Statement : AbstractNode, INullable {} |
||||
|
||||
[CustomImplementation] |
||||
abstract class StatementWithEmbeddedStatement : Statement { |
||||
Statement embeddedStatement; |
||||
} |
||||
|
||||
[CustomImplementation, HasChildren] |
||||
class BlockStatement : Statement {} |
||||
|
||||
class BreakStatement : Statement {} |
||||
|
||||
enum ContinueType {} |
||||
|
||||
class ContinueStatement : Statement { |
||||
ContinueType continueType; |
||||
|
||||
public ContinueStatement() {} |
||||
public ContinueStatement(ContinueType continueType) {} |
||||
} |
||||
|
||||
enum ConditionType {} |
||||
enum ConditionPosition {} |
||||
|
||||
class DoLoopStatement : StatementWithEmbeddedStatement { |
||||
Expression condition; |
||||
ConditionType conditionType; |
||||
ConditionPosition conditionPosition; |
||||
|
||||
public DoLoopStatement(Expression condition, Statement embeddedStatement, ConditionType conditionType, ConditionPosition conditionPosition) {} |
||||
} |
||||
|
||||
class ForeachStatement : StatementWithEmbeddedStatement { |
||||
TypeReference typeReference; |
||||
string variableName; |
||||
Expression expression; |
||||
Expression nextExpression; |
||||
|
||||
public ForeachStatement(TypeReference typeReference, string variableName, Expression expression, Statement embeddedStatement) {} |
||||
public ForeachStatement(TypeReference typeReference, string variableName, Expression expression, Statement embeddedStatement, Expression nextExpression) {} |
||||
} |
||||
|
||||
class ForStatement : StatementWithEmbeddedStatement { |
||||
List<Statement> initializers; |
||||
Expression condition; |
||||
List<Statement> iterator; |
||||
|
||||
public ForStatement(List<Statement> initializers, Expression condition, List<Statement> iterator, Statement embeddedStatement) {} |
||||
} |
||||
|
||||
class GotoStatement : Statement { |
||||
string label; |
||||
|
||||
public GotoStatement(string label) {} |
||||
} |
||||
|
||||
[IncludeMember(@"
|
||||
public IfElseStatement(Expression condition, Statement trueStatement) |
||||
: this(condition) { |
||||
this.trueStatement.Add(Statement.CheckNull(trueStatement)); |
||||
}")]
|
||||
[IncludeMember(@"
|
||||
public IfElseStatement(Expression condition, Statement trueStatement, Statement falseStatement) |
||||
: this(condition) { |
||||
this.trueStatement.Add(Statement.CheckNull(trueStatement)); |
||||
this.falseStatement.Add(Statement.CheckNull(falseStatement)); |
||||
}")]
|
||||
[IncludeBoolProperty("HasElseStatements", "return falseStatement.Count > 0;")] |
||||
[IncludeBoolProperty("HasElseIfSections", "return elseIfSections.Count > 0;")] |
||||
class IfElseStatement : Statement { |
||||
Expression condition; |
||||
List<Statement> trueStatement; // List for stmt : stmt : stmt ... in VB.NET
|
||||
List<Statement> falseStatement; |
||||
List<ElseIfSection> elseIfSections; |
||||
|
||||
public IfElseStatement(Expression condition) {} |
||||
} |
||||
|
||||
class ElseIfSection : StatementWithEmbeddedStatement { |
||||
Expression condition; |
||||
|
||||
public ElseIfSection(Expression condition, Statement embeddedStatement) {} |
||||
} |
||||
|
||||
class LabelStatement : Statement { |
||||
string label; |
||||
|
||||
public LabelStatement(string label) {} |
||||
} |
||||
|
||||
[CustomImplementation] |
||||
class LocalVariableDeclaration : Statement { |
||||
TypeReference typeReference; |
||||
Modifiers modifier; |
||||
List<VariableDeclaration> variables; |
||||
} |
||||
|
||||
class LockStatement : StatementWithEmbeddedStatement |
||||
{ |
||||
Expression lockExpression; |
||||
|
||||
public LockStatement(Expression lockExpression, Statement embeddedStatement) {} |
||||
} |
||||
|
||||
class ReturnStatement : Statement |
||||
{ |
||||
Expression expression; |
||||
|
||||
public ReturnStatement(Expression expression) { } |
||||
} |
||||
|
||||
class ExpressionStatement : Statement { |
||||
Expression expression; |
||||
|
||||
public ExpressionStatement(Expression expression) {} |
||||
} |
||||
|
||||
class SwitchStatement : Statement { |
||||
Expression switchExpression; |
||||
List<SwitchSection> switchSections; |
||||
|
||||
public SwitchStatement(Expression switchExpression, List<SwitchSection> switchSections) {} |
||||
} |
||||
|
||||
class SwitchSection : BlockStatement { |
||||
List<CaseLabel> switchLabels; |
||||
|
||||
public SwitchSection() { } |
||||
public SwitchSection(List<CaseLabel> switchLabels) { } |
||||
} |
||||
|
||||
[IncludeBoolProperty("IsDefault", "return label.IsNull;")] |
||||
class CaseLabel : AbstractNode { |
||||
Expression label; |
||||
BinaryOperatorType binaryOperatorType; |
||||
Expression toExpression; |
||||
|
||||
public CaseLabel() {} |
||||
public CaseLabel(Expression label) {} |
||||
public CaseLabel(Expression label, Expression toExpression) {} |
||||
public CaseLabel(BinaryOperatorType binaryOperatorType, Expression label) {} |
||||
} |
||||
|
||||
class ThrowStatement : Statement { |
||||
Expression expression; |
||||
|
||||
public ThrowStatement(Expression expression) {} |
||||
} |
||||
|
||||
class TryCatchStatement : Statement { |
||||
Statement statementBlock; |
||||
List<CatchClause> catchClauses; |
||||
Statement finallyBlock; |
||||
|
||||
public TryCatchStatement(Statement statementBlock, List<CatchClause> catchClauses, Statement finallyBlock) {} |
||||
} |
||||
|
||||
class CatchClause : AbstractNode { |
||||
TypeReference typeReference; |
||||
string variableName; |
||||
Statement statementBlock; |
||||
Expression condition; |
||||
|
||||
public CatchClause(TypeReference typeReference, string variableName, Statement statementBlock) {} |
||||
public CatchClause(TypeReference typeReference, string variableName, Statement statementBlock, Expression condition) {} |
||||
public CatchClause(Statement statementBlock) {} |
||||
} |
||||
|
||||
class CheckedStatement : Statement { |
||||
Statement block; |
||||
|
||||
public CheckedStatement(Statement block) {} |
||||
} |
||||
|
||||
class EmptyStatement : Statement {} |
||||
|
||||
class FixedStatement : StatementWithEmbeddedStatement { |
||||
TypeReference typeReference; |
||||
List<VariableDeclaration> pointerDeclarators; |
||||
|
||||
public FixedStatement(TypeReference typeReference, List<VariableDeclaration> pointerDeclarators, Statement embeddedStatement) {} |
||||
} |
||||
|
||||
[IncludeBoolProperty("IsDefaultCase", "return expression.IsNull;")] |
||||
class GotoCaseStatement : Statement { |
||||
Expression expression; |
||||
|
||||
public GotoCaseStatement(Expression expression) {} |
||||
} |
||||
|
||||
class UncheckedStatement : Statement { |
||||
Statement block; |
||||
|
||||
public UncheckedStatement(Statement block) {} |
||||
} |
||||
|
||||
class UnsafeStatement : Statement { |
||||
Statement block; |
||||
|
||||
public UnsafeStatement(Statement block) {} |
||||
} |
||||
|
||||
class UsingStatement : StatementWithEmbeddedStatement { |
||||
Statement resourceAcquisition; |
||||
|
||||
public UsingStatement(Statement resourceAcquisition, Statement embeddedStatement) {} |
||||
} |
||||
|
||||
[IncludeBoolProperty("IsYieldReturn", "return statement is ReturnStatement;")] |
||||
[IncludeBoolProperty("IsYieldBreak", "return statement is BreakStatement;")] |
||||
class YieldStatement : Statement { |
||||
Statement statement; |
||||
|
||||
public YieldStatement(Statement statement) {} |
||||
} |
||||
|
||||
class AddHandlerStatement : Statement { |
||||
Expression eventExpression; |
||||
Expression handlerExpression; |
||||
|
||||
public AddHandlerStatement(Expression eventExpression, Expression handlerExpression) {} |
||||
} |
||||
|
||||
class EndStatement : Statement {} |
||||
|
||||
class EraseStatement : Statement { |
||||
List<Expression> expressions; |
||||
|
||||
public EraseStatement() {} |
||||
public EraseStatement(List<Expression> expressions) {} |
||||
} |
||||
|
||||
class ErrorStatement : Statement { |
||||
Expression expression; |
||||
|
||||
public ErrorStatement(Expression expression) {} |
||||
} |
||||
|
||||
enum ExitType {} |
||||
|
||||
class ExitStatement : Statement { |
||||
ExitType exitType; |
||||
|
||||
public ExitStatement(ExitType exitType) {} |
||||
} |
||||
|
||||
class ForNextStatement : StatementWithEmbeddedStatement { |
||||
Expression start; |
||||
Expression end; |
||||
Expression step; |
||||
|
||||
List<Expression> nextExpressions; |
||||
TypeReference typeReference; |
||||
string variableName; |
||||
|
||||
public ForNextStatement(TypeReference typeReference, string variableName, Expression start, Expression end, Expression step, Statement embeddedStatement, List<Expression> nextExpressions) {} |
||||
} |
||||
|
||||
class OnErrorStatement : StatementWithEmbeddedStatement { |
||||
public OnErrorStatement(Statement embeddedStatement) {} |
||||
} |
||||
|
||||
class RaiseEventStatement : Statement { |
||||
string eventName; |
||||
List<Expression> arguments; |
||||
|
||||
public RaiseEventStatement(string eventName, List<Expression> arguments) {} |
||||
} |
||||
|
||||
class ReDimStatement : Statement { |
||||
List<InvocationExpression> reDimClauses; |
||||
bool isPreserve; |
||||
|
||||
public ReDimStatement(bool isPreserve) {} |
||||
} |
||||
|
||||
class RemoveHandlerStatement : Statement { |
||||
Expression eventExpression; |
||||
Expression handlerExpression; |
||||
|
||||
public RemoveHandlerStatement(Expression eventExpression, Expression handlerExpression) {} |
||||
} |
||||
|
||||
class ResumeStatement : Statement { |
||||
string labelName; |
||||
bool isResumeNext; |
||||
|
||||
public ResumeStatement(bool isResumeNext) {} |
||||
|
||||
public ResumeStatement(string labelName) {} |
||||
} |
||||
|
||||
class StopStatement : Statement {} |
||||
|
||||
class WithStatement : Statement { |
||||
Expression expression; |
||||
BlockStatement body; |
||||
|
||||
public WithStatement(Expression expression) {} |
||||
} |
||||
} |
@ -1,261 +0,0 @@
@@ -1,261 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
|
||||
namespace NRefactoryASTGenerator.Ast |
||||
{ |
||||
class VariableDeclaration : AbstractNode |
||||
{ |
||||
string name; |
||||
Expression initializer; |
||||
TypeReference typeReference; |
||||
Expression fixedArrayInitialization; |
||||
|
||||
public VariableDeclaration(string name) {} |
||||
public VariableDeclaration(string name, Expression initializer) {} |
||||
public VariableDeclaration(string name, Expression initializer, TypeReference typeReference) {} |
||||
} |
||||
|
||||
class ConstructorDeclaration : ParametrizedNode |
||||
{ |
||||
ConstructorInitializer constructorInitializer; |
||||
BlockStatement body; |
||||
|
||||
public ConstructorDeclaration(string name, Modifiers modifier, |
||||
List<ParameterDeclarationExpression> parameters, |
||||
List<AttributeSection> attributes) |
||||
: base(modifier, attributes, name, parameters) |
||||
{} |
||||
|
||||
public ConstructorDeclaration(string name, Modifiers modifier, |
||||
List<ParameterDeclarationExpression> parameters, |
||||
ConstructorInitializer constructorInitializer, |
||||
List<AttributeSection> attributes) |
||||
: base(modifier, attributes, name, parameters) |
||||
{} |
||||
} |
||||
|
||||
enum ConstructorInitializerType { None } |
||||
|
||||
[ImplementNullable] |
||||
class ConstructorInitializer : AbstractNode, INullable |
||||
{ |
||||
ConstructorInitializerType constructorInitializerType; |
||||
List<Expression> arguments; |
||||
} |
||||
|
||||
[ImplementNullable(NullableImplementation.Abstract)] |
||||
abstract class EventAddRemoveRegion : AttributedNode |
||||
{ |
||||
BlockStatement block; |
||||
List<ParameterDeclarationExpression> parameters; |
||||
|
||||
public EventAddRemoveRegion(List<AttributeSection> attributes) : base(attributes) {} |
||||
} |
||||
|
||||
[ImplementNullable(NullableImplementation.CompleteAbstract)] |
||||
class EventAddRegion : EventAddRemoveRegion |
||||
{ |
||||
public EventAddRegion(List<AttributeSection> attributes) : base(attributes) {} |
||||
} |
||||
|
||||
[ImplementNullable(NullableImplementation.CompleteAbstract)] |
||||
class EventRemoveRegion : EventAddRemoveRegion |
||||
{ |
||||
public EventRemoveRegion(List<AttributeSection> attributes) : base(attributes) {} |
||||
} |
||||
|
||||
[ImplementNullable(NullableImplementation.CompleteAbstract)] |
||||
class EventRaiseRegion : EventAddRemoveRegion |
||||
{ |
||||
public EventRaiseRegion(List<AttributeSection> attributes) : base(attributes) {} |
||||
} |
||||
|
||||
class InterfaceImplementation : AbstractNode |
||||
{ |
||||
TypeReference interfaceType; |
||||
[QuestionMarkDefault] |
||||
string memberName; |
||||
|
||||
public InterfaceImplementation(TypeReference interfaceType, string memberName) {} |
||||
} |
||||
|
||||
[IncludeBoolProperty("HasAddRegion", "return !addRegion.IsNull;")] |
||||
[IncludeBoolProperty("HasRemoveRegion", "return !removeRegion.IsNull;")] |
||||
[IncludeBoolProperty("HasRaiseRegion", "return !raiseRegion.IsNull;")] |
||||
class EventDeclaration : MemberNode |
||||
{ |
||||
EventAddRegion addRegion; |
||||
EventRemoveRegion removeRegion; |
||||
EventRaiseRegion raiseRegion; |
||||
Location bodyStart; |
||||
Location bodyEnd; |
||||
Expression initializer; |
||||
} |
||||
|
||||
[IncludeMember(@"
|
||||
public TypeReference GetTypeForField(int fieldIndex) |
||||
{ |
||||
if (!typeReference.IsNull) { |
||||
return typeReference; |
||||
} |
||||
return ((VariableDeclaration)Fields[fieldIndex]).TypeReference; |
||||
}")]
|
||||
[IncludeMember(@"
|
||||
public VariableDeclaration GetVariableDeclaration(string variableName) |
||||
{ |
||||
foreach (VariableDeclaration variableDeclaration in Fields) { |
||||
if (variableDeclaration.Name == variableName) { |
||||
return variableDeclaration; |
||||
} |
||||
} |
||||
return null; |
||||
}")]
|
||||
class FieldDeclaration : AttributedNode |
||||
{ |
||||
TypeReference typeReference; |
||||
List<VariableDeclaration> fields; |
||||
|
||||
// for enum members
|
||||
public FieldDeclaration(List<AttributeSection> attributes) : base(attributes) {} |
||||
|
||||
// for all other cases
|
||||
public FieldDeclaration(List<AttributeSection> attributes, TypeReference typeReference, Modifiers modifier) |
||||
: base(modifier, attributes) |
||||
{} |
||||
} |
||||
|
||||
abstract class MemberNode : ParametrizedNode |
||||
{ |
||||
List<InterfaceImplementation> interfaceImplementations; |
||||
TypeReference typeReference; |
||||
|
||||
public MemberNode() {} |
||||
|
||||
public MemberNode(Modifiers modifier, List<AttributeSection> attributes, |
||||
string name, List<ParameterDeclarationExpression> parameters) |
||||
: base(modifier, attributes, name, parameters) |
||||
{} |
||||
} |
||||
|
||||
class MethodDeclaration : MemberNode |
||||
{ |
||||
BlockStatement body; |
||||
List<string> handlesClause; |
||||
List<TemplateDefinition> templates; |
||||
bool isExtensionMethod; |
||||
} |
||||
|
||||
enum ConversionType { None } |
||||
enum OverloadableOperatorType { None } |
||||
|
||||
[IncludeBoolProperty("IsConversionOperator", "return conversionType != ConversionType.None;")] |
||||
class OperatorDeclaration : MethodDeclaration |
||||
{ |
||||
ConversionType conversionType; |
||||
List<AttributeSection> returnTypeAttributes; |
||||
OverloadableOperatorType overloadableOperator; |
||||
} |
||||
|
||||
[IncludeBoolProperty("HasGetRegion", "return !getRegion.IsNull;")] |
||||
[IncludeBoolProperty("HasSetRegion", "return !setRegion.IsNull;")] |
||||
[IncludeBoolProperty("IsReadOnly", "return HasGetRegion && !HasSetRegion;")] |
||||
[IncludeBoolProperty("IsWriteOnly", "return !HasGetRegion && HasSetRegion;")] |
||||
[IncludeMember(@"
|
||||
internal PropertyDeclaration(string name, TypeReference typeReference, Modifiers modifier, List<AttributeSection> attributes) : this(modifier, attributes, name, null) |
||||
{ |
||||
this.TypeReference = typeReference; |
||||
if ((modifier & Modifiers.ReadOnly) != Modifiers.ReadOnly) { |
||||
this.SetRegion = new PropertySetRegion(null, null); |
||||
} |
||||
if ((modifier & Modifiers.WriteOnly) != Modifiers.WriteOnly) { |
||||
this.GetRegion = new PropertyGetRegion(null, null); |
||||
} |
||||
}")]
|
||||
class PropertyDeclaration : MemberNode |
||||
{ |
||||
Location bodyStart; |
||||
Location bodyEnd; |
||||
PropertyGetRegion getRegion; |
||||
PropertySetRegion setRegion; |
||||
|
||||
public PropertyDeclaration(Modifiers modifier, List<AttributeSection> attributes, |
||||
string name, List<ParameterDeclarationExpression> parameters) |
||||
: base(modifier, attributes, name, parameters) |
||||
{} |
||||
} |
||||
|
||||
[ImplementNullable(NullableImplementation.Abstract)] |
||||
abstract class PropertyGetSetRegion : AttributedNode |
||||
{ |
||||
// can be null if only the definition is there (interface declaration)
|
||||
BlockStatement block; |
||||
|
||||
public PropertyGetSetRegion(BlockStatement block, List<AttributeSection> attributes) : base(attributes) {} |
||||
} |
||||
|
||||
[ImplementNullable(NullableImplementation.CompleteAbstract)] |
||||
class PropertyGetRegion : PropertyGetSetRegion |
||||
{ |
||||
public PropertyGetRegion(BlockStatement block, List<AttributeSection> attributes) : base(block, attributes) {} |
||||
} |
||||
|
||||
[ImplementNullable(NullableImplementation.CompleteAbstract)] |
||||
class PropertySetRegion : PropertyGetSetRegion |
||||
{ |
||||
List<ParameterDeclarationExpression> parameters; |
||||
|
||||
public PropertySetRegion(BlockStatement block, List<AttributeSection> attributes) : base(block, attributes) {} |
||||
} |
||||
|
||||
class DestructorDeclaration : AttributedNode |
||||
{ |
||||
string name; |
||||
BlockStatement body; |
||||
|
||||
public DestructorDeclaration(string name, Modifiers modifier, List<AttributeSection> attributes) : base(modifier, attributes) {} |
||||
} |
||||
|
||||
[IncludeBoolProperty("HasGetRegion", "return !getRegion.IsNull;")] |
||||
[IncludeBoolProperty("HasSetRegion", "return !setRegion.IsNull;")] |
||||
[IncludeBoolProperty("IsReadOnly", "return HasGetRegion && !HasSetRegion;")] |
||||
[IncludeBoolProperty("IsWriteOnly", "return !HasGetRegion && HasSetRegion;")] |
||||
class IndexerDeclaration : AttributedNode |
||||
{ |
||||
List<ParameterDeclarationExpression> parameters; |
||||
List<InterfaceImplementation> interfaceImplementations; |
||||
TypeReference typeReference; |
||||
Location bodyStart; |
||||
Location bodyEnd; |
||||
PropertyGetRegion getRegion; |
||||
PropertySetRegion setRegion; |
||||
|
||||
public IndexerDeclaration(Modifiers modifier, List<ParameterDeclarationExpression> parameters, List<AttributeSection> attributes) |
||||
: base(modifier, attributes) |
||||
{} |
||||
|
||||
public IndexerDeclaration(TypeReference typeReference, List<ParameterDeclarationExpression> parameters, Modifiers modifier, List<AttributeSection> attributes) |
||||
: base(modifier, attributes) |
||||
{} |
||||
} |
||||
|
||||
enum CharsetModifier { None } |
||||
|
||||
class DeclareDeclaration : ParametrizedNode |
||||
{ |
||||
string alias; |
||||
string library; |
||||
CharsetModifier charset; |
||||
TypeReference typeReference; |
||||
|
||||
public DeclareDeclaration(string name, Modifiers modifier, TypeReference typeReference, List<ParameterDeclarationExpression> parameters, List<AttributeSection> attributes, string library, string alias, CharsetModifier charset) |
||||
: base(modifier, attributes, name, parameters) |
||||
{} |
||||
} |
||||
} |
@ -1,33 +0,0 @@
@@ -1,33 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System.Reflection; |
||||
using System.Runtime.CompilerServices; |
||||
|
||||
// Information about this assembly is defined by the following
|
||||
// attributes.
|
||||
//
|
||||
// change them to the information which is associated with the assembly
|
||||
// you compile.
|
||||
|
||||
[assembly: AssemblyTitle("NRefactory AST Generator")] |
||||
[assembly: AssemblyDescription("Parser and refactoring library for C# and VB.NET")] |
||||
[assembly: AssemblyConfiguration("")] |
||||
[assembly: AssemblyCompany("ic#code")] |
||||
[assembly: AssemblyProduct("SharpDevelop")] |
||||
[assembly: AssemblyCopyright("2006 AlphaSierraPapa")] |
||||
[assembly: AssemblyTrademark("")] |
||||
[assembly: AssemblyCulture("")] |
||||
|
||||
// The assembly version has following format :
|
||||
//
|
||||
// Major.Minor.Build.Revision
|
||||
//
|
||||
// You can specify all values by your own or you can build default build and revision
|
||||
// numbers with the '*' character (the default):
|
||||
|
||||
[assembly: AssemblyVersion("2.0.0.1")] |
@ -1,180 +0,0 @@
@@ -1,180 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.CodeDom; |
||||
using System.Reflection; |
||||
using ICSharpCode.EasyCodeDom; |
||||
|
||||
namespace NRefactoryASTGenerator |
||||
{ |
||||
public enum NullableImplementation |
||||
{ |
||||
/// <summary>
|
||||
/// Implement INullable with a virtual bool IsNull, create Null class and static instance
|
||||
/// of it.
|
||||
/// </summary>
|
||||
Default, |
||||
/// <summary>
|
||||
/// Create Null class and a static instance using the "new" modifier.
|
||||
/// </summary>
|
||||
Shadow, |
||||
/// <summary>
|
||||
/// Implement INullable with a virtual bool IsNull.
|
||||
/// </summary>
|
||||
Abstract, |
||||
/// <summary>
|
||||
/// Complete an abstract nullable implementation by creating the Null class
|
||||
/// and the static instance.
|
||||
/// </summary>
|
||||
CompleteAbstract |
||||
} |
||||
|
||||
public abstract class TypeImplementationModifierAttribute : Attribute |
||||
{ |
||||
public abstract void ModifyImplementation(CodeNamespace cns, CodeTypeDeclaration ctd, Type type); |
||||
} |
||||
|
||||
[AttributeUsage(AttributeTargets.Class)] |
||||
public class CustomImplementationAttribute : Attribute |
||||
{ |
||||
} |
||||
|
||||
[AttributeUsage(AttributeTargets.Class)] |
||||
public class HasChildrenAttribute : Attribute |
||||
{ |
||||
} |
||||
|
||||
[AttributeUsage(AttributeTargets.Field)] |
||||
public class QuestionMarkDefaultAttribute : Attribute |
||||
{ |
||||
} |
||||
|
||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] |
||||
public class IncludeMemberAttribute : TypeImplementationModifierAttribute |
||||
{ |
||||
string code; |
||||
|
||||
public IncludeMemberAttribute(string code) |
||||
{ |
||||
this.code = code; |
||||
} |
||||
|
||||
public override void ModifyImplementation(CodeNamespace cns, CodeTypeDeclaration ctd, Type type) |
||||
{ |
||||
ctd.Members.Add(new CodeSnippetTypeMember(code)); |
||||
} |
||||
} |
||||
|
||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] |
||||
public class IncludeBoolPropertyAttribute : TypeImplementationModifierAttribute |
||||
{ |
||||
string name; |
||||
string code; |
||||
|
||||
public IncludeBoolPropertyAttribute(string name, string code) |
||||
{ |
||||
this.name = name; |
||||
this.code = code; |
||||
} |
||||
|
||||
public override void ModifyImplementation(CodeNamespace cns, CodeTypeDeclaration ctd, Type type) |
||||
{ |
||||
CodeMemberProperty prop = new CodeMemberProperty(); |
||||
prop.Name = name; |
||||
prop.Type = new CodeTypeReference(typeof(bool)); |
||||
prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; |
||||
prop.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t" + code)); |
||||
ctd.Members.Add(prop); |
||||
} |
||||
} |
||||
|
||||
[AttributeUsage(AttributeTargets.Class)] |
||||
public class ImplementNullableAttribute : TypeImplementationModifierAttribute |
||||
{ |
||||
NullableImplementation implementation; |
||||
|
||||
public ImplementNullableAttribute() |
||||
{ |
||||
this.implementation = NullableImplementation.Default; |
||||
} |
||||
|
||||
public ImplementNullableAttribute(NullableImplementation implementation) |
||||
{ |
||||
this.implementation = implementation; |
||||
} |
||||
|
||||
public override void ModifyImplementation(CodeNamespace cns, CodeTypeDeclaration ctd, Type type) |
||||
{ |
||||
if (implementation == NullableImplementation.Default || implementation == NullableImplementation.Abstract) { |
||||
ctd.BaseTypes.Add(new CodeTypeReference("INullable")); |
||||
CodeMemberProperty prop = new CodeMemberProperty(); |
||||
prop.Name = "IsNull"; |
||||
prop.Type = new CodeTypeReference(typeof(bool)); |
||||
prop.Attributes = MemberAttributes.Public; |
||||
prop.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(false))); |
||||
ctd.Members.Add(prop); |
||||
} |
||||
if (implementation != NullableImplementation.Abstract) { |
||||
EasyTypeDeclaration newType = new EasyTypeDeclaration("Null" + ctd.Name); |
||||
newType.TypeAttributes = TypeAttributes.Class | TypeAttributes.NotPublic | TypeAttributes.Sealed; |
||||
newType.BaseTypes.Add(new CodeTypeReference(ctd.Name)); |
||||
cns.Types.Add(newType); |
||||
|
||||
System.Reflection.ConstructorInfo baseCtor = MainClass.GetBaseCtor(type); |
||||
if (baseCtor != null) { |
||||
CodeConstructor ctor = new CodeConstructor(); |
||||
ctor.Attributes = MemberAttributes.Private; |
||||
foreach (object o in baseCtor.GetParameters()) { |
||||
ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(null)); |
||||
} |
||||
newType.Members.Add(ctor); |
||||
} |
||||
|
||||
CodeMemberField field = new CodeMemberField(newType.Name, "Instance"); |
||||
field.Attributes = MemberAttributes.Static | MemberAttributes.Assembly; |
||||
field.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference(newType.Name)); |
||||
newType.Members.Add(field); |
||||
|
||||
CodeMemberProperty prop = new CodeMemberProperty(); |
||||
prop.Name = "IsNull"; |
||||
prop.Type = new CodeTypeReference(typeof(bool)); |
||||
prop.Attributes = MemberAttributes.Public | MemberAttributes.Override; |
||||
prop.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(true))); |
||||
newType.Members.Add(prop); |
||||
|
||||
CodeMemberMethod method = new CodeMemberMethod(); |
||||
method.Name = "AcceptVisitor"; |
||||
method.Attributes = MemberAttributes.Public | MemberAttributes.Override; |
||||
method.Parameters.Add(new CodeParameterDeclarationExpression("IAstVisitor", "visitor")); |
||||
method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "data")); |
||||
method.ReturnType = new CodeTypeReference(typeof(object)); |
||||
method.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null))); |
||||
newType.Members.Add(method); |
||||
|
||||
method = new CodeMemberMethod(); |
||||
method.Name = "ToString"; |
||||
method.Attributes = MemberAttributes.Public | MemberAttributes.Override; |
||||
method.ReturnType = new CodeTypeReference(typeof(string)); |
||||
method.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("[" + newType.Name + "]"))); |
||||
newType.Members.Add(method); |
||||
|
||||
prop = new CodeMemberProperty(); |
||||
prop.Name = "Null"; |
||||
prop.Type = new CodeTypeReference(ctd.Name); |
||||
prop.Attributes = MemberAttributes.Public | MemberAttributes.Static; |
||||
if (implementation == NullableImplementation.Shadow) { |
||||
prop.Attributes |= MemberAttributes.New; |
||||
} |
||||
CodeExpression ex = new CodeTypeReferenceExpression(newType.Name); |
||||
ex = new CodePropertyReferenceExpression(ex, "Instance"); |
||||
prop.GetStatements.Add(new CodeMethodReturnStatement(ex)); |
||||
ctd.Members.Add(prop); |
||||
} |
||||
} |
||||
} |
||||
} |
@ -1,439 +0,0 @@
@@ -1,439 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.CodeDom; |
||||
|
||||
namespace ICSharpCode.EasyCodeDom |
||||
{ |
||||
public static class Easy |
||||
{ |
||||
public static CodeTypeReference TypeRef(Type type) |
||||
{ |
||||
return new CodeTypeReference(type, CodeTypeReferenceOptions.GlobalReference); |
||||
} |
||||
public static CodeTypeReference TypeRef(CodeTypeDeclaration type) |
||||
{ |
||||
return new CodeTypeReference(type.Name); |
||||
} |
||||
public static CodeTypeReference TypeRef(string typeName, params string[] typeArguments) |
||||
{ |
||||
CodeTypeReference tr = new CodeTypeReference(typeName); |
||||
foreach (string ta in typeArguments) { |
||||
tr.TypeArguments.Add(ta); |
||||
} |
||||
return tr; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Gets the EasyExpression for any primitive value that can be expressed as literal.
|
||||
/// Also works for enumeration values.
|
||||
/// </summary>
|
||||
public static EasyExpression Prim(object literalValue) |
||||
{ |
||||
if (literalValue is Enum) { |
||||
return Type(literalValue.GetType()).Field(literalValue.ToString()); |
||||
} else { |
||||
return new EasyExpression(new CodePrimitiveExpression(literalValue)); |
||||
} |
||||
} |
||||
|
||||
public static EasyExpression Type(Type type) |
||||
{ |
||||
return Type(TypeRef(type)); |
||||
} |
||||
public static EasyExpression Type(CodeTypeReference type) |
||||
{ |
||||
return new EasyExpression(new CodeTypeReferenceExpression(type)); |
||||
} |
||||
public static EasyExpression Type(string type) |
||||
{ |
||||
return Type(new CodeTypeReference(type)); |
||||
} |
||||
|
||||
public static EasyExpression TypeOf(Type type) |
||||
{ |
||||
return TypeOf(TypeRef(type)); |
||||
} |
||||
public static EasyExpression TypeOf(CodeTypeReference type) |
||||
{ |
||||
return new EasyExpression(new CodeTypeOfExpression(type)); |
||||
} |
||||
|
||||
public static EasyExpression New(Type type, params CodeExpression[] arguments) |
||||
{ |
||||
return New(TypeRef(type), arguments); |
||||
} |
||||
public static EasyExpression New(CodeTypeReference type, params CodeExpression[] arguments) |
||||
{ |
||||
return new EasyExpression(new CodeObjectCreateExpression(type, arguments)); |
||||
} |
||||
|
||||
public static EasyExpression Var(string name) |
||||
{ |
||||
return new EasyExpression(new CodeVariableReferenceExpression(name)); |
||||
} |
||||
|
||||
public static EasyExpression Binary(CodeExpression left, |
||||
CodeBinaryOperatorType op, |
||||
CodeExpression right) |
||||
{ |
||||
return new EasyExpression(new CodeBinaryOperatorExpression(left, op, right)); |
||||
} |
||||
|
||||
public static EasyExpression This { |
||||
get { |
||||
return new EasyExpression(new CodeThisReferenceExpression()); |
||||
} |
||||
} |
||||
|
||||
public static EasyExpression Base { |
||||
get { |
||||
return new EasyExpression(new CodeBaseReferenceExpression()); |
||||
} |
||||
} |
||||
|
||||
public static EasyExpression Value { |
||||
get { |
||||
return new EasyExpression(new CodePropertySetValueReferenceExpression()); |
||||
} |
||||
} |
||||
|
||||
public static EasyExpression Null { |
||||
get { |
||||
return new EasyExpression(new CodePrimitiveExpression(null)); |
||||
} |
||||
} |
||||
|
||||
public static void AddSummary(CodeTypeMember member, string summary) |
||||
{ |
||||
member.Comments.Add(new CodeCommentStatement("<summary>", true)); |
||||
member.Comments.Add(new CodeCommentStatement(summary, true)); |
||||
member.Comments.Add(new CodeCommentStatement("</summary>", true)); |
||||
} |
||||
|
||||
internal static CodeAttributeDeclaration AddAttribute(CodeAttributeDeclarationCollection col, |
||||
CodeTypeReference type, |
||||
CodeExpression[] arguments) |
||||
{ |
||||
CodeAttributeArgument[] attributeArguments = new CodeAttributeArgument[arguments.Length]; |
||||
for (int i = 0; i < arguments.Length; i++) { |
||||
attributeArguments[i] = new CodeAttributeArgument(arguments[i]); |
||||
} |
||||
CodeAttributeDeclaration cad = new CodeAttributeDeclaration(type, attributeArguments); |
||||
col.Add(cad); |
||||
return cad; |
||||
} |
||||
} |
||||
|
||||
public sealed class EasyExpression |
||||
{ |
||||
readonly CodeExpression expr; |
||||
|
||||
public EasyExpression(CodeExpression expr) |
||||
{ |
||||
this.expr = expr; |
||||
} |
||||
|
||||
public static implicit operator CodeExpression(EasyExpression expr) |
||||
{ |
||||
return expr.expr; |
||||
} |
||||
|
||||
public EasyExpression InvokeMethod(string name, params CodeExpression[] arguments) |
||||
{ |
||||
return new EasyExpression(new CodeMethodInvokeExpression(expr, name, arguments)); |
||||
} |
||||
|
||||
public EasyExpression CastTo(Type type) |
||||
{ |
||||
return CastTo(Easy.TypeRef(type)); |
||||
} |
||||
public EasyExpression CastTo(CodeTypeReference type) |
||||
{ |
||||
return new EasyExpression(new CodeCastExpression(type, expr)); |
||||
} |
||||
|
||||
public EasyExpression Index(params CodeExpression[] indices) |
||||
{ |
||||
return new EasyExpression(new CodeIndexerExpression(expr, indices)); |
||||
} |
||||
|
||||
public EasyExpression Field(string name) |
||||
{ |
||||
return new EasyExpression(new CodeFieldReferenceExpression(expr, name)); |
||||
} |
||||
|
||||
public EasyExpression Property(string name) |
||||
{ |
||||
return new EasyExpression(new CodePropertyReferenceExpression(expr, name)); |
||||
} |
||||
} |
||||
|
||||
public class EasyCompileUnit : CodeCompileUnit |
||||
{ |
||||
public EasyNamespace AddNamespace(string name) |
||||
{ |
||||
EasyNamespace n = new EasyNamespace(name); |
||||
this.Namespaces.Add(n); |
||||
return n; |
||||
} |
||||
} |
||||
|
||||
public class EasyNamespace : CodeNamespace |
||||
{ |
||||
public EasyNamespace() : base() {} |
||||
public EasyNamespace(string name) : base(name) {} |
||||
|
||||
public EasyTypeDeclaration AddType(string name) |
||||
{ |
||||
EasyTypeDeclaration n = new EasyTypeDeclaration(name); |
||||
this.Types.Add(n); |
||||
return n; |
||||
} |
||||
|
||||
public CodeNamespaceImport AddImport(string nameSpace) |
||||
{ |
||||
CodeNamespaceImport cni = new CodeNamespaceImport(nameSpace); |
||||
this.Imports.Add(cni); |
||||
return cni; |
||||
} |
||||
} |
||||
|
||||
public class EasyTypeDeclaration : CodeTypeDeclaration |
||||
{ |
||||
public EasyTypeDeclaration() : base() {} |
||||
public EasyTypeDeclaration(string name) : base(name) {} |
||||
|
||||
public CodeAttributeDeclaration AddAttribute(Type type, params CodeExpression[] arguments) |
||||
{ |
||||
return Easy.AddAttribute(this.CustomAttributes, Easy.TypeRef(type), arguments); |
||||
} |
||||
public CodeAttributeDeclaration AddAttribute(CodeTypeReference type, params CodeExpression[] arguments) |
||||
{ |
||||
return Easy.AddAttribute(this.CustomAttributes, type, arguments); |
||||
} |
||||
|
||||
public EasyField AddField(Type type, string name) |
||||
{ |
||||
return AddField(Easy.TypeRef(type), name); |
||||
} |
||||
public EasyField AddField(CodeTypeReference type, string name) |
||||
{ |
||||
EasyField f = new EasyField(type, name); |
||||
this.Members.Add(f); |
||||
return f; |
||||
} |
||||
|
||||
public EasyProperty AddProperty(Type type, string name) |
||||
{ |
||||
return AddProperty(Easy.TypeRef(type), name); |
||||
} |
||||
public EasyProperty AddProperty(CodeTypeReference type, string name) |
||||
{ |
||||
EasyProperty p = new EasyProperty(type, name); |
||||
this.Members.Add(p); |
||||
if (this.IsInterface == false) { |
||||
p.Attributes = MemberAttributes.Public | MemberAttributes.Final; |
||||
} |
||||
return p; |
||||
} |
||||
|
||||
public EasyProperty AddProperty(CodeMemberField field, string name) |
||||
{ |
||||
EasyProperty p = AddProperty(field.Type, name); |
||||
p.Getter.Return(new CodeVariableReferenceExpression(field.Name)); |
||||
p.Attributes |= field.Attributes & MemberAttributes.Static; // copy static flag
|
||||
return p; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Adds a method with return type <c>void</c> and attributes=Public|Final to this type.
|
||||
/// </summary>
|
||||
public EasyMethod AddMethod(string name) |
||||
{ |
||||
return AddMethod(Easy.TypeRef(typeof(void)), name); |
||||
} |
||||
/// <summary>
|
||||
/// Adds a method with return type <paramref name="type"/> and attributes=Public|Final to this type.
|
||||
/// </summary>
|
||||
public EasyMethod AddMethod(Type type, string name) |
||||
{ |
||||
return AddMethod(Easy.TypeRef(type), name); |
||||
} |
||||
/// <summary>
|
||||
/// Adds a method with return type <paramref name="type"/> and attributes=Public|Final to this type.
|
||||
/// </summary>
|
||||
public EasyMethod AddMethod(CodeTypeReference type, string name) |
||||
{ |
||||
EasyMethod p = new EasyMethod(type, name); |
||||
this.Members.Add(p); |
||||
if (this.IsInterface == false) { |
||||
p.Attributes = MemberAttributes.Public | MemberAttributes.Final; |
||||
} |
||||
return p; |
||||
} |
||||
} |
||||
|
||||
public class EasyField : CodeMemberField |
||||
{ |
||||
public EasyField() : base() {} |
||||
public EasyField(CodeTypeReference type, string name) : base(type, name) {} |
||||
|
||||
public CodeAttributeDeclaration AddAttribute(Type type, params CodeExpression[] arguments) |
||||
{ |
||||
return Easy.AddAttribute(this.CustomAttributes, Easy.TypeRef(type), arguments); |
||||
} |
||||
public CodeAttributeDeclaration AddAttribute(CodeTypeReference type, params CodeExpression[] arguments) |
||||
{ |
||||
return Easy.AddAttribute(this.CustomAttributes, type, arguments); |
||||
} |
||||
} |
||||
|
||||
public class EasyProperty : CodeMemberProperty |
||||
{ |
||||
EasyBlock getter, setter; |
||||
|
||||
public EasyProperty() |
||||
{ |
||||
getter = new EasyBlock(this.GetStatements); |
||||
setter = new EasyBlock(this.SetStatements); |
||||
} |
||||
|
||||
public EasyProperty(CodeTypeReference type, string name) : this() |
||||
{ |
||||
this.Type = type; |
||||
this.Name = name; |
||||
} |
||||
|
||||
public CodeAttributeDeclaration AddAttribute(Type type, params CodeExpression[] arguments) |
||||
{ |
||||
return Easy.AddAttribute(this.CustomAttributes, Easy.TypeRef(type), arguments); |
||||
} |
||||
public CodeAttributeDeclaration AddAttribute(CodeTypeReference type, params CodeExpression[] arguments) |
||||
{ |
||||
return Easy.AddAttribute(this.CustomAttributes, type, arguments); |
||||
} |
||||
|
||||
public EasyBlock Getter { |
||||
get { return getter; } |
||||
} |
||||
|
||||
public EasyBlock Setter { |
||||
get { return setter; } |
||||
} |
||||
} |
||||
|
||||
public class EasyMethod : CodeMemberMethod |
||||
{ |
||||
EasyBlock body; |
||||
|
||||
public EasyMethod() |
||||
{ |
||||
body = new EasyBlock(this.Statements); |
||||
} |
||||
|
||||
public EasyMethod(CodeTypeReference type, string name) : this() |
||||
{ |
||||
this.ReturnType = type; |
||||
this.Name = name; |
||||
} |
||||
|
||||
public CodeAttributeDeclaration AddAttribute(Type type, params CodeExpression[] arguments) |
||||
{ |
||||
return Easy.AddAttribute(this.CustomAttributes, Easy.TypeRef(type), arguments); |
||||
} |
||||
public CodeAttributeDeclaration AddAttribute(CodeTypeReference type, params CodeExpression[] arguments) |
||||
{ |
||||
return Easy.AddAttribute(this.CustomAttributes, type, arguments); |
||||
} |
||||
|
||||
public CodeParameterDeclarationExpression AddParameter(Type type, string name) |
||||
{ |
||||
return AddParameter(Easy.TypeRef(type), name); |
||||
} |
||||
public CodeParameterDeclarationExpression AddParameter(CodeTypeReference type, string name) |
||||
{ |
||||
CodeParameterDeclarationExpression cpde; |
||||
cpde = new CodeParameterDeclarationExpression(type, name); |
||||
this.Parameters.Add(cpde); |
||||
return cpde; |
||||
} |
||||
|
||||
public EasyBlock Body { |
||||
get { return body; } |
||||
} |
||||
} |
||||
|
||||
public sealed class EasyBlock |
||||
{ |
||||
readonly CodeStatementCollection csc; |
||||
|
||||
public EasyBlock(CodeStatementCollection csc) |
||||
{ |
||||
this.csc = csc; |
||||
} |
||||
|
||||
public CodeMethodReturnStatement Return(CodeExpression expr) |
||||
{ |
||||
CodeMethodReturnStatement st = new CodeMethodReturnStatement(expr); |
||||
csc.Add(st); |
||||
return st; |
||||
} |
||||
|
||||
public CodeAssignStatement Assign(CodeExpression lhs, CodeExpression rhs) |
||||
{ |
||||
CodeAssignStatement st = new CodeAssignStatement(lhs, rhs); |
||||
csc.Add(st); |
||||
return st; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Execute one expression as statement.
|
||||
/// </summary>
|
||||
public CodeExpressionStatement Add(CodeExpression expr) |
||||
{ |
||||
CodeExpressionStatement st = new CodeExpressionStatement(expr); |
||||
csc.Add(st); |
||||
return st; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Adds the statement.
|
||||
/// </summary>
|
||||
public CodeStatement Add(CodeStatement st) |
||||
{ |
||||
csc.Add(st); |
||||
return st; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Invoke a method on target as statement.
|
||||
/// </summary>
|
||||
public CodeExpressionStatement InvokeMethod(CodeExpression target, string name, params CodeExpression[] arguments) |
||||
{ |
||||
return Add(new CodeMethodInvokeExpression(target, name, arguments)); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Declares a local variable.
|
||||
/// </summary>
|
||||
public CodeVariableDeclarationStatement DeclareVariable(Type type, string name) |
||||
{ |
||||
return DeclareVariable(Easy.TypeRef(type), name); |
||||
} |
||||
/// <summary>
|
||||
/// Declares a local variable.
|
||||
/// </summary>
|
||||
public CodeVariableDeclarationStatement DeclareVariable(CodeTypeReference type, string name) |
||||
{ |
||||
CodeVariableDeclarationStatement st = new CodeVariableDeclarationStatement(type, name); |
||||
csc.Add(st); |
||||
return st; |
||||
} |
||||
} |
||||
} |
@ -1,542 +0,0 @@
@@ -1,542 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using System.CodeDom; |
||||
using System.Diagnostics; |
||||
using System.Reflection; |
||||
using System.IO; |
||||
using NRefactoryASTGenerator.Ast; |
||||
using ICSharpCode.EasyCodeDom; |
||||
|
||||
namespace NRefactoryASTGenerator |
||||
{ |
||||
class MainClass |
||||
{ |
||||
public const string VisitPrefix = "Visit"; |
||||
|
||||
public static void Main(string[] args) |
||||
{ |
||||
string directory = "../../../Project/Src/Ast/"; |
||||
string visitorsDir = "../../../Project/Src/Visitors/"; |
||||
Debug.WriteLine("AST Generator running..."); |
||||
if (!File.Exists(directory + "INode.cs")) { |
||||
Debug.WriteLine("did not find output directory"); |
||||
return; |
||||
} |
||||
if (!File.Exists(visitorsDir + "AbstractAstTransformer.cs")) { |
||||
Debug.WriteLine("did not find visitor output directory"); |
||||
return; |
||||
} |
||||
|
||||
List<Type> nodeTypes = new List<Type>(); |
||||
foreach (Type type in typeof(MainClass).Assembly.GetTypes()) { |
||||
if (type.IsClass && typeof(INode).IsAssignableFrom(type)) { |
||||
nodeTypes.Add(type); |
||||
} |
||||
} |
||||
nodeTypes.Sort(delegate(Type a, Type b) { return a.Name.CompareTo(b.Name); }); |
||||
|
||||
EasyCompileUnit ccu = new EasyCompileUnit(); |
||||
EasyNamespace cns = ccu.AddNamespace("ICSharpCode.NRefactory.Ast"); |
||||
cns.AddImport("System"); |
||||
cns.AddImport("System.Collections.Generic"); |
||||
foreach (Type type in nodeTypes) { |
||||
if (type.GetCustomAttributes(typeof(CustomImplementationAttribute), false).Length == 0) { |
||||
EasyTypeDeclaration ctd = cns.AddType(type.Name); |
||||
if (type.IsAbstract) { |
||||
ctd.TypeAttributes |= TypeAttributes.Abstract; |
||||
} |
||||
ctd.BaseTypes.Add(new CodeTypeReference(type.BaseType.Name)); |
||||
|
||||
ProcessType(type, ctd); |
||||
|
||||
foreach (object o in type.GetCustomAttributes(false)) { |
||||
if (o is TypeImplementationModifierAttribute) { |
||||
(o as TypeImplementationModifierAttribute).ModifyImplementation(cns, ctd, type); |
||||
} |
||||
} |
||||
|
||||
if (!type.IsAbstract) { |
||||
CodeMemberMethod method = new CodeMemberMethod(); |
||||
method.Name = "AcceptVisitor"; |
||||
method.Attributes = MemberAttributes.Public | MemberAttributes.Override; |
||||
method.Parameters.Add(new CodeParameterDeclarationExpression("IAstVisitor", "visitor")); |
||||
method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "data")); |
||||
method.ReturnType = new CodeTypeReference(typeof(object)); |
||||
CodeExpression ex = new CodeVariableReferenceExpression("visitor"); |
||||
ex = new CodeMethodInvokeExpression(ex, VisitPrefix + ctd.Name, |
||||
new CodeThisReferenceExpression(), |
||||
new CodeVariableReferenceExpression("data")); |
||||
method.Statements.Add(new CodeMethodReturnStatement(ex)); |
||||
ctd.Members.Add(method); |
||||
|
||||
method = new CodeMemberMethod(); |
||||
method.Name = "ToString"; |
||||
method.Attributes = MemberAttributes.Public | MemberAttributes.Override; |
||||
method.ReturnType = new CodeTypeReference(typeof(string)); |
||||
method.Statements.Add(new CodeMethodReturnStatement(CreateToString(type))); |
||||
ctd.Members.Add(method); |
||||
} |
||||
} |
||||
} |
||||
|
||||
System.CodeDom.Compiler.CodeGeneratorOptions settings = new System.CodeDom.Compiler.CodeGeneratorOptions(); |
||||
settings.IndentString = "\t"; |
||||
settings.VerbatimOrder = true; |
||||
|
||||
using (StringWriter writer = new StringWriter()) { |
||||
new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromCompileUnit(ccu, writer, settings); |
||||
File.WriteAllText(directory + "Generated.cs", writer.ToString()); |
||||
} |
||||
|
||||
ccu = new EasyCompileUnit(); |
||||
cns = ccu.AddNamespace("ICSharpCode.NRefactory"); |
||||
cns.AddImport("System"); |
||||
cns.AddImport("ICSharpCode.NRefactory.Ast"); |
||||
cns.Types.Add(CreateAstVisitorInterface(nodeTypes)); |
||||
|
||||
using (StringWriter writer = new StringWriter()) { |
||||
new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromCompileUnit(ccu, writer, settings); |
||||
File.WriteAllText(visitorsDir + "../IAstVisitor.cs", writer.ToString()); |
||||
} |
||||
|
||||
ccu = new EasyCompileUnit(); |
||||
cns = ccu.AddNamespace("ICSharpCode.NRefactory.Visitors"); |
||||
cns.AddImport("System"); |
||||
cns.AddImport("System.Collections.Generic"); |
||||
cns.AddImport("System.Diagnostics"); |
||||
cns.AddImport("ICSharpCode.NRefactory.Ast"); |
||||
cns.Types.Add(CreateAstVisitorClass(nodeTypes, false)); |
||||
|
||||
using (StringWriter writer = new StringWriter()) { |
||||
new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromCompileUnit(ccu, writer, settings); |
||||
File.WriteAllText(visitorsDir + "AbstractAstVisitor.cs", writer.ToString()); |
||||
} |
||||
|
||||
ccu = new EasyCompileUnit(); |
||||
cns = ccu.AddNamespace("ICSharpCode.NRefactory.Visitors"); |
||||
cns.AddImport("System"); |
||||
cns.AddImport("System.Collections.Generic"); |
||||
cns.AddImport("System.Diagnostics"); |
||||
cns.AddImport("ICSharpCode.NRefactory.Ast"); |
||||
cns.Types.Add(CreateAstVisitorClass(nodeTypes, true)); |
||||
|
||||
using (StringWriter writer = new StringWriter()) { |
||||
new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromCompileUnit(ccu, writer, settings); |
||||
File.WriteAllText(visitorsDir + "AbstractAstTransformer.cs", writer.ToString()); |
||||
} |
||||
|
||||
ccu = new EasyCompileUnit(); |
||||
cns = ccu.AddNamespace("ICSharpCode.NRefactory.Visitors"); |
||||
cns.AddImport("System"); |
||||
cns.AddImport("ICSharpCode.NRefactory.Ast"); |
||||
cns.Types.Add(CreateNodeTrackingAstVisitorClass(nodeTypes)); |
||||
|
||||
using (StringWriter writer = new StringWriter()) { |
||||
new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromCompileUnit(ccu, writer, settings); |
||||
// CodeDom cannot output "sealed", so we need to use this hack:
|
||||
File.WriteAllText(visitorsDir + "NodeTrackingAstVisitor.cs", |
||||
writer.ToString().Replace("public override object", "public sealed override object")); |
||||
} |
||||
} |
||||
|
||||
static CodeTypeDeclaration CreateAstVisitorInterface(List<Type> nodeTypes) |
||||
{ |
||||
EasyTypeDeclaration td = new EasyTypeDeclaration("IAstVisitor"); |
||||
td.IsInterface = true; |
||||
|
||||
foreach (Type t in nodeTypes) { |
||||
if (!t.IsAbstract) { |
||||
EasyMethod m = td.AddMethod(typeof(object), VisitPrefix + t.Name); |
||||
m.AddParameter(ConvertType(t), GetFieldName(t.Name)); |
||||
m.AddParameter(typeof(object), "data"); |
||||
} |
||||
} |
||||
return td; |
||||
} |
||||
|
||||
static CodeTypeDeclaration CreateAstVisitorClass(List<Type> nodeTypes, bool transformer) |
||||
{ |
||||
EasyTypeDeclaration td = new EasyTypeDeclaration(transformer ? "AbstractAstTransformer" : "AbstractAstVisitor"); |
||||
td.TypeAttributes = TypeAttributes.Public | TypeAttributes.Abstract; |
||||
td.BaseTypes.Add(new CodeTypeReference("IAstVisitor")); |
||||
|
||||
if (transformer) { |
||||
string comment = |
||||
"The AbstractAstTransformer will iterate through the whole AST,\n " + |
||||
"just like the AbstractAstVisitor. However, the AbstractAstTransformer allows\n " + |
||||
"you to modify the AST at the same time: It does not use 'foreach' internally,\n " + |
||||
"so you can add members to collections of parents of the current node (but\n " + |
||||
"you cannot insert or delete items as that will make the index used invalid).\n " + |
||||
"You can use the methods ReplaceCurrentNode and RemoveCurrentNode to replace\n " + |
||||
"or remove the current node, totally independent from the type of the parent node."; |
||||
Easy.AddSummary(td, comment); |
||||
|
||||
EasyField field = td.AddField(Easy.TypeRef("Stack", "INode"), "nodeStack"); |
||||
field.InitExpression = Easy.New(field.Type); |
||||
|
||||
/* |
||||
CodeExpression nodeStack = Easy.Var("nodeStack"); |
||||
CodeMemberProperty p = new CodeMemberProperty(); |
||||
p.Name = "CurrentNode"; |
||||
p.Type = new CodeTypeReference("INode"); |
||||
p.Attributes = MemberAttributes.Public | MemberAttributes.Final; |
||||
p.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("currentNode"))); |
||||
p.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("currentNode"), |
||||
new CodePropertySetValueReferenceExpression())); |
||||
td.Members.Add(p); |
||||
*/ |
||||
|
||||
EasyMethod m = td.AddMethod("ReplaceCurrentNode"); |
||||
m.AddParameter(Easy.TypeRef("INode"), "newNode"); |
||||
m.Statements.Add(Easy.Var("nodeStack").InvokeMethod("Pop")); |
||||
m.Statements.Add(Easy.Var("nodeStack").InvokeMethod("Push", Easy.Var("newNode"))); |
||||
|
||||
m = td.AddMethod("RemoveCurrentNode"); |
||||
m.Statements.Add(Easy.Var("nodeStack").InvokeMethod("Pop")); |
||||
m.Statements.Add(Easy.Var("nodeStack").InvokeMethod("Push", Easy.Null)); |
||||
} |
||||
|
||||
foreach (Type type in nodeTypes) { |
||||
if (!type.IsAbstract) { |
||||
EasyMethod m = td.AddMethod(typeof(object), VisitPrefix + type.Name); |
||||
m.Attributes = MemberAttributes.Public; |
||||
m.AddParameter(ConvertType(type), GetFieldName(type.Name)); |
||||
m.AddParameter(typeof(object), "data"); |
||||
|
||||
List<CodeStatement> assertions = new List<CodeStatement>(); |
||||
string varVariableName = GetFieldName(type.Name); |
||||
EasyExpression var = Easy.Var(varVariableName); |
||||
assertions.Add(AssertIsNotNull(var)); |
||||
|
||||
AddFieldVisitCode(m, type, var, assertions, transformer); |
||||
|
||||
if (type.GetCustomAttributes(typeof(HasChildrenAttribute), true).Length > 0) { |
||||
if (transformer) { |
||||
m.Statements.Add(new CodeSnippetStatement(CreateTransformerLoop(varVariableName + ".Children", "INode"))); |
||||
m.Body.Return(Easy.Null); |
||||
} else { |
||||
m.Body.Return(var.InvokeMethod("AcceptChildren", Easy.This, Easy.Var("data"))); |
||||
} |
||||
} else { |
||||
CodeExpressionStatement lastStatement = null; |
||||
if (m.Statements.Count > 0) { |
||||
lastStatement = m.Statements[m.Statements.Count - 1] as CodeExpressionStatement; |
||||
} |
||||
if (lastStatement != null) { |
||||
m.Statements.RemoveAt(m.Statements.Count - 1); |
||||
m.Body.Return(lastStatement.Expression); |
||||
} else { |
||||
m.Body.Return(Easy.Null); |
||||
} |
||||
} |
||||
|
||||
for (int i = 0; i < assertions.Count; i++) { |
||||
m.Statements.Insert(i, assertions[i]); |
||||
} |
||||
} |
||||
} |
||||
return td; |
||||
} |
||||
|
||||
static void AddFieldVisitCode(EasyMethod m, Type type, EasyExpression var, List<CodeStatement> assertions, bool transformer) |
||||
{ |
||||
if (type != null) { |
||||
if (type.BaseType != typeof(StatementWithEmbeddedStatement)) { |
||||
AddFieldVisitCode(m, type.BaseType, var, assertions, transformer); |
||||
} |
||||
foreach (FieldInfo field in type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic)) { |
||||
AddVisitCode(m, field, var, assertions, transformer); |
||||
} |
||||
if (type.BaseType == typeof(StatementWithEmbeddedStatement)) { |
||||
AddFieldVisitCode(m, type.BaseType, var, assertions, transformer); |
||||
} |
||||
} |
||||
} |
||||
|
||||
static CodeStatement AssertIsNotNull(CodeExpression expr) |
||||
{ |
||||
return new CodeExpressionStatement( |
||||
Easy.Type("Debug").InvokeMethod("Assert", |
||||
Easy.Binary(expr, |
||||
CodeBinaryOperatorType.IdentityInequality, |
||||
Easy.Null)) |
||||
); |
||||
} |
||||
|
||||
static string GetCode(CodeExpression ex) |
||||
{ |
||||
using (StringWriter writer = new StringWriter()) { |
||||
new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromExpression(ex, writer, null); |
||||
return writer.ToString(); |
||||
} |
||||
} |
||||
|
||||
static string CreateTransformerLoop(string collection, string typeName) |
||||
{ |
||||
return |
||||
"\t\t\tfor (int i = 0; i < " + collection + ".Count; i++) {\n" + |
||||
"\t\t\t\t" + typeName + " o = " + collection + "[i];\n" + |
||||
"\t\t\t\tDebug.Assert(o != null);\n" + |
||||
"\t\t\t\tnodeStack.Push(o);\n" + |
||||
"\t\t\t\to.AcceptVisitor(this, data);\n" + |
||||
(typeName == "INode" |
||||
? "\t\t\t\to = nodeStack.Pop();\n" |
||||
: "\t\t\t\to = (" + typeName + ")nodeStack.Pop();\n") + |
||||
"\t\t\t\tif (o == null)\n" + |
||||
"\t\t\t\t\t" + collection + ".RemoveAt(i--);\n" + |
||||
"\t\t\t\telse\n" + |
||||
"\t\t\t\t\t" + collection + "[i] = o;\n" + |
||||
"\t\t\t}"; |
||||
} |
||||
|
||||
static bool AddVisitCode(EasyMethod m, FieldInfo field, EasyExpression var, List<CodeStatement> assertions, bool transformer) |
||||
{ |
||||
EasyExpression prop = var.Property(GetPropertyName(field.Name)); |
||||
EasyExpression nodeStack = Easy.Var("nodeStack"); |
||||
if (field.FieldType.FullName.StartsWith("System.Collections.Generic.List")) { |
||||
Type elType = field.FieldType.GetGenericArguments()[0]; |
||||
if (!typeof(INode).IsAssignableFrom(elType)) |
||||
return false; |
||||
assertions.Add(AssertIsNotNull(prop)); |
||||
string code; |
||||
if (transformer) { |
||||
code = CreateTransformerLoop(GetCode(prop), ConvertType(elType).BaseType); |
||||
} else { |
||||
code = |
||||
"\t\t\tforeach (" + ConvertType(elType).BaseType + " o in " + GetCode(prop) + ") {\n" + |
||||
"\t\t\t\tDebug.Assert(o != null);\n" + |
||||
"\t\t\t\to.AcceptVisitor(this, data);\n" + |
||||
"\t\t\t}"; |
||||
} |
||||
m.Statements.Add(new CodeSnippetStatement(code)); |
||||
return true; |
||||
} |
||||
if (!typeof(INode).IsAssignableFrom(field.FieldType)) |
||||
return false; |
||||
assertions.Add(AssertIsNotNull(prop)); |
||||
if (transformer) { |
||||
m.Statements.Add(nodeStack.InvokeMethod("Push", prop)); |
||||
} |
||||
m.Statements.Add(prop.InvokeMethod("AcceptVisitor", |
||||
Easy.This, |
||||
Easy.Var("data"))); |
||||
if (transformer) { |
||||
m.Body.Assign(prop, nodeStack.InvokeMethod("Pop").CastTo(ConvertType(field.FieldType))); |
||||
} |
||||
return true; |
||||
} |
||||
|
||||
static CodeExpression CreateToString(Type type) |
||||
{ |
||||
CodeMethodInvokeExpression ie = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(string)), |
||||
"Format"); |
||||
CodePrimitiveExpression prim = new CodePrimitiveExpression(); |
||||
ie.Parameters.Add(prim); |
||||
string text = "[" + type.Name; |
||||
int index = 0; |
||||
do { |
||||
foreach (FieldInfo field in type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic)) { |
||||
text += " " + GetPropertyName(field.Name) + "={" + index.ToString() + "}"; |
||||
index++; |
||||
if (typeof(System.Collections.ICollection).IsAssignableFrom(field.FieldType)) { |
||||
ie.Parameters.Add(new CodeSnippetExpression("GetCollectionString(" + GetPropertyName(field.Name) + ")")); |
||||
} else { |
||||
ie.Parameters.Add(new CodeVariableReferenceExpression(GetPropertyName(field.Name))); |
||||
} |
||||
} |
||||
type = type.BaseType; |
||||
} while (type != null); |
||||
prim.Value = text + "]"; |
||||
if (ie.Parameters.Count == 1) |
||||
return prim; |
||||
else |
||||
return ie; |
||||
// return String.Format("[AnonymousMethodExpression: Parameters={0} Body={1}]",
|
||||
// GetCollectionString(Parameters),
|
||||
// Body);
|
||||
} |
||||
|
||||
static void ProcessType(Type type, EasyTypeDeclaration ctd) |
||||
{ |
||||
foreach (FieldInfo field in type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic)) { |
||||
ctd.AddField(ConvertType(field.FieldType), field.Name).Attributes = 0; |
||||
} |
||||
foreach (FieldInfo field in type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic)) { |
||||
EasyProperty p = ctd.AddProperty(ConvertType(field.FieldType), GetPropertyName(field.Name)); |
||||
p.Getter.Return(Easy.Var(field.Name)); |
||||
CodeExpression ex; |
||||
if (field.FieldType.IsValueType) |
||||
ex = new CodePropertySetValueReferenceExpression(); |
||||
else |
||||
ex = GetDefaultValue("value", field); |
||||
p.Setter.Assign(Easy.Var(field.Name), ex); |
||||
if (typeof(INode).IsAssignableFrom(field.FieldType) && typeof(INullable).IsAssignableFrom(field.FieldType)) { |
||||
p.SetStatements.Add(new CodeSnippetStatement("\t\t\t\tif (!" +field.Name+".IsNull) "+field.Name+".Parent = this;")); |
||||
} |
||||
} |
||||
foreach (ConstructorInfo ctor in type.GetConstructors()) { |
||||
CodeConstructor c = new CodeConstructor(); |
||||
if (type.IsAbstract) |
||||
c.Attributes = MemberAttributes.Family; |
||||
else |
||||
c.Attributes = MemberAttributes.Public; |
||||
ctd.Members.Add(c); |
||||
ConstructorInfo baseCtor = GetBaseCtor(type); |
||||
foreach(ParameterInfo param in ctor.GetParameters()) { |
||||
c.Parameters.Add(new CodeParameterDeclarationExpression(ConvertType(param.ParameterType), |
||||
param.Name)); |
||||
if (baseCtor != null && Array.Exists(baseCtor.GetParameters(), delegate(ParameterInfo p) { return param.Name == p.Name; })) |
||||
continue; |
||||
c.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(GetPropertyName(param.Name)), |
||||
new CodeVariableReferenceExpression(param.Name))); |
||||
} |
||||
if (baseCtor != null) { |
||||
foreach(ParameterInfo param in baseCtor.GetParameters()) { |
||||
c.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(param.Name)); |
||||
} |
||||
} |
||||
// initialize fields that were not initialized by parameter
|
||||
foreach (FieldInfo field in type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic)) { |
||||
if (field.FieldType.IsValueType && field.FieldType != typeof(Location)) |
||||
continue; |
||||
if (Array.Exists(ctor.GetParameters(), delegate(ParameterInfo p) { return field.Name == p.Name; })) |
||||
continue; |
||||
c.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(field.Name), |
||||
GetDefaultValue(null, field))); |
||||
} |
||||
} |
||||
} |
||||
|
||||
internal static ConstructorInfo GetBaseCtor(Type type) |
||||
{ |
||||
ConstructorInfo[] list = type.BaseType.GetConstructors(); |
||||
if (list.Length == 0) |
||||
return null; |
||||
else |
||||
return list[0]; |
||||
} |
||||
|
||||
internal static CodeExpression GetDefaultValue(string inputVariable, FieldInfo field) |
||||
{ |
||||
string code; |
||||
// get default value:
|
||||
if (field.FieldType == typeof(string)) { |
||||
code = "\"\""; |
||||
if (field.GetCustomAttributes(typeof(QuestionMarkDefaultAttribute), false).Length > 0) { |
||||
if (inputVariable == null) |
||||
return new CodePrimitiveExpression("?"); |
||||
else |
||||
return new CodeSnippetExpression("string.IsNullOrEmpty(" + inputVariable + ") ? \"?\" : " + inputVariable); |
||||
} |
||||
} else if (field.FieldType.FullName.StartsWith("System.Collections.Generic.List")) { |
||||
code = "new List<" + field.FieldType.GetGenericArguments()[0].Name + ">()"; |
||||
} else if (field.FieldType == typeof(Location)) { |
||||
code = "Location.Empty"; |
||||
} else { |
||||
code = field.FieldType.Name + ".Null"; |
||||
} |
||||
if (inputVariable != null) { |
||||
code = inputVariable + " ?? " + code; |
||||
} |
||||
return new CodeSnippetExpression(code); |
||||
} |
||||
|
||||
internal static string GetFieldName(string typeName) |
||||
{ |
||||
return char.ToLower(typeName[0]) + typeName.Substring(1); |
||||
} |
||||
|
||||
internal static string GetPropertyName(string fieldName) |
||||
{ |
||||
return char.ToUpper(fieldName[0]) + fieldName.Substring(1); |
||||
} |
||||
|
||||
internal static CodeTypeReference ConvertType(Type type) |
||||
{ |
||||
if (type.IsGenericType && !type.IsGenericTypeDefinition) { |
||||
CodeTypeReference tr = ConvertType(type.GetGenericTypeDefinition()); |
||||
foreach (Type subType in type.GetGenericArguments()) { |
||||
tr.TypeArguments.Add(ConvertType(subType)); |
||||
} |
||||
return tr; |
||||
} else if (type.FullName.StartsWith("NRefactory") || type.FullName.StartsWith("System.Collections")) { |
||||
if (type.Name == "Attribute") |
||||
return new CodeTypeReference("ICSharpCode.NRefactory.Ast.Attribute"); |
||||
return new CodeTypeReference(type.Name); |
||||
} else { |
||||
return new CodeTypeReference(type); |
||||
} |
||||
} |
||||
|
||||
static CodeTypeDeclaration CreateNodeTrackingAstVisitorClass(List<Type> nodeTypes) |
||||
{ |
||||
EasyTypeDeclaration td = new EasyTypeDeclaration("NodeTrackingAstVisitor"); |
||||
td.TypeAttributes = TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Abstract; |
||||
td.BaseTypes.Add(new CodeTypeReference("AbstractAstVisitor")); |
||||
|
||||
string comment = "<summary>\n " + |
||||
"The NodeTrackingAstVisitor will iterate through the whole AST,\n " + |
||||
"just like the AbstractAstVisitor, and calls the virtual methods\n " + |
||||
"BeginVisit and EndVisit for each node being visited.\n " + |
||||
"</summary>"; |
||||
td.Comments.Add(new CodeCommentStatement(comment, true)); |
||||
comment = "<remarks>\n " + |
||||
"base.Visit(node, data) calls this.TrackedVisit(node, data), so if\n " + |
||||
"you want to visit child nodes using the default visiting behaviour,\n " + |
||||
"use base.TrackedVisit(parentNode, data).\n " + |
||||
"</remarks>"; |
||||
td.Comments.Add(new CodeCommentStatement(comment, true)); |
||||
|
||||
EasyMethod m = td.AddMethod("BeginVisit"); |
||||
m.Attributes = MemberAttributes.Family; |
||||
m.AddParameter(Easy.TypeRef("INode"), "node"); |
||||
|
||||
m = td.AddMethod("EndVisit"); |
||||
m.Attributes = MemberAttributes.Family; |
||||
m.AddParameter(Easy.TypeRef("INode"), "node"); |
||||
|
||||
foreach (Type type in nodeTypes) { |
||||
if (!type.IsAbstract) { |
||||
|
||||
m = td.AddMethod(typeof(object), VisitPrefix + type.Name); |
||||
m.Attributes = MemberAttributes.Public | MemberAttributes.Override; |
||||
m.AddParameter(ConvertType(type), GetFieldName(type.Name)); |
||||
m.AddParameter(new CodeTypeReference(typeof(object)), "data"); |
||||
|
||||
CodeExpression var = Easy.Var(GetFieldName(type.Name)); |
||||
|
||||
// m.Statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "BeginVisit"), new CodeExpression[] { var }));
|
||||
// m.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(object)), "result", new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "TrackedVisit"), new CodeExpression[] { var, new CodeVariableReferenceExpression("data") })));
|
||||
// m.Statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "EndVisit"), new CodeExpression[] { var }));
|
||||
// m.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("result")));
|
||||
m.Body.InvokeMethod(Easy.This, "BeginVisit", var); |
||||
m.Body.DeclareVariable(typeof(object), "result").InitExpression |
||||
= Easy.This.InvokeMethod("TrackedVisit" + type.Name, var, Easy.Var("data")); |
||||
m.Body.InvokeMethod(Easy.This, "EndVisit", var); |
||||
m.Body.Return(Easy.Var("result")); |
||||
} |
||||
} |
||||
|
||||
foreach (Type type in nodeTypes) { |
||||
if (!type.IsAbstract) { |
||||
|
||||
m = td.AddMethod(typeof(object), "TrackedVisit" + type.Name); |
||||
m.Attributes = MemberAttributes.Public; |
||||
m.AddParameter(ConvertType(type), GetFieldName(type.Name)); |
||||
m.AddParameter(new CodeTypeReference(typeof(object)), "data"); |
||||
|
||||
m.Body.Return(Easy.Base.InvokeMethod(VisitPrefix + type.Name, Easy.Var(GetFieldName(type.Name)), Easy.Var("data"))); |
||||
} |
||||
} |
||||
|
||||
return td; |
||||
} |
||||
} |
||||
} |
@ -1,56 +0,0 @@
@@ -1,56 +0,0 @@
|
||||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> |
||||
<PropertyGroup> |
||||
<OutputType>Exe</OutputType> |
||||
<RootNamespace>NRefactoryASTGenerator</RootNamespace> |
||||
<AssemblyName>NRefactoryASTGenerator</AssemblyName> |
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> |
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> |
||||
<ProjectGuid>{B22522AA-B5BF-4A58-AC6D-D4B45805521F}</ProjectGuid> |
||||
<AllowUnsafeBlocks>False</AllowUnsafeBlocks> |
||||
<NoStdLib>False</NoStdLib> |
||||
<RegisterForComInterop>False</RegisterForComInterop> |
||||
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies> |
||||
<BaseAddress>4194304</BaseAddress> |
||||
<PlatformTarget>AnyCPU</PlatformTarget> |
||||
<FileAlignment>4096</FileAlignment> |
||||
<WarningLevel>4</WarningLevel> |
||||
<NoWarn>0169</NoWarn> |
||||
<TreatWarningsAsErrors>false</TreatWarningsAsErrors> |
||||
</PropertyGroup> |
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> |
||||
<OutputPath>bin\Debug\</OutputPath> |
||||
<Optimize>False</Optimize> |
||||
<DefineConstants>DEBUG;TRACE</DefineConstants> |
||||
<DebugSymbols>true</DebugSymbols> |
||||
<DebugType>Full</DebugType> |
||||
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow> |
||||
</PropertyGroup> |
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Release' "> |
||||
<OutputPath>bin\Release\</OutputPath> |
||||
<Optimize>True</Optimize> |
||||
<DefineConstants>TRACE</DefineConstants> |
||||
<DebugSymbols>False</DebugSymbols> |
||||
<DebugType>None</DebugType> |
||||
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> |
||||
</PropertyGroup> |
||||
<ItemGroup> |
||||
<Reference Include="System" /> |
||||
<Reference Include="System.Data" /> |
||||
<Reference Include="System.Xml" /> |
||||
</ItemGroup> |
||||
<ItemGroup> |
||||
<Compile Include="EasyCodeDom.cs" /> |
||||
<Compile Include="Main.cs" /> |
||||
<Compile Include="AssemblyInfo.cs" /> |
||||
<Compile Include="AST\Expressions.cs" /> |
||||
<Compile Include="Attributes.cs" /> |
||||
<Compile Include="AST\Node.cs" /> |
||||
<Compile Include="AST\Statements.cs" /> |
||||
<Compile Include="AST\TypeLevel.cs" /> |
||||
<Compile Include="AST\GlobalLevel.cs" /> |
||||
</ItemGroup> |
||||
<ItemGroup> |
||||
<Folder Include="AST" /> |
||||
</ItemGroup> |
||||
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.Targets" /> |
||||
</Project> |
@ -1,25 +0,0 @@
@@ -1,25 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="none" email=""/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Reflection; |
||||
using System.Runtime.CompilerServices; |
||||
|
||||
[assembly: CLSCompliant(true)] |
||||
[assembly: StringFreezing()] |
||||
|
||||
// Information about this assembly is defined by the following
|
||||
// attributes.
|
||||
//
|
||||
// change them to the information which is associated with the assembly
|
||||
// you compile.
|
||||
|
||||
[assembly: AssemblyTitle("NRefactory")] |
||||
[assembly: AssemblyDescription("Parser and refactoring library for C# and VB.NET")] |
||||
[assembly: AssemblyConfiguration("")] |
||||
[assembly: AssemblyTrademark("")] |
||||
[assembly: AssemblyCulture("")] |
@ -1,157 +0,0 @@
@@ -1,157 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?> |
||||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0"> |
||||
<PropertyGroup> |
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> |
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> |
||||
<ProductVersion>8.0.41115</ProductVersion> |
||||
<SchemaVersion>2.0</SchemaVersion> |
||||
<ProjectGuid>{3A9AE6AA-BC07-4A2F-972C-581E3AE2F195}</ProjectGuid> |
||||
<RootNamespace>ICSharpCode.NRefactory</RootNamespace> |
||||
<AssemblyName>ICSharpCode.NRefactory</AssemblyName> |
||||
<OutputTarget>Library</OutputTarget> |
||||
<WarningLevel>4</WarningLevel> |
||||
<NoStdLib>False</NoStdLib> |
||||
<NoConfig>False</NoConfig> |
||||
<RunPostBuildEvent>OnSuccessfulBuild</RunPostBuildEvent> |
||||
<OutputType>Library</OutputType> |
||||
<SignAssembly>true</SignAssembly> |
||||
<AssemblyOriginatorKeyFile>Resources\ICSharpCode.NRefactory.snk</AssemblyOriginatorKeyFile> |
||||
<AllowUnsafeBlocks>False</AllowUnsafeBlocks> |
||||
<RegisterForComInterop>False</RegisterForComInterop> |
||||
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies> |
||||
<BaseAddress>94896128</BaseAddress> |
||||
<PlatformTarget>AnyCPU</PlatformTarget> |
||||
<FileAlignment>4096</FileAlignment> |
||||
<RunCodeAnalysis>False</RunCodeAnalysis> |
||||
<CodeAnalysisRules>-Microsoft.Design#CA1002;-Microsoft.Design#CA1020;-Microsoft.Design#CA1051;-Microsoft.Design#CA1062;-Microsoft.Globalization#CA1303;-Microsoft.Globalization#CA1305;-Microsoft.Naming#CA1704;-Microsoft.Performance#CA1800;-Microsoft.Performance#CA1805;-Microsoft.Usage#CA2211;-Microsoft.Usage#CA2227</CodeAnalysisRules> |
||||
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion> |
||||
</PropertyGroup> |
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> |
||||
<Optimize>False</Optimize> |
||||
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow> |
||||
<DefineConstants>TEST; DEBUG</DefineConstants> |
||||
<TreatWarningsAsErrors>false</TreatWarningsAsErrors> |
||||
</PropertyGroup> |
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> |
||||
<Optimize>True</Optimize> |
||||
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> |
||||
<DefineConstants>TEST</DefineConstants> |
||||
<TreatWarningsAsErrors>false</TreatWarningsAsErrors> |
||||
</PropertyGroup> |
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> |
||||
<DebugType>Full</DebugType> |
||||
<DebugSymbols>true</DebugSymbols> |
||||
<OutputPath>bin\Debug</OutputPath> |
||||
</PropertyGroup> |
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Release' "> |
||||
<DebugSymbols>false</DebugSymbols> |
||||
<DebugType>None</DebugType> |
||||
<OutputPath>bin\Release</OutputPath> |
||||
</PropertyGroup> |
||||
<ItemGroup> |
||||
<Reference Include="System" /> |
||||
<Reference Include="System.Core"> |
||||
<RequiredTargetFramework>3.5</RequiredTargetFramework> |
||||
</Reference> |
||||
</ItemGroup> |
||||
<ItemGroup> |
||||
<None Include="Resources\ICSharpCode.NRefactory.snk" /> |
||||
<None Include="Src\Lexer\BuildKeywords.pl" /> |
||||
<Compile Include="Configuration\AssemblyInfo.cs" /> |
||||
<Compile Include="Src\Ast\NodeCollection.cs" /> |
||||
<Compile Include="Src\Lexer\AbstractLexer.cs" /> |
||||
<Compile Include="Src\Lexer\CSharp\Keywords.cs" /> |
||||
<Compile Include="Src\Lexer\CSharp\Lexer.cs" /> |
||||
<Compile Include="Src\Lexer\CSharp\Tokens.cs" /> |
||||
<Compile Include="Src\Lexer\ILexer.cs" /> |
||||
<Compile Include="Src\Lexer\LookupTable.cs" /> |
||||
<Compile Include="Src\Lexer\Special\BlankLine.cs" /> |
||||
<Compile Include="Src\Lexer\Special\Comment.cs" /> |
||||
<Compile Include="Src\Lexer\Special\CommentType.cs" /> |
||||
<Compile Include="Src\Lexer\Special\PreProcessingDirective.cs" /> |
||||
<Compile Include="Src\Lexer\Special\SpecialTracker.cs" /> |
||||
<Compile Include="Src\Lexer\Special\TagComment.cs" /> |
||||
<Compile Include="Src\Lexer\Token.cs" /> |
||||
<Compile Include="Src\Lexer\VBNet\Keywords.cs" /> |
||||
<Compile Include="Src\Lexer\VBNet\Lexer.cs" /> |
||||
<Compile Include="Src\Lexer\VBNet\Tokens.cs" /> |
||||
<Compile Include="Src\Lexer\Special\ISpecial.cs" /> |
||||
<Compile Include="Src\OperatorPrecedence.cs" /> |
||||
<Compile Include="Src\Parser\CSharp\CSharpParser.cs" /> |
||||
<Compile Include="Src\Parser\CSharp\Parser.cs" /> |
||||
<Compile Include="Src\Parser\VBNet\Parser.cs" /> |
||||
<Compile Include="Src\Parser\VBNet\VBNetParser.cs" /> |
||||
<Compile Include="Src\Parser\AbstractParser.cs" /> |
||||
<Compile Include="Src\Parser\Errors.cs" /> |
||||
<Compile Include="Src\Parser\IParser.cs" /> |
||||
<Compile Include="Src\Parser\ModifierList.cs" /> |
||||
<Compile Include="Src\PrettyPrinter\CSharp\CSharpOutputVisitor.cs" /> |
||||
<Compile Include="Src\PrettyPrinter\CSharp\OutputFormatter.cs" /> |
||||
<Compile Include="Src\PrettyPrinter\CSharp\PrettyPrintOptions.cs" /> |
||||
<Compile Include="Src\PrettyPrinter\VBNet\VBNetOutputFormatter.cs" /> |
||||
<Compile Include="Src\PrettyPrinter\VBNet\VBNetOutputVisitor.cs" /> |
||||
<Compile Include="Src\PrettyPrinter\VBNet\VBNetPrettyPrintOptions.cs" /> |
||||
<Compile Include="Src\PrettyPrinter\AbstractOutputFormatter.cs" /> |
||||
<Compile Include="Src\PrettyPrinter\AbstractPrettyPrintOptions.cs" /> |
||||
<Compile Include="Src\PrettyPrinter\IOutputAstVisitor.cs" /> |
||||
<Compile Include="Src\PrettyPrinter\SpecialNodesInserter.cs" /> |
||||
<Compile Include="Src\SnippetParser.cs" /> |
||||
<Compile Include="Src\Visitors\AbstractAstTransformer.cs" /> |
||||
<Compile Include="Src\Visitors\AbstractASTVisitor.cs" /> |
||||
<Compile Include="Src\Visitors\CodeDOMOutputVisitor.cs" /> |
||||
<Compile Include="Src\Visitors\CodeDOMVerboseOutputGenerator.cs" /> |
||||
<Compile Include="Src\Visitors\ConvertVisitorBase.cs" /> |
||||
<Compile Include="Src\Visitors\CSharpConstructsConvertVisitor.cs" /> |
||||
<Compile Include="Src\Visitors\LookupTableVisitor.cs" /> |
||||
<Compile Include="Src\Visitors\PrefixFieldsVisitor.cs" /> |
||||
<Compile Include="Src\Visitors\RenameIdentifierVisitor.cs" /> |
||||
<Compile Include="Src\Visitors\ToCSharpConvertVisitor.cs" /> |
||||
<Compile Include="Src\Visitors\ToVBNetConvertVisitor.cs" /> |
||||
<Compile Include="Src\Visitors\ToVBNetRenameConflictingVariables.cs" /> |
||||
<Compile Include="Src\Visitors\VBNetConstructsConvertVisitor.cs" /> |
||||
<Compile Include="Src\EnvironmentInformationProvider.cs" /> |
||||
<Compile Include="Src\IAstVisitor.cs" /> |
||||
<Compile Include="Src\ParserFactory.cs" /> |
||||
<Compile Include="Src\Location.cs" /> |
||||
<Compile Include="Src\Ast\General\BlockStatement.cs" /> |
||||
<Compile Include="Src\Ast\General\CompilationUnit.cs" /> |
||||
<Compile Include="Src\Ast\General\Expression.cs" /> |
||||
<Compile Include="Src\Ast\General\LocalVariableDeclaration.cs" /> |
||||
<Compile Include="Src\Ast\General\PrimitiveExpression.cs" /> |
||||
<Compile Include="Src\Ast\General\Statement.cs" /> |
||||
<Compile Include="Src\Ast\AbstractNode.cs" /> |
||||
<Compile Include="Src\Ast\Enums.cs" /> |
||||
<Compile Include="Src\Ast\Generated.cs" /> |
||||
<Compile Include="Src\Ast\INode.cs" /> |
||||
<Compile Include="Src\Ast\INullable.cs" /> |
||||
<Compile Include="Src\Ast\TypeReference.cs" /> |
||||
<Compile Include="Src\Parser\VBNet\ParamModifierList.cs" /> |
||||
<Compile Include="Src\Visitors\NodeTrackingAstVisitor.cs" /> |
||||
</ItemGroup> |
||||
<ItemGroup> |
||||
<Content Include="Src\Lexer\CSharp\KeywordList.txt" /> |
||||
<Content Include="Src\Lexer\VBNet\KeywordList.txt" /> |
||||
<Folder Include="Src\Parser" /> |
||||
<Folder Include="Src\Parser\CSharp" /> |
||||
<Content Include="Src\Parser\CSharp\cs.ATG" /> |
||||
<Content Include="Src\Parser\CSharp\trace.txt" /> |
||||
<Folder Include="Src\Parser\Frames" /> |
||||
<Content Include="Src\Parser\Frames\OldSharpCoco.exe" /> |
||||
<Content Include="Src\Parser\Frames\Parser.frame" /> |
||||
<Content Include="Src\Parser\Frames\Parser.frame.new" /> |
||||
<Content Include="Src\Parser\Frames\Parser.frame.old" /> |
||||
<Content Include="Src\Parser\Frames\Scanner.frame" /> |
||||
<Content Include="Src\Parser\Frames\SharpCoco.exe" /> |
||||
<Content Include="Src\Parser\Frames\trace.txt" /> |
||||
<Folder Include="Src\Parser\VBNet" /> |
||||
<Content Include="Src\Parser\VBNet\VBNET.ATG" /> |
||||
<Content Include="Src\Parser\gen.bat" /> |
||||
<Folder Include="Src\PrettyPrinter" /> |
||||
<Folder Include="Src\PrettyPrinter\CSharp" /> |
||||
<Folder Include="Src\PrettyPrinter\VBNet" /> |
||||
<Folder Include="Src\Visitors" /> |
||||
<Folder Include="Src\Ast" /> |
||||
<Folder Include="Src\Ast\General" /> |
||||
</ItemGroup> |
||||
<Import Project="$(MSBuildBinPath)\Microsoft.CSHARP.Targets" /> |
||||
</Project> |
Binary file not shown.
@ -1,89 +0,0 @@
@@ -1,89 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections; |
||||
using System.Collections.Generic; |
||||
using System.Diagnostics; |
||||
using System.Text; |
||||
|
||||
namespace ICSharpCode.NRefactory.Ast |
||||
{ |
||||
public abstract class AbstractNode : INode |
||||
{ |
||||
NodeCollection children; |
||||
|
||||
public INode Parent { get; set; } |
||||
public Location StartLocation { get; set; } |
||||
public Location EndLocation { get; set; } |
||||
public Dictionary<string, object> UserData { get; set; } |
||||
|
||||
IList<INode> INode.Children { |
||||
get { |
||||
return children; |
||||
} |
||||
} |
||||
|
||||
public NodeCollection Children { |
||||
get { |
||||
return children; |
||||
} |
||||
set { |
||||
Debug.Assert(value != null); |
||||
children = value; |
||||
} |
||||
} |
||||
|
||||
public AbstractNode() |
||||
{ |
||||
children = new NodeCollection(); |
||||
children.Added += delegate(object sender, NodeEventArgs e) { e.Node.Parent = this; }; |
||||
this.UserData = new Dictionary<string, object>(); |
||||
} |
||||
|
||||
public virtual void AddChild(INode childNode) |
||||
{ |
||||
Debug.Assert(childNode != null); |
||||
children.Add(childNode); |
||||
} |
||||
|
||||
public abstract object AcceptVisitor(IAstVisitor visitor, object data); |
||||
|
||||
public virtual object AcceptChildren(IAstVisitor visitor, object data) |
||||
{ |
||||
foreach (INode child in children) { |
||||
Debug.Assert(child != null); |
||||
child.AcceptVisitor(visitor, data); |
||||
} |
||||
return data; |
||||
} |
||||
|
||||
public static string GetCollectionString<T>(IList<T> collection) |
||||
{ |
||||
StringBuilder output = new StringBuilder(); |
||||
output.Append('{'); |
||||
|
||||
if (collection != null) { |
||||
IEnumerator en = collection.GetEnumerator(); |
||||
bool isFirst = true; |
||||
while (en.MoveNext()) { |
||||
if (!isFirst) { |
||||
output.Append(", "); |
||||
} else { |
||||
isFirst = false; |
||||
} |
||||
output.Append(en.Current == null ? "<null>" : en.Current.ToString()); |
||||
} |
||||
} else { |
||||
return "null"; |
||||
} |
||||
|
||||
output.Append('}'); |
||||
return output.ToString(); |
||||
} |
||||
} |
||||
} |
@ -1,369 +0,0 @@
@@ -1,369 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
|
||||
namespace ICSharpCode.NRefactory.Ast |
||||
{ |
||||
[Flags] |
||||
public enum Modifiers |
||||
{ |
||||
None = 0x0000, |
||||
|
||||
// Access
|
||||
Private = 0x0001, |
||||
/// <summary>C# 'internal', VB 'Friend'</summary>
|
||||
Internal = 0x0002, |
||||
Protected = 0x0004, |
||||
Public = 0x0008, |
||||
Dim = 0x0010, // VB.NET SPECIFIC, for fields/local variables only
|
||||
|
||||
// Scope
|
||||
Abstract = 0x0010, // == MustOverride/MustInherit
|
||||
Virtual = 0x0020, |
||||
Sealed = 0x0040, |
||||
/// <summary>C# 'static', VB 'Shared'</summary>
|
||||
Static = 0x0080, |
||||
Override = 0x0100, |
||||
/// <summary>For fields: readonly (c# and vb), for properties: get-only (vb)</summary>
|
||||
ReadOnly = 0x0200, |
||||
Const = 0x0400, |
||||
/// <summary>C# 'new', VB 'Shadows'</summary>
|
||||
New = 0x0800, |
||||
Partial = 0x1000, |
||||
|
||||
// Special
|
||||
Extern = 0x2000, |
||||
Volatile = 0x4000, |
||||
Unsafe = 0x8000, |
||||
Overloads = 0x10000, // VB specific
|
||||
WithEvents = 0x20000, // VB specific
|
||||
Default = 0x40000, // VB specific
|
||||
Fixed = 0x80000, // C# specific (fixed size arrays in unsafe structs)
|
||||
|
||||
/// <summary>Generated code, not part of parsed code</summary>
|
||||
Synthetic = 0x200000, |
||||
/// <summary>Only for VB properties.</summary>
|
||||
WriteOnly = 0x400000, // VB specific
|
||||
|
||||
Visibility = Private | Public | Protected | Internal, |
||||
Classes = New | Visibility | Abstract | Sealed | Partial | Static, |
||||
VBModules = Visibility, |
||||
VBStructures = Visibility | New, |
||||
VBEnums = Visibility | New, |
||||
VBInterfacs = Visibility | New, |
||||
VBDelegates = Visibility | New, |
||||
VBMethods = Visibility | New | Static | Virtual | Sealed | Abstract | Override | Overloads, |
||||
VBExternalMethods = Visibility | New | Overloads, |
||||
VBEvents = Visibility | New | Overloads, |
||||
VBProperties = VBMethods | Default | ReadOnly | WriteOnly, |
||||
VBCustomEvents = Visibility | New | Overloads, |
||||
VBOperators = Public | Static | Overloads | New, |
||||
|
||||
|
||||
// this is not documented in the spec
|
||||
VBInterfaceEvents = New, |
||||
VBInterfaceMethods = New | Overloads, |
||||
VBInterfaceProperties = New | Overloads | ReadOnly | WriteOnly | Default, |
||||
VBInterfaceEnums = New, |
||||
|
||||
Fields = New | Visibility | Static | ReadOnly | Volatile | Fixed, |
||||
PropertysEventsMethods = New | Visibility | Static | Virtual | Sealed | Override | Abstract | Extern, |
||||
Indexers = New | Visibility | Virtual | Sealed | Override | Abstract | Extern, |
||||
Operators = Public | Static | Extern, |
||||
Constants = New | Visibility, |
||||
StructsInterfacesEnumsDelegates = New | Visibility | Partial, |
||||
StaticConstructors = Extern | Static | Unsafe, |
||||
Destructors = Extern | Unsafe, |
||||
Constructors = Visibility | Extern, |
||||
} |
||||
|
||||
public enum ClassType |
||||
{ |
||||
Class, |
||||
Module, |
||||
Interface, |
||||
Struct, |
||||
Enum |
||||
} |
||||
|
||||
public enum ParentType |
||||
{ |
||||
ClassOrStruct, |
||||
InterfaceOrEnum, |
||||
Namespace, |
||||
Unknown |
||||
} |
||||
|
||||
public enum FieldDirection |
||||
{ |
||||
None, |
||||
In, |
||||
Out, |
||||
Ref |
||||
} |
||||
|
||||
[Flags] |
||||
public enum ParameterModifiers |
||||
{ |
||||
// Values must be the same as in SharpDevelop's ParameterModifiers
|
||||
None = 0, |
||||
In = 1, |
||||
Out = 2, |
||||
Ref = 4, |
||||
Params = 8, |
||||
Optional = 16 |
||||
} |
||||
|
||||
public enum AssignmentOperatorType |
||||
{ |
||||
None, |
||||
Assign, |
||||
|
||||
Add, |
||||
Subtract, |
||||
Multiply, |
||||
Divide, |
||||
Modulus, |
||||
|
||||
Power, // (VB only)
|
||||
DivideInteger, // (VB only)
|
||||
ConcatString, // (VB only)
|
||||
|
||||
ShiftLeft, |
||||
ShiftRight, |
||||
|
||||
BitwiseAnd, |
||||
BitwiseOr, |
||||
ExclusiveOr, |
||||
} |
||||
|
||||
public enum BinaryOperatorType |
||||
{ |
||||
None, |
||||
|
||||
/// <summary>'&' in C#, 'And' in VB.</summary>
|
||||
BitwiseAnd, |
||||
/// <summary>'|' in C#, 'Or' in VB.</summary>
|
||||
BitwiseOr, |
||||
/// <summary>'&&' in C#, 'AndAlso' in VB.</summary>
|
||||
LogicalAnd, |
||||
/// <summary>'||' in C#, 'OrElse' in VB.</summary>
|
||||
LogicalOr, |
||||
/// <summary>'^' in C#, 'Xor' in VB.</summary>
|
||||
ExclusiveOr, |
||||
|
||||
/// <summary>></summary>
|
||||
GreaterThan, |
||||
/// <summary>>=</summary>
|
||||
GreaterThanOrEqual, |
||||
/// <summary>'==' in C#, '=' in VB.</summary>
|
||||
Equality, |
||||
/// <summary>'!=' in C#, '<>' in VB.</summary>
|
||||
InEquality, |
||||
/// <summary><</summary>
|
||||
LessThan, |
||||
/// <summary><=</summary>
|
||||
LessThanOrEqual, |
||||
|
||||
/// <summary>+</summary>
|
||||
Add, |
||||
/// <summary>-</summary>
|
||||
Subtract, |
||||
/// <summary>*</summary>
|
||||
Multiply, |
||||
/// <summary>/</summary>
|
||||
Divide, |
||||
/// <summary>'%' in C#, 'Mod' in VB.</summary>
|
||||
Modulus, |
||||
/// <summary>VB-only: \</summary>
|
||||
DivideInteger, |
||||
/// <summary>VB-only: ^</summary>
|
||||
Power, |
||||
/// <summary>VB-only: &</summary>
|
||||
Concat, |
||||
|
||||
/// <summary>C#: <<</summary>
|
||||
ShiftLeft, |
||||
/// <summary>C#: >></summary>
|
||||
ShiftRight, |
||||
/// <summary>VB-only: Is</summary>
|
||||
ReferenceEquality, |
||||
/// <summary>VB-only: IsNot</summary>
|
||||
ReferenceInequality, |
||||
|
||||
/// <summary>VB-only: Like</summary>
|
||||
Like, |
||||
/// <summary>C#: ??</summary>
|
||||
NullCoalescing, |
||||
} |
||||
|
||||
public enum CastType |
||||
{ |
||||
/// <summary>
|
||||
/// direct cast (C#, VB "DirectCast")
|
||||
/// </summary>
|
||||
Cast, |
||||
/// <summary>
|
||||
/// try cast (C# "as", VB "TryCast")
|
||||
/// </summary>
|
||||
TryCast, |
||||
/// <summary>
|
||||
/// converting cast (VB "CType")
|
||||
/// </summary>
|
||||
Conversion, |
||||
/// <summary>
|
||||
/// primitive converting cast (VB "CString" etc.)
|
||||
/// </summary>
|
||||
PrimitiveConversion |
||||
} |
||||
|
||||
public enum UnaryOperatorType |
||||
{ |
||||
None, |
||||
Not, |
||||
BitNot, |
||||
|
||||
Minus, |
||||
Plus, |
||||
|
||||
Increment, |
||||
Decrement, |
||||
|
||||
PostIncrement, |
||||
PostDecrement, |
||||
|
||||
/// <summary>Dereferencing pointer</summary>
|
||||
Star, |
||||
/// <summary>Get address of</summary>
|
||||
BitWiseAnd |
||||
} |
||||
|
||||
public enum ContinueType |
||||
{ |
||||
None, |
||||
Do, |
||||
For, |
||||
While |
||||
} |
||||
|
||||
public enum ConditionType |
||||
{ |
||||
None, |
||||
Until, |
||||
While, |
||||
DoWhile |
||||
} |
||||
|
||||
public enum ConditionPosition |
||||
{ |
||||
None, |
||||
Start, |
||||
End |
||||
} |
||||
|
||||
public enum ExitType |
||||
{ |
||||
None, |
||||
Sub, |
||||
Function, |
||||
Property, |
||||
Do, |
||||
For, |
||||
While, |
||||
Select, |
||||
Try |
||||
} |
||||
|
||||
public enum ConstructorInitializerType |
||||
{ |
||||
None, |
||||
Base, |
||||
This |
||||
} |
||||
|
||||
public enum ConversionType |
||||
{ |
||||
None, |
||||
Implicit, |
||||
Explicit |
||||
} |
||||
|
||||
public enum OverloadableOperatorType |
||||
{ |
||||
None, |
||||
|
||||
Add, |
||||
Subtract, |
||||
Multiply, |
||||
Divide, |
||||
Modulus, |
||||
Concat, |
||||
|
||||
Not, |
||||
BitNot, |
||||
|
||||
BitwiseAnd, |
||||
BitwiseOr, |
||||
ExclusiveOr, |
||||
|
||||
ShiftLeft, |
||||
ShiftRight, |
||||
|
||||
GreaterThan, |
||||
GreaterThanOrEqual, |
||||
Equality, |
||||
InEquality, |
||||
LessThan, |
||||
LessThanOrEqual, |
||||
|
||||
Increment, |
||||
Decrement, |
||||
|
||||
IsTrue, |
||||
IsFalse, |
||||
|
||||
// VB specific
|
||||
Like, |
||||
Power, |
||||
CType, |
||||
DivideInteger |
||||
} |
||||
|
||||
///<summary>
|
||||
/// Charset types, used in external methods
|
||||
/// declarations (VB only).
|
||||
///</summary>
|
||||
public enum CharsetModifier |
||||
{ |
||||
None, |
||||
Auto, |
||||
Unicode, |
||||
Ansi |
||||
} |
||||
|
||||
///<summary>
|
||||
/// Compare type, used in the <c>Option Compare</c>
|
||||
/// pragma (VB only).
|
||||
///</summary>
|
||||
public enum OptionType |
||||
{ |
||||
None, |
||||
Explicit, |
||||
Strict, |
||||
CompareBinary, |
||||
CompareText |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Specifies the ordering direction of a QueryExpressionOrdering node.
|
||||
/// </summary>
|
||||
public enum QueryExpressionOrderingDirection |
||||
{ |
||||
None, Ascending, Descending |
||||
} |
||||
} |
@ -1,63 +0,0 @@
@@ -1,63 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="none" email=""/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
|
||||
namespace ICSharpCode.NRefactory.Ast |
||||
{ |
||||
public class BlockStatement : Statement |
||||
{ |
||||
// Children in C#: LabelStatement, LocalVariableDeclaration, Statement
|
||||
// Children in VB: LabelStatement, EndStatement, Statement
|
||||
|
||||
public static new BlockStatement Null { |
||||
get { |
||||
return NullBlockStatement.Instance; |
||||
} |
||||
} |
||||
|
||||
public override object AcceptVisitor(IAstVisitor visitor, object data) |
||||
{ |
||||
return visitor.VisitBlockStatement(this, data); |
||||
} |
||||
|
||||
public override string ToString() |
||||
{ |
||||
return String.Format("[BlockStatement: Children={0}]", |
||||
GetCollectionString(base.Children)); |
||||
} |
||||
} |
||||
|
||||
internal sealed class NullBlockStatement : BlockStatement |
||||
{ |
||||
public static readonly NullBlockStatement Instance = new NullBlockStatement(); |
||||
|
||||
public override bool IsNull { |
||||
get { |
||||
return true; |
||||
} |
||||
} |
||||
|
||||
public override object AcceptVisitor(IAstVisitor visitor, object data) |
||||
{ |
||||
return data; |
||||
} |
||||
public override object AcceptChildren(IAstVisitor visitor, object data) |
||||
{ |
||||
return data; |
||||
} |
||||
public override void AddChild(INode childNode) |
||||
{ |
||||
throw new InvalidOperationException(); |
||||
} |
||||
|
||||
public override string ToString() |
||||
{ |
||||
return String.Format("[NullBlockStatement]"); |
||||
} |
||||
} |
||||
} |
@ -1,60 +0,0 @@
@@ -1,60 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections; |
||||
|
||||
namespace ICSharpCode.NRefactory.Ast |
||||
{ |
||||
public class CompilationUnit : AbstractNode |
||||
{ |
||||
// Children in C#: UsingAliasDeclaration, UsingDeclaration, AttributeSection, NamespaceDeclaration
|
||||
// Children in VB: OptionStatements, ImportsStatement, AttributeSection, NamespaceDeclaration
|
||||
|
||||
Stack blockStack = new Stack(); |
||||
|
||||
public CompilationUnit() |
||||
{ |
||||
blockStack.Push(this); |
||||
} |
||||
|
||||
public void BlockStart(INode block) |
||||
{ |
||||
blockStack.Push(block); |
||||
} |
||||
|
||||
public void BlockEnd() |
||||
{ |
||||
blockStack.Pop(); |
||||
} |
||||
|
||||
public INode CurrentBock { |
||||
get { |
||||
return blockStack.Count > 0 ? (INode)blockStack.Peek() : null; |
||||
} |
||||
} |
||||
|
||||
public override void AddChild(INode childNode) |
||||
{ |
||||
if (childNode != null) { |
||||
INode parent = (INode)blockStack.Peek(); |
||||
parent.Children.Add(childNode); |
||||
childNode.Parent = parent; |
||||
} |
||||
} |
||||
|
||||
public override object AcceptVisitor(IAstVisitor visitor, object data) |
||||
{ |
||||
return visitor.VisitCompilationUnit(this, data); |
||||
} |
||||
|
||||
public override string ToString() |
||||
{ |
||||
return String.Format("[CompilationUnit]"); |
||||
} |
||||
} |
||||
} |
@ -1,107 +0,0 @@
@@ -1,107 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
|
||||
namespace ICSharpCode.NRefactory.Ast |
||||
{ |
||||
public abstract class Expression : AbstractNode, INullable |
||||
{ |
||||
public static Expression Null { |
||||
get { |
||||
return NullExpression.Instance; |
||||
} |
||||
} |
||||
|
||||
public virtual bool IsNull { |
||||
get { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
public static Expression CheckNull(Expression expression) |
||||
{ |
||||
return expression == null ? NullExpression.Instance : expression; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Returns the existing expression plus the specified integer value.
|
||||
/// The old <paramref name="expr"/> object is not modified, but might be a subobject on the new expression
|
||||
/// (and thus its parent property is modified).
|
||||
/// </summary>
|
||||
public static Expression AddInteger(Expression expr, int value) |
||||
{ |
||||
PrimitiveExpression pe = expr as PrimitiveExpression; |
||||
if (pe != null && pe.Value is int) { |
||||
int newVal = (int)pe.Value + value; |
||||
return new PrimitiveExpression(newVal, newVal.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); |
||||
} |
||||
BinaryOperatorExpression boe = expr as BinaryOperatorExpression; |
||||
if (boe != null && boe.Op == BinaryOperatorType.Add) { |
||||
// clone boe:
|
||||
boe = new BinaryOperatorExpression(boe.Left, boe.Op, boe.Right); |
||||
|
||||
boe.Right = AddInteger(boe.Right, value); |
||||
if (boe.Right is PrimitiveExpression && ((PrimitiveExpression)boe.Right).Value is int) { |
||||
int newVal = (int)((PrimitiveExpression)boe.Right).Value; |
||||
if (newVal == 0) { |
||||
return boe.Left; |
||||
} else if (newVal < 0) { |
||||
((PrimitiveExpression)boe.Right).Value = -newVal; |
||||
boe.Op = BinaryOperatorType.Subtract; |
||||
} |
||||
} |
||||
return boe; |
||||
} |
||||
if (boe != null && boe.Op == BinaryOperatorType.Subtract) { |
||||
pe = boe.Right as PrimitiveExpression; |
||||
if (pe != null && pe.Value is int) { |
||||
int newVal = (int)pe.Value - value; |
||||
if (newVal == 0) |
||||
return boe.Left; |
||||
|
||||
// clone boe:
|
||||
boe = new BinaryOperatorExpression(boe.Left, boe.Op, boe.Right); |
||||
|
||||
if (newVal < 0) { |
||||
newVal = -newVal; |
||||
boe.Op = BinaryOperatorType.Add; |
||||
} |
||||
boe.Right = new PrimitiveExpression(newVal, newVal.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); |
||||
return boe; |
||||
} |
||||
} |
||||
BinaryOperatorType opType = BinaryOperatorType.Add; |
||||
if (value < 0) { |
||||
value = -value; |
||||
opType = BinaryOperatorType.Subtract; |
||||
} |
||||
return new BinaryOperatorExpression(expr, opType, new PrimitiveExpression(value, value.ToString(System.Globalization.NumberFormatInfo.InvariantInfo))); |
||||
} |
||||
} |
||||
|
||||
internal sealed class NullExpression : Expression |
||||
{ |
||||
internal static readonly NullExpression Instance = new NullExpression(); |
||||
|
||||
public override bool IsNull { |
||||
get { |
||||
return true; |
||||
} |
||||
} |
||||
|
||||
public override object AcceptVisitor(IAstVisitor visitor, object data) |
||||
{ |
||||
return null; |
||||
} |
||||
|
||||
public override string ToString() |
||||
{ |
||||
return String.Format("[NullExpression]"); |
||||
} |
||||
} |
||||
} |
@ -1,102 +0,0 @@
@@ -1,102 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="none" email=""/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
|
||||
namespace ICSharpCode.NRefactory.Ast |
||||
{ |
||||
public class LocalVariableDeclaration : Statement |
||||
{ |
||||
TypeReference typeReference; |
||||
Modifiers modifier = Modifiers.None; |
||||
List<VariableDeclaration> variables = new List<VariableDeclaration>(1); |
||||
|
||||
public TypeReference TypeReference { |
||||
get { |
||||
return typeReference; |
||||
} |
||||
set { |
||||
typeReference = TypeReference.CheckNull(value); |
||||
} |
||||
} |
||||
|
||||
public Modifiers Modifier { |
||||
get { |
||||
return modifier; |
||||
} |
||||
set { |
||||
modifier = value; |
||||
} |
||||
} |
||||
|
||||
public List<VariableDeclaration> Variables { |
||||
get { |
||||
return variables; |
||||
} |
||||
} |
||||
|
||||
public TypeReference GetTypeForVariable(int variableIndex) |
||||
{ |
||||
if (!typeReference.IsNull) { |
||||
return typeReference; |
||||
} |
||||
|
||||
for (int i = variableIndex; i < Variables.Count;++i) { |
||||
if (!((VariableDeclaration)Variables[i]).TypeReference.IsNull) { |
||||
return ((VariableDeclaration)Variables[i]).TypeReference; |
||||
} |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
public LocalVariableDeclaration(VariableDeclaration declaration) : this(TypeReference.Null) |
||||
{ |
||||
Variables.Add(declaration); |
||||
} |
||||
|
||||
public LocalVariableDeclaration(TypeReference typeReference) |
||||
{ |
||||
this.TypeReference = typeReference; |
||||
} |
||||
|
||||
public LocalVariableDeclaration(TypeReference typeReference, Modifiers modifier) |
||||
{ |
||||
this.TypeReference = typeReference; |
||||
this.modifier = modifier; |
||||
} |
||||
|
||||
public LocalVariableDeclaration(Modifiers modifier) |
||||
{ |
||||
this.typeReference = TypeReference.Null; |
||||
this.modifier = modifier; |
||||
} |
||||
|
||||
public VariableDeclaration GetVariableDeclaration(string variableName) |
||||
{ |
||||
foreach (VariableDeclaration variableDeclaration in variables) { |
||||
if (variableDeclaration.Name == variableName) { |
||||
return variableDeclaration; |
||||
} |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
public override object AcceptVisitor(IAstVisitor visitor, object data) |
||||
{ |
||||
return visitor.VisitLocalVariableDeclaration(this, data); |
||||
} |
||||
|
||||
public override string ToString() |
||||
{ |
||||
return String.Format("[LocalVariableDeclaration: Type={0}, Modifier ={1} Variables={2}]", |
||||
typeReference, |
||||
modifier, |
||||
GetCollectionString(variables)); |
||||
} |
||||
} |
||||
} |
@ -1,55 +0,0 @@
@@ -1,55 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="none" email=""/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
|
||||
namespace ICSharpCode.NRefactory.Ast |
||||
{ |
||||
public class PrimitiveExpression : Expression |
||||
{ |
||||
object val; |
||||
string stringValue; |
||||
|
||||
public object Value { |
||||
get { |
||||
return val; |
||||
} |
||||
set { |
||||
val = value; |
||||
} |
||||
} |
||||
|
||||
public string StringValue { |
||||
get { |
||||
return stringValue; |
||||
} |
||||
set { |
||||
stringValue = value == null ? String.Empty : value; |
||||
} |
||||
} |
||||
|
||||
public PrimitiveExpression(object val, string stringValue) |
||||
{ |
||||
this.Value = val; |
||||
this.StringValue = stringValue; |
||||
} |
||||
|
||||
public override object AcceptVisitor(IAstVisitor visitor, object data) |
||||
{ |
||||
return visitor.VisitPrimitiveExpression(this, data); |
||||
} |
||||
|
||||
public override string ToString() |
||||
{ |
||||
return String.Format("[PrimitiveExpression: Value={1}, ValueType={2}, StringValue={0}]", |
||||
stringValue, |
||||
Value, |
||||
Value == null ? "null" : Value.GetType().FullName |
||||
); |
||||
} |
||||
} |
||||
} |
@ -1,66 +0,0 @@
@@ -1,66 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
|
||||
namespace ICSharpCode.NRefactory.Ast |
||||
{ |
||||
public abstract class Statement : AbstractNode, INullable |
||||
{ |
||||
public static Statement Null { |
||||
get { |
||||
return NullStatement.Instance; |
||||
} |
||||
} |
||||
|
||||
public virtual bool IsNull { |
||||
get { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
public static Statement CheckNull(Statement statement) |
||||
{ |
||||
return statement ?? NullStatement.Instance; |
||||
} |
||||
} |
||||
|
||||
public abstract class StatementWithEmbeddedStatement : Statement |
||||
{ |
||||
Statement embeddedStatement; |
||||
|
||||
public Statement EmbeddedStatement { |
||||
get { |
||||
return embeddedStatement; |
||||
} |
||||
set { |
||||
embeddedStatement = Statement.CheckNull(value); |
||||
if (value != null) |
||||
value.Parent = this; |
||||
} |
||||
} |
||||
} |
||||
|
||||
internal sealed class NullStatement : Statement |
||||
{ |
||||
public static readonly NullStatement Instance = new NullStatement(); |
||||
|
||||
public override bool IsNull { |
||||
get { return true; } |
||||
} |
||||
|
||||
public override object AcceptVisitor(IAstVisitor visitor, object data) |
||||
{ |
||||
return data; |
||||
} |
||||
|
||||
public override string ToString() |
||||
{ |
||||
return String.Format("[NullStatement]"); |
||||
} |
||||
} |
||||
} |
File diff suppressed because it is too large
Load Diff
@ -1,93 +0,0 @@
@@ -1,93 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
|
||||
namespace ICSharpCode.NRefactory.Ast |
||||
{ |
||||
public interface INode |
||||
{ |
||||
INode Parent { |
||||
get; |
||||
set; |
||||
} |
||||
|
||||
IList<INode> Children { |
||||
get; |
||||
} |
||||
|
||||
Location StartLocation { |
||||
get; |
||||
set; |
||||
} |
||||
|
||||
Location EndLocation { |
||||
get; |
||||
set; |
||||
} |
||||
|
||||
Dictionary<string, object> UserData { |
||||
get; |
||||
set; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Visits all children
|
||||
/// </summary>
|
||||
/// <param name="visitor">The visitor to accept</param>
|
||||
/// <param name="data">Additional data for the visitor</param>
|
||||
/// <returns>The paremeter <paramref name="data"/></returns>
|
||||
object AcceptChildren(IAstVisitor visitor, object data); |
||||
|
||||
/// <summary>
|
||||
/// Accept the visitor
|
||||
/// </summary>
|
||||
/// <param name="visitor">The visitor to accept</param>
|
||||
/// <param name="data">Additional data for the visitor</param>
|
||||
/// <returns>The value the visitor returns after the visit</returns>
|
||||
object AcceptVisitor(IAstVisitor visitor, object data); |
||||
} |
||||
|
||||
public static class INodeExtensionMethods |
||||
{ |
||||
public static void Remove(this INode node) |
||||
{ |
||||
node.Parent.Children.Remove(node); |
||||
} |
||||
|
||||
public static INode Previous(this INode node) |
||||
{ |
||||
if (node.Parent == null) return null; |
||||
int myIndex = node.Parent.Children.IndexOf(node); |
||||
int index = myIndex - 1; |
||||
if (0 <= index && index < node.Parent.Children.Count) { |
||||
return node.Parent.Children[index]; |
||||
} else { |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
public static INode Next(this INode node) |
||||
{ |
||||
if (node.Parent == null) return null; |
||||
int myIndex = node.Parent.Children.IndexOf(node); |
||||
int index = myIndex + 1; |
||||
if (0 <= index && index < node.Parent.Children.Count) { |
||||
return node.Parent.Children[index]; |
||||
} else { |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
public static void ReplaceWith(this INode node, INode newNode) |
||||
{ |
||||
int myIndex = node.Parent.Children.IndexOf(node); |
||||
node.Parent.Children[myIndex] = newNode; |
||||
} |
||||
} |
||||
} |
@ -1,16 +0,0 @@
@@ -1,16 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Andrea Paatz" email="andrea@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
namespace ICSharpCode.NRefactory.Ast |
||||
{ |
||||
public interface INullable |
||||
{ |
||||
bool IsNull { |
||||
get; |
||||
} |
||||
} |
||||
} |
@ -1,114 +0,0 @@
@@ -1,114 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="David Srbecký" email="dsrbecky@gmail.com"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using System.Collections.ObjectModel; |
||||
|
||||
namespace ICSharpCode.NRefactory.Ast |
||||
{ |
||||
public class NodeCollection: Collection<INode> |
||||
{ |
||||
public event EventHandler<NodeEventArgs> Added; |
||||
public event EventHandler<NodeEventArgs> Removed; |
||||
|
||||
protected virtual void OnAdded(NodeEventArgs e) |
||||
{ |
||||
if (Added != null) { |
||||
Added(this, e); |
||||
} |
||||
} |
||||
|
||||
protected virtual void OnRemoved(NodeEventArgs e) |
||||
{ |
||||
if (Removed != null) { |
||||
Removed(this, e); |
||||
} |
||||
} |
||||
|
||||
protected override void ClearItems() |
||||
{ |
||||
while(this.Count > 0) { |
||||
this.RemoveFirst(); |
||||
} |
||||
} |
||||
|
||||
protected override void InsertItem(int index, INode item) |
||||
{ |
||||
base.InsertItem(index, item); |
||||
OnAdded(new NodeEventArgs(item)); |
||||
} |
||||
|
||||
protected override void RemoveItem(int index) |
||||
{ |
||||
INode removedNode = this[index]; |
||||
base.RemoveItem(index); |
||||
OnRemoved(new NodeEventArgs(removedNode)); |
||||
} |
||||
|
||||
protected override void SetItem(int index, INode item) |
||||
{ |
||||
RemoveItem(index); |
||||
InsertItem(index, item); |
||||
} |
||||
|
||||
#region Convenience methods
|
||||
|
||||
public INode First { |
||||
get { |
||||
if (this.Count > 0) { |
||||
return this[0]; |
||||
} else { |
||||
return null; |
||||
} |
||||
} |
||||
} |
||||
|
||||
public INode Last { |
||||
get { |
||||
if (this.Count > 0) { |
||||
return this[this.Count - 1]; |
||||
} else { |
||||
return null; |
||||
} |
||||
} |
||||
} |
||||
|
||||
public void AddRange(IEnumerable<INode> items) |
||||
{ |
||||
foreach(INode item in items) { |
||||
this.Add(item); |
||||
} |
||||
} |
||||
|
||||
public void RemoveFirst() |
||||
{ |
||||
this.RemoveAt(0); |
||||
} |
||||
|
||||
public void RemoveLast() |
||||
{ |
||||
this.RemoveAt(this.Count - 1); |
||||
} |
||||
|
||||
#endregion
|
||||
} |
||||
|
||||
public class NodeEventArgs: EventArgs |
||||
{ |
||||
INode inode; |
||||
|
||||
public INode Node { |
||||
get { return inode; } |
||||
} |
||||
|
||||
public NodeEventArgs(INode inode) |
||||
{ |
||||
this.inode = inode; |
||||
} |
||||
} |
||||
} |
@ -1,431 +0,0 @@
@@ -1,431 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using System.Diagnostics; |
||||
using System.Globalization; |
||||
using System.Text; |
||||
|
||||
namespace ICSharpCode.NRefactory.Ast |
||||
{ |
||||
public class TypeReference : AbstractNode, INullable, ICloneable |
||||
{ |
||||
public static readonly TypeReference StructConstraint = new TypeReference("constraint: struct"); |
||||
public static readonly TypeReference ClassConstraint = new TypeReference("constraint: class"); |
||||
public static readonly TypeReference NewConstraint = new TypeReference("constraint: new"); |
||||
|
||||
string type = ""; |
||||
string systemType = ""; |
||||
int pointerNestingLevel; |
||||
int[] rankSpecifier; |
||||
List<TypeReference> genericTypes = new List<TypeReference>(); |
||||
bool isGlobal; |
||||
|
||||
#region Static primitive type list
|
||||
static Dictionary<string, string> types = new Dictionary<string, string>(); |
||||
static Dictionary<string, string> vbtypes = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); |
||||
static Dictionary<string, string> typesReverse = new Dictionary<string, string>(); |
||||
static Dictionary<string, string> vbtypesReverse = new Dictionary<string, string>(); |
||||
|
||||
static TypeReference() |
||||
{ |
||||
// C# types
|
||||
types.Add("bool", "System.Boolean"); |
||||
types.Add("byte", "System.Byte"); |
||||
types.Add("char", "System.Char"); |
||||
types.Add("decimal", "System.Decimal"); |
||||
types.Add("double", "System.Double"); |
||||
types.Add("float", "System.Single"); |
||||
types.Add("int", "System.Int32"); |
||||
types.Add("long", "System.Int64"); |
||||
types.Add("object", "System.Object"); |
||||
types.Add("sbyte", "System.SByte"); |
||||
types.Add("short", "System.Int16"); |
||||
types.Add("string", "System.String"); |
||||
types.Add("uint", "System.UInt32"); |
||||
types.Add("ulong", "System.UInt64"); |
||||
types.Add("ushort", "System.UInt16"); |
||||
types.Add("void", "System.Void"); |
||||
|
||||
// VB.NET types
|
||||
vbtypes.Add("Boolean", "System.Boolean"); |
||||
vbtypes.Add("Byte", "System.Byte"); |
||||
vbtypes.Add("SByte", "System.SByte"); |
||||
vbtypes.Add("Date", "System.DateTime"); |
||||
vbtypes.Add("Char", "System.Char"); |
||||
vbtypes.Add("Decimal", "System.Decimal"); |
||||
vbtypes.Add("Double", "System.Double"); |
||||
vbtypes.Add("Single", "System.Single"); |
||||
vbtypes.Add("Integer", "System.Int32"); |
||||
vbtypes.Add("Long", "System.Int64"); |
||||
vbtypes.Add("UInteger","System.UInt32"); |
||||
vbtypes.Add("ULong", "System.UInt64"); |
||||
vbtypes.Add("Object", "System.Object"); |
||||
vbtypes.Add("Short", "System.Int16"); |
||||
vbtypes.Add("UShort", "System.UInt16"); |
||||
vbtypes.Add("String", "System.String"); |
||||
|
||||
foreach (KeyValuePair<string, string> pair in types) { |
||||
typesReverse.Add(pair.Value, pair.Key); |
||||
} |
||||
foreach (KeyValuePair<string, string> pair in vbtypes) { |
||||
vbtypesReverse.Add(pair.Value, pair.Key); |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Gets a shortname=>full name dictionary of C# types.
|
||||
/// </summary>
|
||||
public static IDictionary<string, string> PrimitiveTypesCSharp { |
||||
get { return types; } |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Gets a shortname=>full name dictionary of VB types.
|
||||
/// </summary>
|
||||
public static IDictionary<string, string> PrimitiveTypesVB { |
||||
get { return vbtypes; } |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Gets a full name=>shortname dictionary of C# types.
|
||||
/// </summary>
|
||||
public static IDictionary<string, string> PrimitiveTypesCSharpReverse { |
||||
get { return typesReverse; } |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Gets a full name=>shortname dictionary of VB types.
|
||||
/// </summary>
|
||||
public static IDictionary<string, string> PrimitiveTypesVBReverse { |
||||
get { return vbtypesReverse; } |
||||
} |
||||
|
||||
|
||||
static string GetSystemType(string type) |
||||
{ |
||||
if (types == null) return type; |
||||
|
||||
string systemType; |
||||
if (types.TryGetValue(type, out systemType)) { |
||||
return systemType; |
||||
} |
||||
if (vbtypes.TryGetValue(type, out systemType)) { |
||||
return systemType; |
||||
} |
||||
return type; |
||||
} |
||||
#endregion
|
||||
|
||||
object ICloneable.Clone() |
||||
{ |
||||
return this.Clone(); |
||||
} |
||||
|
||||
public virtual TypeReference Clone() |
||||
{ |
||||
TypeReference c = new TypeReference(type, systemType); |
||||
CopyFields(this, c); |
||||
return c; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Copies the pointerNestingLevel, RankSpecifier, GenericTypes and IsGlobal flag
|
||||
/// from <paramref name="from"/> to <paramref name="to"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If <paramref name="to"/> already contains generics, the new generics are appended to the list.
|
||||
/// </remarks>
|
||||
protected static void CopyFields(TypeReference from, TypeReference to) |
||||
{ |
||||
to.pointerNestingLevel = from.pointerNestingLevel; |
||||
if (from.rankSpecifier != null) { |
||||
to.rankSpecifier = (int[])from.rankSpecifier.Clone(); |
||||
} |
||||
foreach (TypeReference r in from.genericTypes) { |
||||
to.genericTypes.Add(r.Clone()); |
||||
} |
||||
to.isGlobal = from.isGlobal; |
||||
} |
||||
|
||||
public string Type { |
||||
get { |
||||
return type; |
||||
} |
||||
set { |
||||
Debug.Assert(value != null); |
||||
type = value; |
||||
systemType = GetSystemType(type); |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Removes the last identifier from the type.
|
||||
/// e.g. "System.String.Length" becomes "System.String" or
|
||||
/// "System.Collections.IEnumerable(of string).Current" becomes "System.Collections.IEnumerable(of string)"
|
||||
/// This is used for explicit interface implementation in VB.
|
||||
/// </summary>
|
||||
public static string StripLastIdentifierFromType(ref TypeReference tr) |
||||
{ |
||||
if (tr is InnerClassTypeReference && ((InnerClassTypeReference)tr).Type.IndexOf('.') < 0) { |
||||
string ident = ((InnerClassTypeReference)tr).Type; |
||||
tr = ((InnerClassTypeReference)tr).BaseType; |
||||
return ident; |
||||
} else { |
||||
int pos = tr.Type.LastIndexOf('.'); |
||||
if (pos < 0) |
||||
return tr.Type; |
||||
string ident = tr.Type.Substring(pos + 1); |
||||
tr.Type = tr.Type.Substring(0, pos); |
||||
return ident; |
||||
} |
||||
} |
||||
|
||||
public string SystemType { |
||||
get { |
||||
return systemType; |
||||
} |
||||
} |
||||
|
||||
public int PointerNestingLevel { |
||||
get { |
||||
return pointerNestingLevel; |
||||
} |
||||
set { |
||||
Debug.Assert(this.IsNull == false); |
||||
pointerNestingLevel = value; |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// The rank of the array type.
|
||||
/// For "object[]", this is { 0 }; for "object[,]", it is {1}.
|
||||
/// For "object[,][,,][]", it is {1, 2, 0}.
|
||||
/// For non-array types, this property is null or {}.
|
||||
/// </summary>
|
||||
public int[] RankSpecifier { |
||||
get { |
||||
return rankSpecifier; |
||||
} |
||||
set { |
||||
Debug.Assert(this.IsNull == false); |
||||
rankSpecifier = value; |
||||
} |
||||
} |
||||
|
||||
public List<TypeReference> GenericTypes { |
||||
get { |
||||
return genericTypes; |
||||
} |
||||
} |
||||
|
||||
public bool IsArrayType { |
||||
get { |
||||
return rankSpecifier != null && rankSpecifier.Length > 0; |
||||
} |
||||
} |
||||
|
||||
public static TypeReference CheckNull(TypeReference typeReference) |
||||
{ |
||||
return typeReference ?? NullTypeReference.Instance; |
||||
} |
||||
|
||||
public static TypeReference Null { |
||||
get { |
||||
return NullTypeReference.Instance; |
||||
} |
||||
} |
||||
|
||||
public virtual bool IsNull { |
||||
get { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Gets/Sets if the type reference had a "global::" prefix.
|
||||
/// </summary>
|
||||
public bool IsGlobal { |
||||
get { |
||||
return isGlobal; |
||||
} |
||||
set { |
||||
isGlobal = value; |
||||
} |
||||
} |
||||
|
||||
public TypeReference(string type) |
||||
{ |
||||
this.Type = type; |
||||
} |
||||
|
||||
public TypeReference(string type, string systemType) |
||||
{ |
||||
this.type = type; |
||||
this.systemType = systemType; |
||||
} |
||||
|
||||
public TypeReference(string type, List<TypeReference> genericTypes) : this(type) |
||||
{ |
||||
if (genericTypes != null) { |
||||
this.genericTypes = genericTypes; |
||||
} |
||||
} |
||||
|
||||
public TypeReference(string type, int[] rankSpecifier) : this(type, 0, rankSpecifier) |
||||
{ |
||||
} |
||||
|
||||
public TypeReference(string type, int pointerNestingLevel, int[] rankSpecifier) : this(type, pointerNestingLevel, rankSpecifier, null) |
||||
{ |
||||
} |
||||
|
||||
public TypeReference(string type, int pointerNestingLevel, int[] rankSpecifier, List<TypeReference> genericTypes) |
||||
{ |
||||
Debug.Assert(type != null); |
||||
this.type = type; |
||||
this.systemType = GetSystemType(type); |
||||
this.pointerNestingLevel = pointerNestingLevel; |
||||
this.rankSpecifier = rankSpecifier; |
||||
if (genericTypes != null) { |
||||
this.genericTypes = genericTypes; |
||||
} |
||||
} |
||||
|
||||
protected TypeReference() |
||||
{} |
||||
|
||||
public override object AcceptVisitor(IAstVisitor visitor, object data) |
||||
{ |
||||
return visitor.VisitTypeReference(this, data); |
||||
} |
||||
|
||||
public override string ToString() |
||||
{ |
||||
StringBuilder b = new StringBuilder(type); |
||||
if (genericTypes != null && genericTypes.Count > 0) { |
||||
b.Append('<'); |
||||
for (int i = 0; i < genericTypes.Count; i++) { |
||||
if (i > 0) b.Append(','); |
||||
b.Append(genericTypes[i].ToString()); |
||||
} |
||||
b.Append('>'); |
||||
} |
||||
if (pointerNestingLevel > 0) { |
||||
b.Append('*', pointerNestingLevel); |
||||
} |
||||
if (IsArrayType) { |
||||
foreach (int rank in rankSpecifier) { |
||||
b.Append('['); |
||||
if (rank < 0) |
||||
b.Append('`', -rank); |
||||
else |
||||
b.Append(',', rank); |
||||
b.Append(']'); |
||||
} |
||||
} |
||||
return b.ToString(); |
||||
} |
||||
|
||||
public static bool AreEqualReferences(TypeReference a, TypeReference b) |
||||
{ |
||||
if (a == b) return true; |
||||
if (a == null || b == null) return false; |
||||
if (a is InnerClassTypeReference) a = ((InnerClassTypeReference)a).CombineToNormalTypeReference(); |
||||
if (b is InnerClassTypeReference) b = ((InnerClassTypeReference)b).CombineToNormalTypeReference(); |
||||
if (a.systemType != b.systemType) return false; |
||||
if (a.pointerNestingLevel != b.pointerNestingLevel) return false; |
||||
if (a.IsArrayType != b.IsArrayType) return false; |
||||
if (a.IsArrayType) { |
||||
if (a.rankSpecifier.Length != b.rankSpecifier.Length) return false; |
||||
for (int i = 0; i < a.rankSpecifier.Length; i++) { |
||||
if (a.rankSpecifier[i] != b.rankSpecifier[i]) return false; |
||||
} |
||||
} |
||||
if (a.genericTypes.Count != b.genericTypes.Count) return false; |
||||
for (int i = 0; i < a.genericTypes.Count; i++) { |
||||
if (!AreEqualReferences(a.genericTypes[i], b.genericTypes[i])) |
||||
return false; |
||||
} |
||||
return true; |
||||
} |
||||
} |
||||
|
||||
internal sealed class NullTypeReference : TypeReference |
||||
{ |
||||
public static readonly NullTypeReference Instance = new NullTypeReference(); |
||||
public override bool IsNull { |
||||
get { |
||||
return true; |
||||
} |
||||
} |
||||
public override object AcceptVisitor(IAstVisitor visitor, object data) |
||||
{ |
||||
return null; |
||||
} |
||||
|
||||
public override string ToString() |
||||
{ |
||||
return String.Format("[NullTypeReference]"); |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// We need this special type reference for cases like
|
||||
/// OuterClass(Of T1).InnerClass(Of T2) (in expression or type context)
|
||||
/// or Dictionary(Of String, NamespaceStruct).KeyCollection (in type context, otherwise it's a
|
||||
/// MemberReferenceExpression)
|
||||
/// </summary>
|
||||
public class InnerClassTypeReference: TypeReference |
||||
{ |
||||
TypeReference baseType; |
||||
|
||||
public TypeReference BaseType { |
||||
get { return baseType; } |
||||
set { baseType = value; } |
||||
} |
||||
|
||||
public override TypeReference Clone() |
||||
{ |
||||
InnerClassTypeReference c = new InnerClassTypeReference(baseType.Clone(), Type, GenericTypes); |
||||
CopyFields(this, c); |
||||
return c; |
||||
} |
||||
|
||||
public InnerClassTypeReference(TypeReference outerClass, string innerType, List<TypeReference> innerGenericTypes) |
||||
: base(innerType, innerGenericTypes) |
||||
{ |
||||
this.baseType = outerClass; |
||||
} |
||||
|
||||
public override object AcceptVisitor(IAstVisitor visitor, object data) |
||||
{ |
||||
return visitor.VisitInnerClassTypeReference(this, data); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Creates a type reference where all type parameters are specified for the innermost class.
|
||||
/// Namespace.OuterClass(of string).InnerClass(of integer).InnerInnerClass
|
||||
/// becomes Namespace.OuterClass.InnerClass.InnerInnerClass(of string, integer)
|
||||
/// </summary>
|
||||
public TypeReference CombineToNormalTypeReference() |
||||
{ |
||||
TypeReference tr = (baseType is InnerClassTypeReference) |
||||
? ((InnerClassTypeReference)baseType).CombineToNormalTypeReference() |
||||
: baseType.Clone(); |
||||
CopyFields(this, tr); |
||||
tr.Type += "." + Type; |
||||
return tr; |
||||
} |
||||
|
||||
public override string ToString() |
||||
{ |
||||
return "[InnerClassTypeReference: (" + baseType.ToString() + ")." + base.ToString() + "]"; |
||||
} |
||||
} |
||||
} |
@ -1,26 +0,0 @@
@@ -1,26 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
|
||||
namespace ICSharpCode.NRefactory |
||||
{ |
||||
public interface IEnvironmentInformationProvider |
||||
{ |
||||
bool HasField(string fullTypeName, int typeParameterCount, string fieldName); |
||||
} |
||||
|
||||
sealed class DummyEnvironmentInformationProvider : IEnvironmentInformationProvider |
||||
{ |
||||
internal static readonly IEnvironmentInformationProvider Instance = new DummyEnvironmentInformationProvider(); |
||||
|
||||
public bool HasField(string fullTypeName, int typeParameterCount, string fieldName) |
||||
{ |
||||
return false; |
||||
} |
||||
} |
||||
} |
@ -1,240 +0,0 @@
@@ -1,240 +0,0 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
// Runtime Version:2.0.50727.1433
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
namespace ICSharpCode.NRefactory { |
||||
using System; |
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
|
||||
public interface IAstVisitor { |
||||
|
||||
object VisitAddHandlerStatement(AddHandlerStatement addHandlerStatement, object data); |
||||
|
||||
object VisitAddressOfExpression(AddressOfExpression addressOfExpression, object data); |
||||
|
||||
object VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression, object data); |
||||
|
||||
object VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, object data); |
||||
|
||||
object VisitAssignmentExpression(AssignmentExpression assignmentExpression, object data); |
||||
|
||||
object VisitAttribute(ICSharpCode.NRefactory.Ast.Attribute attribute, object data); |
||||
|
||||
object VisitAttributeSection(AttributeSection attributeSection, object data); |
||||
|
||||
object VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression, object data); |
||||
|
||||
object VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression, object data); |
||||
|
||||
object VisitBlockStatement(BlockStatement blockStatement, object data); |
||||
|
||||
object VisitBreakStatement(BreakStatement breakStatement, object data); |
||||
|
||||
object VisitCaseLabel(CaseLabel caseLabel, object data); |
||||
|
||||
object VisitCastExpression(CastExpression castExpression, object data); |
||||
|
||||
object VisitCatchClause(CatchClause catchClause, object data); |
||||
|
||||
object VisitCheckedExpression(CheckedExpression checkedExpression, object data); |
||||
|
||||
object VisitCheckedStatement(CheckedStatement checkedStatement, object data); |
||||
|
||||
object VisitClassReferenceExpression(ClassReferenceExpression classReferenceExpression, object data); |
||||
|
||||
object VisitCollectionInitializerExpression(CollectionInitializerExpression collectionInitializerExpression, object data); |
||||
|
||||
object VisitCompilationUnit(CompilationUnit compilationUnit, object data); |
||||
|
||||
object VisitConditionalExpression(ConditionalExpression conditionalExpression, object data); |
||||
|
||||
object VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, object data); |
||||
|
||||
object VisitConstructorInitializer(ConstructorInitializer constructorInitializer, object data); |
||||
|
||||
object VisitContinueStatement(ContinueStatement continueStatement, object data); |
||||
|
||||
object VisitDeclareDeclaration(DeclareDeclaration declareDeclaration, object data); |
||||
|
||||
object VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression, object data); |
||||
|
||||
object VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, object data); |
||||
|
||||
object VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration, object data); |
||||
|
||||
object VisitDirectionExpression(DirectionExpression directionExpression, object data); |
||||
|
||||
object VisitDoLoopStatement(DoLoopStatement doLoopStatement, object data); |
||||
|
||||
object VisitElseIfSection(ElseIfSection elseIfSection, object data); |
||||
|
||||
object VisitEmptyStatement(EmptyStatement emptyStatement, object data); |
||||
|
||||
object VisitEndStatement(EndStatement endStatement, object data); |
||||
|
||||
object VisitEraseStatement(EraseStatement eraseStatement, object data); |
||||
|
||||
object VisitErrorStatement(ErrorStatement errorStatement, object data); |
||||
|
||||
object VisitEventAddRegion(EventAddRegion eventAddRegion, object data); |
||||
|
||||
object VisitEventDeclaration(EventDeclaration eventDeclaration, object data); |
||||
|
||||
object VisitEventRaiseRegion(EventRaiseRegion eventRaiseRegion, object data); |
||||
|
||||
object VisitEventRemoveRegion(EventRemoveRegion eventRemoveRegion, object data); |
||||
|
||||
object VisitExitStatement(ExitStatement exitStatement, object data); |
||||
|
||||
object VisitExpressionStatement(ExpressionStatement expressionStatement, object data); |
||||
|
||||
object VisitFieldDeclaration(FieldDeclaration fieldDeclaration, object data); |
||||
|
||||
object VisitFixedStatement(FixedStatement fixedStatement, object data); |
||||
|
||||
object VisitForeachStatement(ForeachStatement foreachStatement, object data); |
||||
|
||||
object VisitForNextStatement(ForNextStatement forNextStatement, object data); |
||||
|
||||
object VisitForStatement(ForStatement forStatement, object data); |
||||
|
||||
object VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement, object data); |
||||
|
||||
object VisitGotoStatement(GotoStatement gotoStatement, object data); |
||||
|
||||
object VisitIdentifierExpression(IdentifierExpression identifierExpression, object data); |
||||
|
||||
object VisitIfElseStatement(IfElseStatement ifElseStatement, object data); |
||||
|
||||
object VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration, object data); |
||||
|
||||
object VisitIndexerExpression(IndexerExpression indexerExpression, object data); |
||||
|
||||
object VisitInnerClassTypeReference(InnerClassTypeReference innerClassTypeReference, object data); |
||||
|
||||
object VisitInterfaceImplementation(InterfaceImplementation interfaceImplementation, object data); |
||||
|
||||
object VisitInvocationExpression(InvocationExpression invocationExpression, object data); |
||||
|
||||
object VisitLabelStatement(LabelStatement labelStatement, object data); |
||||
|
||||
object VisitLambdaExpression(LambdaExpression lambdaExpression, object data); |
||||
|
||||
object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data); |
||||
|
||||
object VisitLockStatement(LockStatement lockStatement, object data); |
||||
|
||||
object VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression, object data); |
||||
|
||||
object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data); |
||||
|
||||
object VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression, object data); |
||||
|
||||
object VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration, object data); |
||||
|
||||
object VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression, object data); |
||||
|
||||
object VisitOnErrorStatement(OnErrorStatement onErrorStatement, object data); |
||||
|
||||
object VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration, object data); |
||||
|
||||
object VisitOptionDeclaration(OptionDeclaration optionDeclaration, object data); |
||||
|
||||
object VisitParameterDeclarationExpression(ParameterDeclarationExpression parameterDeclarationExpression, object data); |
||||
|
||||
object VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression, object data); |
||||
|
||||
object VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression, object data); |
||||
|
||||
object VisitPrimitiveExpression(PrimitiveExpression primitiveExpression, object data); |
||||
|
||||
object VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, object data); |
||||
|
||||
object VisitPropertyGetRegion(PropertyGetRegion propertyGetRegion, object data); |
||||
|
||||
object VisitPropertySetRegion(PropertySetRegion propertySetRegion, object data); |
||||
|
||||
object VisitQueryExpression(QueryExpression queryExpression, object data); |
||||
|
||||
object VisitQueryExpressionFromClause(QueryExpressionFromClause queryExpressionFromClause, object data); |
||||
|
||||
object VisitQueryExpressionGroupClause(QueryExpressionGroupClause queryExpressionGroupClause, object data); |
||||
|
||||
object VisitQueryExpressionIntoClause(QueryExpressionIntoClause queryExpressionIntoClause, object data); |
||||
|
||||
object VisitQueryExpressionJoinClause(QueryExpressionJoinClause queryExpressionJoinClause, object data); |
||||
|
||||
object VisitQueryExpressionLetClause(QueryExpressionLetClause queryExpressionLetClause, object data); |
||||
|
||||
object VisitQueryExpressionOrdering(QueryExpressionOrdering queryExpressionOrdering, object data); |
||||
|
||||
object VisitQueryExpressionSelectClause(QueryExpressionSelectClause queryExpressionSelectClause, object data); |
||||
|
||||
object VisitQueryExpressionWhereClause(QueryExpressionWhereClause queryExpressionWhereClause, object data); |
||||
|
||||
object VisitRaiseEventStatement(RaiseEventStatement raiseEventStatement, object data); |
||||
|
||||
object VisitReDimStatement(ReDimStatement reDimStatement, object data); |
||||
|
||||
object VisitRemoveHandlerStatement(RemoveHandlerStatement removeHandlerStatement, object data); |
||||
|
||||
object VisitResumeStatement(ResumeStatement resumeStatement, object data); |
||||
|
||||
object VisitReturnStatement(ReturnStatement returnStatement, object data); |
||||
|
||||
object VisitSizeOfExpression(SizeOfExpression sizeOfExpression, object data); |
||||
|
||||
object VisitStackAllocExpression(StackAllocExpression stackAllocExpression, object data); |
||||
|
||||
object VisitStopStatement(StopStatement stopStatement, object data); |
||||
|
||||
object VisitSwitchSection(SwitchSection switchSection, object data); |
||||
|
||||
object VisitSwitchStatement(SwitchStatement switchStatement, object data); |
||||
|
||||
object VisitTemplateDefinition(TemplateDefinition templateDefinition, object data); |
||||
|
||||
object VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression, object data); |
||||
|
||||
object VisitThrowStatement(ThrowStatement throwStatement, object data); |
||||
|
||||
object VisitTryCatchStatement(TryCatchStatement tryCatchStatement, object data); |
||||
|
||||
object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data); |
||||
|
||||
object VisitTypeOfExpression(TypeOfExpression typeOfExpression, object data); |
||||
|
||||
object VisitTypeOfIsExpression(TypeOfIsExpression typeOfIsExpression, object data); |
||||
|
||||
object VisitTypeReference(TypeReference typeReference, object data); |
||||
|
||||
object VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression, object data); |
||||
|
||||
object VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression, object data); |
||||
|
||||
object VisitUncheckedExpression(UncheckedExpression uncheckedExpression, object data); |
||||
|
||||
object VisitUncheckedStatement(UncheckedStatement uncheckedStatement, object data); |
||||
|
||||
object VisitUnsafeStatement(UnsafeStatement unsafeStatement, object data); |
||||
|
||||
object VisitUsing(Using @using, object data); |
||||
|
||||
object VisitUsingDeclaration(UsingDeclaration usingDeclaration, object data); |
||||
|
||||
object VisitUsingStatement(UsingStatement usingStatement, object data); |
||||
|
||||
object VisitVariableDeclaration(VariableDeclaration variableDeclaration, object data); |
||||
|
||||
object VisitWithStatement(WithStatement withStatement, object data); |
||||
|
||||
object VisitYieldStatement(YieldStatement yieldStatement, object data); |
||||
} |
||||
} |
@ -1,297 +0,0 @@
@@ -1,297 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections; |
||||
using System.Collections.Generic; |
||||
using System.IO; |
||||
using System.Text; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser |
||||
{ |
||||
/// <summary>
|
||||
/// This is the base class for the C# and VB.NET lexer
|
||||
/// </summary>
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1708:IdentifiersShouldDifferByMoreThanCase")] |
||||
public abstract class AbstractLexer : ILexer |
||||
{ |
||||
TextReader reader; |
||||
int col = 1; |
||||
int line = 1; |
||||
|
||||
[CLSCompliant(false)] |
||||
protected Errors errors = new Errors(); |
||||
|
||||
protected Token lastToken = null; |
||||
protected Token curToken = null; |
||||
protected Token peekToken = null; |
||||
|
||||
string[] specialCommentTags = null; |
||||
protected Hashtable specialCommentHash = null; |
||||
List<TagComment> tagComments = new List<TagComment>(); |
||||
protected StringBuilder sb = new StringBuilder(); |
||||
[CLSCompliant(false)] |
||||
protected SpecialTracker specialTracker = new SpecialTracker(); |
||||
|
||||
// used for the original value of strings (with escape sequences).
|
||||
protected StringBuilder originalValue = new StringBuilder(); |
||||
|
||||
bool skipAllComments = false; |
||||
|
||||
public bool SkipAllComments { |
||||
get { |
||||
return skipAllComments; |
||||
} |
||||
set { |
||||
skipAllComments = value; |
||||
} |
||||
} |
||||
|
||||
protected int Line { |
||||
get { |
||||
return line; |
||||
} |
||||
} |
||||
protected int Col { |
||||
get { |
||||
return col; |
||||
} |
||||
} |
||||
protected int ReaderRead() |
||||
{ |
||||
++col; |
||||
return reader.Read(); |
||||
} |
||||
protected int ReaderPeek() |
||||
{ |
||||
return reader.Peek(); |
||||
} |
||||
|
||||
public Errors Errors { |
||||
get { |
||||
return errors; |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Returns the comments that had been read and containing tag key words.
|
||||
/// </summary>
|
||||
public List<TagComment> TagComments { |
||||
get { |
||||
return tagComments; |
||||
} |
||||
} |
||||
|
||||
public SpecialTracker SpecialTracker { |
||||
get { |
||||
return specialTracker; |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Special comment tags are tags like TODO, HACK or UNDONE which are read by the lexer and stored in <see cref="TagComments"/>.
|
||||
/// </summary>
|
||||
public string[] SpecialCommentTags { |
||||
get { |
||||
return specialCommentTags; |
||||
} |
||||
set { |
||||
specialCommentTags = value; |
||||
specialCommentHash = null; |
||||
if (specialCommentTags != null && specialCommentTags.Length > 0) { |
||||
specialCommentHash = new Hashtable(); |
||||
foreach (string str in specialCommentTags) { |
||||
specialCommentHash.Add(str, null); |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// The current Token. <seealso cref="ICSharpCode.NRefactory.Parser.Token"/>
|
||||
/// </summary>
|
||||
public Token Token { |
||||
get { |
||||
// Console.WriteLine("Call to Token");
|
||||
return lastToken; |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// The next Token (The <see cref="Token"/> after <see cref="NextToken"/> call) . <seealso cref="ICSharpCode.NRefactory.Parser.Token"/>
|
||||
/// </summary>
|
||||
public Token LookAhead { |
||||
get { |
||||
// Console.WriteLine("Call to LookAhead");
|
||||
return curToken; |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Constructor for the abstract lexer class.
|
||||
/// </summary>
|
||||
protected AbstractLexer(TextReader reader) |
||||
{ |
||||
this.reader = reader; |
||||
} |
||||
|
||||
#region System.IDisposable interface implementation
|
||||
public virtual void Dispose() |
||||
{ |
||||
reader.Close(); |
||||
reader = null; |
||||
errors = null; |
||||
lastToken = curToken = peekToken = null; |
||||
specialCommentHash = null; |
||||
tagComments = null; |
||||
sb = originalValue = null; |
||||
} |
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Must be called before a peek operation.
|
||||
/// </summary>
|
||||
public void StartPeek() |
||||
{ |
||||
peekToken = curToken; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Gives back the next token. A second call to Peek() gives the next token after the last call for Peek() and so on.
|
||||
/// </summary>
|
||||
/// <returns>An <see cref="Token"/> object.</returns>
|
||||
public Token Peek() |
||||
{ |
||||
// Console.WriteLine("Call to Peek");
|
||||
if (peekToken.next == null) { |
||||
peekToken.next = Next(); |
||||
specialTracker.InformToken(peekToken.next.kind); |
||||
} |
||||
peekToken = peekToken.next; |
||||
return peekToken; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Reads the next token and gives it back.
|
||||
/// </summary>
|
||||
/// <returns>An <see cref="Token"/> object.</returns>
|
||||
public virtual Token NextToken() |
||||
{ |
||||
if (curToken == null) { |
||||
curToken = Next(); |
||||
specialTracker.InformToken(curToken.kind); |
||||
//Console.WriteLine(ICSharpCode.NRefactory.Parser.CSharp.Tokens.GetTokenString(curToken.kind) + " -- " + curToken.val + "(" + curToken.kind + ")");
|
||||
return curToken; |
||||
} |
||||
|
||||
lastToken = curToken; |
||||
|
||||
if (curToken.next == null) { |
||||
curToken.next = Next(); |
||||
if (curToken.next != null) { |
||||
specialTracker.InformToken(curToken.next.kind); |
||||
} |
||||
} |
||||
|
||||
curToken = curToken.next; |
||||
//Console.WriteLine(ICSharpCode.NRefactory.Parser.CSharp.Tokens.GetTokenString(curToken.kind) + " -- " + curToken.val + "(" + curToken.kind + ")");
|
||||
return curToken; |
||||
} |
||||
|
||||
protected abstract Token Next(); |
||||
|
||||
protected static bool IsIdentifierPart(int ch) |
||||
{ |
||||
if (ch == 95) return true; // 95 = '_'
|
||||
if (ch == -1) return false; |
||||
return char.IsLetterOrDigit((char)ch); // accept unicode letters
|
||||
} |
||||
|
||||
protected static bool IsHex(char digit) |
||||
{ |
||||
return Char.IsDigit(digit) || ('A' <= digit && digit <= 'F') || ('a' <= digit && digit <= 'f'); |
||||
} |
||||
|
||||
protected int GetHexNumber(char digit) |
||||
{ |
||||
if (Char.IsDigit(digit)) { |
||||
return digit - '0'; |
||||
} |
||||
if ('A' <= digit && digit <= 'F') { |
||||
return digit - 'A' + 0xA; |
||||
} |
||||
if ('a' <= digit && digit <= 'f') { |
||||
return digit - 'a' + 0xA; |
||||
} |
||||
errors.Error(line, col, String.Format("Invalid hex number '" + digit + "'")); |
||||
return 0; |
||||
} |
||||
|
||||
protected bool WasLineEnd(char ch) |
||||
{ |
||||
// Handle MS-DOS or MacOS line ends.
|
||||
if (ch == '\r') { |
||||
if (reader.Peek() == '\n') { // MS-DOS line end '\r\n'
|
||||
ch = (char)reader.Read(); |
||||
++col; |
||||
} else { // assume MacOS line end which is '\r'
|
||||
ch = '\n'; |
||||
} |
||||
} |
||||
return ch == '\n'; |
||||
} |
||||
|
||||
protected bool HandleLineEnd(char ch) |
||||
{ |
||||
if (WasLineEnd(ch)) { |
||||
++line; |
||||
col = 1; |
||||
return true; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
protected void SkipToEndOfLine() |
||||
{ |
||||
int nextChar; |
||||
while ((nextChar = reader.Read()) != -1) { |
||||
if (HandleLineEnd((char)nextChar)) { |
||||
break; |
||||
} |
||||
} |
||||
} |
||||
|
||||
protected string ReadToEndOfLine() |
||||
{ |
||||
sb.Length = 0; |
||||
int nextChar; |
||||
while ((nextChar = reader.Read()) != -1) { |
||||
char ch = (char)nextChar; |
||||
|
||||
// Return read string, if EOL is reached
|
||||
if (HandleLineEnd(ch)) { |
||||
return sb.ToString(); |
||||
} |
||||
|
||||
sb.Append(ch); |
||||
} |
||||
|
||||
// Got EOF before EOL
|
||||
string retStr = sb.ToString(); |
||||
col += retStr.Length; |
||||
return retStr; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Skips to the end of the current code block.
|
||||
/// For this, the lexer must have read the next token AFTER the token opening the
|
||||
/// block (so that Lexer.Token is the block-opening token, not Lexer.LookAhead).
|
||||
/// After the call, Lexer.LookAhead will be the block-closing token.
|
||||
/// </summary>
|
||||
public abstract void SkipCurrentBlock(int targetToken); |
||||
} |
||||
} |
@ -1,340 +0,0 @@
@@ -1,340 +0,0 @@
|
||||
#!/bin/perl |
||||
|
||||
# File names |
||||
$keyword_file = "KeywordList.txt"; |
||||
$keywords_outfile = "Keywords.cs"; |
||||
$tokens_outfile = "Tokens.cs"; |
||||
$unittests_outfile = "LexerTests.cs"; |
||||
$ATGTokensSection = "ATGTokensSection.gen"; |
||||
|
||||
#read infile |
||||
print "\n"; |
||||
print "Reading keyword definition from '$keyword_file'.\n"; |
||||
open(DAT, $keyword_file) || die("Could not open file '$keyword_file': $!"); |
||||
@raw_data=<DAT>; |
||||
close(DAT); |
||||
print "done.\n"; |
||||
|
||||
#analyse infile |
||||
print "starting analysation ... this could take a few minutes.\n"; |
||||
|
||||
foreach (@raw_data) { |
||||
if ($_=~/^\s*\$(\w+)\s*=\s*(\S+)\s*$/) { |
||||
#properties form: $PROPERTY = "VALUE" |
||||
$properties{$1} = $2; |
||||
} elsif ($_=~/^\s*(\w+)\s*=\s*(\S+)\s*$/) { |
||||
#special characters form: name = "VALUE" |
||||
$specialCharLookup{$2} = $1; |
||||
$special_chars[$#special_chars + 1] = $1; |
||||
$special_values[$#special_values + 1] = $2; |
||||
} elsif ($_=~/^\s*\"(\S+)\s*\"\s*$/) { |
||||
#special keywords form: "VALUE" |
||||
$keywords[$#keywords + 1] = $1; |
||||
} elsif ($_=~/^\s*(\w+)\s*\((.*)\)\s*$/) { |
||||
$sets[$#sets + 1] = $1; |
||||
#Split set values (comma separated list) |
||||
$_ = $2; |
||||
@vals = split/\s*,\s*/; |
||||
|
||||
push @$setValues, [@vals]; |
||||
} elsif ($_=~/^\s*(\w+)\s*$/) { |
||||
#special terminal classes form: name |
||||
$terminals[$#terminals + 1] = $1 |
||||
} elsif ($_=~/^\s*(#.*)?$/) { |
||||
#ignore empty line |
||||
} else { |
||||
print "unknown line: $_"; |
||||
} |
||||
} |
||||
|
||||
|
||||
for ($i=0; $i <= $#keywords; $i++) { |
||||
$upperKeywords[$i] = uc $keywords[$i]; |
||||
} |
||||
sort (ascend @upperKeywords); |
||||
|
||||
|
||||
sort (ascend @keywords); |
||||
print "done.\n"; |
||||
|
||||
#write output |
||||
print "writing output files.\nIf your computer doesn’t respond, then press \"Ctrl-Alt-Delete\"\n"; |
||||
print "\n"; |
||||
&write_keywordfile; |
||||
print "\n"; |
||||
&write_tokensfile; |
||||
print "\n"; |
||||
&write_atgtokensfile; |
||||
print "\n"; |
||||
&write_unittests; |
||||
print "finished.\n"; |
||||
|
||||
sub write_keywordfile |
||||
{ |
||||
print " ->Generating Keywords class to file '$keywords_outfile'\n"; |
||||
open(DAT,">$keywords_outfile") || die("Cannot Open File"); |
||||
print DAT "// this file was autogenerated by a tool.\n"; |
||||
print DAT "using System;\n"; |
||||
print DAT "\n"; |
||||
print DAT "namespace " . $properties{'Namespace'} . "\n"; |
||||
print DAT "{\n"; |
||||
print DAT "\tpublic static class Keywords\n"; |
||||
print DAT "\t{\n"; |
||||
print DAT "\t\tstatic readonly string[] keywordList = {\n"; |
||||
if ($properties{'UpperCaseKeywords'} eq "True") { |
||||
for ($i=0; $i <= $#upperKeywords; $i++) { |
||||
print DAT "\t\t\t\"$upperKeywords[$i]\""; |
||||
if ($i + 1 <= $#upperKeywords) { |
||||
print DAT ","; |
||||
} |
||||
print DAT "\n"; |
||||
} |
||||
} else { |
||||
for ($i=0; $i <= $#keywords; $i++) { |
||||
print DAT "\t\t\t\"$keywords[$i]\""; |
||||
if ($i + 1 <= $#keywords) { |
||||
print DAT ","; |
||||
} |
||||
print DAT "\n"; |
||||
} |
||||
} |
||||
|
||||
print DAT "\t\t};\n"; |
||||
print DAT "\t\t\n"; |
||||
if ($properties{'UpperCaseKeywords'} eq "True") { |
||||
print DAT "\t\tstatic LookupTable keywords = new LookupTable(false);\n"; |
||||
} else { |
||||
print DAT "\t\tstatic LookupTable keywords = new LookupTable(true);\n"; |
||||
} |
||||
|
||||
print DAT "\t\t\n"; |
||||
print DAT "\t\tstatic Keywords()\n"; |
||||
print DAT "\t\t{\n"; |
||||
print DAT "\t\t\tfor (int i = 0; i < keywordList.Length; ++i) {\n"; |
||||
print DAT "\t\t\t\tkeywords[keywordList[i]] = i + Tokens." . ucfirst $keywords[0] . ";\n"; |
||||
print DAT "\t\t\t}\n"; |
||||
print DAT "\t\t}\n"; |
||||
print DAT "\t\t\n"; |
||||
print DAT "\t\tpublic static int GetToken(string keyword)\n"; |
||||
print DAT "\t\t{\n"; |
||||
print DAT "\t\t\treturn keywords[keyword];\n"; |
||||
print DAT "\t\t}\n"; |
||||
print DAT "\t\t\n"; |
||||
print DAT "\t\tpublic static bool IsNonIdentifierKeyword(string word)\n"; |
||||
print DAT "\t\t{\n"; |
||||
print DAT "\t\t\tint token = GetToken(word);\n"; |
||||
print DAT "\t\t\tif (token < 0)\n"; |
||||
print DAT "\t\t\t\treturn false;\n"; |
||||
print DAT "\t\t\treturn !Tokens.IdentifierTokens[token];\n"; |
||||
print DAT "\t\t}\n"; |
||||
print DAT "\t}\n"; |
||||
print DAT "}\n"; |
||||
close(DAT); |
||||
print " ->done.\n"; |
||||
} |
||||
|
||||
sub write_token { |
||||
$formattedString = sprintf("%-20s", ucfirst $tokenName); |
||||
if (($tokenName eq "GetType") or ($tokenName eq "equals")) { |
||||
print DAT "\t\tnew public const int $formattedString = $tokenValue;\n"; |
||||
} else { |
||||
print DAT "\t\tpublic const int $formattedString = $tokenValue;\n"; |
||||
} |
||||
$tokenValue++; |
||||
|
||||
} |
||||
|
||||
sub print_list { |
||||
local ($j, $k, $max, $index); |
||||
|
||||
$index = $_[0]; |
||||
$max = $#{$setValues->[$index]}; |
||||
|
||||
for ($j=0; $j <= $max; $j++) { |
||||
$_ = $setValues->[$index][$j]; |
||||
if (/\"(\w+)\"/) { # Keywords |
||||
print DAT ucfirst $1; |
||||
} elsif (/\"(\W+)\"/) { # special chars |
||||
print DAT $specialCharLookup{$_}; |
||||
} elsif (/@(\w+)/) { # @otherList |
||||
for ($k=0; $k <= $#sets; $k++) { |
||||
if ($sets[$k] eq $1) { |
||||
print_list($k); |
||||
} |
||||
} |
||||
} else { |
||||
print DAT $_; |
||||
} |
||||
|
||||
if ($j + 1 <= $max) { |
||||
print DAT ", "; |
||||
} |
||||
} |
||||
} |
||||
|
||||
|
||||
sub write_tokensfile { |
||||
print " ->Generating Tokens class to file '$tokens_outfile'\n"; |
||||
open(DAT,">$tokens_outfile") || die("Cannot Open File"); |
||||
print DAT "// this file was autogenerated by a tool.\n"; |
||||
print DAT "using System;\n"; |
||||
print DAT "using System.Collections;\n"; |
||||
print DAT "\n"; |
||||
print DAT "namespace " . $properties{'Namespace'} . "\n"; |
||||
print DAT "{\n"; |
||||
print DAT "\tpublic static class Tokens\n"; |
||||
print DAT "\t{\n"; |
||||
$tokenValue = 0; |
||||
|
||||
print DAT "\t\t// ----- terminal classes -----\n"; |
||||
foreach (@terminals) { |
||||
$tokenName = $_; |
||||
write_token(); |
||||
} |
||||
print DAT "\n"; |
||||
print DAT "\t\t// ----- special character -----\n"; |
||||
foreach (@special_chars) { |
||||
$tokenName = $_; |
||||
write_token(); |
||||
} |
||||
print DAT "\n"; |
||||
print DAT "\t\t// ----- keywords -----\n"; |
||||
foreach (@keywords) { |
||||
$tokenName = $_; |
||||
write_token(); |
||||
} |
||||
print DAT "\n"; |
||||
|
||||
print DAT "\t\tpublic const int MaxToken = " . $tokenValue . ";\n"; |
||||
|
||||
#write sets. |
||||
if ($#sets > 0) { |
||||
print DAT "\t\tstatic BitArray NewSet(params int[] values)\n"; |
||||
print DAT "\t\t{\n"; |
||||
print DAT "\t\t\tBitArray bitArray = new BitArray(MaxToken);\n"; |
||||
print DAT "\t\t\tforeach (int val in values) {\n"; |
||||
print DAT "\t\t\tbitArray[val] = true;\n"; |
||||
print DAT "\t\t\t}\n"; |
||||
print DAT "\t\t\treturn bitArray;\n"; |
||||
print DAT "\t\t}\n"; |
||||
for ($i=0; $i <= $#sets; $i++) { |
||||
print DAT "\t\tpublic static BitArray ". $sets[$i] . " = NewSet("; |
||||
print_list($i); |
||||
print DAT ");\n"; |
||||
} |
||||
print DAT "\n"; |
||||
} |
||||
|
||||
#write token number --> string function. |
||||
print DAT "\t\tstatic string[] tokenList = new string[] {\n"; |
||||
print DAT "\t\t\t// ----- terminal classes -----\n"; |
||||
foreach (@terminals) { |
||||
print DAT "\t\t\t\"<$_>\",\n"; |
||||
} |
||||
print DAT "\t\t\t// ----- special character -----\n"; |
||||
foreach (@special_values) { |
||||
print DAT "\t\t\t$_,\n"; |
||||
} |
||||
print DAT "\t\t\t// ----- keywords -----\n"; |
||||
foreach (@keywords) { |
||||
print DAT "\t\t\t\"$_\",\n"; |
||||
} |
||||
print DAT "\t\t};\n"; |
||||
|
||||
|
||||
print DAT "\t\tpublic static string GetTokenString(int token)\n"; |
||||
print DAT "\t\t{\n"; |
||||
print DAT "\t\t\tif (token >= 0 && token < tokenList.Length) {\n"; |
||||
print DAT "\t\t\t\treturn tokenList[token];\n"; |
||||
print DAT "\t\t\t}\n"; |
||||
print DAT "\t\t\tthrow new System.NotSupportedException(\"Unknown token:\" + token);\n"; |
||||
print DAT "\t\t}\n"; |
||||
print DAT "\t}\n"; |
||||
|
||||
|
||||
|
||||
print DAT "}\n"; |
||||
close(DAT); |
||||
print " ->done.\n"; |
||||
} |
||||
|
||||
sub write_unittests { |
||||
open(DAT,">$unittests_outfile") || die("Cannot Open File"); |
||||
print DAT "using System;\n"; |
||||
print DAT "using System.IO;\n"; |
||||
print DAT "using NUnit.Framework;\n"; |
||||
print DAT "using ICSharpCode.NRefactory.Parser;\n"; |
||||
print DAT "using ICSharpCode.NRefactory.PrettyPrinter;\n"; |
||||
|
||||
print DAT "\n"; |
||||
print DAT "namespace ICSharpCode.NRefactory.Tests.Lexer\n"; |
||||
print DAT "{\n"; |
||||
print DAT "\t[TestFixture]\n"; |
||||
print DAT "\tpublic sealed class LexerTests\n"; |
||||
print DAT "\t{\n"; |
||||
print DAT "\t\tILexer GenerateLexer(StringReader sr)\n"; |
||||
print DAT "\t\t{\n"; |
||||
print DAT "\t\t\treturn ParserFactory.CreateLexer(SupportedLanguage.CSharp, sr);\n"; |
||||
print DAT "\t\t}\n\n"; |
||||
|
||||
for ($i=0; $i <= $#special_values; $i++) { |
||||
|
||||
print DAT "\t\t[Test]\n"; |
||||
print DAT "\t\tpublic void Test" . $special_chars[$i] ."()\n"; |
||||
print DAT "\t\t{\n"; |
||||
print DAT "\t\t\tILexer lexer = GenerateLexer(new StringReader(" . $special_values[$i] . "));\n"; |
||||
print DAT "\t\t\tAssert.AreEqual(Tokens." . $special_chars[$i] . ", lexer.NextToken().kind);\n"; |
||||
print DAT "\t\t}\n\n"; |
||||
|
||||
} |
||||
|
||||
foreach (@keywords) { |
||||
print DAT "\t\t[Test()]\n"; |
||||
print DAT "\t\tpublic void Test" . ucfirst $_ ."()\n"; |
||||
print DAT "\t\t{\n"; |
||||
print DAT "\t\t\tILexer lexer = GenerateLexer(new StringReader(\"" . $_ . "\"));\n"; |
||||
print DAT "\t\t\tAssert.AreEqual(Tokens." . ucfirst $_ . ", lexer.NextToken().kind);\n"; |
||||
print DAT "\t\t}\n"; |
||||
} |
||||
|
||||
print DAT "\t}\n"; |
||||
print DAT "}\n"; |
||||
|
||||
|
||||
close(DAT); |
||||
} |
||||
|
||||
sub write_atgtokensfile { |
||||
print " ->Generating ATG TOKENS section and writing it to file '$ATGTokensSection'\n"; |
||||
open(DAT,">$ATGTokensSection") || die("Cannot Open File"); |
||||
print DAT "/* START AUTOGENERATED TOKENS SECTION */\n"; |
||||
print DAT "TOKENS\n"; |
||||
|
||||
print DAT "\t/* ----- terminal classes ----- */\n"; |
||||
print DAT "\t/* EOF is 0 */\n"; |
||||
foreach $term (@terminals) { |
||||
if ($term eq "EOF") { |
||||
} elsif ($term eq "Identifier") { |
||||
print DAT "\tident\n"; |
||||
} else { |
||||
print DAT "\t$term\n"; |
||||
} |
||||
|
||||
} |
||||
|
||||
print DAT "\n"; |
||||
print DAT "\t/* ----- special character ----- */\n"; |
||||
foreach (@special_values) { |
||||
print DAT "\t$_\n"; |
||||
} |
||||
print DAT "\n"; |
||||
print DAT "\t/* ----- keywords ----- */\n"; |
||||
foreach (@keywords) { |
||||
print DAT "\t\"$_\"\n"; |
||||
} |
||||
|
||||
print DAT "/* END AUTOGENERATED TOKENS SECTION */\n"; |
||||
close(DAT); |
||||
print " ->done.\n"; |
||||
} |
||||
|
@ -1,215 +0,0 @@
@@ -1,215 +0,0 @@
|
||||
# this list is used for autogeneration of: |
||||
# - Keywords.cs |
||||
# - Tokens.cs |
||||
# - ATGTokensSection.txt - the TOKENS section of the ATG file |
||||
|
||||
# use BuildKeywords to generate the different lists. |
||||
|
||||
$Namespace=ICSharpCode.NRefactory.Parser.CSharp |
||||
$UpperCaseKeywords=False |
||||
|
||||
# TERMINAL_CLASSES |
||||
EOF |
||||
Identifier |
||||
Literal |
||||
|
||||
# SPECIAL_CHARACTERS |
||||
Assign = "=" |
||||
Plus = "+" |
||||
Minus = "-" |
||||
Times = "*" |
||||
Div = "/" |
||||
Mod = "%" |
||||
|
||||
Colon = ":" |
||||
DoubleColon = "::" |
||||
Semicolon = ";" |
||||
Question = "?" |
||||
DoubleQuestion = "??" |
||||
Comma = "," |
||||
Dot = "." |
||||
|
||||
OpenCurlyBrace = "{" |
||||
CloseCurlyBrace = "}" |
||||
|
||||
OpenSquareBracket = "[" |
||||
CloseSquareBracket = "]" |
||||
|
||||
OpenParenthesis = "(" |
||||
CloseParenthesis = ")" |
||||
|
||||
GreaterThan = ">" |
||||
LessThan = "<" |
||||
|
||||
Not = "!" |
||||
LogicalAnd = "&&" |
||||
LogicalOr = "||" |
||||
|
||||
BitwiseComplement = "~" |
||||
BitwiseAnd = "&" |
||||
BitwiseOr = "|" |
||||
Xor = "^" |
||||
|
||||
Increment = "++" |
||||
Decrement = "--" |
||||
Equal = "==" |
||||
NotEqual = "!=" |
||||
GreaterEqual = ">=" |
||||
LessEqual = "<=" |
||||
|
||||
ShiftLeft = "<<" |
||||
#Removed because of generics |
||||
#ShiftRight = ">>" |
||||
|
||||
PlusAssign = "+=" |
||||
MinusAssign = "-=" |
||||
TimesAssign = "*=" |
||||
DivAssign = "/=" |
||||
ModAssign = "%=" |
||||
BitwiseAndAssign = "&=" |
||||
BitwiseOrAssign = "|=" |
||||
XorAssign = "^=" |
||||
ShiftLeftAssign = "<<=" |
||||
#Removed because of generics |
||||
#ShiftRightAssign = ">>=" |
||||
Pointer = "->" |
||||
LambdaArrow = "=>" |
||||
|
||||
# Keywordlist |
||||
"abstract" |
||||
"as" |
||||
"base" |
||||
"bool" |
||||
"break" |
||||
"byte" |
||||
"case" |
||||
"catch" |
||||
"char" |
||||
"checked" |
||||
"class" |
||||
"const" |
||||
"continue" |
||||
"decimal" |
||||
"default" |
||||
"delegate" |
||||
"do" |
||||
"double" |
||||
"else" |
||||
"enum" |
||||
"event" |
||||
"explicit" |
||||
"extern" |
||||
"false" |
||||
"finally" |
||||
"fixed" |
||||
"float" |
||||
"for" |
||||
"foreach" |
||||
"goto" |
||||
"if" |
||||
"implicit" |
||||
"in" |
||||
"int" |
||||
"interface" |
||||
"internal" |
||||
"is" |
||||
"lock" |
||||
"long" |
||||
"namespace" |
||||
"new" |
||||
"null" |
||||
"object" |
||||
"operator" |
||||
"out" |
||||
"override" |
||||
"params" |
||||
"private" |
||||
"protected" |
||||
"public" |
||||
"readonly" |
||||
"ref" |
||||
"return" |
||||
"sbyte" |
||||
"sealed" |
||||
"short" |
||||
"sizeof" |
||||
"stackalloc" |
||||
"static" |
||||
"string" |
||||
"struct" |
||||
"switch" |
||||
"this" |
||||
"throw" |
||||
"true" |
||||
"try" |
||||
"typeof" |
||||
"uint" |
||||
"ulong" |
||||
"unchecked" |
||||
"unsafe" |
||||
"ushort" |
||||
"using" |
||||
"virtual" |
||||
"void" |
||||
"volatile" |
||||
"while" |
||||
|
||||
# Context dependent keywords. |
||||
"partial" |
||||
"where" |
||||
"get" |
||||
"set" |
||||
"add" |
||||
"remove" |
||||
"yield" |
||||
"select" |
||||
"group" |
||||
"by" |
||||
"into" |
||||
"from" |
||||
"ascending" |
||||
"descending" |
||||
"orderby" |
||||
"let" |
||||
"join" |
||||
"on" |
||||
"equals" |
||||
|
||||
#Sets |
||||
|
||||
# When changing IdentifierTokens, ensure you also change the "Identifier" production in cs.ATG |
||||
IdentifierTokens(Identifier, "partial", "where", "get", "set", "add", "remove", "yield", "select", "group", "by", "into", "from", "ascending", "descending", "orderby", "let", "join", "on", "equals") |
||||
|
||||
OverloadableUnaryOp("-", "!", "~", "++", "--", "true", "false") |
||||
OverloadableBinaryOp("+", "-", "*", "/", "%", "&", "|", "^", "<<", "==", "!=", ">", "<", ">=", "<=") |
||||
|
||||
TypeKW("char", "bool", "object", "string", "sbyte", "byte", "short", "ushort", "int", "uint", "long", "ulong", "float", "double", "decimal") |
||||
UnaryHead("+", "-", "!", "~", "*", "++", "--", "&") |
||||
AssnStartOp("+", "-", "!", "~", "*") |
||||
CastFollower(@SimpleTypeName, Literal, "(", "~", "!", @ExpressionStart) |
||||
AssgnOps("=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "<<=") |
||||
UnaryOp("+", "-", "!", "~", "*", "++", "--", "&") |
||||
TypeDeclarationKW("class", "interface", "struct", "enum", "delegate") |
||||
# for §7.5.4.2 "Grammar ambiguities" disambiguation for F(G<A,B>(7)) |
||||
GenericFollower("(", ")", "]", "}", ":", ";", Comma, ".", "?", "==", "!=") |
||||
|
||||
ValidInsideTypeName(@IdentifierTokens, @TypeKW, "<", ">", ".", "?", "[", Comma, "]", "*", "::") |
||||
|
||||
# Keywords for keyword-code-completion |
||||
KCCClassModifiers("abstract", "sealed", "static", "unsafe", "partial") |
||||
KCCTypeDeclarationStart("public", "internal", @TypeDeclarationKW, @KCCClassModifiers) |
||||
KCCMemberVisibilityModifiers("protected", "private", "public", "internal") |
||||
SimpleTypeName(@TypeKW, @IdentifierTokens, "void") |
||||
GlobalLevel("namespace", "using", @KCCTypeDeclarationStart) |
||||
ExpressionStart("base", "delegate", "false", "new", "null", "sizeof", "this", "true", "typeof", "checked", "unchecked", "from") |
||||
ExpressionContent("as", "is", "out", "ref", "in") |
||||
# interfaces cannot have inner classes etc., the only keyword (expect for type names) that may appear in them is "event" |
||||
InterfaceLevel("event") |
||||
TypeLevel(@KCCTypeDeclarationStart, @KCCMemberVisibilityModifiers, "const", "event", "explicit", "extern", "fixed", "implicit", "new", "operator", "override", "readonly", "virtual", "volatile") |
||||
StatementStart(@ExpressionStart, @ExpressionContent, "break", "case", "catch", "checked", "unchecked", "const", "continue", "default", "do", "else", "finally", "fixed", "for", "foreach", "goto", "if", "lock", "return", "stackalloc", "switch", "throw", "try", "unsafe", "using", "while", "yield") |
||||
QueryExpressionClauseStart("from", "let", "where", "join", "orderby", "group", "select") |
||||
InPropertyDeclaration(@KCCMemberVisibilityModifiers, "get", "set") |
||||
InEventDeclaration("add", "remove") |
||||
|
||||
# unused: where |
||||
# "by", "into", "ascending", "descending", "on", "equals" |
@ -1,129 +0,0 @@
@@ -1,129 +0,0 @@
|
||||
// this file was autogenerated by a tool.
|
||||
using System; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser.CSharp |
||||
{ |
||||
public static class Keywords |
||||
{ |
||||
static readonly string[] keywordList = { |
||||
"abstract", |
||||
"as", |
||||
"base", |
||||
"bool", |
||||
"break", |
||||
"byte", |
||||
"case", |
||||
"catch", |
||||
"char", |
||||
"checked", |
||||
"class", |
||||
"const", |
||||
"continue", |
||||
"decimal", |
||||
"default", |
||||
"delegate", |
||||
"do", |
||||
"double", |
||||
"else", |
||||
"enum", |
||||
"event", |
||||
"explicit", |
||||
"extern", |
||||
"false", |
||||
"finally", |
||||
"fixed", |
||||
"float", |
||||
"for", |
||||
"foreach", |
||||
"goto", |
||||
"if", |
||||
"implicit", |
||||
"in", |
||||
"int", |
||||
"interface", |
||||
"internal", |
||||
"is", |
||||
"lock", |
||||
"long", |
||||
"namespace", |
||||
"new", |
||||
"null", |
||||
"object", |
||||
"operator", |
||||
"out", |
||||
"override", |
||||
"params", |
||||
"private", |
||||
"protected", |
||||
"public", |
||||
"readonly", |
||||
"ref", |
||||
"return", |
||||
"sbyte", |
||||
"sealed", |
||||
"short", |
||||
"sizeof", |
||||
"stackalloc", |
||||
"static", |
||||
"string", |
||||
"struct", |
||||
"switch", |
||||
"this", |
||||
"throw", |
||||
"true", |
||||
"try", |
||||
"typeof", |
||||
"uint", |
||||
"ulong", |
||||
"unchecked", |
||||
"unsafe", |
||||
"ushort", |
||||
"using", |
||||
"virtual", |
||||
"void", |
||||
"volatile", |
||||
"while", |
||||
"partial", |
||||
"where", |
||||
"get", |
||||
"set", |
||||
"add", |
||||
"remove", |
||||
"yield", |
||||
"select", |
||||
"group", |
||||
"by", |
||||
"into", |
||||
"from", |
||||
"ascending", |
||||
"descending", |
||||
"orderby", |
||||
"let", |
||||
"join", |
||||
"on", |
||||
"equals" |
||||
}; |
||||
|
||||
static LookupTable keywords = new LookupTable(true); |
||||
|
||||
static Keywords() |
||||
{ |
||||
for (int i = 0; i < keywordList.Length; ++i) { |
||||
keywords[keywordList[i]] = i + Tokens.Abstract; |
||||
} |
||||
} |
||||
|
||||
public static int GetToken(string keyword) |
||||
{ |
||||
return keywords[keyword]; |
||||
} |
||||
|
||||
public static bool IsNonIdentifierKeyword(string word) |
||||
{ |
||||
int token = GetToken(word); |
||||
if (token < 0) |
||||
return false; |
||||
return !Tokens.IdentifierTokens[token]; |
||||
} |
||||
} |
||||
} |
@ -1,978 +0,0 @@
@@ -1,978 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Andrea Paatz" email="andrea@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Globalization; |
||||
using System.IO; |
||||
using System.Text; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser.CSharp |
||||
{ |
||||
internal sealed class Lexer : AbstractLexer |
||||
{ |
||||
public Lexer(TextReader reader) : base(reader) |
||||
{ |
||||
} |
||||
|
||||
void ReadPreProcessingDirective() |
||||
{ |
||||
Location start = new Location(Col - 1, Line); |
||||
|
||||
// skip spaces between # and the directive
|
||||
while (ReaderPeek() == ' ') |
||||
ReaderRead(); |
||||
|
||||
bool canBeKeyword; |
||||
string directive = ReadIdent('#', out canBeKeyword); |
||||
string argument = ReadToEndOfLine(); |
||||
this.specialTracker.AddPreprocessingDirective(directive, argument.Trim(), start, new Location(start.X + directive.Length + argument.Length, start.Y)); |
||||
} |
||||
|
||||
protected override Token Next() |
||||
{ |
||||
int nextChar; |
||||
char ch; |
||||
bool hadLineEnd = false; |
||||
if (Line == 1 && Col == 1) hadLineEnd = true; // beginning of document
|
||||
|
||||
while ((nextChar = ReaderRead()) != -1) { |
||||
Token token; |
||||
|
||||
switch (nextChar) { |
||||
case ' ': |
||||
case '\t': |
||||
continue; |
||||
case '\r': |
||||
case '\n': |
||||
if (hadLineEnd) { |
||||
// second line end before getting to a token
|
||||
// -> here was a blank line
|
||||
specialTracker.AddEndOfLine(new Location(Col, Line)); |
||||
} |
||||
HandleLineEnd((char)nextChar); |
||||
hadLineEnd = true; |
||||
continue; |
||||
case '/': |
||||
int peek = ReaderPeek(); |
||||
if (peek == '/' || peek == '*') { |
||||
ReadComment(); |
||||
continue; |
||||
} else { |
||||
token = ReadOperator('/'); |
||||
} |
||||
break; |
||||
case '#': |
||||
ReadPreProcessingDirective(); |
||||
continue; |
||||
case '"': |
||||
token = ReadString(); |
||||
break; |
||||
case '\'': |
||||
token = ReadChar(); |
||||
break; |
||||
case '@': |
||||
int next = ReaderRead(); |
||||
if (next == -1) { |
||||
errors.Error(Line, Col, String.Format("EOF after @")); |
||||
continue; |
||||
} else { |
||||
int x = Col - 1; |
||||
int y = Line; |
||||
ch = (char)next; |
||||
if (ch == '"') { |
||||
token = ReadVerbatimString(); |
||||
} else if (Char.IsLetterOrDigit(ch) || ch == '_') { |
||||
bool canBeKeyword; |
||||
token = new Token(Tokens.Identifier, x - 1, y, ReadIdent(ch, out canBeKeyword)); |
||||
} else { |
||||
errors.Error(y, x, String.Format("Unexpected char in Lexer.Next() : {0}", ch)); |
||||
continue; |
||||
} |
||||
} |
||||
break; |
||||
default: |
||||
ch = (char)nextChar; |
||||
if (Char.IsLetter(ch) || ch == '_' || ch == '\\') { |
||||
int x = Col - 1; // Col was incremented above, but we want the start of the identifier
|
||||
int y = Line; |
||||
bool canBeKeyword; |
||||
string s = ReadIdent(ch, out canBeKeyword); |
||||
if (canBeKeyword) { |
||||
int keyWordToken = Keywords.GetToken(s); |
||||
if (keyWordToken >= 0) { |
||||
return new Token(keyWordToken, x, y, s); |
||||
} |
||||
} |
||||
return new Token(Tokens.Identifier, x, y, s); |
||||
} else if (Char.IsDigit(ch)) { |
||||
token = ReadDigit(ch, Col - 1); |
||||
} else { |
||||
token = ReadOperator(ch); |
||||
} |
||||
break; |
||||
} |
||||
|
||||
// try error recovery (token = null -> continue with next char)
|
||||
if (token != null) { |
||||
return token; |
||||
} |
||||
} |
||||
|
||||
return new Token(Tokens.EOF, Col, Line, String.Empty); |
||||
} |
||||
|
||||
// The C# compiler has a fixed size length therefore we'll use a fixed size char array for identifiers
|
||||
// it's also faster than using a string builder.
|
||||
const int MAX_IDENTIFIER_LENGTH = 512; |
||||
char[] identBuffer = new char[MAX_IDENTIFIER_LENGTH]; |
||||
|
||||
string ReadIdent(char ch, out bool canBeKeyword) |
||||
{ |
||||
int peek; |
||||
int curPos = 0; |
||||
canBeKeyword = true; |
||||
while (true) { |
||||
if (ch == '\\') { |
||||
peek = ReaderPeek(); |
||||
if (peek != 'u' && peek != 'U') { |
||||
errors.Error(Line, Col, "Identifiers can only contain unicode escape sequences"); |
||||
} |
||||
canBeKeyword = false; |
||||
string surrogatePair; |
||||
ReadEscapeSequence(out ch, out surrogatePair); |
||||
if (surrogatePair != null) { |
||||
if (!char.IsLetterOrDigit(surrogatePair, 0)) { |
||||
errors.Error(Line, Col, "Unicode escape sequences in identifiers cannot be used to represent characters that are invalid in identifiers"); |
||||
} |
||||
for (int i = 0; i < surrogatePair.Length - 1; i++) { |
||||
if (curPos < MAX_IDENTIFIER_LENGTH) { |
||||
identBuffer[curPos++] = surrogatePair[i]; |
||||
} |
||||
} |
||||
ch = surrogatePair[surrogatePair.Length - 1]; |
||||
} else { |
||||
if (!IsIdentifierPart(ch)) { |
||||
errors.Error(Line, Col, "Unicode escape sequences in identifiers cannot be used to represent characters that are invalid in identifiers"); |
||||
} |
||||
} |
||||
} |
||||
|
||||
if (curPos < MAX_IDENTIFIER_LENGTH) { |
||||
identBuffer[curPos++] = ch; |
||||
} else { |
||||
errors.Error(Line, Col, String.Format("Identifier too long")); |
||||
while (IsIdentifierPart(ReaderPeek())) { |
||||
ReaderRead(); |
||||
} |
||||
break; |
||||
} |
||||
peek = ReaderPeek(); |
||||
if (IsIdentifierPart(peek) || peek == '\\') { |
||||
ch = (char)ReaderRead(); |
||||
} else { |
||||
break; |
||||
} |
||||
} |
||||
return new String(identBuffer, 0, curPos); |
||||
} |
||||
|
||||
Token ReadDigit(char ch, int x) |
||||
{ |
||||
unchecked { // prevent exception when ReaderPeek() = -1 is cast to char
|
||||
int y = Line; |
||||
sb.Length = 0; |
||||
sb.Append(ch); |
||||
string prefix = null; |
||||
string suffix = null; |
||||
|
||||
bool ishex = false; |
||||
bool isunsigned = false; |
||||
bool islong = false; |
||||
bool isfloat = false; |
||||
bool isdouble = false; |
||||
bool isdecimal = false; |
||||
|
||||
char peek = (char)ReaderPeek(); |
||||
|
||||
if (ch == '.') { |
||||
isdouble = true; |
||||
|
||||
while (Char.IsDigit((char)ReaderPeek())) { // read decimal digits beyond the dot
|
||||
sb.Append((char)ReaderRead()); |
||||
} |
||||
peek = (char)ReaderPeek(); |
||||
} else if (ch == '0' && (peek == 'x' || peek == 'X')) { |
||||
ReaderRead(); // skip 'x'
|
||||
sb.Length = 0; // Remove '0' from 0x prefix from the stringvalue
|
||||
while (IsHex((char)ReaderPeek())) { |
||||
sb.Append((char)ReaderRead()); |
||||
} |
||||
if (sb.Length == 0) { |
||||
sb.Append('0'); // dummy value to prevent exception
|
||||
errors.Error(y, x, "Invalid hexadecimal integer literal"); |
||||
} |
||||
ishex = true; |
||||
prefix = "0x"; |
||||
peek = (char)ReaderPeek(); |
||||
} else { |
||||
while (Char.IsDigit((char)ReaderPeek())) { |
||||
sb.Append((char)ReaderRead()); |
||||
} |
||||
peek = (char)ReaderPeek(); |
||||
} |
||||
|
||||
Token nextToken = null; // if we accidently read a 'dot'
|
||||
if (peek == '.') { // read floating point number
|
||||
ReaderRead(); |
||||
peek = (char)ReaderPeek(); |
||||
if (!Char.IsDigit(peek)) { |
||||
nextToken = new Token(Tokens.Dot, Col - 1, Line); |
||||
peek = '.'; |
||||
} else { |
||||
isdouble = true; // double is default
|
||||
if (ishex) { |
||||
errors.Error(y, x, String.Format("No hexadecimal floating point values allowed")); |
||||
} |
||||
sb.Append('.'); |
||||
|
||||
while (Char.IsDigit((char)ReaderPeek())) { // read decimal digits beyond the dot
|
||||
sb.Append((char)ReaderRead()); |
||||
} |
||||
peek = (char)ReaderPeek(); |
||||
} |
||||
} |
||||
|
||||
if (peek == 'e' || peek == 'E') { // read exponent
|
||||
isdouble = true; |
||||
sb.Append((char)ReaderRead()); |
||||
peek = (char)ReaderPeek(); |
||||
if (peek == '-' || peek == '+') { |
||||
sb.Append((char)ReaderRead()); |
||||
} |
||||
while (Char.IsDigit((char)ReaderPeek())) { // read exponent value
|
||||
sb.Append((char)ReaderRead()); |
||||
} |
||||
isunsigned = true; |
||||
peek = (char)ReaderPeek(); |
||||
} |
||||
|
||||
if (peek == 'f' || peek == 'F') { // float value
|
||||
ReaderRead(); |
||||
suffix = "f"; |
||||
isfloat = true; |
||||
} else if (peek == 'd' || peek == 'D') { // double type suffix (obsolete, double is default)
|
||||
ReaderRead(); |
||||
suffix = "d"; |
||||
isdouble = true; |
||||
} else if (peek == 'm' || peek == 'M') { // decimal value
|
||||
ReaderRead(); |
||||
suffix = "m"; |
||||
isdecimal = true; |
||||
} else if (!isdouble) { |
||||
if (peek == 'u' || peek == 'U') { |
||||
ReaderRead(); |
||||
suffix = "u"; |
||||
isunsigned = true; |
||||
peek = (char)ReaderPeek(); |
||||
} |
||||
|
||||
if (peek == 'l' || peek == 'L') { |
||||
ReaderRead(); |
||||
peek = (char)ReaderPeek(); |
||||
islong = true; |
||||
if (!isunsigned && (peek == 'u' || peek == 'U')) { |
||||
ReaderRead(); |
||||
suffix = "Lu"; |
||||
isunsigned = true; |
||||
} else { |
||||
suffix = isunsigned ? "uL" : "L"; |
||||
} |
||||
} |
||||
} |
||||
|
||||
string digit = sb.ToString(); |
||||
string stringValue = prefix + digit + suffix; |
||||
|
||||
if (isfloat) { |
||||
float num; |
||||
if (float.TryParse(digit, NumberStyles.Any, CultureInfo.InvariantCulture, out num)) { |
||||
return new Token(Tokens.Literal, x, y, stringValue, num); |
||||
} else { |
||||
errors.Error(y, x, String.Format("Can't parse float {0}", digit)); |
||||
return new Token(Tokens.Literal, x, y, stringValue, 0f); |
||||
} |
||||
} |
||||
if (isdecimal) { |
||||
decimal num; |
||||
if (decimal.TryParse(digit, NumberStyles.Any, CultureInfo.InvariantCulture, out num)) { |
||||
return new Token(Tokens.Literal, x, y, stringValue, num); |
||||
} else { |
||||
errors.Error(y, x, String.Format("Can't parse decimal {0}", digit)); |
||||
return new Token(Tokens.Literal, x, y, stringValue, 0m); |
||||
} |
||||
} |
||||
if (isdouble) { |
||||
double num; |
||||
if (double.TryParse(digit, NumberStyles.Any, CultureInfo.InvariantCulture, out num)) { |
||||
return new Token(Tokens.Literal, x, y, stringValue, num); |
||||
} else { |
||||
errors.Error(y, x, String.Format("Can't parse double {0}", digit)); |
||||
return new Token(Tokens.Literal, x, y, stringValue, 0d); |
||||
} |
||||
} |
||||
|
||||
// Try to determine a parsable value using ranges.
|
||||
ulong result; |
||||
if (ishex) { |
||||
if (!ulong.TryParse(digit, NumberStyles.HexNumber, null, out result)) { |
||||
errors.Error(y, x, String.Format("Can't parse hexadecimal constant {0}", digit)); |
||||
return new Token(Tokens.Literal, x, y, stringValue.ToString(), 0); |
||||
} |
||||
} else { |
||||
if (!ulong.TryParse(digit, NumberStyles.Integer, null, out result)) { |
||||
errors.Error(y, x, String.Format("Can't parse integral constant {0}", digit)); |
||||
return new Token(Tokens.Literal, x, y, stringValue.ToString(), 0); |
||||
} |
||||
} |
||||
|
||||
if (result > long.MaxValue) { |
||||
islong = true; |
||||
isunsigned = true; |
||||
} else if (result > uint.MaxValue) { |
||||
islong = true; |
||||
} else if (islong == false && result > int.MaxValue) { |
||||
isunsigned = true; |
||||
} |
||||
|
||||
Token token; |
||||
|
||||
if (islong) { |
||||
if (isunsigned) { |
||||
ulong num; |
||||
if (ulong.TryParse(digit, ishex ? NumberStyles.HexNumber : NumberStyles.Number, CultureInfo.InvariantCulture, out num)) { |
||||
token = new Token(Tokens.Literal, x, y, stringValue, num); |
||||
} else { |
||||
errors.Error(y, x, String.Format("Can't parse unsigned long {0}", digit)); |
||||
token = new Token(Tokens.Literal, x, y, stringValue, 0UL); |
||||
} |
||||
} else { |
||||
long num; |
||||
if (long.TryParse(digit, ishex ? NumberStyles.HexNumber : NumberStyles.Number, CultureInfo.InvariantCulture, out num)) { |
||||
token = new Token(Tokens.Literal, x, y, stringValue, num); |
||||
} else { |
||||
errors.Error(y, x, String.Format("Can't parse long {0}", digit)); |
||||
token = new Token(Tokens.Literal, x, y, stringValue, 0L); |
||||
} |
||||
} |
||||
} else { |
||||
if (isunsigned) { |
||||
uint num; |
||||
if (uint.TryParse(digit, ishex ? NumberStyles.HexNumber : NumberStyles.Number, CultureInfo.InvariantCulture, out num)) { |
||||
token = new Token(Tokens.Literal, x, y, stringValue, num); |
||||
} else { |
||||
errors.Error(y, x, String.Format("Can't parse unsigned int {0}", digit)); |
||||
token = new Token(Tokens.Literal, x, y, stringValue, (uint)0); |
||||
} |
||||
} else { |
||||
int num; |
||||
if (int.TryParse(digit, ishex ? NumberStyles.HexNumber : NumberStyles.Number, CultureInfo.InvariantCulture, out num)) { |
||||
token = new Token(Tokens.Literal, x, y, stringValue, num); |
||||
} else { |
||||
errors.Error(y, x, String.Format("Can't parse int {0}", digit)); |
||||
token = new Token(Tokens.Literal, x, y, stringValue, 0); |
||||
} |
||||
} |
||||
} |
||||
token.next = nextToken; |
||||
return token; |
||||
} |
||||
} |
||||
|
||||
Token ReadString() |
||||
{ |
||||
int x = Col - 1; |
||||
int y = Line; |
||||
|
||||
sb.Length = 0; |
||||
originalValue.Length = 0; |
||||
originalValue.Append('"'); |
||||
bool doneNormally = false; |
||||
int nextChar; |
||||
while ((nextChar = ReaderRead()) != -1) { |
||||
char ch = (char)nextChar; |
||||
|
||||
if (ch == '"') { |
||||
doneNormally = true; |
||||
originalValue.Append('"'); |
||||
break; |
||||
} |
||||
|
||||
if (ch == '\\') { |
||||
originalValue.Append('\\'); |
||||
string surrogatePair; |
||||
originalValue.Append(ReadEscapeSequence(out ch, out surrogatePair)); |
||||
if (surrogatePair != null) { |
||||
sb.Append(surrogatePair); |
||||
} else { |
||||
sb.Append(ch); |
||||
} |
||||
} else if (ch == '\n') { |
||||
HandleLineEnd(ch); // ensure line numbers are still correct after the error
|
||||
errors.Error(y, x, String.Format("No new line is allowed inside a string literal")); |
||||
break; |
||||
} else { |
||||
originalValue.Append(ch); |
||||
sb.Append(ch); |
||||
} |
||||
} |
||||
|
||||
if (!doneNormally) { |
||||
errors.Error(y, x, String.Format("End of file reached inside string literal")); |
||||
} |
||||
|
||||
return new Token(Tokens.Literal, x, y, originalValue.ToString(), sb.ToString()); |
||||
} |
||||
|
||||
Token ReadVerbatimString() |
||||
{ |
||||
sb.Length = 0; |
||||
originalValue.Length = 0; |
||||
originalValue.Append("@\""); |
||||
int x = Col - 2; // @ and " already read
|
||||
int y = Line; |
||||
int nextChar; |
||||
while ((nextChar = ReaderRead()) != -1) { |
||||
char ch = (char)nextChar; |
||||
|
||||
if (ch == '"') { |
||||
if (ReaderPeek() != '"') { |
||||
originalValue.Append('"'); |
||||
break; |
||||
} |
||||
originalValue.Append("\"\""); |
||||
sb.Append('"'); |
||||
ReaderRead(); |
||||
} else if (HandleLineEnd(ch)) { |
||||
sb.Append("\r\n"); |
||||
originalValue.Append("\r\n"); |
||||
} else { |
||||
sb.Append(ch); |
||||
originalValue.Append(ch); |
||||
} |
||||
} |
||||
|
||||
if (nextChar == -1) { |
||||
errors.Error(y, x, String.Format("End of file reached inside verbatim string literal")); |
||||
} |
||||
|
||||
return new Token(Tokens.Literal, x, y, originalValue.ToString(), sb.ToString()); |
||||
} |
||||
|
||||
char[] escapeSequenceBuffer = new char[12]; |
||||
|
||||
/// <summary>
|
||||
/// reads an escape sequence
|
||||
/// </summary>
|
||||
/// <param name="ch">The character represented by the escape sequence,
|
||||
/// or '\0' if there was an error or the escape sequence represents a character that
|
||||
/// can be represented only be a suggorate pair</param>
|
||||
/// <param name="surrogatePair">Null, except when the character represented
|
||||
/// by the escape sequence can only be represented by a surrogate pair (then the string
|
||||
/// contains the surrogate pair)</param>
|
||||
/// <returns>The escape sequence</returns>
|
||||
string ReadEscapeSequence(out char ch, out string surrogatePair) |
||||
{ |
||||
surrogatePair = null; |
||||
|
||||
int nextChar = ReaderRead(); |
||||
if (nextChar == -1) { |
||||
errors.Error(Line, Col, String.Format("End of file reached inside escape sequence")); |
||||
ch = '\0'; |
||||
return String.Empty; |
||||
} |
||||
int number; |
||||
char c = (char)nextChar; |
||||
int curPos = 1; |
||||
escapeSequenceBuffer[0] = c; |
||||
switch (c) { |
||||
case '\'': |
||||
ch = '\''; |
||||
break; |
||||
case '\"': |
||||
ch = '\"'; |
||||
break; |
||||
case '\\': |
||||
ch = '\\'; |
||||
break; |
||||
case '0': |
||||
ch = '\0'; |
||||
break; |
||||
case 'a': |
||||
ch = '\a'; |
||||
break; |
||||
case 'b': |
||||
ch = '\b'; |
||||
break; |
||||
case 'f': |
||||
ch = '\f'; |
||||
break; |
||||
case 'n': |
||||
ch = '\n'; |
||||
break; |
||||
case 'r': |
||||
ch = '\r'; |
||||
break; |
||||
case 't': |
||||
ch = '\t'; |
||||
break; |
||||
case 'v': |
||||
ch = '\v'; |
||||
break; |
||||
case 'u': |
||||
case 'x': |
||||
// 16 bit unicode character
|
||||
c = (char)ReaderRead(); |
||||
number = GetHexNumber(c); |
||||
escapeSequenceBuffer[curPos++] = c; |
||||
|
||||
if (number < 0) { |
||||
errors.Error(Line, Col - 1, String.Format("Invalid char in literal : {0}", c)); |
||||
} |
||||
for (int i = 0; i < 3; ++i) { |
||||
if (IsHex((char)ReaderPeek())) { |
||||
c = (char)ReaderRead(); |
||||
int idx = GetHexNumber(c); |
||||
escapeSequenceBuffer[curPos++] = c; |
||||
number = 16 * number + idx; |
||||
} else { |
||||
break; |
||||
} |
||||
} |
||||
ch = (char)number; |
||||
break; |
||||
case 'U': |
||||
// 32 bit unicode character
|
||||
number = 0; |
||||
for (int i = 0; i < 8; ++i) { |
||||
if (IsHex((char)ReaderPeek())) { |
||||
c = (char)ReaderRead(); |
||||
int idx = GetHexNumber(c); |
||||
escapeSequenceBuffer[curPos++] = c; |
||||
number = 16 * number + idx; |
||||
} else { |
||||
errors.Error(Line, Col - 1, String.Format("Invalid char in literal : {0}", (char)ReaderPeek())); |
||||
break; |
||||
} |
||||
} |
||||
if (number > 0xffff) { |
||||
ch = '\0'; |
||||
surrogatePair = char.ConvertFromUtf32(number); |
||||
} else { |
||||
ch = (char)number; |
||||
} |
||||
break; |
||||
default: |
||||
errors.Error(Line, Col, String.Format("Unexpected escape sequence : {0}", c)); |
||||
ch = '\0'; |
||||
break; |
||||
} |
||||
return new String(escapeSequenceBuffer, 0, curPos); |
||||
} |
||||
|
||||
Token ReadChar() |
||||
{ |
||||
int x = Col - 1; |
||||
int y = Line; |
||||
int nextChar = ReaderRead(); |
||||
if (nextChar == -1) { |
||||
errors.Error(y, x, String.Format("End of file reached inside character literal")); |
||||
return null; |
||||
} |
||||
char ch = (char)nextChar; |
||||
char chValue = ch; |
||||
string escapeSequence = String.Empty; |
||||
if (ch == '\\') { |
||||
string surrogatePair; |
||||
escapeSequence = ReadEscapeSequence(out chValue, out surrogatePair); |
||||
if (surrogatePair != null) { |
||||
errors.Error(y, x, String.Format("The unicode character must be represented by a surrogate pair and does not fit into a System.Char")); |
||||
} |
||||
} |
||||
|
||||
unchecked { |
||||
if ((char)ReaderRead() != '\'') { |
||||
errors.Error(y, x, String.Format("Char not terminated")); |
||||
} |
||||
} |
||||
return new Token(Tokens.Literal, x, y, "'" + ch + escapeSequence + "'", chValue); |
||||
} |
||||
|
||||
Token ReadOperator(char ch) |
||||
{ |
||||
int x = Col - 1; |
||||
int y = Line; |
||||
switch (ch) { |
||||
case '+': |
||||
switch (ReaderPeek()) { |
||||
case '+': |
||||
ReaderRead(); |
||||
return new Token(Tokens.Increment, x, y); |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.PlusAssign, x, y); |
||||
} |
||||
return new Token(Tokens.Plus, x, y); |
||||
case '-': |
||||
switch (ReaderPeek()) { |
||||
case '-': |
||||
ReaderRead(); |
||||
return new Token(Tokens.Decrement, x, y); |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.MinusAssign, x, y); |
||||
case '>': |
||||
ReaderRead(); |
||||
return new Token(Tokens.Pointer, x, y); |
||||
} |
||||
return new Token(Tokens.Minus, x, y); |
||||
case '*': |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.TimesAssign, x, y); |
||||
default: |
||||
break; |
||||
} |
||||
return new Token(Tokens.Times, x, y); |
||||
case '/': |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.DivAssign, x, y); |
||||
} |
||||
return new Token(Tokens.Div, x, y); |
||||
case '%': |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.ModAssign, x, y); |
||||
} |
||||
return new Token(Tokens.Mod, x, y); |
||||
case '&': |
||||
switch (ReaderPeek()) { |
||||
case '&': |
||||
ReaderRead(); |
||||
return new Token(Tokens.LogicalAnd, x, y); |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.BitwiseAndAssign, x, y); |
||||
} |
||||
return new Token(Tokens.BitwiseAnd, x, y); |
||||
case '|': |
||||
switch (ReaderPeek()) { |
||||
case '|': |
||||
ReaderRead(); |
||||
return new Token(Tokens.LogicalOr, x, y); |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.BitwiseOrAssign, x, y); |
||||
} |
||||
return new Token(Tokens.BitwiseOr, x, y); |
||||
case '^': |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.XorAssign, x, y); |
||||
default: |
||||
break; |
||||
} |
||||
return new Token(Tokens.Xor, x, y); |
||||
case '!': |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.NotEqual, x, y); |
||||
} |
||||
return new Token(Tokens.Not, x, y); |
||||
case '~': |
||||
return new Token(Tokens.BitwiseComplement, x, y); |
||||
case '=': |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.Equal, x, y); |
||||
case '>': |
||||
ReaderRead(); |
||||
return new Token(Tokens.LambdaArrow, x, y); |
||||
} |
||||
return new Token(Tokens.Assign, x, y); |
||||
case '<': |
||||
switch (ReaderPeek()) { |
||||
case '<': |
||||
ReaderRead(); |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.ShiftLeftAssign, x, y); |
||||
default: |
||||
break; |
||||
} |
||||
return new Token(Tokens.ShiftLeft, x, y); |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.LessEqual, x, y); |
||||
} |
||||
return new Token(Tokens.LessThan, x, y); |
||||
case '>': |
||||
switch (ReaderPeek()) { |
||||
// Removed because of generics:
|
||||
// case '>':
|
||||
// ReaderRead();
|
||||
// if (ReaderPeek() != -1) {
|
||||
// switch ((char)ReaderPeek()) {
|
||||
// case '=':
|
||||
// ReaderRead();
|
||||
// return new Token(Tokens.ShiftRightAssign, x, y);
|
||||
// default:
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// return new Token(Tokens.ShiftRight, x, y);
|
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.GreaterEqual, x, y); |
||||
} |
||||
return new Token(Tokens.GreaterThan, x, y); |
||||
case '?': |
||||
if (ReaderPeek() == '?') { |
||||
ReaderRead(); |
||||
return new Token(Tokens.DoubleQuestion, x, y); |
||||
} |
||||
return new Token(Tokens.Question, x, y); |
||||
case ';': |
||||
return new Token(Tokens.Semicolon, x, y); |
||||
case ':': |
||||
if (ReaderPeek() == ':') { |
||||
ReaderRead(); |
||||
return new Token(Tokens.DoubleColon, x, y); |
||||
} |
||||
return new Token(Tokens.Colon, x, y); |
||||
case ',': |
||||
return new Token(Tokens.Comma, x, y); |
||||
case '.': |
||||
// Prevent OverflowException when ReaderPeek returns -1
|
||||
int tmp = ReaderPeek(); |
||||
if (tmp > 0 && Char.IsDigit((char)tmp)) { |
||||
return ReadDigit('.', Col - 1); |
||||
} |
||||
return new Token(Tokens.Dot, x, y); |
||||
case ')': |
||||
return new Token(Tokens.CloseParenthesis, x, y); |
||||
case '(': |
||||
return new Token(Tokens.OpenParenthesis, x, y); |
||||
case ']': |
||||
return new Token(Tokens.CloseSquareBracket, x, y); |
||||
case '[': |
||||
return new Token(Tokens.OpenSquareBracket, x, y); |
||||
case '}': |
||||
return new Token(Tokens.CloseCurlyBrace, x, y); |
||||
case '{': |
||||
return new Token(Tokens.OpenCurlyBrace, x, y); |
||||
default: |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
void ReadComment() |
||||
{ |
||||
switch (ReaderRead()) { |
||||
case '*': |
||||
ReadMultiLineComment(); |
||||
break; |
||||
case '/': |
||||
if (ReaderPeek() == '/') { |
||||
ReaderRead(); |
||||
ReadSingleLineComment(CommentType.Documentation); |
||||
} else { |
||||
ReadSingleLineComment(CommentType.SingleLine); |
||||
} |
||||
break; |
||||
default: |
||||
errors.Error(Line, Col, String.Format("Error while reading comment")); |
||||
break; |
||||
} |
||||
} |
||||
|
||||
string ReadCommentToEOL() |
||||
{ |
||||
if (specialCommentHash == null) { |
||||
return ReadToEndOfLine(); |
||||
} |
||||
sb.Length = 0; |
||||
StringBuilder curWord = new StringBuilder(); |
||||
|
||||
int nextChar; |
||||
while ((nextChar = ReaderRead()) != -1) { |
||||
char ch = (char)nextChar; |
||||
|
||||
if (HandleLineEnd(ch)) { |
||||
break; |
||||
} |
||||
|
||||
sb.Append(ch); |
||||
if (IsIdentifierPart(nextChar)) { |
||||
curWord.Append(ch); |
||||
} else { |
||||
string tag = curWord.ToString(); |
||||
curWord.Length = 0; |
||||
if (specialCommentHash.ContainsKey(tag)) { |
||||
Location p = new Location(Col, Line); |
||||
string comment = ch + ReadToEndOfLine(); |
||||
this.TagComments.Add(new TagComment(tag, comment, p, new Location(Col, Line))); |
||||
sb.Append(comment); |
||||
break; |
||||
} |
||||
} |
||||
} |
||||
return sb.ToString(); |
||||
} |
||||
|
||||
void ReadSingleLineComment(CommentType commentType) |
||||
{ |
||||
if (this.SkipAllComments) { |
||||
SkipToEndOfLine(); |
||||
} else { |
||||
specialTracker.StartComment(commentType, new Location(Col, Line)); |
||||
specialTracker.AddString(ReadCommentToEOL()); |
||||
specialTracker.FinishComment(new Location(Col, Line)); |
||||
} |
||||
} |
||||
|
||||
void ReadMultiLineComment() |
||||
{ |
||||
int nextChar; |
||||
if (this.SkipAllComments) { |
||||
while ((nextChar = ReaderRead()) != -1) { |
||||
char ch = (char)nextChar; |
||||
if (ch == '*' && ReaderPeek() == '/') { |
||||
ReaderRead(); |
||||
return; |
||||
} else { |
||||
HandleLineEnd(ch); |
||||
} |
||||
} |
||||
} else { |
||||
specialTracker.StartComment(CommentType.Block, new Location(Col, Line)); |
||||
|
||||
// sc* = special comment handling (TO DO markers)
|
||||
string scTag = null; // is set to non-null value when we are inside a comment marker
|
||||
StringBuilder scCurWord = new StringBuilder(); // current word, (scTag == null) or comment (when scTag != null)
|
||||
Location scStartLocation = Location.Empty; |
||||
|
||||
while ((nextChar = ReaderRead()) != -1) { |
||||
char ch = (char)nextChar; |
||||
|
||||
if (HandleLineEnd(ch)) { |
||||
if (scTag != null) { |
||||
this.TagComments.Add(new TagComment(scTag, scCurWord.ToString(), scStartLocation, new Location(Col, Line))); |
||||
scTag = null; |
||||
} |
||||
scCurWord.Length = 0; |
||||
specialTracker.AddString(Environment.NewLine); |
||||
continue; |
||||
} |
||||
|
||||
// End of multiline comment reached ?
|
||||
if (ch == '*' && ReaderPeek() == '/') { |
||||
if (scTag != null) { |
||||
this.TagComments.Add(new TagComment(scTag, scCurWord.ToString(), scStartLocation, new Location(Col, Line))); |
||||
} |
||||
ReaderRead(); |
||||
specialTracker.FinishComment(new Location(Col, Line)); |
||||
return; |
||||
} |
||||
specialTracker.AddChar(ch); |
||||
if (scTag != null || IsIdentifierPart(ch)) { |
||||
scCurWord.Append(ch); |
||||
} else { |
||||
if (specialCommentHash != null && specialCommentHash.ContainsKey(scCurWord.ToString())) { |
||||
scTag = scCurWord.ToString(); |
||||
scStartLocation = new Location(Col, Line); |
||||
} |
||||
scCurWord.Length = 0; |
||||
} |
||||
} |
||||
specialTracker.FinishComment(new Location(Col, Line)); |
||||
} |
||||
// Reached EOF before end of multiline comment.
|
||||
errors.Error(Line, Col, String.Format("Reached EOF before the end of a multiline comment")); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Skips to the end of the current code block.
|
||||
/// For this, the lexer must have read the next token AFTER the token opening the
|
||||
/// block (so that Lexer.Token is the block-opening token, not Lexer.LookAhead).
|
||||
/// After the call, Lexer.LookAhead will be the block-closing token.
|
||||
/// </summary>
|
||||
public override void SkipCurrentBlock(int targetToken) |
||||
{ |
||||
int braceCount = 0; |
||||
while (curToken != null) { |
||||
if (curToken.kind == Tokens.OpenCurlyBrace) { |
||||
++braceCount; |
||||
} else if (curToken.kind == Tokens.CloseCurlyBrace) { |
||||
if (--braceCount < 0) |
||||
return; |
||||
} |
||||
lastToken = curToken; |
||||
curToken = curToken.next; |
||||
} |
||||
int nextChar; |
||||
while ((nextChar = ReaderRead()) != -1) { |
||||
switch (nextChar) { |
||||
case '{': |
||||
braceCount++; |
||||
break; |
||||
case '}': |
||||
if (--braceCount < 0) { |
||||
curToken = new Token(Tokens.CloseCurlyBrace, Col - 1, Line); |
||||
return; |
||||
} |
||||
break; |
||||
case '/': |
||||
int peek = ReaderPeek(); |
||||
if (peek == '/' || peek == '*') { |
||||
ReadComment(); |
||||
} |
||||
break; |
||||
case '#': |
||||
ReadPreProcessingDirective(); |
||||
break; |
||||
case '"': |
||||
ReadString(); |
||||
break; |
||||
case '\'': |
||||
ReadChar(); |
||||
break; |
||||
case '\r': |
||||
case '\n': |
||||
HandleLineEnd((char)nextChar); |
||||
break; |
||||
case '@': |
||||
int next = ReaderRead(); |
||||
if (next == -1) { |
||||
errors.Error(Line, Col, String.Format("EOF after @")); |
||||
} else if (next == '"') { |
||||
ReadVerbatimString(); |
||||
} |
||||
break; |
||||
} |
||||
} |
||||
curToken = new Token(Tokens.EOF, Col, Line); |
||||
} |
||||
} |
||||
} |
@ -1,353 +0,0 @@
@@ -1,353 +0,0 @@
|
||||
// this file was autogenerated by a tool.
|
||||
using System; |
||||
using System.Collections; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser.CSharp |
||||
{ |
||||
public static class Tokens |
||||
{ |
||||
// ----- terminal classes -----
|
||||
public const int EOF = 0; |
||||
public const int Identifier = 1; |
||||
public const int Literal = 2; |
||||
|
||||
// ----- special character -----
|
||||
public const int Assign = 3; |
||||
public const int Plus = 4; |
||||
public const int Minus = 5; |
||||
public const int Times = 6; |
||||
public const int Div = 7; |
||||
public const int Mod = 8; |
||||
public const int Colon = 9; |
||||
public const int DoubleColon = 10; |
||||
public const int Semicolon = 11; |
||||
public const int Question = 12; |
||||
public const int DoubleQuestion = 13; |
||||
public const int Comma = 14; |
||||
public const int Dot = 15; |
||||
public const int OpenCurlyBrace = 16; |
||||
public const int CloseCurlyBrace = 17; |
||||
public const int OpenSquareBracket = 18; |
||||
public const int CloseSquareBracket = 19; |
||||
public const int OpenParenthesis = 20; |
||||
public const int CloseParenthesis = 21; |
||||
public const int GreaterThan = 22; |
||||
public const int LessThan = 23; |
||||
public const int Not = 24; |
||||
public const int LogicalAnd = 25; |
||||
public const int LogicalOr = 26; |
||||
public const int BitwiseComplement = 27; |
||||
public const int BitwiseAnd = 28; |
||||
public const int BitwiseOr = 29; |
||||
public const int Xor = 30; |
||||
public const int Increment = 31; |
||||
public const int Decrement = 32; |
||||
public const int Equal = 33; |
||||
public const int NotEqual = 34; |
||||
public const int GreaterEqual = 35; |
||||
public const int LessEqual = 36; |
||||
public const int ShiftLeft = 37; |
||||
public const int PlusAssign = 38; |
||||
public const int MinusAssign = 39; |
||||
public const int TimesAssign = 40; |
||||
public const int DivAssign = 41; |
||||
public const int ModAssign = 42; |
||||
public const int BitwiseAndAssign = 43; |
||||
public const int BitwiseOrAssign = 44; |
||||
public const int XorAssign = 45; |
||||
public const int ShiftLeftAssign = 46; |
||||
public const int Pointer = 47; |
||||
public const int LambdaArrow = 48; |
||||
|
||||
// ----- keywords -----
|
||||
public const int Abstract = 49; |
||||
public const int As = 50; |
||||
public const int Base = 51; |
||||
public const int Bool = 52; |
||||
public const int Break = 53; |
||||
public const int Byte = 54; |
||||
public const int Case = 55; |
||||
public const int Catch = 56; |
||||
public const int Char = 57; |
||||
public const int Checked = 58; |
||||
public const int Class = 59; |
||||
public const int Const = 60; |
||||
public const int Continue = 61; |
||||
public const int Decimal = 62; |
||||
public const int Default = 63; |
||||
public const int Delegate = 64; |
||||
public const int Do = 65; |
||||
public const int Double = 66; |
||||
public const int Else = 67; |
||||
public const int Enum = 68; |
||||
public const int Event = 69; |
||||
public const int Explicit = 70; |
||||
public const int Extern = 71; |
||||
public const int False = 72; |
||||
public const int Finally = 73; |
||||
public const int Fixed = 74; |
||||
public const int Float = 75; |
||||
public const int For = 76; |
||||
public const int Foreach = 77; |
||||
public const int Goto = 78; |
||||
public const int If = 79; |
||||
public const int Implicit = 80; |
||||
public const int In = 81; |
||||
public const int Int = 82; |
||||
public const int Interface = 83; |
||||
public const int Internal = 84; |
||||
public const int Is = 85; |
||||
public const int Lock = 86; |
||||
public const int Long = 87; |
||||
public const int Namespace = 88; |
||||
public const int New = 89; |
||||
public const int Null = 90; |
||||
public const int Object = 91; |
||||
public const int Operator = 92; |
||||
public const int Out = 93; |
||||
public const int Override = 94; |
||||
public const int Params = 95; |
||||
public const int Private = 96; |
||||
public const int Protected = 97; |
||||
public const int Public = 98; |
||||
public const int Readonly = 99; |
||||
public const int Ref = 100; |
||||
public const int Return = 101; |
||||
public const int Sbyte = 102; |
||||
public const int Sealed = 103; |
||||
public const int Short = 104; |
||||
public const int Sizeof = 105; |
||||
public const int Stackalloc = 106; |
||||
public const int Static = 107; |
||||
public const int String = 108; |
||||
public const int Struct = 109; |
||||
public const int Switch = 110; |
||||
public const int This = 111; |
||||
public const int Throw = 112; |
||||
public const int True = 113; |
||||
public const int Try = 114; |
||||
public const int Typeof = 115; |
||||
public const int Uint = 116; |
||||
public const int Ulong = 117; |
||||
public const int Unchecked = 118; |
||||
public const int Unsafe = 119; |
||||
public const int Ushort = 120; |
||||
public const int Using = 121; |
||||
public const int Virtual = 122; |
||||
public const int Void = 123; |
||||
public const int Volatile = 124; |
||||
public const int While = 125; |
||||
public const int Partial = 126; |
||||
public const int Where = 127; |
||||
public const int Get = 128; |
||||
public const int Set = 129; |
||||
public const int Add = 130; |
||||
public const int Remove = 131; |
||||
public const int Yield = 132; |
||||
public const int Select = 133; |
||||
public const int Group = 134; |
||||
public const int By = 135; |
||||
public const int Into = 136; |
||||
public const int From = 137; |
||||
public const int Ascending = 138; |
||||
public const int Descending = 139; |
||||
public const int Orderby = 140; |
||||
public const int Let = 141; |
||||
public const int Join = 142; |
||||
public const int On = 143; |
||||
new public const int Equals = 144; |
||||
|
||||
public const int MaxToken = 145; |
||||
static BitArray NewSet(params int[] values) |
||||
{ |
||||
BitArray bitArray = new BitArray(MaxToken); |
||||
foreach (int val in values) { |
||||
bitArray[val] = true; |
||||
} |
||||
return bitArray; |
||||
} |
||||
public static BitArray IdentifierTokens = NewSet(Identifier, Partial, Where, Get, Set, Add, Remove, Yield, Select, Group, By, Into, From, Ascending, Descending, Orderby, Let, Join, On, Equals); |
||||
public static BitArray OverloadableUnaryOp = NewSet(Minus, Not, BitwiseComplement, Increment, Decrement, True, False); |
||||
public static BitArray OverloadableBinaryOp = NewSet(Plus, Minus, Times, Div, Mod, BitwiseAnd, BitwiseOr, Xor, ShiftLeft, Equal, NotEqual, GreaterThan, LessThan, GreaterEqual, LessEqual); |
||||
public static BitArray TypeKW = NewSet(Char, Bool, Object, String, Sbyte, Byte, Short, Ushort, Int, Uint, Long, Ulong, Float, Double, Decimal); |
||||
public static BitArray UnaryHead = NewSet(Plus, Minus, Not, BitwiseComplement, Times, Increment, Decrement, BitwiseAnd); |
||||
public static BitArray AssnStartOp = NewSet(Plus, Minus, Not, BitwiseComplement, Times); |
||||
public static BitArray CastFollower = NewSet(Char, Bool, Object, String, Sbyte, Byte, Short, Ushort, Int, Uint, Long, Ulong, Float, Double, Decimal, Identifier, Partial, Where, Get, Set, Add, Remove, Yield, Select, Group, By, Into, From, Ascending, Descending, Orderby, Let, Join, On, Equals, Void, Literal, OpenParenthesis, BitwiseComplement, Not, Base, Delegate, False, New, Null, Sizeof, This, True, Typeof, Checked, Unchecked, From); |
||||
public static BitArray AssgnOps = NewSet(Assign, PlusAssign, MinusAssign, TimesAssign, DivAssign, ModAssign, BitwiseAndAssign, BitwiseOrAssign, ShiftLeftAssign); |
||||
public static BitArray UnaryOp = NewSet(Plus, Minus, Not, BitwiseComplement, Times, Increment, Decrement, BitwiseAnd); |
||||
public static BitArray TypeDeclarationKW = NewSet(Class, Interface, Struct, Enum, Delegate); |
||||
public static BitArray GenericFollower = NewSet(OpenParenthesis, CloseParenthesis, CloseSquareBracket, CloseCurlyBrace, Colon, Semicolon, Comma, Dot, Question, Equal, NotEqual); |
||||
public static BitArray ValidInsideTypeName = NewSet(Identifier, Partial, Where, Get, Set, Add, Remove, Yield, Select, Group, By, Into, From, Ascending, Descending, Orderby, Let, Join, On, Equals, Char, Bool, Object, String, Sbyte, Byte, Short, Ushort, Int, Uint, Long, Ulong, Float, Double, Decimal, LessThan, GreaterThan, Dot, Question, OpenSquareBracket, Comma, CloseSquareBracket, Times, DoubleColon); |
||||
public static BitArray KCCClassModifiers = NewSet(Abstract, Sealed, Static, Unsafe, Partial); |
||||
public static BitArray KCCTypeDeclarationStart = NewSet(Public, Internal, Class, Interface, Struct, Enum, Delegate, Abstract, Sealed, Static, Unsafe, Partial); |
||||
public static BitArray KCCMemberVisibilityModifiers = NewSet(Protected, Private, Public, Internal); |
||||
public static BitArray SimpleTypeName = NewSet(Char, Bool, Object, String, Sbyte, Byte, Short, Ushort, Int, Uint, Long, Ulong, Float, Double, Decimal, Identifier, Partial, Where, Get, Set, Add, Remove, Yield, Select, Group, By, Into, From, Ascending, Descending, Orderby, Let, Join, On, Equals, Void); |
||||
public static BitArray GlobalLevel = NewSet(Namespace, Using, Public, Internal, Class, Interface, Struct, Enum, Delegate, Abstract, Sealed, Static, Unsafe, Partial); |
||||
public static BitArray ExpressionStart = NewSet(Base, Delegate, False, New, Null, Sizeof, This, True, Typeof, Checked, Unchecked, From); |
||||
public static BitArray ExpressionContent = NewSet(As, Is, Out, Ref, In); |
||||
public static BitArray InterfaceLevel = NewSet(Event); |
||||
public static BitArray TypeLevel = NewSet(Public, Internal, Class, Interface, Struct, Enum, Delegate, Abstract, Sealed, Static, Unsafe, Partial, Protected, Private, Public, Internal, Const, Event, Explicit, Extern, Fixed, Implicit, New, Operator, Override, Readonly, Virtual, Volatile); |
||||
public static BitArray StatementStart = NewSet(Base, Delegate, False, New, Null, Sizeof, This, True, Typeof, Checked, Unchecked, From, As, Is, Out, Ref, In, Break, Case, Catch, Checked, Unchecked, Const, Continue, Default, Do, Else, Finally, Fixed, For, Foreach, Goto, If, Lock, Return, Stackalloc, Switch, Throw, Try, Unsafe, Using, While, Yield); |
||||
public static BitArray QueryExpressionClauseStart = NewSet(From, Let, Where, Join, Orderby, Group, Select); |
||||
public static BitArray InPropertyDeclaration = NewSet(Protected, Private, Public, Internal, Get, Set); |
||||
public static BitArray InEventDeclaration = NewSet(Add, Remove); |
||||
|
||||
static string[] tokenList = new string[] { |
||||
// ----- terminal classes -----
|
||||
"<EOF>", |
||||
"<Identifier>", |
||||
"<Literal>", |
||||
// ----- special character -----
|
||||
"=", |
||||
"+", |
||||
"-", |
||||
"*", |
||||
"/", |
||||
"%", |
||||
":", |
||||
"::", |
||||
";", |
||||
"?", |
||||
"??", |
||||
",", |
||||
".", |
||||
"{", |
||||
"}", |
||||
"[", |
||||
"]", |
||||
"(", |
||||
")", |
||||
">", |
||||
"<", |
||||
"!", |
||||
"&&", |
||||
"||", |
||||
"~", |
||||
"&", |
||||
"|", |
||||
"^", |
||||
"++", |
||||
"--", |
||||
"==", |
||||
"!=", |
||||
">=", |
||||
"<=", |
||||
"<<", |
||||
"+=", |
||||
"-=", |
||||
"*=", |
||||
"/=", |
||||
"%=", |
||||
"&=", |
||||
"|=", |
||||
"^=", |
||||
"<<=", |
||||
"->", |
||||
"=>", |
||||
// ----- keywords -----
|
||||
"abstract", |
||||
"as", |
||||
"base", |
||||
"bool", |
||||
"break", |
||||
"byte", |
||||
"case", |
||||
"catch", |
||||
"char", |
||||
"checked", |
||||
"class", |
||||
"const", |
||||
"continue", |
||||
"decimal", |
||||
"default", |
||||
"delegate", |
||||
"do", |
||||
"double", |
||||
"else", |
||||
"enum", |
||||
"event", |
||||
"explicit", |
||||
"extern", |
||||
"false", |
||||
"finally", |
||||
"fixed", |
||||
"float", |
||||
"for", |
||||
"foreach", |
||||
"goto", |
||||
"if", |
||||
"implicit", |
||||
"in", |
||||
"int", |
||||
"interface", |
||||
"internal", |
||||
"is", |
||||
"lock", |
||||
"long", |
||||
"namespace", |
||||
"new", |
||||
"null", |
||||
"object", |
||||
"operator", |
||||
"out", |
||||
"override", |
||||
"params", |
||||
"private", |
||||
"protected", |
||||
"public", |
||||
"readonly", |
||||
"ref", |
||||
"return", |
||||
"sbyte", |
||||
"sealed", |
||||
"short", |
||||
"sizeof", |
||||
"stackalloc", |
||||
"static", |
||||
"string", |
||||
"struct", |
||||
"switch", |
||||
"this", |
||||
"throw", |
||||
"true", |
||||
"try", |
||||
"typeof", |
||||
"uint", |
||||
"ulong", |
||||
"unchecked", |
||||
"unsafe", |
||||
"ushort", |
||||
"using", |
||||
"virtual", |
||||
"void", |
||||
"volatile", |
||||
"while", |
||||
"partial", |
||||
"where", |
||||
"get", |
||||
"set", |
||||
"add", |
||||
"remove", |
||||
"yield", |
||||
"select", |
||||
"group", |
||||
"by", |
||||
"into", |
||||
"from", |
||||
"ascending", |
||||
"descending", |
||||
"orderby", |
||||
"let", |
||||
"join", |
||||
"on", |
||||
"equals", |
||||
}; |
||||
public static string GetTokenString(int token) |
||||
{ |
||||
if (token >= 0 && token < tokenList.Length) { |
||||
return tokenList[token]; |
||||
} |
||||
throw new System.NotSupportedException("Unknown token:" + token); |
||||
} |
||||
} |
||||
} |
@ -1,86 +0,0 @@
@@ -1,86 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser |
||||
{ |
||||
/// <summary>
|
||||
/// Lexer interface
|
||||
/// </summary>
|
||||
public interface ILexer : IDisposable |
||||
{ |
||||
Errors Errors { |
||||
get; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// The current Token. <seealso cref="ICSharpCode.NRefactory.Parser.Token"/>
|
||||
/// </summary>
|
||||
Token Token { |
||||
get; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// The next Token (The <see cref="Token"/> after <see cref="NextToken"/> call) . <seealso cref="ICSharpCode.NRefactory.Parser.Token"/>
|
||||
/// </summary>
|
||||
Token LookAhead { |
||||
get; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Special comment tags are tags like TODO, HACK or UNDONE which are read by the lexer and stored in <see cref="TagComments"/>.
|
||||
/// </summary>
|
||||
string[] SpecialCommentTags { |
||||
get; |
||||
set; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Gets/Sets if the lexer should skip adding comments to the special tracker. Set this
|
||||
/// property to true to improve lexing performance.
|
||||
/// </summary>
|
||||
bool SkipAllComments { |
||||
get; |
||||
set; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Returns the comments that had been read and containing tag key words.
|
||||
/// </summary>
|
||||
List<TagComment> TagComments { |
||||
get; |
||||
} |
||||
|
||||
SpecialTracker SpecialTracker { |
||||
get; |
||||
} |
||||
|
||||
void StartPeek(); |
||||
|
||||
/// <summary>
|
||||
/// Gives back the next token. A second call to Peek() gives the next token after the last call for Peek() and so on.
|
||||
/// </summary>
|
||||
/// <returns>An <see cref="Token"/> object.</returns>
|
||||
Token Peek(); |
||||
|
||||
/// <summary>
|
||||
/// Reads the next token and gives it back.
|
||||
/// </summary>
|
||||
/// <returns>An <see cref="Token"/> object.</returns>
|
||||
Token NextToken(); |
||||
|
||||
/// <summary>
|
||||
/// Skips to the end of the current code block.
|
||||
/// For this, the lexer must have read the next token AFTER the token opening the
|
||||
/// block (so that Lexer.Token is the block-opening token, not Lexer.LookAhead).
|
||||
/// After the call, Lexer.LookAhead will be the block-closing token.
|
||||
/// </summary>
|
||||
void SkipCurrentBlock(int targetToken); |
||||
} |
||||
} |
@ -1,120 +0,0 @@
@@ -1,120 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Globalization; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser |
||||
{ |
||||
/// <summary>
|
||||
/// This class implements a keyword map. It implements a digital search trees (tries) to find
|
||||
/// a word.
|
||||
/// </summary>
|
||||
internal class LookupTable |
||||
{ |
||||
Node root = new Node(-1, null); |
||||
bool casesensitive; |
||||
int length; |
||||
|
||||
/// <value>
|
||||
/// The number of elements in the table
|
||||
/// </value>
|
||||
public int Count { |
||||
get { |
||||
return length; |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Inserts an int in the tree, under keyword
|
||||
/// </summary>
|
||||
public int this[string keyword] { |
||||
get { |
||||
Node next = root; |
||||
|
||||
if (!casesensitive) { |
||||
keyword = keyword.ToUpper(CultureInfo.InvariantCulture); |
||||
} |
||||
|
||||
for (int i = 0; i < keyword.Length; ++i) { |
||||
int index = ((int)keyword[i]) % 256; |
||||
next = next.leaf[index]; |
||||
|
||||
if (next == null) { |
||||
return -1; |
||||
} |
||||
|
||||
if (keyword == next.word) { |
||||
return next.val; |
||||
} |
||||
} |
||||
return -1; |
||||
} |
||||
set { |
||||
Node node = root; |
||||
Node next = root; |
||||
|
||||
if (!casesensitive) { |
||||
keyword = keyword.ToUpper(CultureInfo.InvariantCulture); |
||||
} |
||||
|
||||
++length; |
||||
|
||||
// insert word into the tree
|
||||
for (int i = 0; i < keyword.Length; ++i) { |
||||
int index = ((int)keyword[i]) % 256; // index of curchar
|
||||
bool d = keyword[i] == '\\'; |
||||
|
||||
next = next.leaf[index]; // get node to this index
|
||||
|
||||
if (next == null) { // no node created -> insert word here
|
||||
node.leaf[index] = new Node(value, keyword); |
||||
break; |
||||
} |
||||
|
||||
if (next.word != null && next.word.Length != i) { // node there, take node content and insert them again
|
||||
string tmpword = next.word; // this word will be inserted 1 level deeper (better, don't need too much
|
||||
int tmpval = next.val; // string comparisons for finding.)
|
||||
next.val = -1; |
||||
next.word = null; |
||||
this[tmpword] = tmpval; |
||||
} |
||||
|
||||
if (i == keyword.Length - 1) { // end of keyword reached, insert node there, if a node was here it was
|
||||
next.word = keyword; // reinserted, if it has the same length (keyword EQUALS this word) it will be overwritten
|
||||
next.val = value; |
||||
break; |
||||
} |
||||
|
||||
node = next; |
||||
} |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="LookupTable"/>
|
||||
/// </summary>
|
||||
public LookupTable(bool casesensitive) |
||||
{ |
||||
this.casesensitive = casesensitive; |
||||
} |
||||
|
||||
class Node |
||||
{ |
||||
public Node(int val, string word) |
||||
{ |
||||
this.word = word; |
||||
this.val = val; |
||||
} |
||||
|
||||
public string word; |
||||
public int val; |
||||
|
||||
public Node[] leaf = new Node[256]; |
||||
} |
||||
} |
||||
} |
@ -1,23 +0,0 @@
@@ -1,23 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="none" email=""/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
|
||||
namespace ICSharpCode.NRefactory |
||||
{ |
||||
public class BlankLine : AbstractSpecial |
||||
{ |
||||
public BlankLine(Location point) : base(point) |
||||
{ |
||||
} |
||||
|
||||
public override object AcceptVisitor(ISpecialVisitor visitor, object data) |
||||
{ |
||||
return visitor.Visit(this, data); |
||||
} |
||||
} |
||||
} |
@ -1,53 +0,0 @@
@@ -1,53 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="none" email=""/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
|
||||
namespace ICSharpCode.NRefactory |
||||
{ |
||||
public class Comment : AbstractSpecial |
||||
{ |
||||
CommentType commentType; |
||||
string comment; |
||||
|
||||
public CommentType CommentType { |
||||
get { |
||||
return commentType; |
||||
} |
||||
set { |
||||
commentType = value; |
||||
} |
||||
} |
||||
|
||||
public string CommentText { |
||||
get { |
||||
return comment; |
||||
} |
||||
set { |
||||
comment = value; |
||||
} |
||||
} |
||||
|
||||
public Comment(CommentType commentType, string comment, Location startPosition, Location endPosition) |
||||
: base(startPosition, endPosition) |
||||
{ |
||||
this.commentType = commentType; |
||||
this.comment = comment; |
||||
} |
||||
|
||||
public override string ToString() |
||||
{ |
||||
return String.Format("[{0}: Type = {1}, Text = {2}, Start = {3}, End = {4}]", |
||||
GetType().Name, CommentType, CommentText, StartPosition, EndPosition); |
||||
} |
||||
|
||||
public override object AcceptVisitor(ISpecialVisitor visitor, object data) |
||||
{ |
||||
return visitor.Visit(this, data); |
||||
} |
||||
} |
||||
} |
@ -1,18 +0,0 @@
@@ -1,18 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="none" email=""/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
|
||||
namespace ICSharpCode.NRefactory |
||||
{ |
||||
public enum CommentType |
||||
{ |
||||
Block, |
||||
SingleLine, |
||||
Documentation |
||||
} |
||||
} |
@ -1,73 +0,0 @@
@@ -1,73 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
|
||||
namespace ICSharpCode.NRefactory |
||||
{ |
||||
/// <summary>
|
||||
/// Interface for all specials.
|
||||
/// </summary>
|
||||
public interface ISpecial |
||||
{ |
||||
Location StartPosition { get; } |
||||
Location EndPosition { get; } |
||||
|
||||
object AcceptVisitor(ISpecialVisitor visitor, object data); |
||||
} |
||||
|
||||
public interface ISpecialVisitor |
||||
{ |
||||
object Visit(ISpecial special, object data); |
||||
object Visit(BlankLine special, object data); |
||||
object Visit(Comment special, object data); |
||||
object Visit(PreprocessingDirective special, object data); |
||||
} |
||||
|
||||
public abstract class AbstractSpecial : ISpecial |
||||
{ |
||||
public abstract object AcceptVisitor(ISpecialVisitor visitor, object data); |
||||
|
||||
Location startPosition, endPosition; |
||||
|
||||
protected AbstractSpecial(Location position) |
||||
{ |
||||
this.startPosition = position; |
||||
this.endPosition = position; |
||||
} |
||||
|
||||
protected AbstractSpecial(Location startPosition, Location endPosition) |
||||
{ |
||||
this.startPosition = startPosition; |
||||
this.endPosition = endPosition; |
||||
} |
||||
|
||||
public Location StartPosition { |
||||
get { |
||||
return startPosition; |
||||
} |
||||
set { |
||||
startPosition = value; |
||||
} |
||||
} |
||||
|
||||
public Location EndPosition { |
||||
get { |
||||
return endPosition; |
||||
} |
||||
set { |
||||
endPosition = value; |
||||
} |
||||
} |
||||
|
||||
public override string ToString() |
||||
{ |
||||
return String.Format("[{0}: Start = {1}, End = {2}]", |
||||
GetType().Name, StartPosition, EndPosition); |
||||
} |
||||
} |
||||
} |
@ -1,122 +0,0 @@
@@ -1,122 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="none" email=""/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
|
||||
namespace ICSharpCode.NRefactory |
||||
{ |
||||
public class PreprocessingDirective : AbstractSpecial |
||||
{ |
||||
public static void VBToCSharp(IList<ISpecial> list) |
||||
{ |
||||
for (int i = 0; i < list.Count; ++i) { |
||||
if (list[i] is PreprocessingDirective) |
||||
list[i] = VBToCSharp((PreprocessingDirective)list[i]); |
||||
} |
||||
} |
||||
|
||||
public static PreprocessingDirective VBToCSharp(PreprocessingDirective dir) |
||||
{ |
||||
string cmd = dir.Cmd; |
||||
string arg = dir.Arg; |
||||
if (cmd.Equals("#End", StringComparison.InvariantCultureIgnoreCase)) { |
||||
if (arg.ToLowerInvariant().StartsWith("region")) { |
||||
cmd = "#endregion"; |
||||
arg = ""; |
||||
} else if ("if".Equals(arg, StringComparison.InvariantCultureIgnoreCase)) { |
||||
cmd = "#endif"; |
||||
arg = ""; |
||||
} |
||||
} else if (cmd.Equals("#Region", StringComparison.InvariantCultureIgnoreCase)) { |
||||
cmd = "#region"; |
||||
} else if (cmd.Equals("#If", StringComparison.InvariantCultureIgnoreCase)) { |
||||
cmd = "#if"; |
||||
if (arg.ToLowerInvariant().EndsWith(" then")) |
||||
arg = arg.Substring(0, arg.Length - 5); |
||||
} |
||||
return new PreprocessingDirective(cmd, arg, dir.StartPosition, dir.EndPosition); |
||||
} |
||||
|
||||
public static void CSharpToVB(List<ISpecial> list) |
||||
{ |
||||
for (int i = 0; i < list.Count; ++i) { |
||||
if (list[i] is PreprocessingDirective) |
||||
list[i] = CSharpToVB((PreprocessingDirective)list[i]); |
||||
} |
||||
} |
||||
|
||||
public static PreprocessingDirective CSharpToVB(PreprocessingDirective dir) |
||||
{ |
||||
string cmd = dir.Cmd; |
||||
string arg = dir.Arg; |
||||
switch (cmd) { |
||||
case "#region": |
||||
cmd = "#Region"; |
||||
if (!arg.StartsWith("\"")) { |
||||
arg = "\"" + arg.Trim() + "\""; |
||||
} |
||||
break; |
||||
case "#endregion": |
||||
cmd = "#End"; |
||||
arg = "Region"; |
||||
break; |
||||
case "#endif": |
||||
cmd = "#End"; |
||||
arg = "If"; |
||||
break; |
||||
case "#if": |
||||
arg += " Then"; |
||||
break; |
||||
} |
||||
if (cmd.Length > 1) { |
||||
cmd = cmd.Substring(0, 2).ToUpperInvariant() + cmd.Substring(2); |
||||
} |
||||
return new PreprocessingDirective(cmd, arg, dir.StartPosition, dir.EndPosition); |
||||
} |
||||
|
||||
string cmd; |
||||
string arg; |
||||
|
||||
public string Cmd { |
||||
get { |
||||
return cmd; |
||||
} |
||||
set { |
||||
cmd = value ?? string.Empty; |
||||
} |
||||
} |
||||
|
||||
public string Arg { |
||||
get { |
||||
return arg; |
||||
} |
||||
set { |
||||
arg = value ?? string.Empty; |
||||
} |
||||
} |
||||
|
||||
public override string ToString() |
||||
{ |
||||
return String.Format("[PreProcessingDirective: Cmd = {0}, Arg = {1}]", |
||||
Cmd, |
||||
Arg); |
||||
} |
||||
|
||||
public PreprocessingDirective(string cmd, string arg, Location start, Location end) |
||||
: base(start, end) |
||||
{ |
||||
this.Cmd = cmd; |
||||
this.Arg = arg; |
||||
} |
||||
|
||||
public override object AcceptVisitor(ISpecialVisitor visitor, object data) |
||||
{ |
||||
return visitor.Visit(this, data); |
||||
} |
||||
} |
||||
} |
@ -1,76 +0,0 @@
@@ -1,76 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="none" email=""/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using System.Text; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser |
||||
{ |
||||
public class SpecialTracker |
||||
{ |
||||
List<ISpecial> currentSpecials = new List<ISpecial>(); |
||||
|
||||
CommentType currentCommentType; |
||||
StringBuilder sb = new StringBuilder(); |
||||
Location startPosition; |
||||
|
||||
public List<ISpecial> CurrentSpecials { |
||||
get { |
||||
return currentSpecials; |
||||
} |
||||
} |
||||
|
||||
public void InformToken(int kind) |
||||
{ |
||||
|
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Gets the specials from the SpecialTracker and resets the lists.
|
||||
/// </summary>
|
||||
public List<ISpecial> RetrieveSpecials() |
||||
{ |
||||
List<ISpecial> tmp = currentSpecials; |
||||
currentSpecials = new List<ISpecial>(); |
||||
return tmp; |
||||
} |
||||
|
||||
public void AddEndOfLine(Location point) |
||||
{ |
||||
currentSpecials.Add(new BlankLine(point)); |
||||
} |
||||
|
||||
public void AddPreprocessingDirective(string cmd, string arg, Location start, Location end) |
||||
{ |
||||
currentSpecials.Add(new PreprocessingDirective(cmd, arg, start, end)); |
||||
} |
||||
|
||||
// used for comment tracking
|
||||
public void StartComment(CommentType commentType, Location startPosition) |
||||
{ |
||||
this.currentCommentType = commentType; |
||||
this.startPosition = startPosition; |
||||
this.sb.Length = 0; |
||||
} |
||||
|
||||
public void AddChar(char c) |
||||
{ |
||||
sb.Append(c); |
||||
} |
||||
|
||||
public void AddString(string s) |
||||
{ |
||||
sb.Append(s); |
||||
} |
||||
|
||||
public void FinishComment(Location endPosition) |
||||
{ |
||||
currentSpecials.Add(new Comment(currentCommentType, sb.ToString(), startPosition, endPosition)); |
||||
} |
||||
} |
||||
} |
@ -1,33 +0,0 @@
@@ -1,33 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="none" email=""/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser |
||||
{ |
||||
/// <summary>
|
||||
/// Description of TagComment.
|
||||
/// </summary>
|
||||
public class TagComment : Comment |
||||
{ |
||||
string tag; |
||||
|
||||
public string Tag { |
||||
get { |
||||
return tag; |
||||
} |
||||
set { |
||||
tag = value; |
||||
} |
||||
} |
||||
|
||||
public TagComment(string tag, string comment, Location startPosition, Location endPosition) : base(CommentType.SingleLine, comment, startPosition, endPosition) |
||||
{ |
||||
this.tag = tag; |
||||
} |
||||
} |
||||
} |
@ -1,64 +0,0 @@
@@ -1,64 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser |
||||
{ |
||||
public class Token |
||||
{ |
||||
public int kind; |
||||
|
||||
public int col; |
||||
public int line; |
||||
|
||||
public object literalValue; |
||||
public string val; |
||||
public Token next; |
||||
|
||||
public Location EndLocation { |
||||
get { |
||||
return new Location(val == null ? col + 1 : col + val.Length, line); |
||||
} |
||||
} |
||||
public Location Location { |
||||
get { |
||||
return new Location(col, line); |
||||
} |
||||
} |
||||
|
||||
public Token(int kind) : this(kind, 0, 0) |
||||
{ |
||||
} |
||||
|
||||
public Token(int kind, int col, int line) : this (kind, col, line, null) |
||||
{ |
||||
} |
||||
|
||||
public Token(int kind, int col, int line, string val) : this(kind, col, line, val, null) |
||||
{ |
||||
} |
||||
|
||||
public Token(int kind, int col, int line, string val, object literalValue) |
||||
{ |
||||
this.kind = kind; |
||||
this.col = col; |
||||
this.line = line; |
||||
this.val = val; |
||||
this.literalValue = literalValue; |
||||
} |
||||
|
||||
public override string ToString() |
||||
{ |
||||
return string.Format("[C# {0}/VB {1} line={2} col={3} val={4}]", |
||||
CSharp.Tokens.GetTokenString(kind), |
||||
VB.Tokens.GetTokenString(kind), |
||||
line, col, val); |
||||
|
||||
} |
||||
} |
||||
} |
@ -1,241 +0,0 @@
@@ -1,241 +0,0 @@
|
||||
# this list is used for autogeneration of: |
||||
# - Keywords.cs |
||||
# - Tokens.cs |
||||
# - ATGTokensSection.txt - the TOKENS section of the ATG file |
||||
|
||||
# use BuildKeywords to generate the different lists. |
||||
|
||||
$Namespace=ICSharpCode.NRefactory.Parser.VB |
||||
$UpperCaseKeywords=True |
||||
|
||||
# TERMINAL_CLASSES |
||||
EOF |
||||
EOL |
||||
Identifier |
||||
LiteralString |
||||
LiteralCharacter |
||||
LiteralInteger |
||||
LiteralDouble |
||||
LiteralSingle |
||||
LiteralDecimal |
||||
LiteralDate |
||||
|
||||
# SPECIAL_CHARACTERS |
||||
Dot = "." |
||||
Assign = "=" |
||||
Comma = "," |
||||
Colon =":" |
||||
Plus = "+" |
||||
Minus = "-" |
||||
Times = "*" |
||||
Div ="/" |
||||
DivInteger = "\\" |
||||
ConcatString = "&" |
||||
Power = "^" |
||||
# Question mark is not needed by VB8, but we use it inside the IDE |
||||
QuestionMark = "?" |
||||
|
||||
OpenCurlyBrace = "{" |
||||
CloseCurlyBrace = "}" |
||||
|
||||
OpenParenthesis = "(" |
||||
CloseParenthesis = ")" |
||||
|
||||
GreaterThan = ">" |
||||
LessThan = "<" |
||||
|
||||
NotEqual = "<>" |
||||
GreaterEqual = ">=" |
||||
LessEqual = "<=" |
||||
|
||||
ShiftLeft = "<<" |
||||
ShiftRight = ">>" |
||||
|
||||
PlusAssign = "+=" |
||||
PowerAssign = "^=" |
||||
MinusAssign = "-=" |
||||
TimesAssign = "*=" |
||||
DivAssign = "/=" |
||||
DivIntegerAssign = "\\=" |
||||
ShiftLeftAssign = "<<=" |
||||
ShiftRightAssign = ">>=" |
||||
ConcatStringAssign = "&=" |
||||
|
||||
# keywords according to the spec: |
||||
# Keywordlist |
||||
"AddHandler" |
||||
"AddressOf" |
||||
"Alias" |
||||
"And" |
||||
"AndAlso" |
||||
"Ansi" |
||||
"As" |
||||
"Assembly" |
||||
"Auto" |
||||
"Binary" |
||||
"Boolean" |
||||
"ByRef" |
||||
"Byte" |
||||
"ByVal" |
||||
"Call" |
||||
"Case" |
||||
"Catch" |
||||
"CBool" |
||||
"CByte" |
||||
"CChar" |
||||
"CDate" |
||||
"CDbl" |
||||
"CDec" |
||||
"Char" |
||||
"CInt" |
||||
"Class" |
||||
"CLng" |
||||
"CObj" |
||||
"Compare" |
||||
"Const" |
||||
"CShort" |
||||
"CSng" |
||||
"CStr" |
||||
"CType" |
||||
"Date" |
||||
"Decimal" |
||||
"Declare" |
||||
"Default" |
||||
"Delegate" |
||||
"Dim" |
||||
"DirectCast" |
||||
"Do" |
||||
"Double" |
||||
"Each" |
||||
"Else" |
||||
"ElseIf" |
||||
"End" |
||||
"EndIf" |
||||
"Enum" |
||||
"Erase" |
||||
"Error" |
||||
"Event" |
||||
"Exit" |
||||
"Explicit" |
||||
"False" |
||||
"Finally" |
||||
"For" |
||||
"Friend" |
||||
"Function" |
||||
"Get" |
||||
"GetType" |
||||
"GoSub" |
||||
"GoTo" |
||||
"Handles" |
||||
"If" |
||||
"Implements" |
||||
"Imports" |
||||
"In" |
||||
"Inherits" |
||||
"Integer" |
||||
"Interface" |
||||
"Is" |
||||
"Let" |
||||
"Lib" |
||||
"Like" |
||||
"Long" |
||||
"Loop" |
||||
"Me" |
||||
"Mod" |
||||
"Module" |
||||
"MustInherit" |
||||
"MustOverride" |
||||
"MyBase" |
||||
"MyClass" |
||||
"Namespace" |
||||
"New" |
||||
"Next" |
||||
"Not" |
||||
"Nothing" |
||||
"NotInheritable" |
||||
"NotOverridable" |
||||
"Object" |
||||
"Off" |
||||
"On" |
||||
"Option" |
||||
"Optional" |
||||
"Or" |
||||
"OrElse" |
||||
"Overloads" |
||||
"Overridable" |
||||
"Overrides" |
||||
"ParamArray" |
||||
"Preserve" |
||||
"Private" |
||||
"Property" |
||||
"Protected" |
||||
"Public" |
||||
"RaiseEvent" |
||||
"ReadOnly" |
||||
"ReDim" |
||||
"RemoveHandler" |
||||
"Resume" |
||||
"Return" |
||||
"Select" |
||||
"Set" |
||||
"Shadows" |
||||
"Shared" |
||||
"Short" |
||||
"Single" |
||||
"Static" |
||||
"Step" |
||||
"Stop" |
||||
"Strict" |
||||
"String" |
||||
"Structure" |
||||
"Sub" |
||||
"SyncLock" |
||||
"Text" |
||||
"Then" |
||||
"Throw" |
||||
"To" |
||||
"True" |
||||
"Try" |
||||
"TypeOf" |
||||
"Unicode" |
||||
"Until" |
||||
"Variant" |
||||
"Wend" |
||||
"When" |
||||
"While" |
||||
"With" |
||||
"WithEvents" |
||||
"WriteOnly" |
||||
"Xor" |
||||
# Rem never gets passed to the parser because it is handled by the lexer, but it still |
||||
# has to be in the keyword list for the output formatter |
||||
"Rem" |
||||
|
||||
# VB.NET 2.0 Keywords: |
||||
"Continue" |
||||
"Operator" |
||||
"Using" |
||||
"IsNot" |
||||
# Note: IsTrue and IsFalse are 'NOT' keywords they're only valid in Operator declarations (like get/set/value are no C# 'keywords') |
||||
"SByte" |
||||
"UInteger" |
||||
"ULong" |
||||
"UShort" |
||||
"CSByte" |
||||
"CUShort" |
||||
"CUInt" |
||||
"CULng" |
||||
"Global" |
||||
"TryCast" |
||||
"Of" |
||||
"Narrowing" |
||||
"Widening" |
||||
"Partial" |
||||
"Custom" |
||||
|
||||
#Sets |
||||
Null("Nothing") |
||||
BlockSucc("Case", "Catch", "Else", "ElseIf", "End", "Finally", "Loop", "Next") |
||||
|
||||
# List of keywords that are valid identifiers, must be the same as the "Identifier" production in VBNET.ATG |
||||
IdentifierTokens("Text", "Binary", "Compare", "Assembly", "Ansi", "Auto", "Preserve", "Unicode", "Until", "Explicit", "Off") |
@ -1,197 +0,0 @@
@@ -1,197 +0,0 @@
|
||||
// this file was autogenerated by a tool.
|
||||
using System; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser.VB |
||||
{ |
||||
public static class Keywords |
||||
{ |
||||
static readonly string[] keywordList = { |
||||
"ADDHANDLER", |
||||
"ADDRESSOF", |
||||
"ALIAS", |
||||
"AND", |
||||
"ANDALSO", |
||||
"ANSI", |
||||
"AS", |
||||
"ASSEMBLY", |
||||
"AUTO", |
||||
"BINARY", |
||||
"BOOLEAN", |
||||
"BYREF", |
||||
"BYTE", |
||||
"BYVAL", |
||||
"CALL", |
||||
"CASE", |
||||
"CATCH", |
||||
"CBOOL", |
||||
"CBYTE", |
||||
"CCHAR", |
||||
"CDATE", |
||||
"CDBL", |
||||
"CDEC", |
||||
"CHAR", |
||||
"CINT", |
||||
"CLASS", |
||||
"CLNG", |
||||
"COBJ", |
||||
"COMPARE", |
||||
"CONST", |
||||
"CSHORT", |
||||
"CSNG", |
||||
"CSTR", |
||||
"CTYPE", |
||||
"DATE", |
||||
"DECIMAL", |
||||
"DECLARE", |
||||
"DEFAULT", |
||||
"DELEGATE", |
||||
"DIM", |
||||
"DIRECTCAST", |
||||
"DO", |
||||
"DOUBLE", |
||||
"EACH", |
||||
"ELSE", |
||||
"ELSEIF", |
||||
"END", |
||||
"ENDIF", |
||||
"ENUM", |
||||
"ERASE", |
||||
"ERROR", |
||||
"EVENT", |
||||
"EXIT", |
||||
"EXPLICIT", |
||||
"FALSE", |
||||
"FINALLY", |
||||
"FOR", |
||||
"FRIEND", |
||||
"FUNCTION", |
||||
"GET", |
||||
"GETTYPE", |
||||
"GOSUB", |
||||
"GOTO", |
||||
"HANDLES", |
||||
"IF", |
||||
"IMPLEMENTS", |
||||
"IMPORTS", |
||||
"IN", |
||||
"INHERITS", |
||||
"INTEGER", |
||||
"INTERFACE", |
||||
"IS", |
||||
"LET", |
||||
"LIB", |
||||
"LIKE", |
||||
"LONG", |
||||
"LOOP", |
||||
"ME", |
||||
"MOD", |
||||
"MODULE", |
||||
"MUSTINHERIT", |
||||
"MUSTOVERRIDE", |
||||
"MYBASE", |
||||
"MYCLASS", |
||||
"NAMESPACE", |
||||
"NEW", |
||||
"NEXT", |
||||
"NOT", |
||||
"NOTHING", |
||||
"NOTINHERITABLE", |
||||
"NOTOVERRIDABLE", |
||||
"OBJECT", |
||||
"OFF", |
||||
"ON", |
||||
"OPTION", |
||||
"OPTIONAL", |
||||
"OR", |
||||
"ORELSE", |
||||
"OVERLOADS", |
||||
"OVERRIDABLE", |
||||
"OVERRIDES", |
||||
"PARAMARRAY", |
||||
"PRESERVE", |
||||
"PRIVATE", |
||||
"PROPERTY", |
||||
"PROTECTED", |
||||
"PUBLIC", |
||||
"RAISEEVENT", |
||||
"READONLY", |
||||
"REDIM", |
||||
"REMOVEHANDLER", |
||||
"RESUME", |
||||
"RETURN", |
||||
"SELECT", |
||||
"SET", |
||||
"SHADOWS", |
||||
"SHARED", |
||||
"SHORT", |
||||
"SINGLE", |
||||
"STATIC", |
||||
"STEP", |
||||
"STOP", |
||||
"STRICT", |
||||
"STRING", |
||||
"STRUCTURE", |
||||
"SUB", |
||||
"SYNCLOCK", |
||||
"TEXT", |
||||
"THEN", |
||||
"THROW", |
||||
"TO", |
||||
"TRUE", |
||||
"TRY", |
||||
"TYPEOF", |
||||
"UNICODE", |
||||
"UNTIL", |
||||
"VARIANT", |
||||
"WEND", |
||||
"WHEN", |
||||
"WHILE", |
||||
"WITH", |
||||
"WITHEVENTS", |
||||
"WRITEONLY", |
||||
"XOR", |
||||
"REM", |
||||
"CONTINUE", |
||||
"OPERATOR", |
||||
"USING", |
||||
"ISNOT", |
||||
"SBYTE", |
||||
"UINTEGER", |
||||
"ULONG", |
||||
"USHORT", |
||||
"CSBYTE", |
||||
"CUSHORT", |
||||
"CUINT", |
||||
"CULNG", |
||||
"GLOBAL", |
||||
"TRYCAST", |
||||
"OF", |
||||
"NARROWING", |
||||
"WIDENING", |
||||
"PARTIAL", |
||||
"CUSTOM" |
||||
}; |
||||
|
||||
static LookupTable keywords = new LookupTable(false); |
||||
|
||||
static Keywords() |
||||
{ |
||||
for (int i = 0; i < keywordList.Length; ++i) { |
||||
keywords[keywordList[i]] = i + Tokens.AddHandler; |
||||
} |
||||
} |
||||
|
||||
public static int GetToken(string keyword) |
||||
{ |
||||
return keywords[keyword]; |
||||
} |
||||
|
||||
public static bool IsNonIdentifierKeyword(string word) |
||||
{ |
||||
int token = GetToken(word); |
||||
if (token < 0) |
||||
return false; |
||||
return !Tokens.IdentifierTokens[token]; |
||||
} |
||||
} |
||||
} |
@ -1,731 +0,0 @@
@@ -1,731 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Andrea Paatz" email="andrea@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Globalization; |
||||
using System.IO; |
||||
using System.Text; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser.VB |
||||
{ |
||||
internal sealed class Lexer : AbstractLexer |
||||
{ |
||||
bool lineEnd = true; |
||||
|
||||
public Lexer(TextReader reader) : base(reader) |
||||
{ |
||||
} |
||||
|
||||
public override Token NextToken() |
||||
{ |
||||
if (curToken == null) { // first call of NextToken()
|
||||
curToken = Next(); |
||||
specialTracker.InformToken(curToken.kind); |
||||
//Console.WriteLine("Tok:" + Tokens.GetTokenString(curToken.kind) + " --- " + curToken.val);
|
||||
return curToken; |
||||
} |
||||
|
||||
lastToken = curToken; |
||||
|
||||
if (curToken.next == null) { |
||||
curToken.next = Next(); |
||||
specialTracker.InformToken(curToken.next.kind); |
||||
} |
||||
|
||||
curToken = curToken.next; |
||||
|
||||
if (curToken.kind == Tokens.EOF && !(lastToken.kind == Tokens.EOL)) { // be sure that before EOF there is an EOL token
|
||||
curToken = new Token(Tokens.EOL, curToken.col, curToken.line, "\n"); |
||||
specialTracker.InformToken(curToken.kind); |
||||
curToken.next = new Token(Tokens.EOF, curToken.col, curToken.line, "\n"); |
||||
specialTracker.InformToken(curToken.next.kind); |
||||
} |
||||
//Console.WriteLine("Tok:" + Tokens.GetTokenString(curToken.kind) + " --- " + curToken.val);
|
||||
return curToken; |
||||
} |
||||
|
||||
protected override Token Next() |
||||
{ |
||||
unchecked { |
||||
int nextChar; |
||||
while ((nextChar = ReaderRead()) != -1) { |
||||
char ch = (char)nextChar; |
||||
if (Char.IsWhiteSpace(ch)) { |
||||
int x = Col - 1; |
||||
int y = Line; |
||||
if (HandleLineEnd(ch)) { |
||||
if (lineEnd) { |
||||
// second line end before getting to a token
|
||||
// -> here was a blank line
|
||||
specialTracker.AddEndOfLine(new Location(x, y)); |
||||
} else { |
||||
lineEnd = true; |
||||
return new Token(Tokens.EOL, x, y); |
||||
} |
||||
} |
||||
continue; |
||||
} |
||||
if (ch == '_') { |
||||
if (ReaderPeek() == -1) { |
||||
errors.Error(Line, Col, String.Format("No EOF expected after _")); |
||||
return new Token(Tokens.EOF); |
||||
} |
||||
if (!Char.IsWhiteSpace((char)ReaderPeek())) { |
||||
int x = Col - 1; |
||||
int y = Line; |
||||
string s = ReadIdent('_'); |
||||
lineEnd = false; |
||||
return new Token(Tokens.Identifier, x, y, s); |
||||
} |
||||
ch = (char)ReaderRead(); |
||||
|
||||
bool oldLineEnd = lineEnd; |
||||
lineEnd = false; |
||||
while (Char.IsWhiteSpace(ch)) { |
||||
if (HandleLineEnd(ch)) { |
||||
lineEnd = true; |
||||
break; |
||||
} |
||||
if (ReaderPeek() != -1) { |
||||
ch = (char)ReaderRead(); |
||||
} else { |
||||
errors.Error(Line, Col, String.Format("No EOF expected after _")); |
||||
return new Token(Tokens.EOF); |
||||
} |
||||
} |
||||
if (!lineEnd) { |
||||
errors.Error(Line, Col, String.Format("Return expected")); |
||||
} |
||||
lineEnd = oldLineEnd; |
||||
continue; |
||||
} |
||||
|
||||
if (ch == '#') { |
||||
while (Char.IsWhiteSpace((char)ReaderPeek())) { |
||||
ReaderRead(); |
||||
} |
||||
if (Char.IsDigit((char)ReaderPeek())) { |
||||
int x = Col - 1; |
||||
int y = Line; |
||||
string s = ReadDate(); |
||||
DateTime time = new DateTime(1, 1, 1, 0, 0, 0); |
||||
try { |
||||
time = DateTime.Parse(s, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault); |
||||
} catch (Exception e) { |
||||
errors.Error(Line, Col, String.Format("Invalid date time {0}", e)); |
||||
} |
||||
return new Token(Tokens.LiteralDate, x, y, s, time); |
||||
} else { |
||||
ReadPreprocessorDirective(); |
||||
continue; |
||||
} |
||||
} |
||||
|
||||
if (ch == '[') { // Identifier
|
||||
lineEnd = false; |
||||
if (ReaderPeek() == -1) { |
||||
errors.Error(Line, Col, String.Format("Identifier expected")); |
||||
} |
||||
ch = (char)ReaderRead(); |
||||
if (ch == ']' || Char.IsWhiteSpace(ch)) { |
||||
errors.Error(Line, Col, String.Format("Identifier expected")); |
||||
} |
||||
int x = Col - 1; |
||||
int y = Line; |
||||
string s = ReadIdent(ch); |
||||
if (ReaderPeek() == -1) { |
||||
errors.Error(Line, Col, String.Format("']' expected")); |
||||
} |
||||
ch = (char)ReaderRead(); |
||||
if (!(ch == ']')) { |
||||
errors.Error(Line, Col, String.Format("']' expected")); |
||||
} |
||||
return new Token(Tokens.Identifier, x, y, s); |
||||
} |
||||
if (Char.IsLetter(ch)) { |
||||
int x = Col - 1; |
||||
int y = Line; |
||||
string s = ReadIdent(ch); |
||||
int keyWordToken = Keywords.GetToken(s); |
||||
if (keyWordToken >= 0) { |
||||
lineEnd = false; |
||||
return new Token(keyWordToken, x, y, s); |
||||
} |
||||
|
||||
// handle 'REM' comments
|
||||
if (s.Equals("REM", StringComparison.InvariantCultureIgnoreCase)) { |
||||
ReadComment(); |
||||
if (!lineEnd) { |
||||
lineEnd = true; |
||||
return new Token(Tokens.EOL, Col, Line, "\n"); |
||||
} |
||||
continue; |
||||
} |
||||
|
||||
lineEnd = false; |
||||
return new Token(Tokens.Identifier, x, y, s); |
||||
|
||||
} |
||||
if (Char.IsDigit(ch)) { |
||||
lineEnd = false; |
||||
return ReadDigit(ch, Col - 1); |
||||
} |
||||
if (ch == '&') { |
||||
lineEnd = false; |
||||
if (ReaderPeek() == -1) { |
||||
return ReadOperator('&'); |
||||
} |
||||
ch = (char)ReaderPeek(); |
||||
if (Char.ToUpper(ch, CultureInfo.InvariantCulture) == 'H' || Char.ToUpper(ch, CultureInfo.InvariantCulture) == 'O') { |
||||
return ReadDigit('&', Col - 1); |
||||
} |
||||
return ReadOperator('&'); |
||||
} |
||||
if (ch == '\'' || ch == '\u2018' || ch == '\u2019') { |
||||
int x = Col - 1; |
||||
int y = Line; |
||||
ReadComment(); |
||||
if (!lineEnd) { |
||||
lineEnd = true; |
||||
return new Token(Tokens.EOL, x, y, "\n"); |
||||
} |
||||
continue; |
||||
} |
||||
if (ch == '"') { |
||||
lineEnd = false; |
||||
int x = Col - 1; |
||||
int y = Line; |
||||
string s = ReadString(); |
||||
if (ReaderPeek() != -1 && (ReaderPeek() == 'C' || ReaderPeek() == 'c')) { |
||||
ReaderRead(); |
||||
if (s.Length != 1) { |
||||
errors.Error(Line, Col, String.Format("Chars can only have Length 1 ")); |
||||
} |
||||
if (s.Length == 0) { |
||||
s = "\0"; |
||||
} |
||||
return new Token(Tokens.LiteralCharacter, x, y, '"' + s + "\"C", s[0]); |
||||
} |
||||
return new Token(Tokens.LiteralString, x, y, '"' + s + '"', s); |
||||
} |
||||
Token token = ReadOperator(ch); |
||||
if (token != null) { |
||||
lineEnd = false; |
||||
return token; |
||||
} |
||||
errors.Error(Line, Col, String.Format("Unknown char({0}) which can't be read", ch)); |
||||
} |
||||
|
||||
return new Token(Tokens.EOF); |
||||
} |
||||
} |
||||
|
||||
string ReadIdent(char ch) |
||||
{ |
||||
sb.Length = 0; |
||||
sb.Append(ch); |
||||
int peek; |
||||
while ((peek = ReaderPeek()) != -1 && (Char.IsLetterOrDigit(ch = (char)peek) || ch == '_')) { |
||||
ReaderRead(); |
||||
sb.Append(ch.ToString()); |
||||
} |
||||
if (peek == -1) { |
||||
return sb.ToString(); |
||||
} |
||||
|
||||
if ("%&@!#$".IndexOf((char)peek) != -1) { |
||||
ReaderRead(); |
||||
} |
||||
return sb.ToString(); |
||||
} |
||||
|
||||
char PeekUpperChar() |
||||
{ |
||||
return Char.ToUpper((char)ReaderPeek(), CultureInfo.InvariantCulture); |
||||
} |
||||
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1818:DoNotConcatenateStringsInsideLoops")] |
||||
Token ReadDigit(char ch, int x) |
||||
{ |
||||
sb.Length = 0; |
||||
sb.Append(ch); |
||||
|
||||
int y = Line; |
||||
string digit = ""; |
||||
if (ch != '&') { |
||||
digit += ch; |
||||
} |
||||
|
||||
bool ishex = false; |
||||
bool isokt = false; |
||||
bool issingle = false; |
||||
bool isdouble = false; |
||||
bool isdecimal = false; |
||||
|
||||
if (ReaderPeek() == -1) { |
||||
if (ch == '&') { |
||||
errors.Error(Line, Col, String.Format("digit expected")); |
||||
} |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString() ,ch - '0'); |
||||
} |
||||
if (ch == '.') { |
||||
if (Char.IsDigit((char)ReaderPeek())) { |
||||
isdouble = true; // double is default
|
||||
if (ishex || isokt) { |
||||
errors.Error(Line, Col, String.Format("No hexadecimal or oktadecimal floating point values allowed")); |
||||
} |
||||
while (ReaderPeek() != -1 && Char.IsDigit((char)ReaderPeek())){ // read decimal digits beyond the dot
|
||||
digit += (char)ReaderRead(); |
||||
} |
||||
} |
||||
} else if (ch == '&' && PeekUpperChar() == 'H') { |
||||
const string hex = "0123456789ABCDEF"; |
||||
sb.Append((char)ReaderRead()); // skip 'H'
|
||||
while (ReaderPeek() != -1 && hex.IndexOf(PeekUpperChar()) != -1) { |
||||
ch = (char)ReaderRead(); |
||||
sb.Append(ch); |
||||
digit += Char.ToUpper(ch, CultureInfo.InvariantCulture); |
||||
} |
||||
ishex = true; |
||||
} else if (ReaderPeek() != -1 && ch == '&' && PeekUpperChar() == 'O') { |
||||
const string okt = "01234567"; |
||||
sb.Append((char)ReaderRead()); // skip 'O'
|
||||
while (ReaderPeek() != -1 && okt.IndexOf(PeekUpperChar()) != -1) { |
||||
ch = (char)ReaderRead(); |
||||
sb.Append(ch); |
||||
digit += Char.ToUpper(ch, CultureInfo.InvariantCulture); |
||||
} |
||||
isokt = true; |
||||
} else { |
||||
while (ReaderPeek() != -1 && Char.IsDigit((char)ReaderPeek())) { |
||||
ch = (char)ReaderRead();; |
||||
digit += ch; |
||||
sb.Append(ch); |
||||
} |
||||
} |
||||
|
||||
if (digit.Length == 0) { |
||||
errors.Error(Line, Col, String.Format("digit expected")); |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), 0); |
||||
} |
||||
|
||||
if (ReaderPeek() != -1 && ("%&SILU".IndexOf(PeekUpperChar()) != -1 || ishex || isokt)) { |
||||
ch = (char)ReaderPeek(); |
||||
sb.Append(ch); |
||||
ch = Char.ToUpper(ch, CultureInfo.InvariantCulture); |
||||
bool unsigned = ch == 'U'; |
||||
if (unsigned) { |
||||
ReaderRead(); // read the U
|
||||
ch = (char)ReaderPeek(); |
||||
sb.Append(ch); |
||||
ch = Char.ToUpper(ch, CultureInfo.InvariantCulture); |
||||
if (ch != 'I' && ch != 'L' && ch != 'S') { |
||||
errors.Error(Line, Col, "Invalid type character: U" + ch); |
||||
} |
||||
} |
||||
try { |
||||
if (isokt) { |
||||
ReaderRead(); |
||||
ulong number = 0L; |
||||
for (int i = 0; i < digit.Length; ++i) { |
||||
number = number * 8 + digit[i] - '0'; |
||||
} |
||||
if (ch == 'S') { |
||||
if (unsigned) |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), (ushort)number); |
||||
else |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), (short)number); |
||||
} else if (ch == '%' || ch == 'I') { |
||||
if (unsigned) |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), (uint)number); |
||||
else |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), (int)number); |
||||
} else if (ch == '&' || ch == 'L') { |
||||
if (unsigned) |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), (ulong)number); |
||||
else |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), (long)number); |
||||
} else { |
||||
if (number > uint.MaxValue) { |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), unchecked((long)number)); |
||||
} else { |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), unchecked((int)number)); |
||||
} |
||||
} |
||||
} |
||||
if (ch == 'S') { |
||||
ReaderRead(); |
||||
if (unsigned) |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), UInt16.Parse(digit, ishex ? NumberStyles.HexNumber : NumberStyles.Number)); |
||||
else |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), Int16.Parse(digit, ishex ? NumberStyles.HexNumber : NumberStyles.Number)); |
||||
} else if (ch == '%' || ch == 'I') { |
||||
ReaderRead(); |
||||
if (unsigned) |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), UInt32.Parse(digit, ishex ? NumberStyles.HexNumber : NumberStyles.Number)); |
||||
else |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), Int32.Parse(digit, ishex ? NumberStyles.HexNumber : NumberStyles.Number)); |
||||
} else if (ch == '&' || ch == 'L') { |
||||
ReaderRead(); |
||||
if (unsigned) |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), UInt64.Parse(digit, ishex ? NumberStyles.HexNumber : NumberStyles.Number)); |
||||
else |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), Int64.Parse(digit, ishex ? NumberStyles.HexNumber : NumberStyles.Number)); |
||||
} else if (ishex) { |
||||
ulong number = UInt64.Parse(digit, NumberStyles.HexNumber); |
||||
if (number > uint.MaxValue) { |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), unchecked((long)number)); |
||||
} else { |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), unchecked((int)number)); |
||||
} |
||||
} |
||||
} catch (OverflowException ex) { |
||||
errors.Error(Line, Col, ex.Message); |
||||
return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), 0); |
||||
} |
||||
} |
||||
Token nextToken = null; // if we accedently read a 'dot'
|
||||
if (!isdouble && ReaderPeek() == '.') { // read floating point number
|
||||
ReaderRead(); |
||||
if (ReaderPeek() != -1 && Char.IsDigit((char)ReaderPeek())) { |
||||
isdouble = true; // double is default
|
||||
if (ishex || isokt) { |
||||
errors.Error(Line, Col, String.Format("No hexadecimal or oktadecimal floating point values allowed")); |
||||
} |
||||
digit += '.'; |
||||
while (ReaderPeek() != -1 && Char.IsDigit((char)ReaderPeek())){ // read decimal digits beyond the dot
|
||||
digit += (char)ReaderRead(); |
||||
} |
||||
} else { |
||||
nextToken = new Token(Tokens.Dot, Col - 1, Line); |
||||
} |
||||
} |
||||
|
||||
if (ReaderPeek() != -1 && PeekUpperChar() == 'E') { // read exponent
|
||||
isdouble = true; |
||||
digit += (char)ReaderRead(); |
||||
if (ReaderPeek() != -1 && (ReaderPeek() == '-' || ReaderPeek() == '+')) { |
||||
digit += (char)ReaderRead(); |
||||
} |
||||
while (ReaderPeek() != -1 && Char.IsDigit((char)ReaderPeek())) { // read exponent value
|
||||
digit += (char)ReaderRead(); |
||||
} |
||||
} |
||||
|
||||
if (ReaderPeek() != -1) { |
||||
switch (PeekUpperChar()) { |
||||
case 'R': |
||||
case '#': |
||||
ReaderRead(); |
||||
isdouble = true; |
||||
break; |
||||
case 'D': |
||||
case '@': |
||||
ReaderRead(); |
||||
isdecimal = true; |
||||
break; |
||||
case 'F': |
||||
case '!': |
||||
ReaderRead(); |
||||
issingle = true; |
||||
break; |
||||
} |
||||
} |
||||
|
||||
try { |
||||
if (issingle) { |
||||
return new Token(Tokens.LiteralSingle, x, y, sb.ToString(), Single.Parse(digit, CultureInfo.InvariantCulture)); |
||||
} |
||||
if (isdecimal) { |
||||
return new Token(Tokens.LiteralDecimal, x, y, sb.ToString(), Decimal.Parse(digit, NumberStyles.Currency | NumberStyles.AllowExponent, CultureInfo.InvariantCulture)); |
||||
} |
||||
if (isdouble) { |
||||
return new Token(Tokens.LiteralDouble, x, y, sb.ToString(), Double.Parse(digit, CultureInfo.InvariantCulture)); |
||||
} |
||||
} catch (FormatException) { |
||||
errors.Error(Line, Col, String.Format("{0} is not a parseable number", digit)); |
||||
if (issingle) |
||||
return new Token(Tokens.LiteralSingle, x, y, sb.ToString(), 0f); |
||||
if (isdecimal) |
||||
return new Token(Tokens.LiteralDecimal, x, y, sb.ToString(), 0m); |
||||
if (isdouble) |
||||
return new Token(Tokens.LiteralDouble, x, y, sb.ToString(), 0.0); |
||||
} |
||||
Token token; |
||||
try { |
||||
token = new Token(Tokens.LiteralInteger, x, y, sb.ToString(), Int32.Parse(digit, ishex ? NumberStyles.HexNumber : NumberStyles.Number)); |
||||
} catch (Exception) { |
||||
try { |
||||
token = new Token(Tokens.LiteralInteger, x, y, sb.ToString(), Int64.Parse(digit, ishex ? NumberStyles.HexNumber : NumberStyles.Number)); |
||||
} catch (FormatException) { |
||||
errors.Error(Line, Col, String.Format("{0} is not a parseable number", digit)); |
||||
// fallback, when nothing helps :)
|
||||
token = new Token(Tokens.LiteralInteger, x, y, sb.ToString(), 0); |
||||
} catch (OverflowException) { |
||||
errors.Error(Line, Col, String.Format("{0} is too long for a integer literal", digit)); |
||||
// fallback, when nothing helps :)
|
||||
token = new Token(Tokens.LiteralInteger, x, y, sb.ToString(), 0); |
||||
} |
||||
} |
||||
token.next = nextToken; |
||||
return token; |
||||
} |
||||
|
||||
void ReadPreprocessorDirective() |
||||
{ |
||||
Location start = new Location(Col - 1, Line); |
||||
string directive = ReadIdent('#'); |
||||
string argument = ReadToEndOfLine(); |
||||
this.specialTracker.AddPreprocessingDirective(directive, argument.Trim(), start, new Location(start.X + directive.Length + argument.Length, start.Y)); |
||||
} |
||||
|
||||
string ReadDate() |
||||
{ |
||||
char ch = '\0'; |
||||
sb.Length = 0; |
||||
int nextChar; |
||||
while ((nextChar = ReaderRead()) != -1) { |
||||
ch = (char)nextChar; |
||||
if (ch == '#') { |
||||
break; |
||||
} else if (ch == '\n') { |
||||
errors.Error(Line, Col, String.Format("No return allowed inside Date literal")); |
||||
} else { |
||||
sb.Append(ch); |
||||
} |
||||
} |
||||
if (ch != '#') { |
||||
errors.Error(Line, Col, String.Format("End of File reached before Date literal terminated")); |
||||
} |
||||
return sb.ToString(); |
||||
} |
||||
|
||||
string ReadString() |
||||
{ |
||||
char ch = '\0'; |
||||
sb.Length = 0; |
||||
int nextChar; |
||||
while ((nextChar = ReaderRead()) != -1) { |
||||
ch = (char)nextChar; |
||||
if (ch == '"') { |
||||
if (ReaderPeek() != -1 && ReaderPeek() == '"') { |
||||
sb.Append('"'); |
||||
ReaderRead(); |
||||
} else { |
||||
break; |
||||
} |
||||
} else if (ch == '\n') { |
||||
errors.Error(Line, Col, String.Format("No return allowed inside String literal")); |
||||
} else { |
||||
sb.Append(ch); |
||||
} |
||||
} |
||||
if (ch != '"') { |
||||
errors.Error(Line, Col, String.Format("End of File reached before String terminated ")); |
||||
} |
||||
return sb.ToString(); |
||||
} |
||||
|
||||
void ReadComment() |
||||
{ |
||||
Location startPos = new Location(Col, Line); |
||||
sb.Length = 0; |
||||
StringBuilder curWord = specialCommentHash != null ? new StringBuilder() : null; |
||||
int missingApostrophes = 2; // no. of ' missing until it is a documentation comment
|
||||
int nextChar; |
||||
while ((nextChar = ReaderRead()) != -1) { |
||||
char ch = (char)nextChar; |
||||
|
||||
if (HandleLineEnd(ch)) { |
||||
break; |
||||
} |
||||
|
||||
sb.Append(ch); |
||||
|
||||
if (missingApostrophes > 0) { |
||||
if (ch == '\'' || ch == '\u2018' || ch == '\u2019') { |
||||
if (--missingApostrophes == 0) { |
||||
specialTracker.StartComment(CommentType.Documentation, startPos); |
||||
sb.Length = 0; |
||||
} |
||||
} else { |
||||
specialTracker.StartComment(CommentType.SingleLine, startPos); |
||||
missingApostrophes = 0; |
||||
} |
||||
} |
||||
|
||||
if (specialCommentHash != null) { |
||||
if (Char.IsLetter(ch)) { |
||||
curWord.Append(ch); |
||||
} else { |
||||
string tag = curWord.ToString(); |
||||
curWord.Length = 0; |
||||
if (specialCommentHash.ContainsKey(tag)) { |
||||
Location p = new Location(Col, Line); |
||||
string comment = ch + ReadToEndOfLine(); |
||||
this.TagComments.Add(new TagComment(tag, comment, p, new Location(Col, Line))); |
||||
sb.Append(comment); |
||||
break; |
||||
} |
||||
} |
||||
} |
||||
} |
||||
if (missingApostrophes > 0) { |
||||
specialTracker.StartComment(CommentType.SingleLine, startPos); |
||||
} |
||||
specialTracker.AddString(sb.ToString()); |
||||
specialTracker.FinishComment(new Location(Col, Line)); |
||||
} |
||||
|
||||
Token ReadOperator(char ch) |
||||
{ |
||||
int x = Col - 1; |
||||
int y = Line; |
||||
switch(ch) { |
||||
case '+': |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.PlusAssign, x, y); |
||||
default: |
||||
break; |
||||
} |
||||
return new Token(Tokens.Plus, x, y); |
||||
case '-': |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.MinusAssign, x, y); |
||||
default: |
||||
break; |
||||
} |
||||
return new Token(Tokens.Minus, x, y); |
||||
case '*': |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.TimesAssign, x, y); |
||||
default: |
||||
break; |
||||
} |
||||
return new Token(Tokens.Times, x, y, "*"); |
||||
case '/': |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.DivAssign, x, y); |
||||
default: |
||||
break; |
||||
} |
||||
return new Token(Tokens.Div, x, y); |
||||
case '\\': |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.DivIntegerAssign, x, y); |
||||
default: |
||||
break; |
||||
} |
||||
return new Token(Tokens.DivInteger, x, y); |
||||
case '&': |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.ConcatStringAssign, x, y); |
||||
default: |
||||
break; |
||||
} |
||||
return new Token(Tokens.ConcatString, x, y); |
||||
case '^': |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.PowerAssign, x, y); |
||||
default: |
||||
break; |
||||
} |
||||
return new Token(Tokens.Power, x, y); |
||||
case ':': |
||||
return new Token(Tokens.Colon, x, y); |
||||
case '=': |
||||
return new Token(Tokens.Assign, x, y); |
||||
case '<': |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.LessEqual, x, y); |
||||
case '>': |
||||
ReaderRead(); |
||||
return new Token(Tokens.NotEqual, x, y); |
||||
case '<': |
||||
ReaderRead(); |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.ShiftLeftAssign, x, y); |
||||
default: |
||||
break; |
||||
} |
||||
return new Token(Tokens.ShiftLeft, x, y); |
||||
} |
||||
return new Token(Tokens.LessThan, x, y); |
||||
case '>': |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.GreaterEqual, x, y); |
||||
case '>': |
||||
ReaderRead(); |
||||
if (ReaderPeek() != -1) { |
||||
switch (ReaderPeek()) { |
||||
case '=': |
||||
ReaderRead(); |
||||
return new Token(Tokens.ShiftRightAssign, x, y); |
||||
default: |
||||
break; |
||||
} |
||||
} |
||||
return new Token(Tokens.ShiftRight, x, y); |
||||
} |
||||
return new Token(Tokens.GreaterThan, x, y); |
||||
case ',': |
||||
return new Token(Tokens.Comma, x, y); |
||||
case '.': |
||||
// Prevent OverflowException when Peek returns -1
|
||||
int tmp = ReaderPeek(); |
||||
if (tmp > 0 && Char.IsDigit((char)tmp)) { |
||||
return ReadDigit('.', Col); |
||||
} |
||||
return new Token(Tokens.Dot, x, y); |
||||
case '(': |
||||
return new Token(Tokens.OpenParenthesis, x, y); |
||||
case ')': |
||||
return new Token(Tokens.CloseParenthesis, x, y); |
||||
case '{': |
||||
return new Token(Tokens.OpenCurlyBrace, x, y); |
||||
case '}': |
||||
return new Token(Tokens.CloseCurlyBrace, x, y); |
||||
case '?': |
||||
return new Token(Tokens.QuestionMark, x, y); |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
public override void SkipCurrentBlock(int targetToken) |
||||
{ |
||||
int lastKind = -1; |
||||
int kind = base.lastToken.kind; |
||||
while (kind != Tokens.EOF && |
||||
!(lastKind == Tokens.End && kind == targetToken)) |
||||
{ |
||||
lastKind = kind; |
||||
NextToken(); |
||||
kind = lastToken.kind; |
||||
} |
||||
} |
||||
} |
||||
} |
@ -1,453 +0,0 @@
@@ -1,453 +0,0 @@
|
||||
// this file was autogenerated by a tool.
|
||||
using System; |
||||
using System.Collections; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser.VB |
||||
{ |
||||
public static class Tokens |
||||
{ |
||||
// ----- terminal classes -----
|
||||
public const int EOF = 0; |
||||
public const int EOL = 1; |
||||
public const int Identifier = 2; |
||||
public const int LiteralString = 3; |
||||
public const int LiteralCharacter = 4; |
||||
public const int LiteralInteger = 5; |
||||
public const int LiteralDouble = 6; |
||||
public const int LiteralSingle = 7; |
||||
public const int LiteralDecimal = 8; |
||||
public const int LiteralDate = 9; |
||||
|
||||
// ----- special character -----
|
||||
public const int Dot = 10; |
||||
public const int Assign = 11; |
||||
public const int Comma = 12; |
||||
public const int Colon = 13; |
||||
public const int Plus = 14; |
||||
public const int Minus = 15; |
||||
public const int Times = 16; |
||||
public const int Div = 17; |
||||
public const int DivInteger = 18; |
||||
public const int ConcatString = 19; |
||||
public const int Power = 20; |
||||
public const int QuestionMark = 21; |
||||
public const int OpenCurlyBrace = 22; |
||||
public const int CloseCurlyBrace = 23; |
||||
public const int OpenParenthesis = 24; |
||||
public const int CloseParenthesis = 25; |
||||
public const int GreaterThan = 26; |
||||
public const int LessThan = 27; |
||||
public const int NotEqual = 28; |
||||
public const int GreaterEqual = 29; |
||||
public const int LessEqual = 30; |
||||
public const int ShiftLeft = 31; |
||||
public const int ShiftRight = 32; |
||||
public const int PlusAssign = 33; |
||||
public const int PowerAssign = 34; |
||||
public const int MinusAssign = 35; |
||||
public const int TimesAssign = 36; |
||||
public const int DivAssign = 37; |
||||
public const int DivIntegerAssign = 38; |
||||
public const int ShiftLeftAssign = 39; |
||||
public const int ShiftRightAssign = 40; |
||||
public const int ConcatStringAssign = 41; |
||||
|
||||
// ----- keywords -----
|
||||
public const int AddHandler = 42; |
||||
public const int AddressOf = 43; |
||||
public const int Alias = 44; |
||||
public const int And = 45; |
||||
public const int AndAlso = 46; |
||||
public const int Ansi = 47; |
||||
public const int As = 48; |
||||
public const int Assembly = 49; |
||||
public const int Auto = 50; |
||||
public const int Binary = 51; |
||||
public const int Boolean = 52; |
||||
public const int ByRef = 53; |
||||
public const int Byte = 54; |
||||
public const int ByVal = 55; |
||||
public const int Call = 56; |
||||
public const int Case = 57; |
||||
public const int Catch = 58; |
||||
public const int CBool = 59; |
||||
public const int CByte = 60; |
||||
public const int CChar = 61; |
||||
public const int CDate = 62; |
||||
public const int CDbl = 63; |
||||
public const int CDec = 64; |
||||
public const int Char = 65; |
||||
public const int CInt = 66; |
||||
public const int Class = 67; |
||||
public const int CLng = 68; |
||||
public const int CObj = 69; |
||||
public const int Compare = 70; |
||||
public const int Const = 71; |
||||
public const int CShort = 72; |
||||
public const int CSng = 73; |
||||
public const int CStr = 74; |
||||
public const int CType = 75; |
||||
public const int Date = 76; |
||||
public const int Decimal = 77; |
||||
public const int Declare = 78; |
||||
public const int Default = 79; |
||||
public const int Delegate = 80; |
||||
public const int Dim = 81; |
||||
public const int DirectCast = 82; |
||||
public const int Do = 83; |
||||
public const int Double = 84; |
||||
public const int Each = 85; |
||||
public const int Else = 86; |
||||
public const int ElseIf = 87; |
||||
public const int End = 88; |
||||
public const int EndIf = 89; |
||||
public const int Enum = 90; |
||||
public const int Erase = 91; |
||||
public const int Error = 92; |
||||
public const int Event = 93; |
||||
public const int Exit = 94; |
||||
public const int Explicit = 95; |
||||
public const int False = 96; |
||||
public const int Finally = 97; |
||||
public const int For = 98; |
||||
public const int Friend = 99; |
||||
public const int Function = 100; |
||||
public const int Get = 101; |
||||
new public const int GetType = 102; |
||||
public const int GoSub = 103; |
||||
public const int GoTo = 104; |
||||
public const int Handles = 105; |
||||
public const int If = 106; |
||||
public const int Implements = 107; |
||||
public const int Imports = 108; |
||||
public const int In = 109; |
||||
public const int Inherits = 110; |
||||
public const int Integer = 111; |
||||
public const int Interface = 112; |
||||
public const int Is = 113; |
||||
public const int Let = 114; |
||||
public const int Lib = 115; |
||||
public const int Like = 116; |
||||
public const int Long = 117; |
||||
public const int Loop = 118; |
||||
public const int Me = 119; |
||||
public const int Mod = 120; |
||||
public const int Module = 121; |
||||
public const int MustInherit = 122; |
||||
public const int MustOverride = 123; |
||||
public const int MyBase = 124; |
||||
public const int MyClass = 125; |
||||
public const int Namespace = 126; |
||||
public const int New = 127; |
||||
public const int Next = 128; |
||||
public const int Not = 129; |
||||
public const int Nothing = 130; |
||||
public const int NotInheritable = 131; |
||||
public const int NotOverridable = 132; |
||||
public const int Object = 133; |
||||
public const int Off = 134; |
||||
public const int On = 135; |
||||
public const int Option = 136; |
||||
public const int Optional = 137; |
||||
public const int Or = 138; |
||||
public const int OrElse = 139; |
||||
public const int Overloads = 140; |
||||
public const int Overridable = 141; |
||||
public const int Overrides = 142; |
||||
public const int ParamArray = 143; |
||||
public const int Preserve = 144; |
||||
public const int Private = 145; |
||||
public const int Property = 146; |
||||
public const int Protected = 147; |
||||
public const int Public = 148; |
||||
public const int RaiseEvent = 149; |
||||
public const int ReadOnly = 150; |
||||
public const int ReDim = 151; |
||||
public const int RemoveHandler = 152; |
||||
public const int Resume = 153; |
||||
public const int Return = 154; |
||||
public const int Select = 155; |
||||
public const int Set = 156; |
||||
public const int Shadows = 157; |
||||
public const int Shared = 158; |
||||
public const int Short = 159; |
||||
public const int Single = 160; |
||||
public const int Static = 161; |
||||
public const int Step = 162; |
||||
public const int Stop = 163; |
||||
public const int Strict = 164; |
||||
public const int String = 165; |
||||
public const int Structure = 166; |
||||
public const int Sub = 167; |
||||
public const int SyncLock = 168; |
||||
public const int Text = 169; |
||||
public const int Then = 170; |
||||
public const int Throw = 171; |
||||
public const int To = 172; |
||||
public const int True = 173; |
||||
public const int Try = 174; |
||||
public const int TypeOf = 175; |
||||
public const int Unicode = 176; |
||||
public const int Until = 177; |
||||
public const int Variant = 178; |
||||
public const int Wend = 179; |
||||
public const int When = 180; |
||||
public const int While = 181; |
||||
public const int With = 182; |
||||
public const int WithEvents = 183; |
||||
public const int WriteOnly = 184; |
||||
public const int Xor = 185; |
||||
public const int Rem = 186; |
||||
public const int Continue = 187; |
||||
public const int Operator = 188; |
||||
public const int Using = 189; |
||||
public const int IsNot = 190; |
||||
public const int SByte = 191; |
||||
public const int UInteger = 192; |
||||
public const int ULong = 193; |
||||
public const int UShort = 194; |
||||
public const int CSByte = 195; |
||||
public const int CUShort = 196; |
||||
public const int CUInt = 197; |
||||
public const int CULng = 198; |
||||
public const int Global = 199; |
||||
public const int TryCast = 200; |
||||
public const int Of = 201; |
||||
public const int Narrowing = 202; |
||||
public const int Widening = 203; |
||||
public const int Partial = 204; |
||||
public const int Custom = 205; |
||||
|
||||
public const int MaxToken = 206; |
||||
static BitArray NewSet(params int[] values) |
||||
{ |
||||
BitArray bitArray = new BitArray(MaxToken); |
||||
foreach (int val in values) { |
||||
bitArray[val] = true; |
||||
} |
||||
return bitArray; |
||||
} |
||||
public static BitArray Null = NewSet(Nothing); |
||||
public static BitArray BlockSucc = NewSet(Case, Catch, Else, ElseIf, End, Finally, Loop, Next); |
||||
public static BitArray IdentifierTokens = NewSet(Text, Binary, Compare, Assembly, Ansi, Auto, Preserve, Unicode, Until, Explicit, Off); |
||||
|
||||
static string[] tokenList = new string[] { |
||||
// ----- terminal classes -----
|
||||
"<EOF>", |
||||
"<EOL>", |
||||
"<Identifier>", |
||||
"<LiteralString>", |
||||
"<LiteralCharacter>", |
||||
"<LiteralInteger>", |
||||
"<LiteralDouble>", |
||||
"<LiteralSingle>", |
||||
"<LiteralDecimal>", |
||||
"<LiteralDate>", |
||||
// ----- special character -----
|
||||
".", |
||||
"=", |
||||
",", |
||||
":", |
||||
"+", |
||||
"-", |
||||
"*", |
||||
"/", |
||||
"\\", |
||||
"&", |
||||
"^", |
||||
"?", |
||||
"{", |
||||
"}", |
||||
"(", |
||||
")", |
||||
">", |
||||
"<", |
||||
"<>", |
||||
">=", |
||||
"<=", |
||||
"<<", |
||||
">>", |
||||
"+=", |
||||
"^=", |
||||
"-=", |
||||
"*=", |
||||
"/=", |
||||
"\\=", |
||||
"<<=", |
||||
">>=", |
||||
"&=", |
||||
// ----- keywords -----
|
||||
"AddHandler", |
||||
"AddressOf", |
||||
"Alias", |
||||
"And", |
||||
"AndAlso", |
||||
"Ansi", |
||||
"As", |
||||
"Assembly", |
||||
"Auto", |
||||
"Binary", |
||||
"Boolean", |
||||
"ByRef", |
||||
"Byte", |
||||
"ByVal", |
||||
"Call", |
||||
"Case", |
||||
"Catch", |
||||
"CBool", |
||||
"CByte", |
||||
"CChar", |
||||
"CDate", |
||||
"CDbl", |
||||
"CDec", |
||||
"Char", |
||||
"CInt", |
||||
"Class", |
||||
"CLng", |
||||
"CObj", |
||||
"Compare", |
||||
"Const", |
||||
"CShort", |
||||
"CSng", |
||||
"CStr", |
||||
"CType", |
||||
"Date", |
||||
"Decimal", |
||||
"Declare", |
||||
"Default", |
||||
"Delegate", |
||||
"Dim", |
||||
"DirectCast", |
||||
"Do", |
||||
"Double", |
||||
"Each", |
||||
"Else", |
||||
"ElseIf", |
||||
"End", |
||||
"EndIf", |
||||
"Enum", |
||||
"Erase", |
||||
"Error", |
||||
"Event", |
||||
"Exit", |
||||
"Explicit", |
||||
"False", |
||||
"Finally", |
||||
"For", |
||||
"Friend", |
||||
"Function", |
||||
"Get", |
||||
"GetType", |
||||
"GoSub", |
||||
"GoTo", |
||||
"Handles", |
||||
"If", |
||||
"Implements", |
||||
"Imports", |
||||
"In", |
||||
"Inherits", |
||||
"Integer", |
||||
"Interface", |
||||
"Is", |
||||
"Let", |
||||
"Lib", |
||||
"Like", |
||||
"Long", |
||||
"Loop", |
||||
"Me", |
||||
"Mod", |
||||
"Module", |
||||
"MustInherit", |
||||
"MustOverride", |
||||
"MyBase", |
||||
"MyClass", |
||||
"Namespace", |
||||
"New", |
||||
"Next", |
||||
"Not", |
||||
"Nothing", |
||||
"NotInheritable", |
||||
"NotOverridable", |
||||
"Object", |
||||
"Off", |
||||
"On", |
||||
"Option", |
||||
"Optional", |
||||
"Or", |
||||
"OrElse", |
||||
"Overloads", |
||||
"Overridable", |
||||
"Overrides", |
||||
"ParamArray", |
||||
"Preserve", |
||||
"Private", |
||||
"Property", |
||||
"Protected", |
||||
"Public", |
||||
"RaiseEvent", |
||||
"ReadOnly", |
||||
"ReDim", |
||||
"RemoveHandler", |
||||
"Resume", |
||||
"Return", |
||||
"Select", |
||||
"Set", |
||||
"Shadows", |
||||
"Shared", |
||||
"Short", |
||||
"Single", |
||||
"Static", |
||||
"Step", |
||||
"Stop", |
||||
"Strict", |
||||
"String", |
||||
"Structure", |
||||
"Sub", |
||||
"SyncLock", |
||||
"Text", |
||||
"Then", |
||||
"Throw", |
||||
"To", |
||||
"True", |
||||
"Try", |
||||
"TypeOf", |
||||
"Unicode", |
||||
"Until", |
||||
"Variant", |
||||
"Wend", |
||||
"When", |
||||
"While", |
||||
"With", |
||||
"WithEvents", |
||||
"WriteOnly", |
||||
"Xor", |
||||
"Rem", |
||||
"Continue", |
||||
"Operator", |
||||
"Using", |
||||
"IsNot", |
||||
"SByte", |
||||
"UInteger", |
||||
"ULong", |
||||
"UShort", |
||||
"CSByte", |
||||
"CUShort", |
||||
"CUInt", |
||||
"CULng", |
||||
"Global", |
||||
"TryCast", |
||||
"Of", |
||||
"Narrowing", |
||||
"Widening", |
||||
"Partial", |
||||
"Custom", |
||||
}; |
||||
public static string GetTokenString(int token) |
||||
{ |
||||
if (token >= 0 && token < tokenList.Length) { |
||||
return tokenList[token]; |
||||
} |
||||
throw new System.NotSupportedException("Unknown token:" + token); |
||||
} |
||||
} |
||||
} |
@ -1,125 +0,0 @@
@@ -1,125 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
|
||||
namespace ICSharpCode.NRefactory |
||||
{ |
||||
/// <summary>
|
||||
/// A line/column position.
|
||||
/// NRefactory lines/columns are counting from one.
|
||||
/// </summary>
|
||||
public struct Location : IComparable<Location>, IEquatable<Location> |
||||
{ |
||||
public static readonly Location Empty = new Location(-1, -1); |
||||
|
||||
public Location(int column, int line) |
||||
{ |
||||
x = column; |
||||
y = line; |
||||
} |
||||
|
||||
int x, y; |
||||
|
||||
public int X { |
||||
get { return x; } |
||||
set { x = value; } |
||||
} |
||||
|
||||
public int Y { |
||||
get { return y; } |
||||
set { y = value; } |
||||
} |
||||
|
||||
public int Line { |
||||
get { return y; } |
||||
set { y = value; } |
||||
} |
||||
|
||||
public int Column { |
||||
get { return x; } |
||||
set { x = value; } |
||||
} |
||||
|
||||
public bool IsEmpty { |
||||
get { |
||||
return x <= 0 && y <= 0; |
||||
} |
||||
} |
||||
|
||||
public override string ToString() |
||||
{ |
||||
return string.Format("(Line {1}, Col {0})", this.x, this.y); |
||||
} |
||||
|
||||
public override int GetHashCode() |
||||
{ |
||||
return unchecked (87 * x.GetHashCode() ^ y.GetHashCode()); |
||||
} |
||||
|
||||
public override bool Equals(object obj) |
||||
{ |
||||
if (!(obj is Location)) return false; |
||||
return (Location)obj == this; |
||||
} |
||||
|
||||
public bool Equals(Location other) |
||||
{ |
||||
return this == other; |
||||
} |
||||
|
||||
public static bool operator ==(Location a, Location b) |
||||
{ |
||||
return a.x == b.x && a.y == b.y; |
||||
} |
||||
|
||||
public static bool operator !=(Location a, Location b) |
||||
{ |
||||
return a.x != b.x || a.y != b.y; |
||||
} |
||||
|
||||
public static bool operator <(Location a, Location b) |
||||
{ |
||||
if (a.y < b.y) |
||||
return true; |
||||
else if (a.y == b.y) |
||||
return a.x < b.x; |
||||
else |
||||
return false; |
||||
} |
||||
|
||||
public static bool operator >(Location a, Location b) |
||||
{ |
||||
if (a.y > b.y) |
||||
return true; |
||||
else if (a.y == b.y) |
||||
return a.x > b.x; |
||||
else |
||||
return false; |
||||
} |
||||
|
||||
public static bool operator <=(Location a, Location b) |
||||
{ |
||||
return !(a > b); |
||||
} |
||||
|
||||
public static bool operator >=(Location a, Location b) |
||||
{ |
||||
return !(a < b); |
||||
} |
||||
|
||||
public int CompareTo(Location other) |
||||
{ |
||||
if (this == other) |
||||
return 0; |
||||
if (this < other) |
||||
return -1; |
||||
else |
||||
return 1; |
||||
} |
||||
} |
||||
} |
@ -1,88 +0,0 @@
@@ -1,88 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision: 2644$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
namespace ICSharpCode.NRefactory |
||||
{ |
||||
/// <summary>
|
||||
/// Stores the operator precedences for the output visitor.
|
||||
/// </summary>
|
||||
static class OperatorPrecedence |
||||
{ |
||||
static readonly Dictionary<BinaryOperatorType, int> vbDict = MakePrecedenceTable( |
||||
new BinaryOperatorType[] { BinaryOperatorType.Power }, |
||||
new BinaryOperatorType[] { BinaryOperatorType.Multiply, BinaryOperatorType.Divide }, |
||||
new BinaryOperatorType[] { BinaryOperatorType.DivideInteger }, |
||||
new BinaryOperatorType[] { BinaryOperatorType.Modulus }, |
||||
new BinaryOperatorType[] { BinaryOperatorType.Add, BinaryOperatorType.Subtract }, |
||||
new BinaryOperatorType[] { BinaryOperatorType.Concat }, |
||||
new BinaryOperatorType[] { BinaryOperatorType.ShiftLeft, BinaryOperatorType.ShiftRight }, |
||||
new BinaryOperatorType[] { |
||||
BinaryOperatorType.Equality, BinaryOperatorType.InEquality, |
||||
BinaryOperatorType.LessThan, BinaryOperatorType.LessThanOrEqual, |
||||
BinaryOperatorType.GreaterThan, BinaryOperatorType.GreaterThanOrEqual, |
||||
BinaryOperatorType.ReferenceEquality, BinaryOperatorType.ReferenceInequality, |
||||
BinaryOperatorType.Like |
||||
}, |
||||
new BinaryOperatorType[] { BinaryOperatorType.LogicalAnd, BinaryOperatorType.BitwiseAnd }, |
||||
new BinaryOperatorType[] { BinaryOperatorType.LogicalOr, BinaryOperatorType.BitwiseOr }, |
||||
new BinaryOperatorType[] { BinaryOperatorType.ExclusiveOr } |
||||
); |
||||
|
||||
static readonly Dictionary<BinaryOperatorType, int> csharpDict = MakePrecedenceTable( |
||||
new BinaryOperatorType[] { BinaryOperatorType.Multiply, BinaryOperatorType.Divide, BinaryOperatorType.Modulus }, |
||||
new BinaryOperatorType[] { BinaryOperatorType.Add, BinaryOperatorType.Subtract }, |
||||
new BinaryOperatorType[] { BinaryOperatorType.ShiftLeft, BinaryOperatorType.ShiftRight }, |
||||
new BinaryOperatorType[] { |
||||
BinaryOperatorType.LessThan, BinaryOperatorType.LessThanOrEqual, |
||||
BinaryOperatorType.GreaterThan, BinaryOperatorType.GreaterThanOrEqual, |
||||
}, |
||||
new BinaryOperatorType[] { BinaryOperatorType.Equality, BinaryOperatorType.InEquality }, |
||||
new BinaryOperatorType[] { BinaryOperatorType.BitwiseAnd }, |
||||
new BinaryOperatorType[] { BinaryOperatorType.ExclusiveOr }, |
||||
new BinaryOperatorType[] { BinaryOperatorType.BitwiseOr }, |
||||
new BinaryOperatorType[] { BinaryOperatorType.LogicalAnd, BinaryOperatorType.LogicalOr }, |
||||
new BinaryOperatorType[] { BinaryOperatorType.NullCoalescing } |
||||
); |
||||
|
||||
// create a dictionary operator->precedence (higher value = higher precedence)
|
||||
static Dictionary<BinaryOperatorType, int> MakePrecedenceTable(params BinaryOperatorType[][] input) |
||||
{ |
||||
Dictionary<BinaryOperatorType, int> dict = new Dictionary<BinaryOperatorType, int>(); |
||||
for (int i = 0; i < input.Length; i++) { |
||||
foreach (BinaryOperatorType op in input[i]) { |
||||
dict.Add(op, input.Length - i); |
||||
} |
||||
} |
||||
return dict; |
||||
} |
||||
|
||||
public static int ComparePrecedenceVB(BinaryOperatorType op1, BinaryOperatorType op2) |
||||
{ |
||||
int p1 = GetOperatorPrecedence(vbDict, op1); |
||||
int p2 = GetOperatorPrecedence(vbDict, op2); |
||||
return p1.CompareTo(p2); |
||||
} |
||||
|
||||
public static int ComparePrecedenceCSharp(BinaryOperatorType op1, BinaryOperatorType op2) |
||||
{ |
||||
int p1 = GetOperatorPrecedence(vbDict, op1); |
||||
int p2 = GetOperatorPrecedence(vbDict, op2); |
||||
return p1.CompareTo(p2); |
||||
} |
||||
|
||||
static int GetOperatorPrecedence(Dictionary<BinaryOperatorType, int> dict, BinaryOperatorType op) |
||||
{ |
||||
int p; |
||||
dict.TryGetValue(op, out p); |
||||
return p; |
||||
} |
||||
} |
||||
} |
@ -1,109 +0,0 @@
@@ -1,109 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser |
||||
{ |
||||
public abstract class AbstractParser : IParser |
||||
{ |
||||
protected const int MinErrDist = 2; |
||||
protected const string ErrMsgFormat = "-- line {0} col {1}: {2}"; // 0=line, 1=column, 2=text
|
||||
|
||||
|
||||
private Errors errors; |
||||
private ILexer lexer; |
||||
|
||||
protected int errDist = MinErrDist; |
||||
|
||||
[CLSCompliant(false)] |
||||
protected CompilationUnit compilationUnit; |
||||
|
||||
bool parseMethodContents = true; |
||||
|
||||
public bool ParseMethodBodies { |
||||
get { |
||||
return parseMethodContents; |
||||
} |
||||
set { |
||||
parseMethodContents = value; |
||||
} |
||||
} |
||||
|
||||
public ILexer Lexer { |
||||
get { |
||||
return lexer; |
||||
} |
||||
} |
||||
|
||||
public Errors Errors { |
||||
get { |
||||
return errors; |
||||
} |
||||
} |
||||
|
||||
public CompilationUnit CompilationUnit { |
||||
get { |
||||
return compilationUnit; |
||||
} |
||||
} |
||||
|
||||
internal AbstractParser(ILexer lexer) |
||||
{ |
||||
this.errors = lexer.Errors; |
||||
this.lexer = lexer; |
||||
errors.SynErr = new ErrorCodeProc(SynErr); |
||||
} |
||||
|
||||
public abstract void Parse(); |
||||
|
||||
public abstract Expression ParseExpression(); |
||||
public abstract BlockStatement ParseBlock(); |
||||
public abstract IList<INode> ParseTypeMembers(); |
||||
|
||||
protected abstract void SynErr(int line, int col, int errorNumber); |
||||
|
||||
protected void SynErr(int n) |
||||
{ |
||||
if (errDist >= MinErrDist) { |
||||
errors.SynErr(lexer.LookAhead.line, lexer.LookAhead.col, n); |
||||
} |
||||
errDist = 0; |
||||
} |
||||
|
||||
protected void SemErr(string msg) |
||||
{ |
||||
if (errDist >= MinErrDist) { |
||||
errors.Error(lexer.Token.line, lexer.Token.col, msg); |
||||
} |
||||
errDist = 0; |
||||
} |
||||
|
||||
protected void Expect(int n) |
||||
{ |
||||
if (lexer.LookAhead.kind == n) { |
||||
lexer.NextToken(); |
||||
} else { |
||||
SynErr(n); |
||||
} |
||||
} |
||||
|
||||
#region System.IDisposable interface implementation
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly")] |
||||
public void Dispose() |
||||
{ |
||||
errors = null; |
||||
if (lexer != null) { |
||||
lexer.Dispose(); |
||||
} |
||||
lexer = null; |
||||
} |
||||
#endregion
|
||||
} |
||||
} |
@ -1,598 +0,0 @@
@@ -1,598 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using System.Text; |
||||
using System.Diagnostics; |
||||
|
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser.CSharp |
||||
{ |
||||
internal sealed partial class Parser : AbstractParser |
||||
{ |
||||
Lexer lexer; |
||||
|
||||
public Parser(ILexer lexer) : base(lexer) |
||||
{ |
||||
this.lexer = (Lexer)lexer; |
||||
// due to anonymous methods, we always need a compilation unit, so
|
||||
// create it in the constructor
|
||||
compilationUnit = new CompilationUnit(); |
||||
} |
||||
|
||||
StringBuilder qualidentBuilder = new StringBuilder(); |
||||
|
||||
Token t { |
||||
[System.Diagnostics.DebuggerStepThrough] |
||||
get { |
||||
return lexer.Token; |
||||
} |
||||
} |
||||
|
||||
Token la { |
||||
[System.Diagnostics.DebuggerStepThrough] |
||||
get { |
||||
return lexer.LookAhead; |
||||
} |
||||
} |
||||
|
||||
public void Error(string s) |
||||
{ |
||||
if (errDist >= MinErrDist) { |
||||
this.Errors.Error(la.line, la.col, s); |
||||
} |
||||
errDist = 0; |
||||
} |
||||
|
||||
public override Expression ParseExpression() |
||||
{ |
||||
lexer.NextToken(); |
||||
Expression expr; |
||||
Expr(out expr); |
||||
// SEMICOLON HACK : without a trailing semicolon, parsing expressions does not work correctly
|
||||
if (la.kind == Tokens.Semicolon) lexer.NextToken(); |
||||
Expect(Tokens.EOF); |
||||
return expr; |
||||
} |
||||
|
||||
public override BlockStatement ParseBlock() |
||||
{ |
||||
lexer.NextToken(); |
||||
compilationUnit = new CompilationUnit(); |
||||
|
||||
BlockStatement blockStmt = new BlockStatement(); |
||||
blockStmt.StartLocation = la.Location; |
||||
compilationUnit.BlockStart(blockStmt); |
||||
|
||||
while (la.kind != Tokens.EOF) { |
||||
Token oldLa = la; |
||||
Statement(); |
||||
if (la == oldLa) { |
||||
// did not advance lexer position, we cannot parse this as a statement block
|
||||
return null; |
||||
} |
||||
} |
||||
|
||||
compilationUnit.BlockEnd(); |
||||
Expect(Tokens.EOF); |
||||
return blockStmt; |
||||
} |
||||
|
||||
public override IList<INode> ParseTypeMembers() |
||||
{ |
||||
lexer.NextToken(); |
||||
compilationUnit = new CompilationUnit(); |
||||
|
||||
TypeDeclaration newType = new TypeDeclaration(Modifiers.None, null); |
||||
compilationUnit.BlockStart(newType); |
||||
ClassBody(); |
||||
compilationUnit.BlockEnd(); |
||||
Expect(Tokens.EOF); |
||||
return newType.Children; |
||||
} |
||||
|
||||
// Begin ISTypeCast
|
||||
bool IsTypeCast() |
||||
{ |
||||
if (la.kind != Tokens.OpenParenthesis) { |
||||
return false; |
||||
} |
||||
if (IsSimpleTypeCast()) { |
||||
return true; |
||||
} |
||||
return GuessTypeCast(); |
||||
} |
||||
|
||||
// "(" ( typeKW [ "[" {","} "]" | "*" ] | void ( "[" {","} "]" | "*" ) ) ")"
|
||||
// only for built-in types, all others use GuessTypeCast!
|
||||
bool IsSimpleTypeCast () |
||||
{ |
||||
// assert: la.kind == _lpar
|
||||
lexer.StartPeek(); |
||||
Token pt = lexer.Peek(); |
||||
|
||||
if (!IsTypeKWForTypeCast(ref pt)) { |
||||
return false; |
||||
} |
||||
if (pt.kind == Tokens.Question) // TODO: check if IsTypeKWForTypeCast doesn't already to this
|
||||
pt = lexer.Peek(); |
||||
return pt.kind == Tokens.CloseParenthesis; |
||||
} |
||||
|
||||
/* !!! Proceeds from current peek position !!! */ |
||||
bool IsTypeKWForTypeCast(ref Token pt) |
||||
{ |
||||
if (Tokens.TypeKW[pt.kind]) { |
||||
pt = lexer.Peek(); |
||||
return IsPointerOrDims(ref pt) && SkipQuestionMark(ref pt); |
||||
} else if (pt.kind == Tokens.Void) { |
||||
pt = lexer.Peek(); |
||||
return IsPointerOrDims(ref pt); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/* !!! Proceeds from current peek position !!! */ |
||||
bool IsTypeNameOrKWForTypeCast(ref Token pt) |
||||
{ |
||||
if (Tokens.TypeKW[pt.kind] || pt.kind == Tokens.Void) |
||||
return IsTypeKWForTypeCast(ref pt); |
||||
else |
||||
return IsTypeNameForTypeCast(ref pt); |
||||
} |
||||
|
||||
// TypeName = ident [ "::" ident ] { ["<" TypeNameOrKW { "," TypeNameOrKW } ">" ] "." ident } ["?"] PointerOrDims
|
||||
/* !!! Proceeds from current peek position !!! */ |
||||
bool IsTypeNameForTypeCast(ref Token pt) |
||||
{ |
||||
// ident
|
||||
if (!IsIdentifierToken(pt)) { |
||||
return false; |
||||
} |
||||
pt = Peek(); |
||||
// "::" ident
|
||||
if (pt.kind == Tokens.DoubleColon) { |
||||
pt = Peek(); |
||||
if (!IsIdentifierToken(pt)) { |
||||
return false; |
||||
} |
||||
pt = Peek(); |
||||
} |
||||
// { ["<" TypeNameOrKW { "," TypeNameOrKW } ">" ] "." ident }
|
||||
while (true) { |
||||
if (pt.kind == Tokens.LessThan) { |
||||
do { |
||||
pt = Peek(); |
||||
if (!IsTypeNameOrKWForTypeCast(ref pt)) { |
||||
return false; |
||||
} |
||||
} while (pt.kind == Tokens.Comma); |
||||
if (pt.kind != Tokens.GreaterThan) { |
||||
return false; |
||||
} |
||||
pt = Peek(); |
||||
} |
||||
if (pt.kind != Tokens.Dot) |
||||
break; |
||||
pt = Peek(); |
||||
if (pt.kind != Tokens.Identifier) { |
||||
return false; |
||||
} |
||||
pt = Peek(); |
||||
} |
||||
// ["?"]
|
||||
if (pt.kind == Tokens.Question) { |
||||
pt = Peek(); |
||||
} |
||||
if (pt.kind == Tokens.Times || pt.kind == Tokens.OpenSquareBracket) { |
||||
return IsPointerOrDims(ref pt); |
||||
} |
||||
return true; |
||||
} |
||||
|
||||
// "(" TypeName ")" castFollower
|
||||
bool GuessTypeCast () |
||||
{ |
||||
// assert: la.kind == _lpar
|
||||
StartPeek(); |
||||
Token pt = Peek(); |
||||
|
||||
if (!IsTypeNameForTypeCast(ref pt)) { |
||||
return false; |
||||
} |
||||
|
||||
// ")"
|
||||
if (pt.kind != Tokens.CloseParenthesis) { |
||||
return false; |
||||
} |
||||
// check successor
|
||||
pt = Peek(); |
||||
return Tokens.CastFollower[pt.kind]; |
||||
} |
||||
// END IsTypeCast
|
||||
|
||||
// Gets if the token is a possible token for an expression start
|
||||
// Is used to determine if "a is Type ? token" a the start of a ternary
|
||||
// expression or a type test for Nullable<Type>
|
||||
bool IsPossibleExpressionStart(int token) |
||||
{ |
||||
return Tokens.CastFollower[token] || Tokens.UnaryOp[token]; |
||||
} |
||||
|
||||
// ( { [TypeNameOrKWForTypeCast] ident "," } )
|
||||
bool IsLambdaExpression() |
||||
{ |
||||
if (la.kind != Tokens.OpenParenthesis) { |
||||
return false; |
||||
} |
||||
StartPeek(); |
||||
Token pt = Peek(); |
||||
while (pt.kind != Tokens.CloseParenthesis) { |
||||
if (!IsTypeNameOrKWForTypeCast(ref pt)) { |
||||
return false; |
||||
} |
||||
if (IsIdentifierToken(pt)) { |
||||
// make ident optional: if implicitly typed lambda arguments are used, IsTypeNameForTypeCast
|
||||
// has already accepted the identifier
|
||||
pt = Peek(); |
||||
} |
||||
if (pt.kind == Tokens.CloseParenthesis) { |
||||
break; |
||||
} |
||||
// require comma between parameters:
|
||||
if (pt.kind == Tokens.Comma) { |
||||
pt = Peek(); |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
pt = Peek(); |
||||
return pt.kind == Tokens.LambdaArrow; |
||||
} |
||||
|
||||
/* Checks whether the next sequences of tokens is a qualident * |
||||
* and returns the qualident string */ |
||||
/* !!! Proceeds from current peek position !!! */ |
||||
bool IsQualident(ref Token pt, out string qualident) |
||||
{ |
||||
if (IsIdentifierToken(pt)) { |
||||
qualidentBuilder.Length = 0; qualidentBuilder.Append(pt.val); |
||||
pt = Peek(); |
||||
while (pt.kind == Tokens.Dot || pt.kind == Tokens.DoubleColon) { |
||||
pt = Peek(); |
||||
if (!IsIdentifierToken(pt)) { |
||||
qualident = String.Empty; |
||||
return false; |
||||
} |
||||
qualidentBuilder.Append('.'); |
||||
qualidentBuilder.Append(pt.val); |
||||
pt = Peek(); |
||||
} |
||||
qualident = qualidentBuilder.ToString(); |
||||
return true; |
||||
} |
||||
qualident = String.Empty; |
||||
return false; |
||||
} |
||||
|
||||
/* Skips generic type extensions */ |
||||
/* !!! Proceeds from current peek position !!! */ |
||||
|
||||
/* skip: { "*" | "[" { "," } "]" } */ |
||||
/* !!! Proceeds from current peek position !!! */ |
||||
bool IsPointerOrDims (ref Token pt) |
||||
{ |
||||
for (;;) { |
||||
if (pt.kind == Tokens.OpenSquareBracket) { |
||||
do pt = Peek(); |
||||
while (pt.kind == Tokens.Comma); |
||||
if (pt.kind != Tokens.CloseSquareBracket) return false; |
||||
} else if (pt.kind != Tokens.Times) break; |
||||
pt = Peek(); |
||||
} |
||||
return true; |
||||
} |
||||
|
||||
/* Return the n-th token after the current lookahead token */ |
||||
void StartPeek() |
||||
{ |
||||
lexer.StartPeek(); |
||||
} |
||||
|
||||
Token Peek() |
||||
{ |
||||
return lexer.Peek(); |
||||
} |
||||
|
||||
Token Peek (int n) |
||||
{ |
||||
lexer.StartPeek(); |
||||
Token x = la; |
||||
while (n > 0) { |
||||
x = lexer.Peek(); |
||||
n--; |
||||
} |
||||
return x; |
||||
} |
||||
|
||||
/*-----------------------------------------------------------------* |
||||
* Resolver routines to resolve LL(1) conflicts: * * |
||||
* These resolution routine return a boolean value that indicates * |
||||
* whether the alternative at hand shall be choosen or not. * |
||||
* They are used in IF ( ... ) expressions. * |
||||
*-----------------------------------------------------------------*/ |
||||
|
||||
/* True, if ident is followed by "=" */ |
||||
bool IdentAndAsgn () |
||||
{ |
||||
return IsIdentifierToken(la) && Peek(1).kind == Tokens.Assign; |
||||
} |
||||
|
||||
bool IdentAndDoubleColon () |
||||
{ |
||||
return IsIdentifierToken(la) && Peek(1).kind == Tokens.DoubleColon; |
||||
} |
||||
|
||||
bool IsAssignment () { return IdentAndAsgn(); } |
||||
|
||||
/* True, if ident is followed by ",", "=", "[" or ";" */ |
||||
bool IsVarDecl () { |
||||
int peek = Peek(1).kind; |
||||
return IsIdentifierToken(la) && |
||||
(peek == Tokens.Comma || peek == Tokens.Assign || peek == Tokens.Semicolon || peek == Tokens.OpenSquareBracket); |
||||
} |
||||
|
||||
/* True, if the comma is not a trailing one, * |
||||
* like the last one in: a, b, c, */ |
||||
bool NotFinalComma () { |
||||
int peek = Peek(1).kind; |
||||
return la.kind == Tokens.Comma && |
||||
peek != Tokens.CloseCurlyBrace && peek != Tokens.CloseSquareBracket; |
||||
} |
||||
|
||||
/* True, if "void" is followed by "*" */ |
||||
bool NotVoidPointer () { |
||||
return la.kind == Tokens.Void && Peek(1).kind != Tokens.Times; |
||||
} |
||||
|
||||
/* True, if "checked" or "unchecked" are followed by "{" */ |
||||
bool UnCheckedAndLBrace () { |
||||
return la.kind == Tokens.Checked || la.kind == Tokens.Unchecked && |
||||
Peek(1).kind == Tokens.OpenCurlyBrace; |
||||
} |
||||
|
||||
/* True, if "." is followed by an ident */ |
||||
bool DotAndIdent () { |
||||
return la.kind == Tokens.Dot && IsIdentifierToken(Peek(1)); |
||||
} |
||||
|
||||
/* True, if ident is followed by ":" */ |
||||
bool IdentAndColon () { |
||||
return IsIdentifierToken(la) && Peek(1).kind == Tokens.Colon; |
||||
} |
||||
|
||||
bool IsLabel () { return IdentAndColon(); } |
||||
|
||||
/* True, if ident is followed by "(" */ |
||||
bool IdentAndLPar () { |
||||
return IsIdentifierToken(la) && Peek(1).kind == Tokens.OpenParenthesis; |
||||
} |
||||
|
||||
/* True, if "catch" is followed by "(" */ |
||||
bool CatchAndLPar () { |
||||
return la.kind == Tokens.Catch && Peek(1).kind == Tokens.OpenParenthesis; |
||||
} |
||||
bool IsTypedCatch () { return CatchAndLPar(); } |
||||
|
||||
/* True, if "[" is followed by the ident "assembly" */ |
||||
bool IsGlobalAttrTarget () { |
||||
Token pt = Peek(1); |
||||
return la.kind == Tokens.OpenSquareBracket && |
||||
IsIdentifierToken(pt) && (pt.val == "assembly" || pt.val == "module"); |
||||
} |
||||
|
||||
/* True, if "[" is followed by "," or "]" */ |
||||
bool LBrackAndCommaOrRBrack () { |
||||
int peek = Peek(1).kind; |
||||
return la.kind == Tokens.OpenSquareBracket && |
||||
(peek == Tokens.Comma || peek == Tokens.CloseSquareBracket); |
||||
} |
||||
|
||||
/* True, if "[" is followed by "," or "]" */ |
||||
/* or if the current token is "*" */ |
||||
bool TimesOrLBrackAndCommaOrRBrack () { |
||||
return la.kind == Tokens.Times || LBrackAndCommaOrRBrack(); |
||||
} |
||||
bool IsPointerOrDims () { return TimesOrLBrackAndCommaOrRBrack(); } |
||||
bool IsPointer () { return la.kind == Tokens.Times; } |
||||
|
||||
|
||||
bool SkipGeneric(ref Token pt) |
||||
{ |
||||
if (pt.kind == Tokens.LessThan) { |
||||
do { |
||||
pt = Peek(); |
||||
if (!IsTypeNameOrKWForTypeCast(ref pt)) return false; |
||||
} while (pt.kind == Tokens.Comma); |
||||
if (pt.kind != Tokens.GreaterThan) return false; |
||||
pt = Peek(); |
||||
} |
||||
return true; |
||||
} |
||||
bool SkipQuestionMark(ref Token pt) |
||||
{ |
||||
if (pt.kind == Tokens.Question) { |
||||
pt = Peek(); |
||||
} |
||||
return true; |
||||
} |
||||
|
||||
/* True, if lookahead is a primitive type keyword, or */ |
||||
/* if it is a type declaration followed by an ident */ |
||||
bool IsLocalVarDecl () { |
||||
if (IsYieldStatement()) { |
||||
return false; |
||||
} |
||||
if ((Tokens.TypeKW[la.kind] && Peek(1).kind != Tokens.Dot) || la.kind == Tokens.Void) { |
||||
return true; |
||||
} |
||||
|
||||
StartPeek(); |
||||
Token pt = la; |
||||
return IsTypeNameOrKWForTypeCast(ref pt) && IsIdentifierToken(pt); |
||||
} |
||||
|
||||
/* True if lookahead is a type argument list (<...>) followed by |
||||
* one of "( ) ] } : ; , . ? == !=" */ |
||||
bool IsGenericInSimpleNameOrMemberAccess() |
||||
{ |
||||
Token t = la; |
||||
if (t.kind != Tokens.LessThan) return false; |
||||
StartPeek(); |
||||
return SkipGeneric(ref t) && Tokens.GenericFollower[t.kind]; |
||||
} |
||||
|
||||
bool IsExplicitInterfaceImplementation() |
||||
{ |
||||
StartPeek(); |
||||
Token pt = la; |
||||
pt = Peek(); |
||||
if (pt.kind == Tokens.Dot || pt.kind == Tokens.DoubleColon) |
||||
return true; |
||||
if (pt.kind == Tokens.LessThan) { |
||||
if (SkipGeneric(ref pt)) |
||||
return pt.kind == Tokens.Dot; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
/* True, if lookahead ident is "yield" and than follows a break or return */ |
||||
bool IsYieldStatement () { |
||||
return la.kind == Tokens.Yield && (Peek(1).kind == Tokens.Return || Peek(1).kind == Tokens.Break); |
||||
} |
||||
|
||||
/* True, if lookahead is a local attribute target specifier, * |
||||
* i.e. one of "event", "return", "field", "method", * |
||||
* "module", "param", "property", or "type" */ |
||||
bool IsLocalAttrTarget () { |
||||
int cur = la.kind; |
||||
string val = la.val; |
||||
|
||||
return (cur == Tokens.Event || cur == Tokens.Return || |
||||
(Tokens.IdentifierTokens[cur] && |
||||
(val == "field" || val == "method" || val == "module" || |
||||
val == "param" || val == "property" || val == "type"))) && |
||||
Peek(1).kind == Tokens.Colon; |
||||
} |
||||
|
||||
bool IsShiftRight() |
||||
{ |
||||
Token next = Peek(1); |
||||
// TODO : Add col test (seems not to work, lexer bug...) : && la.col == next.col - 1
|
||||
return (la.kind == Tokens.GreaterThan && next.kind == Tokens.GreaterThan); |
||||
} |
||||
|
||||
bool IsGenericExpression(Expression expr) |
||||
{ |
||||
if (expr is IdentifierExpression) |
||||
return ((IdentifierExpression)expr).TypeArguments.Count > 0; |
||||
else if (expr is MemberReferenceExpression) |
||||
return ((MemberReferenceExpression)expr).TypeArguments.Count > 0; |
||||
else |
||||
return false; |
||||
} |
||||
|
||||
bool ShouldConvertTargetExpressionToTypeReference(Expression targetExpr) |
||||
{ |
||||
if (targetExpr is IdentifierExpression) |
||||
return ((IdentifierExpression)targetExpr).TypeArguments.Count > 0; |
||||
else if (targetExpr is MemberReferenceExpression) |
||||
return ((MemberReferenceExpression)targetExpr).TypeArguments.Count > 0; |
||||
else |
||||
return false; |
||||
} |
||||
|
||||
TypeReference GetTypeReferenceFromExpression(Expression expr) |
||||
{ |
||||
if (expr is TypeReferenceExpression) |
||||
return (expr as TypeReferenceExpression).TypeReference; |
||||
|
||||
IdentifierExpression ident = expr as IdentifierExpression; |
||||
if (ident != null) { |
||||
return new TypeReference(ident.Identifier, ident.TypeArguments); |
||||
} |
||||
|
||||
MemberReferenceExpression member = expr as MemberReferenceExpression; |
||||
if (member != null) { |
||||
TypeReference targetType = GetTypeReferenceFromExpression(member.TargetObject); |
||||
if (targetType != null) { |
||||
if (targetType.GenericTypes.Count == 0 && targetType.IsArrayType == false) { |
||||
TypeReference tr = new TypeReference(targetType.Type + "." + member.MemberName, member.TypeArguments); |
||||
tr.IsGlobal = targetType.IsGlobal; |
||||
return tr; |
||||
} else { |
||||
return new InnerClassTypeReference(targetType, member.MemberName, member.TypeArguments); |
||||
} |
||||
} |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
bool IsMostNegativeIntegerWithoutTypeSuffix() |
||||
{ |
||||
Token token = la; |
||||
if (token.kind == Tokens.Literal) { |
||||
return token.val == "2147483648" || token.val == "9223372036854775808"; |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
bool LastExpressionIsUnaryMinus(System.Collections.ArrayList expressions) |
||||
{ |
||||
if (expressions.Count == 0) return false; |
||||
UnaryOperatorExpression uoe = expressions[expressions.Count - 1] as UnaryOperatorExpression; |
||||
if (uoe != null) { |
||||
return uoe.Op == UnaryOperatorType.Minus; |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
bool StartOfQueryExpression() |
||||
{ |
||||
if (la.kind == Tokens.From) { |
||||
Token p = Peek(1); |
||||
if (IsIdentifierToken(p) || Tokens.TypeKW[p.kind]) |
||||
return true; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
static bool IsIdentifierToken(Token tk) |
||||
{ |
||||
return Tokens.IdentifierTokens[tk.kind]; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Adds a child item to a collection stored in the parent node.
|
||||
/// Also set's the item's parent to <paramref name="parent"/>.
|
||||
/// Does nothing if item is null.
|
||||
/// </summary>
|
||||
static void SafeAdd<T>(INode parent, List<T> list, T item) where T : class, INode |
||||
{ |
||||
Debug.Assert(parent != null); |
||||
Debug.Assert((parent is INullable) ? !(parent as INullable).IsNull : true); |
||||
if (item != null) { |
||||
list.Add(item); |
||||
item.Parent = parent; |
||||
} |
||||
} |
||||
} |
||||
} |
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,60 +0,0 @@
@@ -1,60 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="none" email=""/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Text; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser |
||||
{ |
||||
public delegate void ErrorCodeProc(int line, int col, int n); |
||||
public delegate void ErrorMsgProc(int line, int col, string msg); |
||||
|
||||
public class Errors |
||||
{ |
||||
int count = 0; // number of errors detected
|
||||
public ErrorCodeProc SynErr; |
||||
public ErrorCodeProc SemErr; |
||||
public ErrorMsgProc Error; |
||||
StringBuilder errorText = new StringBuilder(); |
||||
|
||||
public string ErrorOutput { |
||||
get { |
||||
return errorText.ToString(); |
||||
} |
||||
} |
||||
|
||||
public Errors() |
||||
{ |
||||
SynErr = new ErrorCodeProc(DefaultCodeError); // syntactic errors
|
||||
SemErr = new ErrorCodeProc(DefaultCodeError); // semantic errors
|
||||
Error = new ErrorMsgProc(DefaultMsgError); // user defined string based errors
|
||||
} |
||||
|
||||
public int Count { |
||||
get { |
||||
return count; |
||||
} |
||||
} |
||||
|
||||
// public void Exception (string s)
|
||||
// {
|
||||
// Console.WriteLine(s);
|
||||
// System.Environment.Exit(0);
|
||||
// }
|
||||
|
||||
void DefaultCodeError(int line, int col, int n) |
||||
{ |
||||
errorText.AppendLine(String.Format("-- line {0} col {1}: error {2}", line, col, n)); |
||||
count++; |
||||
} |
||||
|
||||
void DefaultMsgError(int line, int col, string s) { |
||||
errorText.AppendLine(String.Format("-- line {0} col {1}: {2}", line, col, s)); |
||||
count++; |
||||
} |
||||
} // Errors
|
||||
} |
@ -1,50 +0,0 @@
@@ -1,50 +0,0 @@
|
||||
/* |
||||
Parser.frame file for NRefactory. |
||||
*/ |
||||
using System; |
||||
using System.Reflection; |
||||
|
||||
-->namespace |
||||
|
||||
-->tokens |
||||
|
||||
partial class Parser : AbstractParser |
||||
{ |
||||
-->constants |
||||
const bool T = true; |
||||
const bool x = false; |
||||
|
||||
-->declarations |
||||
|
||||
/* |
||||
-->pragmas |
||||
*/ |
||||
|
||||
-->productions |
||||
|
||||
public override void Parse() |
||||
{ |
||||
-->parseRoot |
||||
} |
||||
|
||||
protected override void SynErr(int line, int col, int errorNumber) |
||||
{ |
||||
string s; |
||||
switch (errorNumber) { |
||||
-->errors |
||||
default: s = "error " + errorNumber; break; |
||||
} |
||||
this.Errors.Error(line, col, s); |
||||
} |
||||
|
||||
private bool StartOf(int s) |
||||
{ |
||||
return set[s, lexer.LookAhead.kind]; |
||||
} |
||||
|
||||
static bool[,] set = { |
||||
-->initialization |
||||
}; |
||||
} // end Parser |
||||
|
||||
$$$ |
@ -1,202 +0,0 @@
@@ -1,202 +0,0 @@
|
||||
/*---------------------------------------------------------------------- |
||||
Compiler Generator Coco/R, |
||||
Copyright (c) 1990, 2004 Hanspeter Moessenboeck, University of Linz |
||||
extended by M. Loeberbauer & A. Woess, Univ. of Linz |
||||
with improvements by Pat Terry, Rhodes University |
||||
|
||||
This program is free software; you can redistribute it and/or modify it |
||||
under the terms of the GNU General Public License as published by the |
||||
Free Software Foundation; either version 2, or (at your option) any |
||||
later version. |
||||
|
||||
This program is distributed in the hope that it will be useful, but |
||||
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY |
||||
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
||||
for more details. |
||||
|
||||
You should have received a copy of the GNU General Public License along |
||||
with this program; if not, write to the Free Software Foundation, Inc., |
||||
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
||||
|
||||
As an exception, it is allowed to write an extension of Coco/R that is |
||||
used as a plugin in non-free software. |
||||
|
||||
If not otherwise stated, any source code generated by Coco/R (other than |
||||
Coco/R itself) does not fall under the GNU General Public License. |
||||
-----------------------------------------------------------------------*/ |
||||
-->begin |
||||
using System; |
||||
using System.IO; |
||||
using System.Collections; |
||||
using System.Text; |
||||
|
||||
-->namespace |
||||
|
||||
public class Token { |
||||
public int kind; // token kind |
||||
public int pos; // token position in the source text (starting at 0) |
||||
public int col; // token column (starting at 0) |
||||
public int line; // token line (starting at 1) |
||||
public string val; // token value |
||||
public Token next; // AW 2003-03-07 Tokens are kept in linked list |
||||
} |
||||
|
||||
public class Buffer { |
||||
public const char EOF = (char)256; |
||||
static byte[] buf; |
||||
static int bufLen; |
||||
static int pos; |
||||
// CHANGES by M.KRUEGER |
||||
public static int CountLines(int offset) |
||||
{ |
||||
int line = 0; |
||||
for (int i = 0; i <= offset; ++i) { |
||||
if (buf[i] == '\n') { |
||||
++line; |
||||
} |
||||
} |
||||
return line; |
||||
} |
||||
//EOC |
||||
public static void Fill (Stream s) { |
||||
bufLen = (int) s.Length; |
||||
buf = new byte[bufLen]; |
||||
s.Read(buf, 0, bufLen); |
||||
pos = 0; |
||||
} |
||||
|
||||
public static int Read () { |
||||
if (pos < bufLen) return buf[pos++]; |
||||
else return EOF; /* pdt */ |
||||
} |
||||
|
||||
public static int Peek () { |
||||
if (pos < bufLen) return buf[pos]; |
||||
else return EOF; /* pdt */ |
||||
} |
||||
|
||||
/* AW 2003-03-10 moved this from ParserGen.cs */ |
||||
public static string GetString (int beg, int end) { |
||||
StringBuilder s = new StringBuilder(64); |
||||
int oldPos = Buffer.Pos; |
||||
Buffer.Pos = beg; |
||||
while (beg < end) { s.Append((char)Buffer.Read()); beg++; } |
||||
Buffer.Pos = oldPos; |
||||
return s.ToString(); |
||||
} |
||||
|
||||
public static int Pos { |
||||
get { return pos; } |
||||
set { |
||||
if (value < 0) pos = 0; |
||||
else if (value >= bufLen) pos = bufLen; |
||||
else pos = value; |
||||
} |
||||
} |
||||
} |
||||
|
||||
public class Scanner { |
||||
const char EOL = '\n'; |
||||
const int eofSym = 0; /* pdt */ |
||||
-->declarations |
||||
|
||||
static Token t; // current token |
||||
static char ch; // current input character |
||||
static int pos; // column number of current character |
||||
static int line; // line number of current character |
||||
static int lineStart; // start position of current line |
||||
static int oldEols; // EOLs that appeared in a comment; |
||||
static BitArray ignore; // set of characters to be ignored by the scanner |
||||
|
||||
static Token tokens; // the complete input token stream |
||||
static Token pt; // current peek token |
||||
|
||||
public static void Init (string fileName) { |
||||
FileStream s = null; |
||||
try { |
||||
s = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); |
||||
Init(s); |
||||
} catch (IOException) { |
||||
Console.WriteLine("--- Cannot open file {0}", fileName); |
||||
System.Environment.Exit(1); |
||||
} finally { |
||||
if (s != null) s.Close(); |
||||
} |
||||
} |
||||
|
||||
public static void Init (Stream s) { |
||||
Buffer.Fill(s); |
||||
pos = -1; line = 1; lineStart = 0; |
||||
oldEols = 0; |
||||
NextCh(); |
||||
-->initialization |
||||
//--- AW: fill token list |
||||
tokens = new Token(); // first token is a dummy |
||||
Token node = tokens; |
||||
do { |
||||
node.next = NextToken(); |
||||
node = node.next; |
||||
} while (node.kind != eofSym); |
||||
node.next = node; |
||||
node.val = "EOF"; |
||||
t = pt = tokens; |
||||
} |
||||
|
||||
static void NextCh() { |
||||
if (oldEols > 0) { ch = EOL; oldEols--; } |
||||
else { |
||||
ch = (char)Buffer.Read(); pos++; |
||||
// replace isolated '\r' by '\n' in order to make |
||||
// eol handling uniform across Windows, Unix and Mac |
||||
if (ch == '\r' && Buffer.Peek() != '\n') ch = EOL; |
||||
if (ch == EOL) { line++; lineStart = pos + 1; } |
||||
} |
||||
-->casing |
||||
} |
||||
|
||||
-->comments |
||||
|
||||
static void CheckLiteral() { |
||||
-->literals |
||||
} |
||||
|
||||
/* AW Scan() renamed to NextToken() */ |
||||
static Token NextToken() { |
||||
while (ignore[ch]) NextCh(); |
||||
-->scan1 |
||||
t = new Token(); |
||||
t.pos = pos; t.col = pos - lineStart + 1; t.line = line; |
||||
int state = start[ch]; |
||||
StringBuilder buf = new StringBuilder(16); |
||||
-->scan2 |
||||
|
||||
switch (state) { |
||||
case -1: { t.kind = eofSym; goto done; } // NextCh already done /* pdt */ |
||||
case 0: { t.kind = noSym; goto done; } // NextCh already done |
||||
-->scan3 |
||||
} |
||||
done: |
||||
t.val = buf.ToString(); |
||||
return t; |
||||
} |
||||
|
||||
/* AW 2003-03-07 get the next token, move on and synch peek token with current */ |
||||
public static Token Scan () { |
||||
t = pt = t.next; |
||||
return t; |
||||
} |
||||
|
||||
/* AW 2003-03-07 get the next token, ignore pragmas */ |
||||
public static Token Peek () { |
||||
do { // skip pragmas while peeking |
||||
pt = pt.next; |
||||
} while (pt.kind > maxT); |
||||
return pt; |
||||
} |
||||
|
||||
/* AW 2003-03-11 to make sure peek start at current scan position */ |
||||
public static void ResetPeek () { pt = t; } |
||||
|
||||
} // end Scanner |
||||
|
||||
$$$ |
Binary file not shown.
@ -1,41 +0,0 @@
@@ -1,41 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
namespace ICSharpCode.NRefactory |
||||
{ |
||||
/// <summary>
|
||||
/// Parser interface.
|
||||
/// </summary>
|
||||
public interface IParser : IDisposable |
||||
{ |
||||
Parser.Errors Errors { |
||||
get; |
||||
} |
||||
|
||||
Parser.ILexer Lexer { |
||||
get; |
||||
} |
||||
|
||||
CompilationUnit CompilationUnit { |
||||
get; |
||||
} |
||||
|
||||
bool ParseMethodBodies { |
||||
get; set; |
||||
} |
||||
|
||||
void Parse(); |
||||
|
||||
Expression ParseExpression(); |
||||
BlockStatement ParseBlock(); |
||||
IList<INode> ParseTypeMembers(); |
||||
} |
||||
} |
@ -1,73 +0,0 @@
@@ -1,73 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="none" email=""/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser |
||||
{ |
||||
internal class ModifierList |
||||
{ |
||||
Modifiers cur; |
||||
Location location = new Location(-1, -1); |
||||
|
||||
public Modifiers Modifier { |
||||
get { |
||||
return cur; |
||||
} |
||||
} |
||||
|
||||
public Location GetDeclarationLocation(Location keywordLocation) |
||||
{ |
||||
if(location.X == -1 && location.Y == -1) { |
||||
return keywordLocation; |
||||
} |
||||
return location; |
||||
} |
||||
|
||||
// public Location Location {
|
||||
// get {
|
||||
// return location;
|
||||
// }
|
||||
// set {
|
||||
// location = value;
|
||||
// }
|
||||
// }
|
||||
|
||||
public bool isNone { get { return cur == Modifiers.None; } } |
||||
|
||||
public bool Contains(Modifiers m) |
||||
{ |
||||
return ((cur & m) != 0); |
||||
} |
||||
|
||||
public void Add(Modifiers m, Location tokenLocation) |
||||
{ |
||||
if(location.X == -1 && location.Y == -1) { |
||||
location = tokenLocation; |
||||
} |
||||
|
||||
if ((cur & m) == 0) { |
||||
cur |= m; |
||||
} else { |
||||
// parser.Error("modifier " + m + " already defined");
|
||||
} |
||||
} |
||||
|
||||
// public void Add(Modifiers m)
|
||||
// {
|
||||
// Add(m.cur, m.Location);
|
||||
// }
|
||||
|
||||
public void Check(Modifiers allowed) |
||||
{ |
||||
Modifiers wrong = cur & ~allowed; |
||||
if (wrong != Modifiers.None) { |
||||
// parser.Error("modifier(s) " + wrong + " not allowed here");
|
||||
} |
||||
} |
||||
} |
||||
} |
@ -1,53 +0,0 @@
@@ -1,53 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="none" email=""/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser.VB |
||||
{ |
||||
internal class ParamModifierList |
||||
{ |
||||
ParameterModifiers cur; |
||||
Parser parser; |
||||
|
||||
public ParameterModifiers Modifier { |
||||
get { |
||||
return cur; |
||||
} |
||||
} |
||||
|
||||
public ParamModifierList(Parser parser) |
||||
{ |
||||
this.parser = parser; |
||||
cur = ParameterModifiers.None; |
||||
} |
||||
|
||||
public bool isNone { get { return cur == ParameterModifiers.None; } } |
||||
|
||||
public void Add(ParameterModifiers m) |
||||
{ |
||||
if ((cur & m) == 0) { |
||||
cur |= m; |
||||
} else { |
||||
parser.Error("param modifier " + m + " already defined"); |
||||
} |
||||
} |
||||
|
||||
public void Add(ParamModifierList m) |
||||
{ |
||||
Add(m.cur); |
||||
} |
||||
|
||||
public void Check() |
||||
{ |
||||
if((cur & ParameterModifiers.In) != 0 && |
||||
(cur & ParameterModifiers.Ref) != 0) { |
||||
parser.Error("ByRef and ByVal are not allowed at the same time."); |
||||
} |
||||
} |
||||
} |
||||
} |
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,304 +0,0 @@
@@ -1,304 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using System.Text; |
||||
using System.Diagnostics; |
||||
|
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
namespace ICSharpCode.NRefactory.Parser.VB |
||||
{ |
||||
internal sealed partial class Parser : AbstractParser |
||||
{ |
||||
Lexer lexer; |
||||
|
||||
public Parser(ILexer lexer) : base(lexer) |
||||
{ |
||||
this.lexer = (Lexer)lexer; |
||||
} |
||||
|
||||
private StringBuilder qualidentBuilder = new StringBuilder(); |
||||
|
||||
Token t |
||||
{ |
||||
[System.Diagnostics.DebuggerStepThrough] |
||||
get { |
||||
return lexer.Token; |
||||
} |
||||
} |
||||
Token la |
||||
{ |
||||
[System.Diagnostics.DebuggerStepThrough] |
||||
get { |
||||
return lexer.LookAhead; |
||||
} |
||||
} |
||||
|
||||
Token Peek (int n) |
||||
{ |
||||
lexer.StartPeek(); |
||||
Token x = la; |
||||
while (n > 0) { |
||||
x = lexer.Peek(); |
||||
n--; |
||||
} |
||||
return x; |
||||
} |
||||
|
||||
public void Error(string s) |
||||
{ |
||||
if (errDist >= MinErrDist) { |
||||
this.Errors.Error(la.line, la.col, s); |
||||
} |
||||
errDist = 0; |
||||
} |
||||
|
||||
public override Expression ParseExpression() |
||||
{ |
||||
lexer.NextToken(); |
||||
Expression expr; |
||||
Expr(out expr); |
||||
while (la.kind == Tokens.EOL) lexer.NextToken(); |
||||
Expect(Tokens.EOF); |
||||
return expr; |
||||
} |
||||
|
||||
public override BlockStatement ParseBlock() |
||||
{ |
||||
lexer.NextToken(); |
||||
compilationUnit = new CompilationUnit(); |
||||
|
||||
Statement st; |
||||
Block(out st); |
||||
Expect(Tokens.EOF); |
||||
return st as BlockStatement; |
||||
} |
||||
|
||||
public override IList<INode> ParseTypeMembers() |
||||
{ |
||||
lexer.NextToken(); |
||||
compilationUnit = new CompilationUnit(); |
||||
|
||||
TypeDeclaration newType = new TypeDeclaration(Modifiers.None, null); |
||||
compilationUnit.BlockStart(newType); |
||||
ClassBody(newType); |
||||
compilationUnit.BlockEnd(); |
||||
Expect(Tokens.EOF); |
||||
return newType.Children; |
||||
} |
||||
|
||||
bool LeaveBlock() |
||||
{ |
||||
int peek = Peek(1).kind; |
||||
return Tokens.BlockSucc[la.kind] && (la.kind != Tokens.End || peek == Tokens.EOL || peek == Tokens.Colon); |
||||
} |
||||
|
||||
/* True, if "." is followed by an ident */ |
||||
bool DotAndIdentOrKw () { |
||||
int peek = Peek(1).kind; |
||||
return la.kind == Tokens.Dot && (peek == Tokens.Identifier || peek >= Tokens.AddHandler); |
||||
} |
||||
|
||||
bool IsEndStmtAhead() |
||||
{ |
||||
int peek = Peek(1).kind; |
||||
return la.kind == Tokens.End && (peek == Tokens.EOL || peek == Tokens.Colon); |
||||
} |
||||
|
||||
bool IsNotClosingParenthesis() { |
||||
return la.kind != Tokens.CloseParenthesis; |
||||
} |
||||
|
||||
/* |
||||
True, if ident is followed by "=" or by ":" and "=" |
||||
*/ |
||||
bool IsNamedAssign() { |
||||
if(Peek(1).kind == Tokens.Colon && Peek(2).kind == Tokens.Assign) return true; |
||||
return false; |
||||
} |
||||
|
||||
bool IsObjectCreation() { |
||||
return la.kind == Tokens.As && Peek(1).kind == Tokens.New; |
||||
} |
||||
|
||||
/* |
||||
True, if "<" is followed by the ident "assembly" or "module" |
||||
*/ |
||||
bool IsGlobalAttrTarget () { |
||||
Token pt = Peek(1); |
||||
return la.kind == Tokens.LessThan && ( string.Equals(pt.val, "assembly", StringComparison.InvariantCultureIgnoreCase) || string.Equals(pt.val, "module", StringComparison.InvariantCultureIgnoreCase)); |
||||
} |
||||
|
||||
/* |
||||
True if the next token is a "(" and is followed by "," or ")" |
||||
*/ |
||||
bool IsDims() |
||||
{ |
||||
int peek = Peek(1).kind; |
||||
return la.kind == Tokens.OpenParenthesis |
||||
&& (peek == Tokens.Comma || peek == Tokens.CloseParenthesis); |
||||
} |
||||
|
||||
bool IsSize() |
||||
{ |
||||
return la.kind == Tokens.OpenParenthesis; |
||||
} |
||||
|
||||
/* |
||||
True, if the comma is not a trailing one, |
||||
like the last one in: a, b, c, |
||||
*/ |
||||
bool NotFinalComma() { |
||||
int peek = Peek(1).kind; |
||||
return la.kind == Tokens.Comma && |
||||
peek != Tokens.CloseCurlyBrace; |
||||
} |
||||
|
||||
/* |
||||
True, if the next token is "Else" and this one |
||||
if followed by "If" |
||||
*/ |
||||
bool IsElseIf() |
||||
{ |
||||
int peek = Peek(1).kind; |
||||
return la.kind == Tokens.Else && peek == Tokens.If; |
||||
} |
||||
|
||||
/* |
||||
True if the next token is goto and this one is |
||||
followed by minus ("-") (this is allowd in in |
||||
error clauses) |
||||
*/ |
||||
bool IsNegativeLabelName() |
||||
{ |
||||
int peek = Peek(1).kind; |
||||
return la.kind == Tokens.GoTo && peek == Tokens.Minus; |
||||
} |
||||
|
||||
/* |
||||
True if the next statement is a "Resume next" statement |
||||
*/ |
||||
bool IsResumeNext() |
||||
{ |
||||
int peek = Peek(1).kind; |
||||
return la.kind == Tokens.Resume && peek == Tokens.Next; |
||||
} |
||||
|
||||
/* |
||||
True, if ident/literal integer is followed by ":" |
||||
*/ |
||||
bool IsLabel() |
||||
{ |
||||
return (la.kind == Tokens.Identifier || la.kind == Tokens.LiteralInteger) |
||||
&& Peek(1).kind == Tokens.Colon; |
||||
} |
||||
|
||||
bool IsNotStatementSeparator() |
||||
{ |
||||
return la.kind == Tokens.Colon && Peek(1).kind == Tokens.EOL; |
||||
} |
||||
|
||||
static bool IsMustOverride(ModifierList m) |
||||
{ |
||||
return m.Contains(Modifiers.Abstract); |
||||
} |
||||
|
||||
TypeReferenceExpression GetTypeReferenceExpression(Expression expr, List<TypeReference> genericTypes) |
||||
{ |
||||
TypeReferenceExpression tre = expr as TypeReferenceExpression; |
||||
if (tre != null) { |
||||
return new TypeReferenceExpression(new TypeReference(tre.TypeReference.Type, tre.TypeReference.PointerNestingLevel, tre.TypeReference.RankSpecifier, genericTypes)); |
||||
} |
||||
StringBuilder b = new StringBuilder(); |
||||
if (!WriteFullTypeName(b, expr)) { |
||||
// there is some TypeReferenceExpression hidden in the expression
|
||||
while (expr is MemberReferenceExpression) { |
||||
expr = ((MemberReferenceExpression)expr).TargetObject; |
||||
} |
||||
tre = expr as TypeReferenceExpression; |
||||
if (tre != null) { |
||||
TypeReference typeRef = tre.TypeReference; |
||||
if (typeRef.GenericTypes.Count == 0) { |
||||
typeRef = typeRef.Clone(); |
||||
typeRef.Type += "." + b.ToString(); |
||||
typeRef.GenericTypes.AddRange(genericTypes); |
||||
} else { |
||||
typeRef = new InnerClassTypeReference(typeRef, b.ToString(), genericTypes); |
||||
} |
||||
return new TypeReferenceExpression(typeRef); |
||||
} |
||||
} |
||||
return new TypeReferenceExpression(new TypeReference(b.ToString(), 0, null, genericTypes)); |
||||
} |
||||
|
||||
/* Writes the type name represented through the expression into the string builder. */ |
||||
/* Returns true when the expression was converted successfully, returns false when */ |
||||
/* There was an unknown expression (e.g. TypeReferenceExpression) in it */ |
||||
bool WriteFullTypeName(StringBuilder b, Expression expr) |
||||
{ |
||||
MemberReferenceExpression fre = expr as MemberReferenceExpression; |
||||
if (fre != null) { |
||||
bool result = WriteFullTypeName(b, fre.TargetObject); |
||||
if (b.Length > 0) b.Append('.'); |
||||
b.Append(fre.MemberName); |
||||
return result; |
||||
} else if (expr is IdentifierExpression) { |
||||
b.Append(((IdentifierExpression)expr).Identifier); |
||||
return true; |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
/* |
||||
True, if lookahead is a local attribute target specifier, |
||||
i.e. one of "event", "return", "field", "method", |
||||
"module", "param", "property", or "type" |
||||
*/ |
||||
bool IsLocalAttrTarget() { |
||||
// TODO
|
||||
return false; |
||||
} |
||||
|
||||
void EnsureIsZero(Expression expr) |
||||
{ |
||||
if (!(expr is PrimitiveExpression) || (expr as PrimitiveExpression).StringValue != "0") |
||||
Error("lower bound of array must be zero"); |
||||
} |
||||
|
||||
InvocationExpression CreateInvocationExpression(Expression target, List<Expression> parameters, List<TypeReference> typeArguments) |
||||
{ |
||||
if (typeArguments != null && typeArguments.Count > 0) { |
||||
if (target is IdentifierExpression) { |
||||
((IdentifierExpression)target).TypeArguments = typeArguments; |
||||
} else if (target is MemberReferenceExpression) { |
||||
((MemberReferenceExpression)target).TypeArguments = typeArguments; |
||||
} else { |
||||
Error("Type arguments only allowed on IdentifierExpression and MemberReferenceExpression"); |
||||
} |
||||
} |
||||
return new InvocationExpression(target, parameters); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Adds a child item to a collection stored in the parent node.
|
||||
/// Also set's the item's parent to <paramref name="parent"/>.
|
||||
/// Does nothing if item is null.
|
||||
/// </summary>
|
||||
static void SafeAdd<T>(INode parent, List<T> list, T item) where T : class, INode |
||||
{ |
||||
Debug.Assert(parent != null); |
||||
Debug.Assert((parent is INullable) ? !(parent as INullable).IsNull : true); |
||||
if (item != null) { |
||||
list.Add(item); |
||||
item.Parent = parent; |
||||
} |
||||
} |
||||
} |
||||
} |
@ -1,24 +0,0 @@
@@ -1,24 +0,0 @@
|
||||
@echo off |
||||
|
||||
goto old |
||||
|
||||
|
||||
:old |
||||
echo Generating with #Coco |
||||
|
||||
cd Frames |
||||
|
||||
copy ..\CSharp\cs.ATG |
||||
SharpCoco -namespace ICSharpCode.NRefactory.Parser.CSharp cs.ATG |
||||
move Parser.cs ..\CSharp |
||||
|
||||
copy ..\VBNet\VBNET.ATG |
||||
SharpCoco -trace GIPXA -namespace ICSharpCode.NRefactory.Parser.VB VBNET.ATG |
||||
move Parser.cs ..\VBNet |
||||
|
||||
del cs.ATG |
||||
del VBNET.ATG |
||||
|
||||
:exit |
||||
pause |
||||
cd .. |
@ -1,62 +0,0 @@
@@ -1,62 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="none" email=""/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.IO; |
||||
using System.Text; |
||||
|
||||
namespace ICSharpCode.NRefactory |
||||
{ |
||||
public enum SupportedLanguage { |
||||
CSharp, |
||||
VBNet |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Static helper class that constructs lexer and parser objects.
|
||||
/// </summary>
|
||||
public static class ParserFactory |
||||
{ |
||||
public static Parser.ILexer CreateLexer(SupportedLanguage language, TextReader textReader) |
||||
{ |
||||
switch (language) { |
||||
case SupportedLanguage.CSharp: |
||||
return new ICSharpCode.NRefactory.Parser.CSharp.Lexer(textReader); |
||||
case SupportedLanguage.VBNet: |
||||
return new ICSharpCode.NRefactory.Parser.VB.Lexer(textReader); |
||||
} |
||||
throw new System.NotSupportedException(language + " not supported."); |
||||
} |
||||
|
||||
public static IParser CreateParser(SupportedLanguage language, TextReader textReader) |
||||
{ |
||||
Parser.ILexer lexer = CreateLexer(language, textReader); |
||||
switch (language) { |
||||
case SupportedLanguage.CSharp: |
||||
return new ICSharpCode.NRefactory.Parser.CSharp.Parser(lexer); |
||||
case SupportedLanguage.VBNet: |
||||
return new ICSharpCode.NRefactory.Parser.VB.Parser(lexer); |
||||
} |
||||
throw new System.NotSupportedException(language + " not supported."); |
||||
} |
||||
|
||||
public static IParser CreateParser(string fileName) |
||||
{ |
||||
return CreateParser(fileName, Encoding.UTF8); |
||||
} |
||||
|
||||
public static IParser CreateParser(string fileName, Encoding encoding) |
||||
{ |
||||
string ext = Path.GetExtension(fileName); |
||||
if (ext.Equals(".cs", StringComparison.InvariantCultureIgnoreCase)) |
||||
return CreateParser(SupportedLanguage.CSharp, new StreamReader(fileName, encoding)); |
||||
if (ext.Equals(".vb", StringComparison.InvariantCultureIgnoreCase)) |
||||
return CreateParser(SupportedLanguage.VBNet, new StreamReader(fileName, encoding)); |
||||
return null; |
||||
} |
||||
} |
||||
} |
@ -1,207 +0,0 @@
@@ -1,207 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections; |
||||
using System.Text; |
||||
|
||||
namespace ICSharpCode.NRefactory.PrettyPrinter |
||||
{ |
||||
/// <summary>
|
||||
/// Base class of output formatters.
|
||||
/// </summary>
|
||||
public abstract class AbstractOutputFormatter : IOutputFormatter |
||||
{ |
||||
StringBuilder text = new StringBuilder(); |
||||
|
||||
int indentationLevel = 0; |
||||
bool indent = true; |
||||
bool doNewLine = true; |
||||
AbstractPrettyPrintOptions prettyPrintOptions; |
||||
|
||||
public bool IsInMemberBody { get; set; } |
||||
|
||||
public int IndentationLevel { |
||||
get { |
||||
return indentationLevel; |
||||
} |
||||
set { |
||||
indentationLevel = value; |
||||
} |
||||
} |
||||
|
||||
public string Text { |
||||
get { |
||||
return text.ToString(); |
||||
} |
||||
} |
||||
|
||||
public int TextLength { |
||||
get { |
||||
return text.Length; |
||||
} |
||||
} |
||||
|
||||
|
||||
public bool DoIndent { |
||||
get { |
||||
return indent; |
||||
} |
||||
set { |
||||
indent = value; |
||||
} |
||||
} |
||||
|
||||
public bool DoNewLine { |
||||
get { |
||||
return doNewLine; |
||||
} |
||||
set { |
||||
doNewLine = value; |
||||
} |
||||
} |
||||
|
||||
protected AbstractOutputFormatter(AbstractPrettyPrintOptions prettyPrintOptions) |
||||
{ |
||||
this.prettyPrintOptions = prettyPrintOptions; |
||||
} |
||||
|
||||
public void Indent() |
||||
{ |
||||
if (DoIndent) { |
||||
int indent = 0; |
||||
while (indent < prettyPrintOptions.IndentSize * indentationLevel) { |
||||
char ch = prettyPrintOptions.IndentationChar; |
||||
if (ch == '\t' && indent + prettyPrintOptions.TabSize > prettyPrintOptions.IndentSize * indentationLevel) { |
||||
ch = ' '; |
||||
} |
||||
text.Append(ch); |
||||
if (ch == '\t') { |
||||
indent += prettyPrintOptions.TabSize; |
||||
} else { |
||||
++indent; |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
public void Space() |
||||
{ |
||||
text.Append(' '); |
||||
} |
||||
|
||||
internal int lastLineStart = 0; |
||||
internal int lineBeforeLastStart = 0; |
||||
|
||||
public bool LastCharacterIsNewLine { |
||||
get { |
||||
return text.Length == lastLineStart; |
||||
} |
||||
} |
||||
|
||||
public bool LastCharacterIsWhiteSpace { |
||||
get { |
||||
return text.Length == 0 || char.IsWhiteSpace(text[text.Length - 1]); |
||||
} |
||||
} |
||||
|
||||
public virtual void NewLine() |
||||
{ |
||||
if (DoNewLine) { |
||||
if (!LastCharacterIsNewLine) { |
||||
lineBeforeLastStart = lastLineStart; |
||||
} |
||||
text.AppendLine(); |
||||
lastLineStart = text.Length; |
||||
} |
||||
} |
||||
|
||||
public virtual void EndFile() |
||||
{ |
||||
} |
||||
|
||||
protected void WriteLineInPreviousLine(string txt, bool forceWriteInPreviousBlock) |
||||
{ |
||||
WriteInPreviousLine(txt + Environment.NewLine, forceWriteInPreviousBlock); |
||||
} |
||||
|
||||
protected void WriteInPreviousLine(string txt, bool forceWriteInPreviousBlock) |
||||
{ |
||||
if (txt.Length == 0) return; |
||||
|
||||
bool lastCharacterWasNewLine = LastCharacterIsNewLine; |
||||
if (lastCharacterWasNewLine) { |
||||
if (forceWriteInPreviousBlock == false) { |
||||
if (txt != Environment.NewLine) Indent(); |
||||
text.Append(txt); |
||||
lineBeforeLastStart = lastLineStart; |
||||
lastLineStart = text.Length; |
||||
return; |
||||
} |
||||
lastLineStart = lineBeforeLastStart; |
||||
} |
||||
string lastLine = text.ToString(lastLineStart, text.Length - lastLineStart); |
||||
text.Remove(lastLineStart, text.Length - lastLineStart); |
||||
if (txt != Environment.NewLine) { |
||||
if (forceWriteInPreviousBlock) ++indentationLevel; |
||||
Indent(); |
||||
if (forceWriteInPreviousBlock) --indentationLevel; |
||||
} |
||||
text.Append(txt); |
||||
lineBeforeLastStart = lastLineStart; |
||||
lastLineStart = text.Length; |
||||
text.Append(lastLine); |
||||
if (lastCharacterWasNewLine) { |
||||
lineBeforeLastStart = lastLineStart; |
||||
lastLineStart = text.Length; |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Prints a text that cannot be inserted before using WriteInPreviousLine
|
||||
/// into the current line
|
||||
/// </summary>
|
||||
protected void PrintSpecialText(string specialText) |
||||
{ |
||||
lineBeforeLastStart = text.Length; |
||||
text.Append(specialText); |
||||
lastLineStart = text.Length; |
||||
} |
||||
|
||||
public void PrintTokenList(ArrayList tokenList) |
||||
{ |
||||
foreach (int token in tokenList) { |
||||
PrintToken(token); |
||||
Space(); |
||||
} |
||||
} |
||||
|
||||
public abstract void PrintComment(Comment comment, bool forceWriteInPreviousBlock); |
||||
|
||||
public virtual void PrintPreprocessingDirective(PreprocessingDirective directive, bool forceWriteInPreviousBlock) |
||||
{ |
||||
if (string.IsNullOrEmpty(directive.Arg)) |
||||
WriteLineInPreviousLine(directive.Cmd, forceWriteInPreviousBlock); |
||||
else |
||||
WriteLineInPreviousLine(directive.Cmd + " " + directive.Arg, forceWriteInPreviousBlock); |
||||
} |
||||
|
||||
public void PrintBlankLine(bool forceWriteInPreviousBlock) |
||||
{ |
||||
WriteInPreviousLine(Environment.NewLine, forceWriteInPreviousBlock); |
||||
} |
||||
|
||||
public abstract void PrintToken(int token); |
||||
|
||||
public void PrintText(string text) |
||||
{ |
||||
this.text.Append(text); |
||||
} |
||||
|
||||
public abstract void PrintIdentifier(string identifier); |
||||
} |
||||
} |
@ -1,46 +0,0 @@
@@ -1,46 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
namespace ICSharpCode.NRefactory.PrettyPrinter |
||||
{ |
||||
/// <summary>
|
||||
/// Description of PrettyPrintOptions.
|
||||
/// </summary>
|
||||
public class AbstractPrettyPrintOptions |
||||
{ |
||||
char indentationChar = '\t'; |
||||
int tabSize = 4; |
||||
int indentSize = 4; |
||||
|
||||
public char IndentationChar { |
||||
get { |
||||
return indentationChar; |
||||
} |
||||
set { |
||||
indentationChar = value; |
||||
} |
||||
} |
||||
|
||||
public int TabSize { |
||||
get { |
||||
return tabSize; |
||||
} |
||||
set { |
||||
tabSize = value; |
||||
} |
||||
} |
||||
|
||||
public int IndentSize { |
||||
get { |
||||
return indentSize; |
||||
} |
||||
set { |
||||
indentSize = value; |
||||
} |
||||
} |
||||
} |
||||
} |
File diff suppressed because it is too large
Load Diff
@ -1,133 +0,0 @@
@@ -1,133 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System.Collections; |
||||
using ICSharpCode.NRefactory.Parser.CSharp; |
||||
|
||||
namespace ICSharpCode.NRefactory.PrettyPrinter |
||||
{ |
||||
public sealed class CSharpOutputFormatter : AbstractOutputFormatter |
||||
{ |
||||
PrettyPrintOptions prettyPrintOptions; |
||||
|
||||
bool emitSemicolon = true; |
||||
|
||||
public bool EmitSemicolon { |
||||
get { |
||||
return emitSemicolon; |
||||
} |
||||
set { |
||||
emitSemicolon = value; |
||||
} |
||||
} |
||||
|
||||
public CSharpOutputFormatter(PrettyPrintOptions prettyPrintOptions) : base(prettyPrintOptions) |
||||
{ |
||||
this.prettyPrintOptions = prettyPrintOptions; |
||||
} |
||||
|
||||
public override void PrintToken(int token) |
||||
{ |
||||
if (token == Tokens.Semicolon && !EmitSemicolon) { |
||||
return; |
||||
} |
||||
PrintText(Tokens.GetTokenString(token)); |
||||
} |
||||
|
||||
Stack braceStack = new Stack(); |
||||
|
||||
public void BeginBrace(BraceStyle style) |
||||
{ |
||||
switch (style) { |
||||
case BraceStyle.EndOfLine: |
||||
if (!LastCharacterIsWhiteSpace) { |
||||
Space(); |
||||
} |
||||
PrintToken(Tokens.OpenCurlyBrace); |
||||
NewLine(); |
||||
++IndentationLevel; |
||||
break; |
||||
case BraceStyle.NextLine: |
||||
NewLine(); |
||||
Indent(); |
||||
PrintToken(Tokens.OpenCurlyBrace); |
||||
NewLine(); |
||||
++IndentationLevel; |
||||
break; |
||||
case BraceStyle.NextLineShifted: |
||||
NewLine(); |
||||
++IndentationLevel; |
||||
Indent(); |
||||
PrintToken(Tokens.OpenCurlyBrace); |
||||
NewLine(); |
||||
break; |
||||
case BraceStyle.NextLineShifted2: |
||||
NewLine(); |
||||
++IndentationLevel; |
||||
Indent(); |
||||
PrintToken(Tokens.OpenCurlyBrace); |
||||
NewLine(); |
||||
++IndentationLevel; |
||||
break; |
||||
} |
||||
braceStack.Push(style); |
||||
} |
||||
|
||||
public void EndBrace() |
||||
{ |
||||
BraceStyle style = (BraceStyle)braceStack.Pop(); |
||||
switch (style) { |
||||
case BraceStyle.EndOfLine: |
||||
case BraceStyle.NextLine: |
||||
--IndentationLevel; |
||||
Indent(); |
||||
PrintToken(Tokens.CloseCurlyBrace); |
||||
NewLine(); |
||||
break; |
||||
case BraceStyle.NextLineShifted: |
||||
Indent(); |
||||
PrintToken(Tokens.CloseCurlyBrace); |
||||
NewLine(); |
||||
--IndentationLevel; |
||||
break; |
||||
case BraceStyle.NextLineShifted2: |
||||
--IndentationLevel; |
||||
Indent(); |
||||
PrintToken(Tokens.CloseCurlyBrace); |
||||
NewLine(); |
||||
--IndentationLevel; |
||||
break; |
||||
} |
||||
} |
||||
|
||||
public override void PrintIdentifier(string identifier) |
||||
{ |
||||
if (Keywords.GetToken(identifier) >= 0) |
||||
PrintText("@"); |
||||
PrintText(identifier); |
||||
} |
||||
|
||||
public override void PrintComment(Comment comment, bool forceWriteInPreviousBlock) |
||||
{ |
||||
switch (comment.CommentType) { |
||||
case CommentType.Block: |
||||
if (forceWriteInPreviousBlock) { |
||||
WriteInPreviousLine("/*" + comment.CommentText + "*/", forceWriteInPreviousBlock); |
||||
} else { |
||||
PrintSpecialText("/*" + comment.CommentText + "*/"); |
||||
} |
||||
break; |
||||
case CommentType.Documentation: |
||||
WriteLineInPreviousLine("///" + comment.CommentText, forceWriteInPreviousBlock); |
||||
break; |
||||
default: |
||||
WriteLineInPreviousLine("//" + comment.CommentText, forceWriteInPreviousBlock); |
||||
break; |
||||
} |
||||
} |
||||
} |
||||
} |
@ -1,508 +0,0 @@
@@ -1,508 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
namespace ICSharpCode.NRefactory.PrettyPrinter |
||||
{ |
||||
public enum BraceStyle { |
||||
EndOfLine, |
||||
NextLine, |
||||
NextLineShifted, |
||||
NextLineShifted2 |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Description of PrettyPrintOptions.
|
||||
/// </summary>
|
||||
public class PrettyPrintOptions : AbstractPrettyPrintOptions |
||||
{ |
||||
#region BraceStyle
|
||||
BraceStyle namespaceBraceStyle = BraceStyle.NextLine; |
||||
BraceStyle classBraceStyle = BraceStyle.NextLine; |
||||
BraceStyle interfaceBraceStyle = BraceStyle.NextLine; |
||||
BraceStyle structBraceStyle = BraceStyle.NextLine; |
||||
BraceStyle enumBraceStyle = BraceStyle.NextLine; |
||||
|
||||
BraceStyle constructorBraceStyle = BraceStyle.NextLine; |
||||
BraceStyle destructorBraceStyle = BraceStyle.NextLine; |
||||
BraceStyle methodBraceStyle = BraceStyle.NextLine; |
||||
|
||||
BraceStyle propertyBraceStyle = BraceStyle.EndOfLine; |
||||
BraceStyle propertyGetBraceStyle = BraceStyle.EndOfLine; |
||||
BraceStyle propertySetBraceStyle = BraceStyle.EndOfLine; |
||||
|
||||
BraceStyle eventAddBraceStyle = BraceStyle.EndOfLine; |
||||
BraceStyle eventRemoveBraceStyle = BraceStyle.EndOfLine; |
||||
|
||||
BraceStyle statementBraceStyle = BraceStyle.EndOfLine; |
||||
|
||||
public BraceStyle StatementBraceStyle { |
||||
get { |
||||
return statementBraceStyle; |
||||
} |
||||
set { |
||||
statementBraceStyle = value; |
||||
} |
||||
} |
||||
|
||||
public BraceStyle NamespaceBraceStyle { |
||||
get { |
||||
return namespaceBraceStyle; |
||||
} |
||||
set { |
||||
namespaceBraceStyle = value; |
||||
} |
||||
} |
||||
|
||||
public BraceStyle ClassBraceStyle { |
||||
get { |
||||
return classBraceStyle; |
||||
} |
||||
set { |
||||
classBraceStyle = value; |
||||
} |
||||
} |
||||
|
||||
public BraceStyle InterfaceBraceStyle { |
||||
get { |
||||
return interfaceBraceStyle; |
||||
} |
||||
set { |
||||
interfaceBraceStyle = value; |
||||
} |
||||
} |
||||
|
||||
public BraceStyle StructBraceStyle { |
||||
get { |
||||
return structBraceStyle; |
||||
} |
||||
set { |
||||
structBraceStyle = value; |
||||
} |
||||
} |
||||
|
||||
public BraceStyle EnumBraceStyle { |
||||
get { |
||||
return enumBraceStyle; |
||||
} |
||||
set { |
||||
enumBraceStyle = value; |
||||
} |
||||
} |
||||
|
||||
|
||||
public BraceStyle ConstructorBraceStyle { |
||||
get { |
||||
return constructorBraceStyle; |
||||
} |
||||
set { |
||||
constructorBraceStyle = value; |
||||
} |
||||
} |
||||
|
||||
public BraceStyle DestructorBraceStyle { |
||||
get { |
||||
return destructorBraceStyle; |
||||
} |
||||
set { |
||||
destructorBraceStyle = value; |
||||
} |
||||
} |
||||
|
||||
public BraceStyle MethodBraceStyle { |
||||
get { |
||||
return methodBraceStyle; |
||||
} |
||||
set { |
||||
methodBraceStyle = value; |
||||
} |
||||
} |
||||
|
||||
public BraceStyle PropertyBraceStyle { |
||||
get { |
||||
return propertyBraceStyle; |
||||
} |
||||
set { |
||||
propertyBraceStyle = value; |
||||
} |
||||
} |
||||
public BraceStyle PropertyGetBraceStyle { |
||||
get { |
||||
return propertyGetBraceStyle; |
||||
} |
||||
set { |
||||
propertyGetBraceStyle = value; |
||||
} |
||||
} |
||||
public BraceStyle PropertySetBraceStyle { |
||||
get { |
||||
return propertySetBraceStyle; |
||||
} |
||||
set { |
||||
propertySetBraceStyle = value; |
||||
} |
||||
} |
||||
|
||||
public BraceStyle EventAddBraceStyle { |
||||
get { |
||||
return eventAddBraceStyle; |
||||
} |
||||
set { |
||||
eventAddBraceStyle = value; |
||||
} |
||||
} |
||||
public BraceStyle EventRemoveBraceStyle { |
||||
get { |
||||
return eventRemoveBraceStyle; |
||||
} |
||||
set { |
||||
eventRemoveBraceStyle = value; |
||||
} |
||||
} |
||||
#endregion
|
||||
|
||||
#region Before Parentheses
|
||||
bool beforeMethodCallParentheses = false; |
||||
bool beforeDelegateDeclarationParentheses = false; |
||||
bool beforeMethodDeclarationParentheses = false; |
||||
bool beforeConstructorDeclarationParentheses = false; |
||||
|
||||
bool ifParentheses = true; |
||||
bool whileParentheses = true; |
||||
bool forParentheses = true; |
||||
bool foreachParentheses = true; |
||||
bool catchParentheses = true; |
||||
bool switchParentheses = true; |
||||
bool lockParentheses = true; |
||||
bool usingParentheses = true; |
||||
bool fixedParentheses = true; |
||||
bool sizeOfParentheses = false; |
||||
bool typeOfParentheses = false; |
||||
bool checkedParentheses = false; |
||||
bool uncheckedParentheses = false; |
||||
bool newParentheses = false; |
||||
|
||||
public bool CheckedParentheses { |
||||
get { |
||||
return checkedParentheses; |
||||
} |
||||
set { |
||||
checkedParentheses = value; |
||||
} |
||||
} |
||||
public bool NewParentheses { |
||||
get { |
||||
return newParentheses; |
||||
} |
||||
set { |
||||
newParentheses = value; |
||||
} |
||||
} |
||||
public bool SizeOfParentheses { |
||||
get { |
||||
return sizeOfParentheses; |
||||
} |
||||
set { |
||||
sizeOfParentheses = value; |
||||
} |
||||
} |
||||
public bool TypeOfParentheses { |
||||
get { |
||||
return typeOfParentheses; |
||||
} |
||||
set { |
||||
typeOfParentheses = value; |
||||
} |
||||
} |
||||
public bool UncheckedParentheses { |
||||
get { |
||||
return uncheckedParentheses; |
||||
} |
||||
set { |
||||
uncheckedParentheses = value; |
||||
} |
||||
} |
||||
|
||||
public bool BeforeConstructorDeclarationParentheses { |
||||
get { |
||||
return beforeConstructorDeclarationParentheses; |
||||
} |
||||
set { |
||||
beforeConstructorDeclarationParentheses = value; |
||||
} |
||||
} |
||||
|
||||
public bool BeforeDelegateDeclarationParentheses { |
||||
get { |
||||
return beforeDelegateDeclarationParentheses; |
||||
} |
||||
set { |
||||
beforeDelegateDeclarationParentheses = value; |
||||
} |
||||
} |
||||
|
||||
public bool BeforeMethodCallParentheses { |
||||
get { |
||||
return beforeMethodCallParentheses; |
||||
} |
||||
set { |
||||
beforeMethodCallParentheses = value; |
||||
} |
||||
} |
||||
|
||||
public bool BeforeMethodDeclarationParentheses { |
||||
get { |
||||
return beforeMethodDeclarationParentheses; |
||||
} |
||||
set { |
||||
beforeMethodDeclarationParentheses = value; |
||||
} |
||||
} |
||||
|
||||
public bool IfParentheses { |
||||
get { |
||||
return ifParentheses; |
||||
} |
||||
set { |
||||
ifParentheses = value; |
||||
} |
||||
} |
||||
|
||||
public bool WhileParentheses { |
||||
get { |
||||
return whileParentheses; |
||||
} |
||||
set { |
||||
whileParentheses = value; |
||||
} |
||||
} |
||||
public bool ForeachParentheses { |
||||
get { |
||||
return foreachParentheses; |
||||
} |
||||
set { |
||||
foreachParentheses = value; |
||||
} |
||||
} |
||||
public bool LockParentheses { |
||||
get { |
||||
return lockParentheses; |
||||
} |
||||
set { |
||||
lockParentheses = value; |
||||
} |
||||
} |
||||
public bool UsingParentheses { |
||||
get { |
||||
return usingParentheses; |
||||
} |
||||
set { |
||||
usingParentheses = value; |
||||
} |
||||
} |
||||
|
||||
public bool CatchParentheses { |
||||
get { |
||||
return catchParentheses; |
||||
} |
||||
set { |
||||
catchParentheses = value; |
||||
} |
||||
} |
||||
public bool FixedParentheses { |
||||
get { |
||||
return fixedParentheses; |
||||
} |
||||
set { |
||||
fixedParentheses = value; |
||||
} |
||||
} |
||||
public bool SwitchParentheses { |
||||
get { |
||||
return switchParentheses; |
||||
} |
||||
set { |
||||
switchParentheses = value; |
||||
} |
||||
} |
||||
public bool ForParentheses { |
||||
get { |
||||
return forParentheses; |
||||
} |
||||
set { |
||||
forParentheses = value; |
||||
} |
||||
} |
||||
|
||||
#endregion
|
||||
|
||||
#region AroundOperators
|
||||
bool aroundAssignmentParentheses = true; |
||||
bool aroundLogicalOperatorParentheses = true; |
||||
bool aroundEqualityOperatorParentheses = true; |
||||
bool aroundRelationalOperatorParentheses = true; |
||||
bool aroundBitwiseOperatorParentheses = true; |
||||
bool aroundAdditiveOperatorParentheses = true; |
||||
bool aroundMultiplicativeOperatorParentheses = true; |
||||
bool aroundShiftOperatorParentheses = true; |
||||
|
||||
public bool AroundAdditiveOperatorParentheses { |
||||
get { |
||||
return aroundAdditiveOperatorParentheses; |
||||
} |
||||
set { |
||||
aroundAdditiveOperatorParentheses = value; |
||||
} |
||||
} |
||||
public bool AroundAssignmentParentheses { |
||||
get { |
||||
return aroundAssignmentParentheses; |
||||
} |
||||
set { |
||||
aroundAssignmentParentheses = value; |
||||
} |
||||
} |
||||
public bool AroundBitwiseOperatorParentheses { |
||||
get { |
||||
return aroundBitwiseOperatorParentheses; |
||||
} |
||||
set { |
||||
aroundBitwiseOperatorParentheses = value; |
||||
} |
||||
} |
||||
public bool AroundEqualityOperatorParentheses { |
||||
get { |
||||
return aroundEqualityOperatorParentheses; |
||||
} |
||||
set { |
||||
aroundEqualityOperatorParentheses = value; |
||||
} |
||||
} |
||||
public bool AroundLogicalOperatorParentheses { |
||||
get { |
||||
return aroundLogicalOperatorParentheses; |
||||
} |
||||
set { |
||||
aroundLogicalOperatorParentheses = value; |
||||
} |
||||
} |
||||
public bool AroundMultiplicativeOperatorParentheses { |
||||
get { |
||||
return aroundMultiplicativeOperatorParentheses; |
||||
} |
||||
set { |
||||
aroundMultiplicativeOperatorParentheses = value; |
||||
} |
||||
} |
||||
public bool AroundRelationalOperatorParentheses { |
||||
get { |
||||
return aroundRelationalOperatorParentheses; |
||||
} |
||||
set { |
||||
aroundRelationalOperatorParentheses = value; |
||||
} |
||||
} |
||||
public bool AroundShiftOperatorParentheses { |
||||
get { |
||||
return aroundShiftOperatorParentheses; |
||||
} |
||||
set { |
||||
aroundShiftOperatorParentheses = value; |
||||
} |
||||
} |
||||
#endregion
|
||||
|
||||
#region SpacesInConditionalOperator
|
||||
bool conditionalOperatorBeforeConditionSpace = true; |
||||
bool conditionalOperatorAfterConditionSpace = true; |
||||
|
||||
bool conditionalOperatorBeforeSeparatorSpace = true; |
||||
bool conditionalOperatorAfterSeparatorSpace = true; |
||||
|
||||
public bool ConditionalOperatorAfterConditionSpace { |
||||
get { |
||||
return conditionalOperatorAfterConditionSpace; |
||||
} |
||||
set { |
||||
conditionalOperatorAfterConditionSpace = value; |
||||
} |
||||
} |
||||
public bool ConditionalOperatorAfterSeparatorSpace { |
||||
get { |
||||
return conditionalOperatorAfterSeparatorSpace; |
||||
} |
||||
set { |
||||
conditionalOperatorAfterSeparatorSpace = value; |
||||
} |
||||
} |
||||
public bool ConditionalOperatorBeforeConditionSpace { |
||||
get { |
||||
return conditionalOperatorBeforeConditionSpace; |
||||
} |
||||
set { |
||||
conditionalOperatorBeforeConditionSpace = value; |
||||
} |
||||
} |
||||
public bool ConditionalOperatorBeforeSeparatorSpace { |
||||
get { |
||||
return conditionalOperatorBeforeSeparatorSpace; |
||||
} |
||||
set { |
||||
conditionalOperatorBeforeSeparatorSpace = value; |
||||
} |
||||
} |
||||
#endregion
|
||||
|
||||
#region OtherSpaces
|
||||
bool spacesWithinBrackets = false; |
||||
bool spacesAfterComma = true; |
||||
bool spacesBeforeComma = false; |
||||
bool spacesAfterSemicolon = true; |
||||
bool spacesAfterTypecast = false; |
||||
|
||||
public bool SpacesAfterComma { |
||||
get { |
||||
return spacesAfterComma; |
||||
} |
||||
set { |
||||
spacesAfterComma = value; |
||||
} |
||||
} |
||||
public bool SpacesAfterSemicolon { |
||||
get { |
||||
return spacesAfterSemicolon; |
||||
} |
||||
set { |
||||
spacesAfterSemicolon = value; |
||||
} |
||||
} |
||||
public bool SpacesAfterTypecast { |
||||
get { |
||||
return spacesAfterTypecast; |
||||
} |
||||
set { |
||||
spacesAfterTypecast = value; |
||||
} |
||||
} |
||||
public bool SpacesBeforeComma { |
||||
get { |
||||
return spacesBeforeComma; |
||||
} |
||||
set { |
||||
spacesBeforeComma = value; |
||||
} |
||||
} |
||||
public bool SpacesWithinBrackets { |
||||
get { |
||||
return spacesWithinBrackets; |
||||
} |
||||
set { |
||||
spacesWithinBrackets = value; |
||||
} |
||||
} |
||||
#endregion
|
||||
} |
||||
} |
@ -1,56 +0,0 @@
@@ -1,56 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using ICSharpCode.NRefactory.Parser; |
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
namespace ICSharpCode.NRefactory.PrettyPrinter |
||||
{ |
||||
/// <summary>
|
||||
/// Description of IOutputASTVisitor.
|
||||
/// </summary>
|
||||
public interface IOutputAstVisitor : IAstVisitor |
||||
{ |
||||
event Action<INode> BeforeNodeVisit; |
||||
event Action<INode> AfterNodeVisit; |
||||
|
||||
string Text { |
||||
get; |
||||
} |
||||
|
||||
Errors Errors { |
||||
get; |
||||
} |
||||
|
||||
AbstractPrettyPrintOptions Options { |
||||
get; |
||||
} |
||||
IOutputFormatter OutputFormatter { |
||||
get; |
||||
} |
||||
} |
||||
public interface IOutputFormatter |
||||
{ |
||||
int IndentationLevel { |
||||
get; |
||||
set; |
||||
} |
||||
string Text { |
||||
get; |
||||
} |
||||
bool IsInMemberBody { |
||||
get; |
||||
set; |
||||
} |
||||
void NewLine(); |
||||
void Indent(); |
||||
void PrintComment(Comment comment, bool forceWriteInPreviousBlock); |
||||
void PrintPreprocessingDirective(PreprocessingDirective directive, bool forceWriteInPreviousBlock); |
||||
void PrintBlankLine(bool forceWriteInPreviousBlock); |
||||
} |
||||
} |
@ -1,146 +0,0 @@
@@ -1,146 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
namespace ICSharpCode.NRefactory.PrettyPrinter |
||||
{ |
||||
public class SpecialOutputVisitor : ISpecialVisitor |
||||
{ |
||||
readonly IOutputFormatter formatter; |
||||
|
||||
public SpecialOutputVisitor(IOutputFormatter formatter) |
||||
{ |
||||
this.formatter = formatter; |
||||
} |
||||
|
||||
public bool ForceWriteInPreviousLine; |
||||
|
||||
public object Visit(ISpecial special, object data) |
||||
{ |
||||
Console.WriteLine("Warning: SpecialOutputVisitor.Visit(ISpecial) called with " + special); |
||||
return data; |
||||
} |
||||
|
||||
public object Visit(BlankLine special, object data) |
||||
{ |
||||
formatter.PrintBlankLine(ForceWriteInPreviousLine); |
||||
return data; |
||||
} |
||||
|
||||
public object Visit(Comment special, object data) |
||||
{ |
||||
formatter.PrintComment(special, ForceWriteInPreviousLine); |
||||
return data; |
||||
} |
||||
|
||||
public object Visit(PreprocessingDirective special, object data) |
||||
{ |
||||
formatter.PrintPreprocessingDirective(special, ForceWriteInPreviousLine); |
||||
return data; |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// This class inserts specials between INodes.
|
||||
/// </summary>
|
||||
public sealed class SpecialNodesInserter : IDisposable |
||||
{ |
||||
IEnumerator<ISpecial> enumerator; |
||||
SpecialOutputVisitor visitor; |
||||
bool available; // true when more specials are available
|
||||
|
||||
public SpecialNodesInserter(IEnumerable<ISpecial> specials, SpecialOutputVisitor visitor) |
||||
{ |
||||
if (specials == null) throw new ArgumentNullException("specials"); |
||||
if (visitor == null) throw new ArgumentNullException("visitor"); |
||||
enumerator = specials.GetEnumerator(); |
||||
this.visitor = visitor; |
||||
available = enumerator.MoveNext(); |
||||
} |
||||
|
||||
void WriteCurrent() |
||||
{ |
||||
enumerator.Current.AcceptVisitor(visitor, null); |
||||
available = enumerator.MoveNext(); |
||||
} |
||||
|
||||
AttributedNode currentAttributedNode; |
||||
|
||||
/// <summary>
|
||||
/// Writes all specials up to the start position of the node.
|
||||
/// </summary>
|
||||
public void AcceptNodeStart(INode node) |
||||
{ |
||||
if (node is AttributedNode) { |
||||
currentAttributedNode = node as AttributedNode; |
||||
if (currentAttributedNode.Attributes.Count == 0) { |
||||
AcceptPoint(node.StartLocation); |
||||
currentAttributedNode = null; |
||||
} |
||||
} else { |
||||
AcceptPoint(node.StartLocation); |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Writes all specials up to the end position of the node.
|
||||
/// </summary>
|
||||
public void AcceptNodeEnd(INode node) |
||||
{ |
||||
visitor.ForceWriteInPreviousLine = true; |
||||
AcceptPoint(node.EndLocation); |
||||
visitor.ForceWriteInPreviousLine = false; |
||||
if (currentAttributedNode != null) { |
||||
if (node == currentAttributedNode.Attributes[currentAttributedNode.Attributes.Count - 1]) { |
||||
AcceptPoint(currentAttributedNode.StartLocation); |
||||
currentAttributedNode = null; |
||||
} |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Writes all specials up to the specified location.
|
||||
/// </summary>
|
||||
public void AcceptPoint(Location loc) |
||||
{ |
||||
while (available && enumerator.Current.StartPosition <= loc) { |
||||
WriteCurrent(); |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Outputs all missing specials to the writer.
|
||||
/// </summary>
|
||||
public void Finish() |
||||
{ |
||||
while (available) { |
||||
WriteCurrent(); |
||||
} |
||||
} |
||||
|
||||
void IDisposable.Dispose() |
||||
{ |
||||
Finish(); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Registers a new SpecialNodesInserter with the output visitor.
|
||||
/// Make sure to call Finish() (or Dispose()) on the returned SpecialNodesInserter
|
||||
/// when the output is finished.
|
||||
/// </summary>
|
||||
public static SpecialNodesInserter Install(IEnumerable<ISpecial> specials, IOutputAstVisitor outputVisitor) |
||||
{ |
||||
SpecialNodesInserter sni = new SpecialNodesInserter(specials, new SpecialOutputVisitor(outputVisitor.OutputFormatter)); |
||||
outputVisitor.BeforeNodeVisit += sni.AcceptNodeStart; |
||||
outputVisitor.AfterNodeVisit += sni.AcceptNodeEnd; |
||||
return sni; |
||||
} |
||||
} |
||||
} |
@ -1,73 +0,0 @@
@@ -1,73 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using ICSharpCode.NRefactory.Parser.VB; |
||||
|
||||
namespace ICSharpCode.NRefactory.PrettyPrinter |
||||
{ |
||||
/// <summary>
|
||||
/// Description of VBNetOutputFormatter.
|
||||
/// </summary>
|
||||
public sealed class VBNetOutputFormatter : AbstractOutputFormatter |
||||
{ |
||||
public VBNetOutputFormatter(VBNetPrettyPrintOptions prettyPrintOptions) : base(prettyPrintOptions) |
||||
{ |
||||
} |
||||
|
||||
public override void PrintToken(int token) |
||||
{ |
||||
PrintText(Tokens.GetTokenString(token)); |
||||
} |
||||
|
||||
public override void PrintIdentifier(string identifier) |
||||
{ |
||||
if (Keywords.IsNonIdentifierKeyword(identifier)) { |
||||
PrintText("["); |
||||
PrintText(identifier); |
||||
PrintText("]"); |
||||
} else { |
||||
PrintText(identifier); |
||||
} |
||||
} |
||||
|
||||
public override void PrintComment(Comment comment, bool forceWriteInPreviousBlock) |
||||
{ |
||||
switch (comment.CommentType) { |
||||
case CommentType.Block: |
||||
WriteLineInPreviousLine("'" + comment.CommentText.Replace("\n", "\n'"), forceWriteInPreviousBlock); |
||||
break; |
||||
case CommentType.Documentation: |
||||
WriteLineInPreviousLine("'''" + comment.CommentText, forceWriteInPreviousBlock); |
||||
break; |
||||
default: |
||||
WriteLineInPreviousLine("'" + comment.CommentText, forceWriteInPreviousBlock); |
||||
break; |
||||
} |
||||
} |
||||
|
||||
public override void PrintPreprocessingDirective(PreprocessingDirective directive, bool forceWriteInPreviousBlock) |
||||
{ |
||||
if (IsInMemberBody |
||||
&& (string.Equals(directive.Cmd, "#Region", StringComparison.InvariantCultureIgnoreCase) |
||||
|| string.Equals(directive.Cmd, "#End", StringComparison.InvariantCultureIgnoreCase) |
||||
&& directive.Arg.ToLowerInvariant().StartsWith("region"))) |
||||
{ |
||||
WriteLineInPreviousLine("'" + directive.Cmd + " " + directive.Arg, forceWriteInPreviousBlock); |
||||
} else { |
||||
base.PrintPreprocessingDirective(directive, forceWriteInPreviousBlock); |
||||
} |
||||
} |
||||
|
||||
public void PrintLineContinuation() |
||||
{ |
||||
if (!LastCharacterIsWhiteSpace) |
||||
Space(); |
||||
PrintText("_\r\n"); |
||||
} |
||||
} |
||||
} |
File diff suppressed because it is too large
Load Diff
@ -1,22 +0,0 @@
@@ -1,22 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
|
||||
namespace ICSharpCode.NRefactory.PrettyPrinter |
||||
{ |
||||
/// <summary>
|
||||
/// Description of VBNetPrettyPrintOptions.
|
||||
/// </summary>
|
||||
public class VBNetPrettyPrintOptions : AbstractPrettyPrintOptions |
||||
{ |
||||
/// <summary>
|
||||
/// Gets/Sets if the optional "ByVal" modifier should be written.
|
||||
/// </summary>
|
||||
public bool OutputByValModifier { get; set; } |
||||
} |
||||
} |
@ -1,136 +0,0 @@
@@ -1,136 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using System.IO; |
||||
using ICSharpCode.NRefactory.Ast; |
||||
using ICSharpCode.NRefactory.Parser; |
||||
|
||||
namespace ICSharpCode.NRefactory |
||||
{ |
||||
/// <summary>
|
||||
/// The snippet parser supports parsing code snippets that are not valid as a full compilation unit.
|
||||
/// </summary>
|
||||
public class SnippetParser |
||||
{ |
||||
readonly SupportedLanguage language; |
||||
|
||||
public SnippetParser(SupportedLanguage language) |
||||
{ |
||||
this.language = language; |
||||
} |
||||
|
||||
Errors errors; |
||||
List<ISpecial> specials; |
||||
|
||||
/// <summary>
|
||||
/// Gets the errors of the last call to Parse(). Returns null if parse was not yet called.
|
||||
/// </summary>
|
||||
public Errors Errors { |
||||
get { return errors; } |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Gets the specials of the last call to Parse(). Returns null if parse was not yet called.
|
||||
/// </summary>
|
||||
public List<ISpecial> Specials { |
||||
get { return specials; } |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Parse the code. The result may be a CompilationUnit, an Expression, a list of statements or a list of class
|
||||
/// members.
|
||||
/// </summary>
|
||||
public INode Parse(string code) |
||||
{ |
||||
IParser parser = ParserFactory.CreateParser(language, new StringReader(code)); |
||||
parser.Parse(); |
||||
errors = parser.Errors; |
||||
specials = parser.Lexer.SpecialTracker.RetrieveSpecials(); |
||||
INode result = parser.CompilationUnit; |
||||
|
||||
if (errors.Count > 0) { |
||||
if (language == SupportedLanguage.CSharp) { |
||||
// SEMICOLON HACK : without a trailing semicolon, parsing expressions does not work correctly
|
||||
parser = ParserFactory.CreateParser(language, new StringReader(code + ";")); |
||||
} else { |
||||
parser = ParserFactory.CreateParser(language, new StringReader(code)); |
||||
} |
||||
Expression expression = parser.ParseExpression(); |
||||
if (expression != null && parser.Errors.Count < errors.Count) { |
||||
errors = parser.Errors; |
||||
specials = parser.Lexer.SpecialTracker.RetrieveSpecials(); |
||||
result = expression; |
||||
} |
||||
} |
||||
if (errors.Count > 0) { |
||||
parser = ParserFactory.CreateParser(language, new StringReader(code)); |
||||
BlockStatement block = parser.ParseBlock(); |
||||
if (block != null && parser.Errors.Count < errors.Count) { |
||||
errors = parser.Errors; |
||||
specials = parser.Lexer.SpecialTracker.RetrieveSpecials(); |
||||
result = block; |
||||
} |
||||
} |
||||
if (errors.Count > 0) { |
||||
parser = ParserFactory.CreateParser(language, new StringReader(code)); |
||||
IList<INode> members = parser.ParseTypeMembers(); |
||||
if (members != null && members.Count > 0 && parser.Errors.Count < errors.Count) { |
||||
errors = parser.Errors; |
||||
specials = parser.Lexer.SpecialTracker.RetrieveSpecials(); |
||||
result = new NodeListNode(members); |
||||
} |
||||
} |
||||
return result; |
||||
} |
||||
|
||||
sealed class NodeListNode : INode |
||||
{ |
||||
IList<INode> nodes; |
||||
|
||||
public NodeListNode(IList<INode> nodes) |
||||
{ |
||||
this.nodes = nodes; |
||||
} |
||||
|
||||
public INode Parent { |
||||
get { return null; } |
||||
set { throw new NotSupportedException(); } |
||||
} |
||||
|
||||
public IList<INode> Children { |
||||
get { return nodes; } |
||||
} |
||||
|
||||
public Location StartLocation { |
||||
get { return Location.Empty; } |
||||
set { throw new NotSupportedException(); } |
||||
} |
||||
|
||||
public Location EndLocation { |
||||
get { return Location.Empty; } |
||||
set { throw new NotSupportedException(); } |
||||
} |
||||
|
||||
public Dictionary<string, object> UserData { get; set; } |
||||
|
||||
public object AcceptChildren(IAstVisitor visitor, object data) |
||||
{ |
||||
foreach (INode n in nodes) { |
||||
n.AcceptVisitor(visitor, data); |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
public object AcceptVisitor(IAstVisitor visitor, object data) |
||||
{ |
||||
return AcceptChildren(visitor, data); |
||||
} |
||||
} |
||||
} |
||||
} |
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,229 +0,0 @@
@@ -1,229 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
namespace ICSharpCode.NRefactory.Visitors |
||||
{ |
||||
/// <summary>
|
||||
/// Converts special C# constructs to use more general AST classes.
|
||||
/// </summary>
|
||||
public class CSharpConstructsConvertVisitor : ConvertVisitorBase |
||||
{ |
||||
// The following conversions are implemented:
|
||||
// a == null -> a Is Nothing
|
||||
// a != null -> a Is Not Nothing
|
||||
// i++ / ++i as statement: convert to i += 1
|
||||
// i-- / --i as statement: convert to i -= 1
|
||||
// ForStatement -> ForNextStatement when for-loop is simple
|
||||
// if (Event != null) Event(this, bla); -> RaiseEvent Event(this, bla)
|
||||
// Casts to value types are marked as conversions
|
||||
|
||||
public override object VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression, object data) |
||||
{ |
||||
if (binaryOperatorExpression.Op == BinaryOperatorType.Equality || binaryOperatorExpression.Op == BinaryOperatorType.InEquality) { |
||||
if (IsNullLiteralExpression(binaryOperatorExpression.Left)) { |
||||
Expression tmp = binaryOperatorExpression.Left; |
||||
binaryOperatorExpression.Left = binaryOperatorExpression.Right; |
||||
binaryOperatorExpression.Right = tmp; |
||||
} |
||||
if (IsNullLiteralExpression(binaryOperatorExpression.Right)) { |
||||
if (binaryOperatorExpression.Op == BinaryOperatorType.Equality) { |
||||
binaryOperatorExpression.Op = BinaryOperatorType.ReferenceEquality; |
||||
} else { |
||||
binaryOperatorExpression.Op = BinaryOperatorType.ReferenceInequality; |
||||
} |
||||
} |
||||
} |
||||
return base.VisitBinaryOperatorExpression(binaryOperatorExpression, data); |
||||
} |
||||
|
||||
static bool IsNullLiteralExpression(Expression expr) |
||||
{ |
||||
PrimitiveExpression pe = expr as PrimitiveExpression; |
||||
if (pe == null) return false; |
||||
return pe.Value == null; |
||||
} |
||||
|
||||
|
||||
public override object VisitExpressionStatement(ExpressionStatement expressionStatement, object data) |
||||
{ |
||||
UnaryOperatorExpression uoe = expressionStatement.Expression as UnaryOperatorExpression; |
||||
if (uoe != null) { |
||||
switch (uoe.Op) { |
||||
case UnaryOperatorType.Increment: |
||||
case UnaryOperatorType.PostIncrement: |
||||
expressionStatement.Expression = new AssignmentExpression(uoe.Expression, AssignmentOperatorType.Add, new PrimitiveExpression(1, "1")); |
||||
break; |
||||
case UnaryOperatorType.Decrement: |
||||
case UnaryOperatorType.PostDecrement: |
||||
expressionStatement.Expression = new AssignmentExpression(uoe.Expression, AssignmentOperatorType.Subtract, new PrimitiveExpression(1, "1")); |
||||
break; |
||||
} |
||||
} |
||||
return base.VisitExpressionStatement(expressionStatement, data); |
||||
} |
||||
|
||||
public override object VisitIfElseStatement(IfElseStatement ifElseStatement, object data) |
||||
{ |
||||
BinaryOperatorExpression boe = ifElseStatement.Condition as BinaryOperatorExpression; |
||||
// the BinaryOperatorExpression might be inside a ParenthesizedExpression
|
||||
if (boe == null && ifElseStatement.Condition is ParenthesizedExpression) { |
||||
boe = (ifElseStatement.Condition as ParenthesizedExpression).Expression as BinaryOperatorExpression; |
||||
} |
||||
if (ifElseStatement.ElseIfSections.Count == 0 |
||||
&& ifElseStatement.FalseStatement.Count == 0 |
||||
&& ifElseStatement.TrueStatement.Count == 1 |
||||
&& boe != null |
||||
&& boe.Op == BinaryOperatorType.InEquality |
||||
&& (IsNullLiteralExpression(boe.Left) || IsNullLiteralExpression(boe.Right)) |
||||
) |
||||
{ |
||||
string ident = GetPossibleEventName(boe.Left) ?? GetPossibleEventName(boe.Right); |
||||
ExpressionStatement se = ifElseStatement.TrueStatement[0] as ExpressionStatement; |
||||
if (se == null) { |
||||
BlockStatement block = ifElseStatement.TrueStatement[0] as BlockStatement; |
||||
if (block != null && block.Children.Count == 1) { |
||||
se = block.Children[0] as ExpressionStatement; |
||||
} |
||||
} |
||||
if (ident != null && se != null) { |
||||
InvocationExpression ie = se.Expression as InvocationExpression; |
||||
if (ie != null && GetPossibleEventName(ie.TargetObject) == ident) { |
||||
ReplaceCurrentNode(new RaiseEventStatement(ident, ie.Arguments)); |
||||
} |
||||
} |
||||
} |
||||
return base.VisitIfElseStatement(ifElseStatement, data); |
||||
} |
||||
|
||||
string GetPossibleEventName(Expression expression) |
||||
{ |
||||
IdentifierExpression ident = expression as IdentifierExpression; |
||||
if (ident != null) |
||||
return ident.Identifier; |
||||
MemberReferenceExpression fre = expression as MemberReferenceExpression; |
||||
if (fre != null && fre.TargetObject is ThisReferenceExpression) |
||||
return fre.MemberName; |
||||
return null; |
||||
} |
||||
|
||||
public override object VisitForStatement(ForStatement forStatement, object data) |
||||
{ |
||||
base.VisitForStatement(forStatement, data); |
||||
ConvertForStatement(forStatement); |
||||
return null; |
||||
} |
||||
|
||||
void ConvertForStatement(ForStatement forStatement) |
||||
{ |
||||
// ForStatement -> ForNextStatement when for-loop is simple
|
||||
|
||||
// only the following forms of the for-statement are allowed:
|
||||
// for (TypeReference name = start; name < oneAfterEnd; name += step)
|
||||
// for (name = start; name < oneAfterEnd; name += step)
|
||||
// for (TypeReference name = start; name <= end; name += step)
|
||||
// for (name = start; name <= end; name += step)
|
||||
// for (TypeReference name = start; name > oneAfterEnd; name -= step)
|
||||
// for (name = start; name > oneAfterEnd; name -= step)
|
||||
// for (TypeReference name = start; name >= end; name -= step)
|
||||
// for (name = start; name >= end; name -= step)
|
||||
|
||||
// check if the form is valid and collect TypeReference, name, start, end and step
|
||||
if (forStatement.Initializers.Count != 1) |
||||
return; |
||||
if (forStatement.Iterator.Count != 1) |
||||
return; |
||||
ExpressionStatement statement = forStatement.Iterator[0] as ExpressionStatement; |
||||
if (statement == null) |
||||
return; |
||||
AssignmentExpression iterator = statement.Expression as AssignmentExpression; |
||||
if (iterator == null || (iterator.Op != AssignmentOperatorType.Add && iterator.Op != AssignmentOperatorType.Subtract)) |
||||
return; |
||||
IdentifierExpression iteratorIdentifier = iterator.Left as IdentifierExpression; |
||||
if (iteratorIdentifier == null) |
||||
return; |
||||
PrimitiveExpression stepExpression = iterator.Right as PrimitiveExpression; |
||||
if (stepExpression == null || !(stepExpression.Value is int)) |
||||
return; |
||||
int step = (int)stepExpression.Value; |
||||
if (iterator.Op == AssignmentOperatorType.Subtract) |
||||
step = -step; |
||||
|
||||
BinaryOperatorExpression condition = forStatement.Condition as BinaryOperatorExpression; |
||||
if (condition == null || !(condition.Left is IdentifierExpression)) |
||||
return; |
||||
if ((condition.Left as IdentifierExpression).Identifier != iteratorIdentifier.Identifier) |
||||
return; |
||||
Expression end; |
||||
if (iterator.Op == AssignmentOperatorType.Subtract) { |
||||
if (condition.Op == BinaryOperatorType.GreaterThanOrEqual) { |
||||
end = condition.Right; |
||||
} else if (condition.Op == BinaryOperatorType.GreaterThan) { |
||||
end = Expression.AddInteger(condition.Right, 1); |
||||
} else { |
||||
return; |
||||
} |
||||
} else { |
||||
if (condition.Op == BinaryOperatorType.LessThanOrEqual) { |
||||
end = condition.Right; |
||||
} else if (condition.Op == BinaryOperatorType.LessThan) { |
||||
end = Expression.AddInteger(condition.Right, -1); |
||||
} else { |
||||
return; |
||||
} |
||||
} |
||||
|
||||
Expression start; |
||||
TypeReference typeReference = null; |
||||
LocalVariableDeclaration varDecl = forStatement.Initializers[0] as LocalVariableDeclaration; |
||||
if (varDecl != null) { |
||||
if (varDecl.Variables.Count != 1 |
||||
|| varDecl.Variables[0].Name != iteratorIdentifier.Identifier |
||||
|| varDecl.Variables[0].Initializer == null) |
||||
return; |
||||
typeReference = varDecl.GetTypeForVariable(0); |
||||
start = varDecl.Variables[0].Initializer; |
||||
} else { |
||||
statement = forStatement.Initializers[0] as ExpressionStatement; |
||||
if (statement == null) |
||||
return; |
||||
AssignmentExpression assign = statement.Expression as AssignmentExpression; |
||||
if (assign == null || assign.Op != AssignmentOperatorType.Assign) |
||||
return; |
||||
if (!(assign.Left is IdentifierExpression)) |
||||
return; |
||||
if ((assign.Left as IdentifierExpression).Identifier != iteratorIdentifier.Identifier) |
||||
return; |
||||
start = assign.Right; |
||||
} |
||||
|
||||
ReplaceCurrentNode(new ForNextStatement(typeReference, iteratorIdentifier.Identifier, |
||||
start, end, |
||||
(step == 1) ? null : new PrimitiveExpression(step, step.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)), |
||||
forStatement.EmbeddedStatement, null)); |
||||
} |
||||
|
||||
public override object VisitCastExpression(CastExpression castExpression, object data) |
||||
{ |
||||
if (castExpression.CastType == CastType.Cast) { |
||||
// Casts to value types are marked as conversions
|
||||
// this code only supports primitive types, user-defined value types are handled by
|
||||
// the DOM-aware CSharpToVBNetConvertVisitor
|
||||
string type; |
||||
if (TypeReference.PrimitiveTypesCSharpReverse.TryGetValue(castExpression.CastTo.SystemType, out type)) { |
||||
if (type != "object" && type != "string") { |
||||
// type is value type
|
||||
castExpression.CastType = CastType.Conversion; |
||||
} |
||||
} |
||||
} |
||||
return base.VisitCastExpression(castExpression, data); |
||||
} |
||||
} |
||||
} |
File diff suppressed because it is too large
Load Diff
@ -1,360 +0,0 @@
@@ -1,360 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.CodeDom; |
||||
using System.CodeDom.Compiler; |
||||
using System.IO; |
||||
using System.Security.Permissions; |
||||
|
||||
namespace ICSharpCode.NRefactory.Visitors |
||||
{ |
||||
[PermissionSet(SecurityAction.InheritanceDemand, Name = "FullTrust")] |
||||
[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] |
||||
public class CodeDomVerboseOutputGenerator : System.CodeDom.Compiler.CodeGenerator |
||||
{ |
||||
#region System.CodeDom.Compiler.CodeGenerator abstract class implementation
|
||||
protected override string NullToken { |
||||
get { |
||||
return "[NULL]"; |
||||
} |
||||
} |
||||
|
||||
protected override void OutputType(CodeTypeReference typeRef) |
||||
{ |
||||
Output.Write("[CodeTypeReference: {0}", typeRef.BaseType); |
||||
if (typeRef.ArrayRank > 0) { |
||||
Output.Write(" Rank:" + typeRef.ArrayRank); |
||||
} |
||||
Output.Write("]"); |
||||
} |
||||
|
||||
protected override void GenerateArrayCreateExpression(CodeArrayCreateExpression e) |
||||
{ |
||||
Output.Write("[CodeArrayCreateExpression: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateBaseReferenceExpression(CodeBaseReferenceExpression e) |
||||
{ |
||||
Output.Write("[CodeBaseReferenceExpression: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateCastExpression(CodeCastExpression e) |
||||
{ |
||||
Output.Write("[CodeCastExpression: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateDelegateCreateExpression(CodeDelegateCreateExpression e) |
||||
{ |
||||
Output.Write("[CodeDelegateCreateExpression: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateFieldReferenceExpression(CodeFieldReferenceExpression e) |
||||
{ |
||||
Output.Write("[CodeFieldReferenceExpression: Name={0}, Target=", e.FieldName); |
||||
this.GenerateExpression(e.TargetObject); |
||||
Output.Write("]"); |
||||
} |
||||
|
||||
protected override void GenerateMethodReferenceExpression(CodeMethodReferenceExpression e) |
||||
{ |
||||
Output.Write("[CodeMethodReferenceExpression: Name={0}, Target=", e.MethodName); |
||||
this.GenerateExpression(e.TargetObject); |
||||
Output.Write("]"); |
||||
} |
||||
|
||||
protected override void GenerateEventReferenceExpression(CodeEventReferenceExpression e) |
||||
{ |
||||
Output.Write("[CodeEventReferenceExpression: Name={0}, Target=", e.EventName); |
||||
this.GenerateExpression(e.TargetObject); |
||||
Output.Write("]"); |
||||
} |
||||
|
||||
protected override void GenerateArgumentReferenceExpression(CodeArgumentReferenceExpression e) |
||||
{ |
||||
Output.Write("[CodeArgumentReferenceExpression: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateVariableReferenceExpression(CodeVariableReferenceExpression e) |
||||
{ |
||||
Output.Write("[CodeVariableReferenceExpression: Name={0}]", e.VariableName); |
||||
} |
||||
|
||||
protected override void GenerateIndexerExpression(CodeIndexerExpression e) |
||||
{ |
||||
Output.Write("[CodeIndexerExpression: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateArrayIndexerExpression(CodeArrayIndexerExpression e) |
||||
{ |
||||
Output.Write("[CodeArrayIndexerExpression: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateSnippetExpression(CodeSnippetExpression e) |
||||
{ |
||||
Output.Write("[CodeSnippetExpression: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateMethodInvokeExpression(CodeMethodInvokeExpression e) |
||||
{ |
||||
Output.Write("[CodeMethodInvokeExpression: Method="); |
||||
GenerateMethodReferenceExpression(e.Method); |
||||
Output.Write(", Parameters="); |
||||
bool first = true; |
||||
foreach (CodeExpression expr in e.Parameters) { |
||||
if (first) first = false; else Output.Write(", "); |
||||
this.GenerateExpression(expr); |
||||
} |
||||
Output.Write("]"); |
||||
} |
||||
|
||||
protected override void GenerateDelegateInvokeExpression(CodeDelegateInvokeExpression e) |
||||
{ |
||||
Output.Write("[CodeDelegateInvokeExpression: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateObjectCreateExpression(CodeObjectCreateExpression e) |
||||
{ |
||||
Output.Write("[CodeObjectCreateExpression: Type={0}, Parameters=", e.CreateType.BaseType); |
||||
bool first = true; |
||||
foreach (CodeExpression expr in e.Parameters) { |
||||
if (first) first = false; else Output.Write(", "); |
||||
this.GenerateExpression(expr); |
||||
} |
||||
Output.Write("]"); |
||||
} |
||||
|
||||
protected override void GeneratePropertyReferenceExpression(CodePropertyReferenceExpression e) |
||||
{ |
||||
Output.Write("[CodePropertyReferenceExpression: Name={0}, Target=", e.PropertyName); |
||||
this.GenerateExpression(e.TargetObject); |
||||
Output.Write("]"); |
||||
} |
||||
|
||||
protected override void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e) |
||||
{ |
||||
Output.Write("[CodePropertySetValueReferenceExpression: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateThisReferenceExpression(CodeThisReferenceExpression e) |
||||
{ |
||||
Output.Write("[CodeThisReferenceExpression]"); |
||||
} |
||||
|
||||
protected override void GenerateExpressionStatement(CodeExpressionStatement e) |
||||
{ |
||||
Output.Write("[CodeExpressionStatement:"); |
||||
base.GenerateExpression(e.Expression); |
||||
Output.WriteLine("]"); |
||||
} |
||||
|
||||
protected override void GenerateIterationStatement(CodeIterationStatement e) |
||||
{ |
||||
Output.WriteLine("[CodeIterationStatement: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateThrowExceptionStatement(CodeThrowExceptionStatement e) |
||||
{ |
||||
Output.WriteLine("[CodeThrowExceptionStatement: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateComment(CodeComment e) |
||||
{ |
||||
Output.WriteLine("[CodeComment: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateMethodReturnStatement(CodeMethodReturnStatement e) |
||||
{ |
||||
Output.WriteLine("[CodeMethodReturnStatement: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateConditionStatement(CodeConditionStatement e) |
||||
{ |
||||
Output.WriteLine("[GenerateConditionStatement: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e) |
||||
{ |
||||
Output.WriteLine("[CodeTryCatchFinallyStatement: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateAssignStatement(CodeAssignStatement e) |
||||
{ |
||||
Output.Write("[CodeAssignStatement: Left="); |
||||
base.GenerateExpression(e.Left); |
||||
Output.Write(", Right="); |
||||
base.GenerateExpression(e.Right); |
||||
Output.WriteLine("]"); |
||||
} |
||||
|
||||
protected override void GenerateAttachEventStatement(CodeAttachEventStatement e) |
||||
{ |
||||
Output.WriteLine("[CodeAttachEventStatement: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateRemoveEventStatement(CodeRemoveEventStatement e) |
||||
{ |
||||
Output.WriteLine("[CodeRemoveEventStatement: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateGotoStatement(CodeGotoStatement e) |
||||
{ |
||||
Output.WriteLine("[CodeGotoStatement: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateLabeledStatement(CodeLabeledStatement e) |
||||
{ |
||||
Output.WriteLine("[CodeLabeledStatement: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateVariableDeclarationStatement(CodeVariableDeclarationStatement e) |
||||
{ |
||||
Output.WriteLine("[CodeVariableDeclarationStatement: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateLinePragmaStart(CodeLinePragma e) |
||||
{ |
||||
Output.WriteLine("[CodeLinePragma: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateLinePragmaEnd(CodeLinePragma e) |
||||
{ |
||||
Output.WriteLine("[CodeLinePragma: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c) |
||||
{ |
||||
Output.WriteLine("[CodeMemberEvent: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateField(CodeMemberField e) |
||||
{ |
||||
Output.Write("[CodeMemberField: Name={0}, Type=", e.Name); |
||||
Output.Write(e.Type.BaseType); |
||||
Output.WriteLine("]"); |
||||
} |
||||
|
||||
protected override void GenerateSnippetMember(CodeSnippetTypeMember e) |
||||
{ |
||||
Output.WriteLine("[CodeSnippetTypeMember: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateEntryPointMethod(CodeEntryPointMethod e, CodeTypeDeclaration c) |
||||
{ |
||||
Output.WriteLine("[CodeEntryPointMethod: {0}]", e.ToString()); |
||||
} |
||||
|
||||
public void PublicGenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o) |
||||
{ |
||||
((ICodeGenerator)this).GenerateCodeFromStatement(e, w, o); |
||||
} |
||||
|
||||
protected override void GenerateMethod(CodeMemberMethod e, CodeTypeDeclaration c) |
||||
{ |
||||
Output.WriteLine("[CodeMemberMethod: Name={0}, Parameterns={1}]", e.Name, e.Parameters.Count); |
||||
++Indent; |
||||
GenerateStatements(e.Statements); |
||||
--Indent; |
||||
} |
||||
|
||||
protected override void GenerateProperty(CodeMemberProperty e, CodeTypeDeclaration c) |
||||
{ |
||||
Output.WriteLine("[CodeMemberProperty : {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateConstructor(CodeConstructor e, CodeTypeDeclaration c) |
||||
{ |
||||
Output.WriteLine("[CodeConstructor : {0}]", e.ToString()); |
||||
++Indent; |
||||
GenerateStatements(e.Statements); |
||||
--Indent; |
||||
} |
||||
|
||||
protected override void GenerateTypeConstructor(CodeTypeConstructor e) |
||||
{ |
||||
Output.WriteLine("[CodeTypeConstructor : {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateTypeStart(CodeTypeDeclaration e) |
||||
{ |
||||
Output.WriteLine("[CodeTypeDeclaration : {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateTypeEnd(CodeTypeDeclaration e) |
||||
{ |
||||
Output.WriteLine("[CodeTypeDeclaration: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateNamespaceStart(CodeNamespace e) |
||||
{ |
||||
Output.WriteLine("[CodeNamespaceStart: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateNamespaceEnd(CodeNamespace e) |
||||
{ |
||||
Output.WriteLine("[CodeNamespaceEnd: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateNamespaceImport(CodeNamespaceImport e) |
||||
{ |
||||
Output.WriteLine("[CodeNamespaceImport: {0}]", e.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateAttributeDeclarationsStart(CodeAttributeDeclarationCollection attributes) |
||||
{ |
||||
Output.WriteLine("[CodeAttributeDeclarationCollection: {0}]", attributes.ToString()); |
||||
} |
||||
|
||||
protected override void GenerateAttributeDeclarationsEnd(CodeAttributeDeclarationCollection attributes) |
||||
{ |
||||
Output.WriteLine("[CodeAttributeDeclarationCollection: {0}]", attributes.ToString()); |
||||
} |
||||
|
||||
protected override void GeneratePrimitiveExpression(CodePrimitiveExpression e) |
||||
{ |
||||
if (e.Value == null) { |
||||
Output.WriteLine("[CodePrimitiveExpression: null]"); |
||||
} else { |
||||
Output.Write("[CodePrimitiveExpression: "); |
||||
base.GeneratePrimitiveExpression(e); |
||||
Output.WriteLine(" (" + e.Value.GetType().Name + ")]"); |
||||
} |
||||
} |
||||
|
||||
protected override bool Supports(GeneratorSupport support) |
||||
{ |
||||
return true; |
||||
} |
||||
|
||||
protected override bool IsValidIdentifier(string value) |
||||
{ |
||||
return true; |
||||
} |
||||
|
||||
protected override string CreateEscapedIdentifier(string value) |
||||
{ |
||||
return value; |
||||
} |
||||
|
||||
protected override string CreateValidIdentifier(string value) |
||||
{ |
||||
return value; |
||||
} |
||||
|
||||
protected override string GetTypeOutput(CodeTypeReference value) |
||||
{ |
||||
return value.ToString(); |
||||
} |
||||
|
||||
protected override string QuoteSnippetString(string value) |
||||
{ |
||||
return "\"" + value + "\""; |
||||
} |
||||
|
||||
#endregion
|
||||
} |
||||
} |
@ -1,28 +0,0 @@
@@ -1,28 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
namespace ICSharpCode.NRefactory.Visitors |
||||
{ |
||||
/// <summary>
|
||||
/// Base class for the conversion visitors.
|
||||
/// </summary>
|
||||
public class ConvertVisitorBase : AbstractAstTransformer |
||||
{ |
||||
// inserting before current position is not allowed in a Transformer
|
||||
// but inserting after it is possible
|
||||
protected void InsertAfterSibling(INode sibling, INode newNode) |
||||
{ |
||||
if (sibling == null || sibling.Parent == null) return; |
||||
int index = sibling.Parent.Children.IndexOf(sibling); |
||||
sibling.Parent.Children.Insert(index + 1, newNode); |
||||
newNode.Parent = sibling.Parent; |
||||
} |
||||
} |
||||
} |
@ -1,280 +0,0 @@
@@ -1,280 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="none" email=""/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
|
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
namespace ICSharpCode.NRefactory.Visitors |
||||
{ |
||||
public sealed class LocalLookupVariable |
||||
{ |
||||
public readonly string Name; |
||||
public readonly TypeReference TypeRef; |
||||
public readonly Location StartPos; |
||||
public readonly Location EndPos; |
||||
public readonly bool IsConst; |
||||
public readonly bool IsLoopVariable; |
||||
public readonly Expression Initializer; |
||||
|
||||
public LocalLookupVariable(string name, TypeReference typeRef, Location startPos, Location endPos, bool isConst, bool isLoopVariable, Expression initializer) |
||||
{ |
||||
this.Name = name; |
||||
this.TypeRef = typeRef; |
||||
this.StartPos = startPos; |
||||
this.EndPos = endPos; |
||||
this.IsConst = isConst; |
||||
this.IsLoopVariable = isLoopVariable; |
||||
this.Initializer = initializer; |
||||
} |
||||
} |
||||
|
||||
public sealed class LookupTableVisitor : AbstractAstVisitor |
||||
{ |
||||
Dictionary<string, List<LocalLookupVariable>> variables; |
||||
SupportedLanguage language; |
||||
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] |
||||
public Dictionary<string, List<LocalLookupVariable>> Variables { |
||||
get { |
||||
return variables; |
||||
} |
||||
} |
||||
|
||||
List<WithStatement> withStatements = new List<WithStatement>(); |
||||
|
||||
public List<WithStatement> WithStatements { |
||||
get { |
||||
return withStatements; |
||||
} |
||||
} |
||||
|
||||
public LookupTableVisitor(SupportedLanguage language) |
||||
{ |
||||
this.language = language; |
||||
if (language == SupportedLanguage.VBNet) { |
||||
variables = new Dictionary<string, List<LocalLookupVariable>>(StringComparer.InvariantCultureIgnoreCase); |
||||
} else { |
||||
variables = new Dictionary<string, List<LocalLookupVariable>>(StringComparer.InvariantCulture); |
||||
} |
||||
} |
||||
|
||||
public void AddVariable(TypeReference typeRef, string name, |
||||
Location startPos, Location endPos, bool isConst, |
||||
bool isLoopVariable, Expression initializer) |
||||
{ |
||||
if (name == null || name.Length == 0) { |
||||
return; |
||||
} |
||||
List<LocalLookupVariable> list; |
||||
if (!variables.ContainsKey(name)) { |
||||
variables[name] = list = new List<LocalLookupVariable>(); |
||||
} else { |
||||
list = (List<LocalLookupVariable>)variables[name]; |
||||
} |
||||
list.Add(new LocalLookupVariable(name, typeRef, startPos, endPos, isConst, isLoopVariable, initializer)); |
||||
} |
||||
|
||||
public override object VisitWithStatement(WithStatement withStatement, object data) |
||||
{ |
||||
withStatements.Add(withStatement); |
||||
return base.VisitWithStatement(withStatement, data); |
||||
} |
||||
|
||||
Stack<Location> endLocationStack = new Stack<Location>(); |
||||
|
||||
Location CurrentEndLocation { |
||||
get { |
||||
return (endLocationStack.Count == 0) ? Location.Empty : endLocationStack.Peek(); |
||||
} |
||||
} |
||||
|
||||
public override object VisitBlockStatement(BlockStatement blockStatement, object data) |
||||
{ |
||||
endLocationStack.Push(blockStatement.EndLocation); |
||||
base.VisitBlockStatement(blockStatement, data); |
||||
endLocationStack.Pop(); |
||||
return null; |
||||
} |
||||
|
||||
public override object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) |
||||
{ |
||||
for (int i = 0; i < localVariableDeclaration.Variables.Count; ++i) { |
||||
VariableDeclaration varDecl = (VariableDeclaration)localVariableDeclaration.Variables[i]; |
||||
|
||||
AddVariable(localVariableDeclaration.GetTypeForVariable(i), |
||||
varDecl.Name, |
||||
localVariableDeclaration.StartLocation, |
||||
CurrentEndLocation, |
||||
(localVariableDeclaration.Modifier & Modifiers.Const) == Modifiers.Const, |
||||
false, varDecl.Initializer); |
||||
} |
||||
return base.VisitLocalVariableDeclaration(localVariableDeclaration, data); |
||||
} |
||||
|
||||
public override object VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression, object data) |
||||
{ |
||||
foreach (ParameterDeclarationExpression p in anonymousMethodExpression.Parameters) { |
||||
AddVariable(p.TypeReference, p.ParameterName, |
||||
anonymousMethodExpression.StartLocation, anonymousMethodExpression.EndLocation, |
||||
false, false, null); |
||||
} |
||||
return base.VisitAnonymousMethodExpression(anonymousMethodExpression, data); |
||||
} |
||||
|
||||
public override object VisitLambdaExpression(LambdaExpression lambdaExpression, object data) |
||||
{ |
||||
foreach (ParameterDeclarationExpression p in lambdaExpression.Parameters) { |
||||
AddVariable(p.TypeReference, p.ParameterName, |
||||
lambdaExpression.StartLocation, lambdaExpression.EndLocation, |
||||
false, false, null); |
||||
} |
||||
return base.VisitLambdaExpression(lambdaExpression, data); |
||||
} |
||||
|
||||
public override object VisitQueryExpressionFromClause(QueryExpressionFromClause fromClause, object data) |
||||
{ |
||||
QueryExpression parentExpression = fromClause.Parent as QueryExpression; |
||||
if (parentExpression != null) { |
||||
AddVariable(fromClause.Type, fromClause.Identifier, |
||||
parentExpression.StartLocation, parentExpression.EndLocation, |
||||
false, true, fromClause.InExpression); |
||||
} |
||||
return base.VisitQueryExpressionFromClause(fromClause, data); |
||||
} |
||||
|
||||
public override object VisitQueryExpressionJoinClause(QueryExpressionJoinClause joinClause, object data) |
||||
{ |
||||
if (string.IsNullOrEmpty(joinClause.IntoIdentifier)) { |
||||
QueryExpression parentExpression = joinClause.Parent as QueryExpression; |
||||
if (parentExpression != null) { |
||||
AddVariable(joinClause.Type, joinClause.Identifier, |
||||
parentExpression.StartLocation, parentExpression.EndLocation, |
||||
false, true, joinClause.InExpression); |
||||
} |
||||
} else { |
||||
AddVariable(joinClause.Type, joinClause.Identifier, |
||||
joinClause.StartLocation, joinClause.EndLocation, |
||||
false, true, joinClause.InExpression); |
||||
|
||||
QueryExpression parentExpression = joinClause.Parent as QueryExpression; |
||||
if (parentExpression != null) { |
||||
AddVariable(joinClause.Type, joinClause.IntoIdentifier, |
||||
parentExpression.StartLocation, parentExpression.EndLocation, |
||||
false, false, joinClause.InExpression); |
||||
} |
||||
} |
||||
return base.VisitQueryExpressionJoinClause(joinClause, data); |
||||
} |
||||
|
||||
public override object VisitQueryExpressionLetClause(QueryExpressionLetClause letClause, object data) |
||||
{ |
||||
QueryExpression parentExpression = letClause.Parent as QueryExpression; |
||||
if (parentExpression != null) { |
||||
AddVariable(null, letClause.Identifier, |
||||
parentExpression.StartLocation, parentExpression.EndLocation, |
||||
false, false, letClause.Expression); |
||||
} |
||||
return base.VisitQueryExpressionLetClause(letClause, data); |
||||
} |
||||
|
||||
public override object VisitForNextStatement(ForNextStatement forNextStatement, object data) |
||||
{ |
||||
// uses LocalVariableDeclaration, we just have to put the end location on the stack
|
||||
if (forNextStatement.EmbeddedStatement.EndLocation.IsEmpty) { |
||||
return base.VisitForNextStatement(forNextStatement, data); |
||||
} else { |
||||
endLocationStack.Push(forNextStatement.EmbeddedStatement.EndLocation); |
||||
base.VisitForNextStatement(forNextStatement, data); |
||||
endLocationStack.Pop(); |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
public override object VisitForStatement(ForStatement forStatement, object data) |
||||
{ |
||||
// uses LocalVariableDeclaration, we just have to put the end location on the stack
|
||||
if (forStatement.EmbeddedStatement.EndLocation.IsEmpty) { |
||||
return base.VisitForStatement(forStatement, data); |
||||
} else { |
||||
endLocationStack.Push(forStatement.EmbeddedStatement.EndLocation); |
||||
base.VisitForStatement(forStatement, data); |
||||
endLocationStack.Pop(); |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
public override object VisitUsingStatement(UsingStatement usingStatement, object data) |
||||
{ |
||||
// uses LocalVariableDeclaration, we just have to put the end location on the stack
|
||||
if (usingStatement.EmbeddedStatement.EndLocation.IsEmpty) { |
||||
return base.VisitUsingStatement(usingStatement, data); |
||||
} else { |
||||
endLocationStack.Push(usingStatement.EmbeddedStatement.EndLocation); |
||||
base.VisitUsingStatement(usingStatement, data); |
||||
endLocationStack.Pop(); |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
public override object VisitSwitchSection(SwitchSection switchSection, object data) |
||||
{ |
||||
if (language == SupportedLanguage.VBNet) { |
||||
return VisitBlockStatement(switchSection, data); |
||||
} else { |
||||
return base.VisitSwitchSection(switchSection, data); |
||||
} |
||||
} |
||||
|
||||
public override object VisitForeachStatement(ForeachStatement foreachStatement, object data) |
||||
{ |
||||
AddVariable(foreachStatement.TypeReference, |
||||
foreachStatement.VariableName, |
||||
foreachStatement.StartLocation, |
||||
foreachStatement.EndLocation, |
||||
false, true, |
||||
foreachStatement.Expression); |
||||
|
||||
if (foreachStatement.Expression != null) { |
||||
foreachStatement.Expression.AcceptVisitor(this, data); |
||||
} |
||||
if (foreachStatement.EmbeddedStatement == null) { |
||||
return data; |
||||
} |
||||
return foreachStatement.EmbeddedStatement.AcceptVisitor(this, data); |
||||
} |
||||
|
||||
public override object VisitTryCatchStatement(TryCatchStatement tryCatchStatement, object data) |
||||
{ |
||||
if (tryCatchStatement == null) { |
||||
return data; |
||||
} |
||||
if (tryCatchStatement.StatementBlock != null) { |
||||
tryCatchStatement.StatementBlock.AcceptVisitor(this, data); |
||||
} |
||||
if (tryCatchStatement.CatchClauses != null) { |
||||
foreach (CatchClause catchClause in tryCatchStatement.CatchClauses) { |
||||
if (catchClause != null) { |
||||
if (catchClause.TypeReference != null && catchClause.VariableName != null) { |
||||
AddVariable(catchClause.TypeReference, |
||||
catchClause.VariableName, |
||||
catchClause.StatementBlock.StartLocation, |
||||
catchClause.StatementBlock.EndLocation, |
||||
false, false, null); |
||||
} |
||||
catchClause.StatementBlock.AcceptVisitor(this, data); |
||||
} |
||||
} |
||||
} |
||||
if (tryCatchStatement.FinallyBlock != null) { |
||||
return tryCatchStatement.FinallyBlock.AcceptVisitor(this, data); |
||||
} |
||||
return data; |
||||
} |
||||
} |
||||
} |
File diff suppressed because it is too large
Load Diff
@ -1,147 +0,0 @@
@@ -1,147 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
namespace ICSharpCode.NRefactory.Visitors |
||||
{ |
||||
/// <summary>
|
||||
/// Prefixes the names of the specified fields with the prefix and replaces the use.
|
||||
/// </summary>
|
||||
public class PrefixFieldsVisitor : AbstractAstVisitor |
||||
{ |
||||
List<VariableDeclaration> fields; |
||||
List<string> curBlock = new List<string>(); |
||||
Stack<List<string>> blocks = new Stack<List<string>>(); |
||||
string prefix; |
||||
|
||||
public PrefixFieldsVisitor(List<VariableDeclaration> fields, string prefix) |
||||
{ |
||||
this.fields = fields; |
||||
this.prefix = prefix; |
||||
} |
||||
|
||||
public void Run(INode typeDeclaration) |
||||
{ |
||||
typeDeclaration.AcceptVisitor(this, null); |
||||
foreach (VariableDeclaration decl in fields) { |
||||
decl.Name = prefix + decl.Name; |
||||
} |
||||
} |
||||
|
||||
public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data) |
||||
{ |
||||
Push(); |
||||
object result = base.VisitTypeDeclaration(typeDeclaration, data); |
||||
Pop(); |
||||
return result; |
||||
} |
||||
|
||||
public override object VisitBlockStatement(BlockStatement blockStatement, object data) |
||||
{ |
||||
Push(); |
||||
object result = base.VisitBlockStatement(blockStatement, data); |
||||
Pop(); |
||||
return result; |
||||
} |
||||
|
||||
public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data) |
||||
{ |
||||
Push(); |
||||
object result = base.VisitMethodDeclaration(methodDeclaration, data); |
||||
Pop(); |
||||
return result; |
||||
} |
||||
|
||||
public override object VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, object data) |
||||
{ |
||||
Push(); |
||||
object result = base.VisitPropertyDeclaration(propertyDeclaration, data); |
||||
Pop(); |
||||
return result; |
||||
} |
||||
|
||||
public override object VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, object data) |
||||
{ |
||||
Push(); |
||||
object result = base.VisitConstructorDeclaration(constructorDeclaration, data); |
||||
Pop(); |
||||
return result; |
||||
} |
||||
|
||||
private void Push() |
||||
{ |
||||
blocks.Push(curBlock); |
||||
curBlock = new List<string>(); |
||||
} |
||||
|
||||
private void Pop() |
||||
{ |
||||
curBlock = blocks.Pop(); |
||||
} |
||||
|
||||
public override object VisitVariableDeclaration(VariableDeclaration variableDeclaration, object data) |
||||
{ |
||||
// process local variables only
|
||||
if (fields.Contains(variableDeclaration)) { |
||||
return null; |
||||
} |
||||
curBlock.Add(variableDeclaration.Name); |
||||
return base.VisitVariableDeclaration(variableDeclaration, data); |
||||
} |
||||
|
||||
public override object VisitParameterDeclarationExpression(ParameterDeclarationExpression parameterDeclarationExpression, object data) |
||||
{ |
||||
curBlock.Add(parameterDeclarationExpression.ParameterName); |
||||
//print("add parameter ${parameterDeclarationExpression.ParameterName} to block")
|
||||
return base.VisitParameterDeclarationExpression(parameterDeclarationExpression, data); |
||||
} |
||||
|
||||
public override object VisitForeachStatement(ForeachStatement foreachStatement, object data) |
||||
{ |
||||
curBlock.Add(foreachStatement.VariableName); |
||||
return base.VisitForeachStatement(foreachStatement, data); |
||||
} |
||||
|
||||
public override object VisitIdentifierExpression(IdentifierExpression identifierExpression, object data) |
||||
{ |
||||
string name = identifierExpression.Identifier; |
||||
foreach (VariableDeclaration var in fields) { |
||||
if (var.Name == name && !IsLocal(name)) { |
||||
identifierExpression.Identifier = prefix + name; |
||||
break; |
||||
} |
||||
} |
||||
return base.VisitIdentifierExpression(identifierExpression, data); |
||||
} |
||||
|
||||
public override object VisitMemberReferenceExpression(MemberReferenceExpression fieldReferenceExpression, object data) |
||||
{ |
||||
if (fieldReferenceExpression.TargetObject is ThisReferenceExpression) { |
||||
string name = fieldReferenceExpression.MemberName; |
||||
foreach (VariableDeclaration var in fields) { |
||||
if (var.Name == name) { |
||||
fieldReferenceExpression.MemberName = prefix + name; |
||||
break; |
||||
} |
||||
} |
||||
} |
||||
return base.VisitMemberReferenceExpression(fieldReferenceExpression, data); |
||||
} |
||||
|
||||
bool IsLocal(string name) |
||||
{ |
||||
foreach (List<string> block in blocks) { |
||||
if (block.Contains(name)) |
||||
return true; |
||||
} |
||||
return curBlock.Contains(name); |
||||
} |
||||
} |
||||
} |
@ -1,65 +0,0 @@
@@ -1,65 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
namespace ICSharpCode.NRefactory.Visitors |
||||
{ |
||||
class RenameIdentifierVisitor : AbstractAstVisitor |
||||
{ |
||||
protected StringComparer nameComparer; |
||||
protected string from, to; |
||||
|
||||
public RenameIdentifierVisitor(string from, string to, StringComparer nameComparer) |
||||
{ |
||||
this.nameComparer = nameComparer; |
||||
this.from = from; |
||||
this.to = to; |
||||
} |
||||
|
||||
public override object VisitIdentifierExpression(IdentifierExpression identifierExpression, object data) |
||||
{ |
||||
if (nameComparer.Equals(identifierExpression.Identifier, from)) { |
||||
identifierExpression.Identifier = to; |
||||
} |
||||
return base.VisitIdentifierExpression(identifierExpression, data); |
||||
} |
||||
} |
||||
|
||||
sealed class RenameLocalVariableVisitor : RenameIdentifierVisitor |
||||
{ |
||||
public RenameLocalVariableVisitor(string from, string to, StringComparer nameComparer) |
||||
: base(from, to, nameComparer) |
||||
{ |
||||
} |
||||
|
||||
public override object VisitVariableDeclaration(VariableDeclaration variableDeclaration, object data) |
||||
{ |
||||
if (nameComparer.Equals(from, variableDeclaration.Name)) { |
||||
variableDeclaration.Name = to; |
||||
} |
||||
return base.VisitVariableDeclaration(variableDeclaration, data); |
||||
} |
||||
|
||||
public override object VisitParameterDeclarationExpression(ParameterDeclarationExpression parameterDeclarationExpression, object data) |
||||
{ |
||||
if (nameComparer.Equals(from, parameterDeclarationExpression.ParameterName)) { |
||||
parameterDeclarationExpression.ParameterName = to; |
||||
} |
||||
return base.VisitParameterDeclarationExpression(parameterDeclarationExpression, data); |
||||
} |
||||
|
||||
public override object VisitForeachStatement(ForeachStatement foreachStatement, object data) |
||||
{ |
||||
if (nameComparer.Equals(from, foreachStatement.VariableName)) { |
||||
foreachStatement.VariableName = to; |
||||
} |
||||
return base.VisitForeachStatement(foreachStatement, data); |
||||
} |
||||
} |
||||
} |
@ -1,229 +0,0 @@
@@ -1,229 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
namespace ICSharpCode.NRefactory.Visitors |
||||
{ |
||||
/// <summary>
|
||||
/// Converts elements not supported by C# to their C# representation.
|
||||
/// Not all elements are converted here, most simple elements (e.g. StopStatement)
|
||||
/// are converted in the output visitor.
|
||||
/// </summary>
|
||||
public class ToCSharpConvertVisitor : ConvertVisitorBase |
||||
{ |
||||
// The following conversions are implemented:
|
||||
// Public Event EventName(param As String) -> automatic delegate declaration
|
||||
// static variables inside methods become fields
|
||||
// Explicit interface implementation:
|
||||
// => create additional member for implementing the interface
|
||||
// or convert to implicit interface implementation
|
||||
// Modules: make all members static
|
||||
|
||||
public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data) |
||||
{ |
||||
if (typeDeclaration.Type == ClassType.Module) { |
||||
typeDeclaration.Type = ClassType.Class; |
||||
typeDeclaration.Modifier |= Modifiers.Static; |
||||
foreach (INode node in typeDeclaration.Children) { |
||||
MemberNode aNode = node as MemberNode; |
||||
if (aNode != null) { |
||||
aNode.Modifier |= Modifiers.Static; |
||||
} |
||||
FieldDeclaration fd = node as FieldDeclaration; |
||||
if (fd != null) { |
||||
fd.Modifier |= Modifiers.Static; |
||||
} |
||||
} |
||||
} |
||||
|
||||
return base.VisitTypeDeclaration(typeDeclaration, data); |
||||
} |
||||
|
||||
public override object VisitEventDeclaration(EventDeclaration eventDeclaration, object data) |
||||
{ |
||||
if (!eventDeclaration.HasAddRegion && !eventDeclaration.HasRaiseRegion && !eventDeclaration.HasRemoveRegion) { |
||||
if (eventDeclaration.TypeReference.IsNull) { |
||||
DelegateDeclaration dd = new DelegateDeclaration(eventDeclaration.Modifier, null); |
||||
dd.Name = eventDeclaration.Name + "EventHandler"; |
||||
dd.Parameters = eventDeclaration.Parameters; |
||||
dd.ReturnType = new TypeReference("System.Void"); |
||||
dd.Parent = eventDeclaration.Parent; |
||||
eventDeclaration.Parameters = null; |
||||
InsertAfterSibling(eventDeclaration, dd); |
||||
eventDeclaration.TypeReference = new TypeReference(dd.Name); |
||||
} |
||||
} |
||||
return base.VisitEventDeclaration(eventDeclaration, data); |
||||
} |
||||
|
||||
public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data) |
||||
{ |
||||
ConvertInterfaceImplementation(methodDeclaration); |
||||
return base.VisitMethodDeclaration(methodDeclaration, data); |
||||
} |
||||
|
||||
void ConvertInterfaceImplementation(MethodDeclaration member) |
||||
{ |
||||
// members without modifiers are already C# explicit interface implementations, do not convert them
|
||||
if (member.Modifier == Modifiers.None) |
||||
return; |
||||
while (member.InterfaceImplementations.Count > 0) { |
||||
InterfaceImplementation impl = member.InterfaceImplementations[0]; |
||||
member.InterfaceImplementations.RemoveAt(0); |
||||
if (member.Name != impl.MemberName) { |
||||
MethodDeclaration newMember = new MethodDeclaration { |
||||
Name = impl.MemberName, |
||||
TypeReference = member.TypeReference, |
||||
Parameters = member.Parameters, |
||||
Body = new BlockStatement() |
||||
}; |
||||
InvocationExpression callExpression = new InvocationExpression(new IdentifierExpression(member.Name)); |
||||
foreach (ParameterDeclarationExpression decl in member.Parameters) { |
||||
callExpression.Arguments.Add(new IdentifierExpression(decl.ParameterName)); |
||||
} |
||||
if (member.TypeReference.SystemType == "System.Void") { |
||||
newMember.Body.AddChild(new ExpressionStatement(callExpression)); |
||||
} else { |
||||
newMember.Body.AddChild(new ReturnStatement(callExpression)); |
||||
} |
||||
newMember.InterfaceImplementations.Add(impl); |
||||
InsertAfterSibling(member, newMember); |
||||
} |
||||
} |
||||
} |
||||
|
||||
public override object VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, object data) |
||||
{ |
||||
ConvertInterfaceImplementation(propertyDeclaration); |
||||
return base.VisitPropertyDeclaration(propertyDeclaration, data); |
||||
} |
||||
|
||||
void ConvertInterfaceImplementation(PropertyDeclaration member) |
||||
{ |
||||
// members without modifiers are already C# explicit interface implementations, do not convert them
|
||||
if (member.Modifier == Modifiers.None) |
||||
return; |
||||
while (member.InterfaceImplementations.Count > 0) { |
||||
InterfaceImplementation impl = member.InterfaceImplementations[0]; |
||||
member.InterfaceImplementations.RemoveAt(0); |
||||
if (member.Name != impl.MemberName) { |
||||
PropertyDeclaration newMember = new PropertyDeclaration(Modifiers.None, null, impl.MemberName, null); |
||||
newMember.TypeReference = member.TypeReference; |
||||
if (member.HasGetRegion) { |
||||
newMember.GetRegion = new PropertyGetRegion(new BlockStatement(), null); |
||||
newMember.GetRegion.Block.AddChild(new ReturnStatement(new IdentifierExpression(member.Name))); |
||||
} |
||||
if (member.HasSetRegion) { |
||||
newMember.SetRegion = new PropertySetRegion(new BlockStatement(), null); |
||||
newMember.SetRegion.Block.AddChild(new ExpressionStatement( |
||||
new AssignmentExpression( |
||||
new IdentifierExpression(member.Name), |
||||
AssignmentOperatorType.Assign, |
||||
new IdentifierExpression("value") |
||||
))); |
||||
} |
||||
newMember.Parameters = member.Parameters; |
||||
newMember.InterfaceImplementations.Add(impl); |
||||
InsertAfterSibling(member, newMember); |
||||
} |
||||
} |
||||
} |
||||
|
||||
public override object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) |
||||
{ |
||||
base.VisitLocalVariableDeclaration(localVariableDeclaration, data); |
||||
if ((localVariableDeclaration.Modifier & Modifiers.Static) == Modifiers.Static) { |
||||
INode parent = localVariableDeclaration.Parent; |
||||
while (parent != null && !IsTypeLevel(parent)) { |
||||
parent = parent.Parent; |
||||
} |
||||
if (parent != null) { |
||||
INode type = parent.Parent; |
||||
if (type != null) { |
||||
int pos = type.Children.IndexOf(parent); |
||||
if (pos >= 0) { |
||||
FieldDeclaration field = new FieldDeclaration(null); |
||||
field.TypeReference = localVariableDeclaration.TypeReference; |
||||
field.Modifier = Modifiers.Static; |
||||
field.Fields = localVariableDeclaration.Variables; |
||||
new PrefixFieldsVisitor(field.Fields, "static_" + GetTypeLevelEntityName(parent) + "_").Run(parent); |
||||
type.Children.Insert(pos + 1, field); |
||||
RemoveCurrentNode(); |
||||
} |
||||
} |
||||
} |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
public override object VisitWithStatement(WithStatement withStatement, object data) |
||||
{ |
||||
withStatement.Body.AcceptVisitor(new ReplaceWithAccessTransformer(withStatement.Expression), data); |
||||
base.VisitWithStatement(withStatement, data); |
||||
ReplaceCurrentNode(withStatement.Body); |
||||
return null; |
||||
} |
||||
|
||||
sealed class ReplaceWithAccessTransformer : AbstractAstTransformer |
||||
{ |
||||
readonly Expression replaceWith; |
||||
|
||||
public ReplaceWithAccessTransformer(Expression replaceWith) |
||||
{ |
||||
this.replaceWith = replaceWith; |
||||
} |
||||
|
||||
public override object VisitMemberReferenceExpression(MemberReferenceExpression fieldReferenceExpression, object data) |
||||
{ |
||||
if (fieldReferenceExpression.TargetObject.IsNull) { |
||||
fieldReferenceExpression.TargetObject = replaceWith; |
||||
return null; |
||||
} else { |
||||
return base.VisitMemberReferenceExpression(fieldReferenceExpression, data); |
||||
} |
||||
} |
||||
|
||||
public override object VisitWithStatement(WithStatement withStatement, object data) |
||||
{ |
||||
// do not visit the body of the WithStatement
|
||||
return withStatement.Expression.AcceptVisitor(this, data); |
||||
} |
||||
} |
||||
|
||||
static bool IsTypeLevel(INode node) |
||||
{ |
||||
return node is MethodDeclaration || node is PropertyDeclaration || node is EventDeclaration |
||||
|| node is OperatorDeclaration || node is FieldDeclaration; |
||||
} |
||||
|
||||
static string GetTypeLevelEntityName(INode node) |
||||
{ |
||||
if (node is ParametrizedNode) |
||||
return ((ParametrizedNode)node).Name; |
||||
else if (node is FieldDeclaration) |
||||
return ((FieldDeclaration)node).Fields[0].Name; |
||||
else |
||||
throw new ArgumentException(); |
||||
} |
||||
|
||||
public override object VisitSwitchSection(SwitchSection switchSection, object data) |
||||
{ |
||||
// Check if a 'break' should be auto inserted.
|
||||
if (switchSection.Children.Count == 0 || |
||||
!(switchSection.Children[switchSection.Children.Count - 1] is BreakStatement || |
||||
switchSection.Children[switchSection.Children.Count - 1] is ContinueStatement || |
||||
switchSection.Children[switchSection.Children.Count - 1] is ThrowStatement || |
||||
switchSection.Children[switchSection.Children.Count - 1] is ReturnStatement)) |
||||
{ |
||||
switchSection.Children.Add(new BreakStatement()); |
||||
} |
||||
return base.VisitSwitchSection(switchSection, data); |
||||
} |
||||
} |
||||
} |
@ -1,351 +0,0 @@
@@ -1,351 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using ICSharpCode.NRefactory.Ast; |
||||
using Attribute = ICSharpCode.NRefactory.Ast.Attribute; |
||||
|
||||
namespace ICSharpCode.NRefactory.Visitors |
||||
{ |
||||
/// <summary>
|
||||
/// Converts elements not supported by VB to their VB representation.
|
||||
/// Not all elements are converted here, most simple elements (e.g. ConditionalExpression)
|
||||
/// are converted in the output visitor.
|
||||
/// </summary>
|
||||
public class ToVBNetConvertVisitor : ConvertVisitorBase |
||||
{ |
||||
// The following conversions are implemented:
|
||||
// Conflicting field/property names -> m_field
|
||||
// Conflicting variable names inside methods
|
||||
// Anonymous methods are put into new methods
|
||||
// Simple event handler creation is replaced with AddressOfExpression
|
||||
// Move Imports-statements out of namespaces
|
||||
// Parenthesis around Cast expressions remove - these are syntax errors in VB.NET
|
||||
// Decrease array creation size - VB specifies upper bound instead of array length
|
||||
|
||||
List<INode> nodesToMoveToCompilationUnit = new List<INode>(); |
||||
|
||||
public override object VisitCompilationUnit(CompilationUnit compilationUnit, object data) |
||||
{ |
||||
base.VisitCompilationUnit(compilationUnit, data); |
||||
for (int i = 0; i < nodesToMoveToCompilationUnit.Count; i++) { |
||||
compilationUnit.Children.Insert(i, nodesToMoveToCompilationUnit[i]); |
||||
nodesToMoveToCompilationUnit[i].Parent = compilationUnit; |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
public override object VisitUsingDeclaration(UsingDeclaration usingDeclaration, object data) |
||||
{ |
||||
base.VisitUsingDeclaration(usingDeclaration, data); |
||||
if (usingDeclaration.Parent is NamespaceDeclaration) { |
||||
nodesToMoveToCompilationUnit.Add(usingDeclaration); |
||||
RemoveCurrentNode(); |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
TypeDeclaration currentType; |
||||
|
||||
public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data) |
||||
{ |
||||
// fix default inner type visibility
|
||||
if (currentType != null && (typeDeclaration.Modifier & Modifiers.Visibility) == 0) |
||||
typeDeclaration.Modifier |= Modifiers.Private; |
||||
|
||||
TypeDeclaration outerType = currentType; |
||||
currentType = typeDeclaration; |
||||
|
||||
if ((typeDeclaration.Modifier & Modifiers.Static) == Modifiers.Static) { |
||||
typeDeclaration.Modifier &= ~Modifiers.Static; |
||||
typeDeclaration.Modifier |= Modifiers.Sealed; |
||||
typeDeclaration.Children.Insert(0, new ConstructorDeclaration("#ctor", Modifiers.Private, null, null)); |
||||
} |
||||
|
||||
// Conflicting field/property names -> m_field
|
||||
List<string> properties = new List<string>(); |
||||
foreach (object o in typeDeclaration.Children) { |
||||
PropertyDeclaration pd = o as PropertyDeclaration; |
||||
if (pd != null) { |
||||
properties.Add(pd.Name); |
||||
} |
||||
} |
||||
List<VariableDeclaration> conflicts = new List<VariableDeclaration>(); |
||||
foreach (object o in typeDeclaration.Children) { |
||||
FieldDeclaration fd = o as FieldDeclaration; |
||||
if (fd != null) { |
||||
foreach (VariableDeclaration var in fd.Fields) { |
||||
string name = var.Name; |
||||
foreach (string propertyName in properties) { |
||||
if (name.Equals(propertyName, StringComparison.InvariantCultureIgnoreCase)) { |
||||
conflicts.Add(var); |
||||
} |
||||
} |
||||
} |
||||
} |
||||
} |
||||
new PrefixFieldsVisitor(conflicts, "m_").Run(typeDeclaration); |
||||
base.VisitTypeDeclaration(typeDeclaration, data); |
||||
currentType = outerType; |
||||
|
||||
return null; |
||||
} |
||||
|
||||
public override object VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, object data) |
||||
{ |
||||
// fix default inner type visibility
|
||||
if (currentType != null && (delegateDeclaration.Modifier & Modifiers.Visibility) == 0) |
||||
delegateDeclaration.Modifier |= Modifiers.Private; |
||||
|
||||
return base.VisitDelegateDeclaration(delegateDeclaration, data); |
||||
} |
||||
|
||||
public override object VisitExpressionStatement(ExpressionStatement expressionStatement, object data) |
||||
{ |
||||
base.VisitExpressionStatement(expressionStatement, data); |
||||
AssignmentExpression ass = expressionStatement.Expression as AssignmentExpression; |
||||
if (ass != null && ass.Right is AddressOfExpression) { |
||||
if (ass.Op == AssignmentOperatorType.Add) { |
||||
ReplaceCurrentNode(new AddHandlerStatement(ass.Left, ass.Right)); |
||||
} else if (ass.Op == AssignmentOperatorType.Subtract) { |
||||
ReplaceCurrentNode(new RemoveHandlerStatement(ass.Left, ass.Right)); |
||||
} |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
static string GetMemberNameOnThisReference(Expression expr) |
||||
{ |
||||
IdentifierExpression ident = expr as IdentifierExpression; |
||||
if (ident != null) |
||||
return ident.Identifier; |
||||
MemberReferenceExpression fre = expr as MemberReferenceExpression; |
||||
if (fre != null && fre.TargetObject is ThisReferenceExpression) |
||||
return fre.MemberName; |
||||
return null; |
||||
} |
||||
|
||||
public override object VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression, object data) |
||||
{ |
||||
base.VisitAnonymousMethodExpression(anonymousMethodExpression, data); |
||||
if (anonymousMethodExpression.Body.Children.Count == 1) { |
||||
ReturnStatement rs = anonymousMethodExpression.Body.Children[0] as ReturnStatement; |
||||
if (rs != null) { |
||||
LambdaExpression lambda = new LambdaExpression(); |
||||
lambda.ExpressionBody = rs.Expression; |
||||
lambda.Parameters = anonymousMethodExpression.Parameters; |
||||
ReplaceCurrentNode(lambda); |
||||
} |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
public override object VisitAssignmentExpression(AssignmentExpression assignmentExpression, object data) |
||||
{ |
||||
base.VisitAssignmentExpression(assignmentExpression, data); |
||||
if (assignmentExpression.Op == AssignmentOperatorType.Assign && !(assignmentExpression.Parent is ExpressionStatement)) { |
||||
AddInlineAssignHelper(); |
||||
ReplaceCurrentNode( |
||||
new InvocationExpression( |
||||
new IdentifierExpression("InlineAssignHelper"), |
||||
new List<Expression> { assignmentExpression.Left, assignmentExpression.Right } |
||||
)); |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
void AddInlineAssignHelper() |
||||
{ |
||||
MethodDeclaration method; |
||||
foreach (INode node in currentType.Children) { |
||||
method = node as MethodDeclaration; |
||||
if (method != null && method.Name == "InlineAssignHelper") { |
||||
// inline assign helper already exists
|
||||
return; |
||||
} |
||||
} |
||||
|
||||
method = new MethodDeclaration { |
||||
Name = "InlineAssignHelper", |
||||
Modifier = Modifiers.Private | Modifiers.Static, |
||||
TypeReference = new TypeReference("T"), |
||||
Parameters = new List<ParameterDeclarationExpression> { |
||||
new ParameterDeclarationExpression(new TypeReference("T"), "target", ParameterModifiers.Ref), |
||||
new ParameterDeclarationExpression(new TypeReference("T"), "value") |
||||
}}; |
||||
method.Templates.Add(new TemplateDefinition("T", null)); |
||||
method.Body = new BlockStatement(); |
||||
method.Body.AddChild(new ExpressionStatement(new AssignmentExpression( |
||||
new IdentifierExpression("target"), |
||||
AssignmentOperatorType.Assign, |
||||
new IdentifierExpression("value")))); |
||||
method.Body.AddChild(new ReturnStatement(new IdentifierExpression("value"))); |
||||
currentType.AddChild(method); |
||||
} |
||||
|
||||
bool IsClassType(ClassType c) |
||||
{ |
||||
if (currentType == null) return false; |
||||
return currentType.Type == c; |
||||
} |
||||
|
||||
public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data) |
||||
{ |
||||
if (!IsClassType(ClassType.Interface) && (methodDeclaration.Modifier & Modifiers.Visibility) == 0) |
||||
methodDeclaration.Modifier |= Modifiers.Private; |
||||
|
||||
base.VisitMethodDeclaration(methodDeclaration, data); |
||||
|
||||
const Modifiers externStatic = Modifiers.Static | Modifiers.Extern; |
||||
if ((methodDeclaration.Modifier & externStatic) == externStatic |
||||
&& methodDeclaration.Body.IsNull) |
||||
{ |
||||
foreach (AttributeSection sec in methodDeclaration.Attributes) { |
||||
foreach (Attribute att in sec.Attributes) { |
||||
if ("DllImport".Equals(att.Name, StringComparison.InvariantCultureIgnoreCase)) { |
||||
if (ConvertPInvoke(methodDeclaration, att)) { |
||||
sec.Attributes.Remove(att); |
||||
break; |
||||
} |
||||
} |
||||
} |
||||
if (sec.Attributes.Count == 0) { |
||||
methodDeclaration.Attributes.Remove(sec); |
||||
break; |
||||
} |
||||
} |
||||
} |
||||
|
||||
ToVBNetRenameConflictingVariablesVisitor.RenameConflicting(methodDeclaration); |
||||
|
||||
return null; |
||||
} |
||||
|
||||
bool ConvertPInvoke(MethodDeclaration method, ICSharpCode.NRefactory.Ast.Attribute att) |
||||
{ |
||||
if (att.PositionalArguments.Count != 1) |
||||
return false; |
||||
PrimitiveExpression pe = att.PositionalArguments[0] as PrimitiveExpression; |
||||
if (pe == null || !(pe.Value is string)) |
||||
return false; |
||||
string libraryName = (string)pe.Value; |
||||
string alias = null; |
||||
bool setLastError = false; |
||||
bool exactSpelling = false; |
||||
CharsetModifier charSet = CharsetModifier.Auto; |
||||
foreach (NamedArgumentExpression arg in att.NamedArguments) { |
||||
switch (arg.Name) { |
||||
case "SetLastError": |
||||
pe = arg.Expression as PrimitiveExpression; |
||||
if (pe != null && pe.Value is bool) |
||||
setLastError = (bool)pe.Value; |
||||
else |
||||
return false; |
||||
break; |
||||
case "ExactSpelling": |
||||
pe = arg.Expression as PrimitiveExpression; |
||||
if (pe != null && pe.Value is bool) |
||||
exactSpelling = (bool)pe.Value; |
||||
else |
||||
return false; |
||||
break; |
||||
case "CharSet": |
||||
{ |
||||
MemberReferenceExpression fre = arg.Expression as MemberReferenceExpression; |
||||
if (fre == null || !(fre.TargetObject is IdentifierExpression)) |
||||
return false; |
||||
if ((fre.TargetObject as IdentifierExpression).Identifier != "CharSet") |
||||
return false; |
||||
switch (fre.MemberName) { |
||||
case "Unicode": |
||||
charSet = CharsetModifier.Unicode; |
||||
break; |
||||
case "Auto": |
||||
charSet = CharsetModifier.Auto; |
||||
break; |
||||
case "Ansi": |
||||
charSet = CharsetModifier.Ansi; |
||||
break; |
||||
default: |
||||
return false; |
||||
} |
||||
} |
||||
break; |
||||
case "EntryPoint": |
||||
pe = arg.Expression as PrimitiveExpression; |
||||
if (pe != null) |
||||
alias = pe.Value as string; |
||||
break; |
||||
default: |
||||
return false; |
||||
} |
||||
} |
||||
if (setLastError && exactSpelling) { |
||||
// Only P/Invokes with SetLastError and ExactSpelling can be converted to a DeclareDeclaration
|
||||
const Modifiers removeModifiers = Modifiers.Static | Modifiers.Extern; |
||||
DeclareDeclaration decl = new DeclareDeclaration(method.Name, method.Modifier &~ removeModifiers, |
||||
method.TypeReference, |
||||
method.Parameters, |
||||
method.Attributes, |
||||
libraryName, alias, charSet); |
||||
ReplaceCurrentNode(decl); |
||||
base.VisitDeclareDeclaration(decl, null); |
||||
return true; |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
public override object VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, object data) |
||||
{ |
||||
if (!IsClassType(ClassType.Interface) && (propertyDeclaration.Modifier & Modifiers.Visibility) == 0) |
||||
propertyDeclaration.Modifier |= Modifiers.Private; |
||||
base.VisitPropertyDeclaration(propertyDeclaration, data); |
||||
|
||||
ToVBNetRenameConflictingVariablesVisitor.RenameConflicting(propertyDeclaration); |
||||
|
||||
return null; |
||||
} |
||||
|
||||
public override object VisitEventDeclaration(EventDeclaration eventDeclaration, object data) |
||||
{ |
||||
if (!IsClassType(ClassType.Interface) && (eventDeclaration.Modifier & Modifiers.Visibility) == 0) |
||||
eventDeclaration.Modifier |= Modifiers.Private; |
||||
return base.VisitEventDeclaration(eventDeclaration, data); |
||||
} |
||||
|
||||
public override object VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, object data) |
||||
{ |
||||
// make constructor private if visiblity is not set (unless constructor is static)
|
||||
if ((constructorDeclaration.Modifier & (Modifiers.Visibility | Modifiers.Static)) == 0) |
||||
constructorDeclaration.Modifier |= Modifiers.Private; |
||||
base.VisitConstructorDeclaration(constructorDeclaration, data); |
||||
|
||||
ToVBNetRenameConflictingVariablesVisitor.RenameConflicting(constructorDeclaration); |
||||
|
||||
return null; |
||||
} |
||||
|
||||
public override object VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression, object data) |
||||
{ |
||||
base.VisitParenthesizedExpression(parenthesizedExpression, data); |
||||
if (parenthesizedExpression.Expression is CastExpression) { |
||||
ReplaceCurrentNode(parenthesizedExpression.Expression); // remove parenthesis
|
||||
} |
||||
return null; |
||||
} |
||||
|
||||
public override object VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, object data) |
||||
{ |
||||
for (int i = 0; i < arrayCreateExpression.Arguments.Count; i++) { |
||||
arrayCreateExpression.Arguments[i] = Expression.AddInteger(arrayCreateExpression.Arguments[i], -1); |
||||
} |
||||
return base.VisitArrayCreateExpression(arrayCreateExpression, data); |
||||
} |
||||
} |
||||
} |
@ -1,91 +0,0 @@
@@ -1,91 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using ICSharpCode.NRefactory.Ast; |
||||
|
||||
namespace ICSharpCode.NRefactory.Visitors |
||||
{ |
||||
/// <summary>
|
||||
/// Renames local variables if they conflict with other locals, fields or parameters.
|
||||
/// </summary>
|
||||
static class ToVBNetRenameConflictingVariablesVisitor |
||||
{ |
||||
public static void RenameConflicting(ParametrizedNode method) |
||||
{ |
||||
// variable name => case sensitive variable name
|
||||
// value is null if there are multiple casings for the variable -> the variable is conflicting
|
||||
Dictionary<string, string> caseInsensitive = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); |
||||
|
||||
LookupTableVisitor ltv = new LookupTableVisitor(SupportedLanguage.CSharp); |
||||
method.AcceptVisitor(ltv, null); |
||||
|
||||
// add method parameters to caseInsensitive
|
||||
foreach (ParameterDeclarationExpression pde in method.Parameters) { |
||||
AddVariableToDict(caseInsensitive, pde.ParameterName, true); |
||||
} |
||||
|
||||
// add local variables to caseInsensitive
|
||||
foreach (KeyValuePair<string, List<LocalLookupVariable>> var in ltv.Variables) { |
||||
AddVariableToDict(caseInsensitive, var.Key, true); |
||||
} |
||||
|
||||
// add used identifiers to caseInsensitive
|
||||
FindIdentifiersVisitor fvv = new FindIdentifiersVisitor(); |
||||
method.AcceptVisitor(fvv, null); |
||||
|
||||
foreach (KeyValuePair<string, string> pair in fvv.usedIdentifiers) { |
||||
AddVariableToDict(caseInsensitive, pair.Key, false); |
||||
} |
||||
|
||||
int index = 0; |
||||
foreach (ParameterDeclarationExpression pde in method.Parameters) { |
||||
if (caseInsensitive[pde.ParameterName] == null) { |
||||
RenameVariable(method, pde.ParameterName, ref index); |
||||
} |
||||
} |
||||
foreach (KeyValuePair<string, List<LocalLookupVariable>> var in ltv.Variables) { |
||||
if (caseInsensitive[var.Key] == null) { |
||||
RenameVariable(method, var.Key, ref index); |
||||
} |
||||
} |
||||
} |
||||
|
||||
static void RenameVariable(INode method, string from, ref int index) |
||||
{ |
||||
index += 1; |
||||
method.AcceptVisitor(new RenameLocalVariableVisitor(from, from + "__" + index, StringComparer.InvariantCulture), null); |
||||
} |
||||
|
||||
static void AddVariableToDict(Dictionary<string, string> caseInsensitive, string varName, bool hasDeclaration) |
||||
{ |
||||
string existing; |
||||
if (caseInsensitive.TryGetValue(varName, out existing)) { |
||||
if (existing != null && existing != varName) { |
||||
caseInsensitive[varName] = null; |
||||
} |
||||
} else { |
||||
if (hasDeclaration) { |
||||
caseInsensitive.Add(varName, varName); |
||||
} |
||||
} |
||||
} |
||||
|
||||
sealed class FindIdentifiersVisitor : AbstractAstVisitor |
||||
{ |
||||
// use dictionary as HashSet to remember used identifiers
|
||||
internal readonly Dictionary<string, string> usedIdentifiers = new Dictionary<string, string>(); |
||||
|
||||
public override object VisitIdentifierExpression(IdentifierExpression identifierExpression, object data) |
||||
{ |
||||
usedIdentifiers[identifierExpression.Identifier] = null; |
||||
return null; |
||||
} |
||||
} |
||||
} |
||||
} |
@ -1,537 +0,0 @@
@@ -1,537 +0,0 @@
|
||||
// <file>
|
||||
// <copyright see="prj:///doc/copyright.txt"/>
|
||||
// <license see="prj:///doc/license.txt"/>
|
||||
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
|
||||
// <version>$Revision$</version>
|
||||
// </file>
|
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using System.Reflection; |
||||
|
||||
using ICSharpCode.NRefactory.Ast; |
||||
using Attribute = ICSharpCode.NRefactory.Ast.Attribute; |
||||
|
||||
namespace ICSharpCode.NRefactory.Visitors |
||||
{ |
||||
/// <summary>
|
||||
/// Converts special VB constructs to use more general AST classes.
|
||||
/// </summary>
|
||||
public class VBNetConstructsConvertVisitor : ConvertVisitorBase |
||||
{ |
||||
// The following conversions are implemented:
|
||||
// MyBase.New() and MyClass.New() calls inside the constructor are converted to :base() and :this()
|
||||
// Add Public Modifier to inner types, methods, properties and fields in structures
|
||||
// Override Finalize => Destructor
|
||||
// IIF(cond, true, false) => ConditionalExpression
|
||||
// Built-in methods => Prefix with class name
|
||||
// Function A() \n A = SomeValue \n End Function -> convert to return statement
|
||||
// Array creation => add 1 to upper bound to get array length
|
||||
// Comparison with empty string literal -> string.IsNullOrEmpty
|
||||
// Add default value to local variable declarations without initializer
|
||||
|
||||
/// <summary>
|
||||
/// Specifies whether the "Add default value to local variable declarations without initializer"
|
||||
/// operation is executed by this convert visitor.
|
||||
/// </summary>
|
||||
public bool AddDefaultValueInitializerToLocalVariableDeclarations = true; |
||||
|
||||
Dictionary<string, string> usings; |
||||
List<UsingDeclaration> addedUsings; |
||||
TypeDeclaration currentTypeDeclaration; |
||||
|
||||
public override object VisitCompilationUnit(CompilationUnit compilationUnit, object data) |
||||
{ |
||||
usings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); |
||||
addedUsings = new List<UsingDeclaration>(); |
||||
base.VisitCompilationUnit(compilationUnit, data); |
||||
int i; |
||||
for (i = 0; i < compilationUnit.Children.Count; i++) { |
||||
if (!(compilationUnit.Children[i] is UsingDeclaration)) |
||||
break; |
||||
} |
||||
foreach (UsingDeclaration decl in addedUsings) { |
||||
decl.Parent = compilationUnit; |
||||
compilationUnit.Children.Insert(i++, decl); |
||||
} |
||||
usings = null; |
||||
addedUsings = null; |
||||
return null; |
||||
} |
||||
|
||||
public override object VisitUsing(Using @using, object data) |
||||
{ |
||||
if (usings != null && !@using.IsAlias) { |
||||
usings[@using.Name] = @using.Name; |
||||
} |
||||
return base.VisitUsing(@using, data); |
||||
} |
||||
|
||||
public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data) |
||||
{ |
||||
// fix default visibility of inner classes
|
||||
if (currentTypeDeclaration != null && (typeDeclaration.Modifier & Modifiers.Visibility) == 0) |
||||
typeDeclaration.Modifier |= Modifiers.Public; |
||||
|
||||
TypeDeclaration oldTypeDeclaration = currentTypeDeclaration; |
||||
currentTypeDeclaration = typeDeclaration; |
||||
base.VisitTypeDeclaration(typeDeclaration, data); |
||||
currentTypeDeclaration = oldTypeDeclaration; |
||||
return null; |
||||
} |
||||
|
||||
public override object VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, object data) |
||||
{ |
||||
// fix default visibility of inner classes
|
||||
if (currentTypeDeclaration != null && (delegateDeclaration.Modifier & Modifiers.Visibility) == 0) |
||||
delegateDeclaration.Modifier |= Modifiers.Public; |
||||
|
||||
return base.VisitDelegateDeclaration(delegateDeclaration, data); |
||||
} |
||||
|
||||
bool IsClassType(ClassType c) |
||||
{ |
||||
if (currentTypeDeclaration == null) return false; |
||||
return currentTypeDeclaration.Type == c; |
||||
} |
||||
|
||||
public override object VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, object data) |
||||
{ |
||||
// make constructor public if visiblity is not set (unless constructor is static)
|
||||
if ((constructorDeclaration.Modifier & (Modifiers.Visibility | Modifiers.Static)) == 0) |
||||
constructorDeclaration.Modifier |= Modifiers.Public; |
||||
|
||||
// MyBase.New() and MyClass.New() calls inside the constructor are converted to :base() and :this()
|
||||
BlockStatement body = constructorDeclaration.Body; |
||||
if (body != null && body.Children.Count > 0) { |
||||
ExpressionStatement se = body.Children[0] as ExpressionStatement; |
||||
if (se != null) { |
||||
InvocationExpression ie = se.Expression as InvocationExpression; |
||||
if (ie != null) { |
||||
MemberReferenceExpression fre = ie.TargetObject as MemberReferenceExpression; |
||||
if (fre != null && "New".Equals(fre.MemberName, StringComparison.InvariantCultureIgnoreCase)) { |
||||
if (fre.TargetObject is BaseReferenceExpression || fre.TargetObject is ClassReferenceExpression || fre.TargetObject is ThisReferenceExpression) { |
||||
body.Children.RemoveAt(0); |
||||
ConstructorInitializer ci = new ConstructorInitializer(); |
||||
ci.Arguments = ie.Arguments; |
||||
if (fre.TargetObject is BaseReferenceExpression) |
||||
ci.ConstructorInitializerType = ConstructorInitializerType.Base; |
||||
else |
||||
ci.ConstructorInitializerType = ConstructorInitializerType.This; |
||||
constructorDeclaration.ConstructorInitializer = ci; |
||||
} |
||||
} |
||||
} |
||||
} |
||||
} |
||||
return base.VisitConstructorDeclaration(constructorDeclaration, data); |
||||
} |
||||
|
||||
public override object VisitDeclareDeclaration(DeclareDeclaration declareDeclaration, object data) |
||||
{ |
||||
if (usings != null && !usings.ContainsKey("System.Runtime.InteropServices")) { |
||||
UsingDeclaration @using = new UsingDeclaration("System.Runtime.InteropServices"); |
||||
addedUsings.Add(@using); |
||||
base.VisitUsingDeclaration(@using, data); |
||||
} |
||||
|
||||
MethodDeclaration method = new MethodDeclaration { |
||||
Name = declareDeclaration.Name, |
||||
Modifier = declareDeclaration.Modifier, |
||||
TypeReference = declareDeclaration.TypeReference, |
||||
Parameters = declareDeclaration.Parameters, |
||||
Attributes = declareDeclaration.Attributes |
||||
}; |
||||
|
||||
if ((method.Modifier & Modifiers.Visibility) == 0) |
||||
method.Modifier |= Modifiers.Public; |
||||
method.Modifier |= Modifiers.Extern | Modifiers.Static; |
||||
|
||||
if (method.TypeReference.IsNull) { |
||||
method.TypeReference = new TypeReference("System.Void"); |
||||
} |
||||
|
||||
Attribute att = new Attribute("DllImport", null, null); |
||||
att.PositionalArguments.Add(CreateStringLiteral(declareDeclaration.Library)); |
||||
if (declareDeclaration.Alias.Length > 0) { |
||||
att.NamedArguments.Add(new NamedArgumentExpression("EntryPoint", CreateStringLiteral(declareDeclaration.Alias))); |
||||
} |
||||
switch (declareDeclaration.Charset) { |
||||
case CharsetModifier.Auto: |
||||
att.NamedArguments.Add(new NamedArgumentExpression("CharSet", |
||||
new MemberReferenceExpression(new IdentifierExpression("CharSet"), |
||||
"Auto"))); |
||||
break; |
||||
case CharsetModifier.Unicode: |
||||
att.NamedArguments.Add(new NamedArgumentExpression("CharSet", |
||||
new MemberReferenceExpression(new IdentifierExpression("CharSet"), |
||||
"Unicode"))); |
||||
break; |
||||
default: |
||||
att.NamedArguments.Add(new NamedArgumentExpression("CharSet", |
||||
new MemberReferenceExpression(new IdentifierExpression("CharSet"), |
||||
"Ansi"))); |
||||
break; |
||||
} |
||||
att.NamedArguments.Add(new NamedArgumentExpression("SetLastError", new PrimitiveExpression(true, true.ToString()))); |
||||
att.NamedArguments.Add(new NamedArgumentExpression("ExactSpelling", new PrimitiveExpression(true, true.ToString()))); |
||||
method.Attributes.Add(new AttributeSection { Attributes = { att } }); |
||||
ReplaceCurrentNode(method); |
||||
return base.VisitMethodDeclaration(method, data); |
||||
} |
||||
|
||||
static PrimitiveExpression CreateStringLiteral(string text) |
||||
{ |
||||
return new PrimitiveExpression(text, text); |
||||
} |
||||
|
||||
public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data) |
||||
{ |
||||
if (!IsClassType(ClassType.Interface) && (methodDeclaration.Modifier & Modifiers.Visibility) == 0) |
||||
methodDeclaration.Modifier |= Modifiers.Public; |
||||
|
||||
if ("Finalize".Equals(methodDeclaration.Name, StringComparison.InvariantCultureIgnoreCase) |
||||
&& methodDeclaration.Parameters.Count == 0 |
||||
&& methodDeclaration.Modifier == (Modifiers.Protected | Modifiers.Override) |
||||
&& methodDeclaration.Body.Children.Count == 1) |
||||
{ |
||||
TryCatchStatement tcs = methodDeclaration.Body.Children[0] as TryCatchStatement; |
||||
if (tcs != null |
||||
&& tcs.StatementBlock is BlockStatement |
||||
&& tcs.CatchClauses.Count == 0 |
||||
&& tcs.FinallyBlock is BlockStatement |
||||
&& tcs.FinallyBlock.Children.Count == 1) |
||||
{ |
||||
ExpressionStatement se = tcs.FinallyBlock.Children[0] as ExpressionStatement; |
||||
if (se != null) { |
||||
InvocationExpression ie = se.Expression as InvocationExpression; |
||||
if (ie != null |
||||
&& ie.Arguments.Count == 0 |
||||
&& ie.TargetObject is MemberReferenceExpression |
||||
&& (ie.TargetObject as MemberReferenceExpression).TargetObject is BaseReferenceExpression |
||||
&& "Finalize".Equals((ie.TargetObject as MemberReferenceExpression).MemberName, StringComparison.InvariantCultureIgnoreCase)) |
||||
{ |
||||
DestructorDeclaration des = new DestructorDeclaration("Destructor", Modifiers.None, methodDeclaration.Attributes); |
||||
ReplaceCurrentNode(des); |
||||
des.Body = (BlockStatement)tcs.StatementBlock; |
||||
return base.VisitDestructorDeclaration(des, data); |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
if ((methodDeclaration.Modifier & (Modifiers.Static | Modifiers.Extern)) == Modifiers.Static |
||||
&& methodDeclaration.Body.Children.Count == 0) |
||||
{ |
||||
foreach (AttributeSection sec in methodDeclaration.Attributes) { |
||||
foreach (Attribute att in sec.Attributes) { |
||||
if ("DllImport".Equals(att.Name, StringComparison.InvariantCultureIgnoreCase)) { |
||||
methodDeclaration.Modifier |= Modifiers.Extern; |
||||
methodDeclaration.Body = null; |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
if (methodDeclaration.TypeReference.SystemType != "System.Void" && methodDeclaration.Body.Children.Count > 0) { |
||||
if (IsAssignmentTo(methodDeclaration.Body.Children[methodDeclaration.Body.Children.Count - 1], methodDeclaration.Name)) |
||||
{ |
||||
ReturnStatement rs = new ReturnStatement(GetAssignmentFromStatement(methodDeclaration.Body.Children[methodDeclaration.Body.Children.Count - 1]).Right); |
||||
methodDeclaration.Body.Children.RemoveAt(methodDeclaration.Body.Children.Count - 1); |
||||
methodDeclaration.Body.AddChild(rs); |
||||
} else { |
||||
ReturnStatementForFunctionAssignment visitor = new ReturnStatementForFunctionAssignment(methodDeclaration.Name); |
||||
methodDeclaration.Body.AcceptVisitor(visitor, null); |
||||
if (visitor.replacementCount > 0) { |
||||
Expression init; |
||||
init = GetDefaultValueForType(methodDeclaration.TypeReference); |
||||
methodDeclaration.Body.Children.Insert(0, new LocalVariableDeclaration(new VariableDeclaration(FunctionReturnValueName, init, methodDeclaration.TypeReference))); |
||||
methodDeclaration.Body.Children[0].Parent = methodDeclaration.Body; |
||||
methodDeclaration.Body.AddChild(new ReturnStatement(new IdentifierExpression(FunctionReturnValueName))); |
||||
} |
||||
} |
||||
} |
||||
|
||||
return base.VisitMethodDeclaration(methodDeclaration, data); |
||||
} |
||||
|
||||
public const string FunctionReturnValueName = "functionReturnValue"; |
||||
|
||||
static AssignmentExpression GetAssignmentFromStatement(INode statement) |
||||
{ |
||||
ExpressionStatement se = statement as ExpressionStatement; |
||||
if (se == null) return null; |
||||
return se.Expression as AssignmentExpression; |
||||
} |
||||
|
||||
static bool IsAssignmentTo(INode statement, string varName) |
||||
{ |
||||
AssignmentExpression ass = GetAssignmentFromStatement(statement); |
||||
if (ass == null) return false; |
||||
IdentifierExpression ident = ass.Left as IdentifierExpression; |
||||
if (ident == null) return false; |
||||
return ident.Identifier.Equals(varName, StringComparison.InvariantCultureIgnoreCase); |
||||
} |
||||
|
||||
#region Create return statement for assignment to function name
|
||||
class ReturnStatementForFunctionAssignment : AbstractAstTransformer |
||||
{ |
||||
string functionName; |
||||
internal int replacementCount = 0; |
||||
|
||||
public ReturnStatementForFunctionAssignment(string functionName) |
||||
{ |
||||
this.functionName = functionName; |
||||
} |
||||
|
||||
public override object VisitIdentifierExpression(IdentifierExpression identifierExpression, object data) |
||||
{ |
||||
if (identifierExpression.Identifier.Equals(functionName, StringComparison.InvariantCultureIgnoreCase)) { |
||||
if (!(identifierExpression.Parent is AddressOfExpression) && !(identifierExpression.Parent is InvocationExpression)) { |
||||
identifierExpression.Identifier = FunctionReturnValueName; |
||||
replacementCount++; |
||||
} |
||||
} |
||||
return base.VisitIdentifierExpression(identifierExpression, data); |
||||
} |
||||
} |
||||
#endregion
|
||||
|
||||
public override object VisitFieldDeclaration(FieldDeclaration fieldDeclaration, object data) |
||||
{ |
||||
fieldDeclaration.Modifier &= ~Modifiers.Dim; // remove "Dim" flag
|
||||
if (IsClassType(ClassType.Struct)) { |
||||
if ((fieldDeclaration.Modifier & Modifiers.Visibility) == 0) |
||||
fieldDeclaration.Modifier |= Modifiers.Public; |
||||
} |
||||
return base.VisitFieldDeclaration(fieldDeclaration, data); |
||||
} |
||||
|
||||
public override object VisitEventDeclaration(EventDeclaration eventDeclaration, object data) |
||||
{ |
||||
if (!IsClassType(ClassType.Interface) && (eventDeclaration.Modifier & Modifiers.Visibility) == 0) |
||||
eventDeclaration.Modifier |= Modifiers.Public; |
||||
|
||||
return base.VisitEventDeclaration(eventDeclaration, data); |
||||
} |
||||
|
||||
public override object VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, object data) |
||||
{ |
||||
if (!IsClassType(ClassType.Interface) && (propertyDeclaration.Modifier & Modifiers.Visibility) == 0) |
||||
propertyDeclaration.Modifier |= Modifiers.Public; |
||||
|
||||
if (propertyDeclaration.HasSetRegion) { |
||||
string from = "Value"; |
||||
if (propertyDeclaration.SetRegion.Parameters.Count > 0) { |
||||
ParameterDeclarationExpression p = propertyDeclaration.SetRegion.Parameters[0]; |
||||
from = p.ParameterName; |
||||
p.ParameterName = "Value"; |
||||
} |
||||
propertyDeclaration.SetRegion.AcceptVisitor(new RenameIdentifierVisitor(from, "value", StringComparer.InvariantCultureIgnoreCase), null); |
||||
} |
||||
|
||||
return base.VisitPropertyDeclaration(propertyDeclaration, data); |
||||
} |
||||
|
||||
static volatile Dictionary<string, Expression> constantTable; |
||||
static volatile Dictionary<string, Expression> methodTable; |
||||
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] |
||||
public static readonly string VBAssemblyName = "Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; |
||||
|
||||
static Dictionary<string, Expression> CreateDictionary(params string[] classNames) |
||||
{ |
||||
Dictionary<string, Expression> d = new Dictionary<string, Expression>(StringComparer.InvariantCultureIgnoreCase); |
||||
Assembly asm = Assembly.Load(VBAssemblyName); |
||||
foreach (string className in classNames) { |
||||
Type type = asm.GetType("Microsoft.VisualBasic." + className); |
||||
Expression expr = new IdentifierExpression(className); |
||||
foreach (MemberInfo member in type.GetMembers()) { |
||||
if (member.DeclaringType == type) { // only direct members
|
||||
d[member.Name] = expr; |
||||
} |
||||
} |
||||
} |
||||
return d; |
||||
} |
||||
|
||||
public override object VisitIdentifierExpression(IdentifierExpression identifierExpression, object data) |
||||
{ |
||||
if (constantTable == null) { |
||||
constantTable = CreateDictionary("Constants"); |
||||
} |
||||
Expression expr; |
||||
if (constantTable.TryGetValue(identifierExpression.Identifier, out expr)) { |
||||
MemberReferenceExpression fre = new MemberReferenceExpression(expr, identifierExpression.Identifier); |
||||
ReplaceCurrentNode(fre); |
||||
return base.VisitMemberReferenceExpression(fre, data); |
||||
} |
||||
return base.VisitIdentifierExpression(identifierExpression, data); |
||||
} |
||||
|
||||
public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data) |
||||
{ |
||||
IdentifierExpression ident = invocationExpression.TargetObject as IdentifierExpression; |
||||
if (ident != null) { |
||||
if ("IIF".Equals(ident.Identifier, StringComparison.InvariantCultureIgnoreCase) |
||||
&& invocationExpression.Arguments.Count == 3) |
||||
{ |
||||
ConditionalExpression ce = new ConditionalExpression(invocationExpression.Arguments[0], |
||||
invocationExpression.Arguments[1], |
||||
invocationExpression.Arguments[2]); |
||||
ReplaceCurrentNode(new ParenthesizedExpression(ce)); |
||||
return base.VisitConditionalExpression(ce, data); |
||||
} |
||||
if ("IsNothing".Equals(ident.Identifier, StringComparison.InvariantCultureIgnoreCase) |
||||
&& invocationExpression.Arguments.Count == 1) |
||||
{ |
||||
BinaryOperatorExpression boe = new BinaryOperatorExpression(invocationExpression.Arguments[0], |
||||
BinaryOperatorType.ReferenceEquality, |
||||
new PrimitiveExpression(null, "null")); |
||||
ReplaceCurrentNode(new ParenthesizedExpression(boe)); |
||||
return base.VisitBinaryOperatorExpression(boe, data); |
||||
} |
||||
if (methodTable == null) { |
||||
methodTable = CreateDictionary("Conversion", "FileSystem", "Financial", "Information", |
||||
"Interaction", "Strings", "VBMath"); |
||||
} |
||||
Expression expr; |
||||
if (methodTable.TryGetValue(ident.Identifier, out expr)) { |
||||
MemberReferenceExpression fre = new MemberReferenceExpression(expr, ident.Identifier); |
||||
invocationExpression.TargetObject = fre; |
||||
} |
||||
} |
||||
return base.VisitInvocationExpression(invocationExpression, data); |
||||
} |
||||
|
||||
public override object VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression, object data) |
||||
{ |
||||
base.VisitUnaryOperatorExpression(unaryOperatorExpression, data); |
||||
if (unaryOperatorExpression.Op == UnaryOperatorType.Not) { |
||||
if (unaryOperatorExpression.Expression is BinaryOperatorExpression) { |
||||
unaryOperatorExpression.Expression = new ParenthesizedExpression(unaryOperatorExpression.Expression); |
||||
} |
||||
ParenthesizedExpression pe = unaryOperatorExpression.Expression as ParenthesizedExpression; |
||||
if (pe != null) { |
||||
BinaryOperatorExpression boe = pe.Expression as BinaryOperatorExpression; |
||||
if (boe != null && boe.Op == BinaryOperatorType.ReferenceEquality) { |
||||
boe.Op = BinaryOperatorType.ReferenceInequality; |
||||
ReplaceCurrentNode(pe); |
||||
} |
||||
} |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
public override object VisitUsingStatement(UsingStatement usingStatement, object data) |
||||
{ |
||||
LocalVariableDeclaration lvd = usingStatement.ResourceAcquisition as LocalVariableDeclaration; |
||||
if (lvd != null && lvd.Variables.Count > 1) { |
||||
usingStatement.ResourceAcquisition = new LocalVariableDeclaration(lvd.Variables[0]); |
||||
for (int i = 1; i < lvd.Variables.Count; i++) { |
||||
UsingStatement n = new UsingStatement(new LocalVariableDeclaration(lvd.Variables[i]), |
||||
usingStatement.EmbeddedStatement); |
||||
usingStatement.EmbeddedStatement = new BlockStatement(); |
||||
usingStatement.EmbeddedStatement.AddChild(n); |
||||
usingStatement = n; |
||||
} |
||||
} |
||||
return base.VisitUsingStatement(usingStatement, data); |
||||
} |
||||
|
||||
public override object VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, object data) |
||||
{ |
||||
for (int i = 0; i < arrayCreateExpression.Arguments.Count; i++) { |
||||
arrayCreateExpression.Arguments[i] = Expression.AddInteger(arrayCreateExpression.Arguments[i], 1); |
||||
} |
||||
if (arrayCreateExpression.ArrayInitializer.CreateExpressions.Count == 0) { |
||||
arrayCreateExpression.ArrayInitializer = null; |
||||
} |
||||
return base.VisitArrayCreateExpression(arrayCreateExpression, data); |
||||
} |
||||
|
||||
bool IsEmptyStringLiteral(Expression expression) |
||||
{ |
||||
PrimitiveExpression pe = expression as PrimitiveExpression; |
||||
if (pe != null) { |
||||
return (pe.Value as string) == ""; |
||||
} else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
Expression CallStringIsNullOrEmpty(Expression stringVariable) |
||||
{ |
||||
List<Expression> arguments = new List<Expression>(); |
||||
arguments.Add(stringVariable); |
||||
return new InvocationExpression( |
||||
new MemberReferenceExpression(new TypeReferenceExpression("System.String"), "IsNullOrEmpty"), |
||||
arguments); |
||||
} |
||||
|
||||
public override object VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression, object data) |
||||
{ |
||||
base.VisitBinaryOperatorExpression(binaryOperatorExpression, data); |
||||
if (IsEmptyStringLiteral(binaryOperatorExpression.Right)) { |
||||
if (binaryOperatorExpression.Op == BinaryOperatorType.Equality) { |
||||
ReplaceCurrentNode(CallStringIsNullOrEmpty(binaryOperatorExpression.Left)); |
||||
} else if (binaryOperatorExpression.Op == BinaryOperatorType.InEquality) { |
||||
ReplaceCurrentNode(new UnaryOperatorExpression(CallStringIsNullOrEmpty(binaryOperatorExpression.Left), |
||||
UnaryOperatorType.Not)); |
||||
} |
||||
} else if (IsEmptyStringLiteral(binaryOperatorExpression.Left)) { |
||||
if (binaryOperatorExpression.Op == BinaryOperatorType.Equality) { |
||||
ReplaceCurrentNode(CallStringIsNullOrEmpty(binaryOperatorExpression.Right)); |
||||
} else if (binaryOperatorExpression.Op == BinaryOperatorType.InEquality) { |
||||
ReplaceCurrentNode(new UnaryOperatorExpression(CallStringIsNullOrEmpty(binaryOperatorExpression.Right), |
||||
UnaryOperatorType.Not)); |
||||
} |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
public override object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data) |
||||
{ |
||||
if (AddDefaultValueInitializerToLocalVariableDeclarations) { |
||||
for (int i = 0; i < localVariableDeclaration.Variables.Count; i++) { |
||||
VariableDeclaration decl = localVariableDeclaration.Variables[i]; |
||||
if (decl.FixedArrayInitialization.IsNull && decl.Initializer.IsNull) { |
||||
TypeReference type = localVariableDeclaration.GetTypeForVariable(i); |
||||
decl.Initializer = GetDefaultValueForType(type); |
||||
} |
||||
} |
||||
} |
||||
return base.VisitLocalVariableDeclaration(localVariableDeclaration, data); |
||||
} |
||||
|
||||
Expression GetDefaultValueForType(TypeReference type) |
||||
{ |
||||
if (type != null && !type.IsArrayType) { |
||||
switch (type.SystemType) { |
||||
case "System.SByte": |
||||
case "System.Byte": |
||||
case "System.Int16": |
||||
case "System.UInt16": |
||||
case "System.Int32": |
||||
case "System.UInt32": |
||||
case "System.Int64": |
||||
case "System.UInt64": |
||||
case "System.Single": |
||||
case "System.Double": |
||||
return new PrimitiveExpression(0, "0"); |
||||
case "System.Char": |
||||
return new PrimitiveExpression('\0', "'\\0'"); |
||||
case "System.Object": |
||||
case "System.String": |
||||
return new PrimitiveExpression(null, "null"); |
||||
case "System.Boolean": |
||||
return new PrimitiveExpression(false, "false"); |
||||
default: |
||||
return new DefaultValueExpression(type); |
||||
} |
||||
} else { |
||||
return new PrimitiveExpression(null, "null"); |
||||
} |
||||
} |
||||
} |
||||
} |
Loading…
Reference in new issue