⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 csharpvisitor.cs

📁 c#源代码
💻 CS
📖 第 1 页 / 共 4 页
字号:
				case BinaryOperatorType.IS:
					op = " == ";
					break;
				case BinaryOperatorType.LessThanOrEqual:
					op = " <= ";
					break;
				case BinaryOperatorType.Power:
					return "Math.Pow(" + left + ", " + right + ")";
				default:
					throw new Exception("Unknown binary operator:" + binaryOperatorExpression.Op);
			}
			
			return String.Concat(left,
			                     op,
			                     right);
		}
		
		public object Visit(ParenthesizedExpression parenthesizedExpression, object data)
		{
			DebugOutput(parenthesizedExpression);
			string innerExpr = parenthesizedExpression.Expression.AcceptVisitor(this, data).ToString();
			return String.Concat("(", innerExpr, ")");
		}
		
		public object Visit(InvocationExpression invocationExpression, object data)
		{
			DebugOutput(invocationExpression);
			return String.Concat(invocationExpression.TargetObject.AcceptVisitor(this, data),
			                     GetParameters(invocationExpression.Parameters)
			                     );
		}
		
		public object Visit(IdentifierExpression identifierExpression, object data)
		{
			DebugOutput(identifierExpression);
			if ("value" == identifierExpression.Identifier.ToLower(System.Globalization.CultureInfo.InvariantCulture))
			{
				return "value";
			}
			return identifierExpression.Identifier;
		}
		
		public object Visit(TypeReferenceExpression typeReferenceExpression, object data)
		{
			DebugOutput(typeReferenceExpression);
			return GetTypeString(typeReferenceExpression.TypeReference);
		}
		
		public object Visit(UnaryOperatorExpression unaryOperatorExpression, object data)
		{
			DebugOutput(unaryOperatorExpression);
			switch (unaryOperatorExpression.Op) {
				case UnaryOperatorType.BitNot:
					return String.Concat("~", unaryOperatorExpression.Expression.AcceptVisitor(this, data));
				case UnaryOperatorType.Decrement:
					return String.Concat("--", unaryOperatorExpression.Expression.AcceptVisitor(this, data), ")");
				case UnaryOperatorType.Increment:
					return String.Concat("++", unaryOperatorExpression.Expression.AcceptVisitor(this, data), ")");
				case UnaryOperatorType.Minus:
					return String.Concat("-", unaryOperatorExpression.Expression.AcceptVisitor(this, data));
				case UnaryOperatorType.Not:
					return String.Concat("!(", unaryOperatorExpression.Expression.AcceptVisitor(this, data), ")");
				case UnaryOperatorType.Plus:
					return String.Concat("+", unaryOperatorExpression.Expression.AcceptVisitor(this, data));
				case UnaryOperatorType.PostDecrement:
					return String.Concat(unaryOperatorExpression.Expression.AcceptVisitor(this, data), "--");
				case UnaryOperatorType.PostIncrement:
					return String.Concat(unaryOperatorExpression.Expression.AcceptVisitor(this, data), "++");
			}
			throw new System.NotSupportedException();
		}
		
		public object Visit(AssignmentExpression assignmentExpression, object data)
		{
			DebugOutput(assignmentExpression);
			string op    = null;
			string left  = assignmentExpression.Left.AcceptVisitor(this, data).ToString();
			string right = assignmentExpression.Right.AcceptVisitor(this, data).ToString();
			
			switch (assignmentExpression.Op) {
				case AssignmentOperatorType.Assign:
					op = " = ";
					break;
				case AssignmentOperatorType.ConcatString:
				case AssignmentOperatorType.Add:
					op = " += ";
					break;
				case AssignmentOperatorType.Subtract:
					op = " -= ";
					break;
				case AssignmentOperatorType.Multiply:
					op = " *= ";
					break;
				case AssignmentOperatorType.Divide:
					op = " /= ";
					break;
				case AssignmentOperatorType.ShiftLeft:
					op = " <<= ";
					break;
				case AssignmentOperatorType.ShiftRight:
					op = " >>= ";
					break;
				
				case AssignmentOperatorType.ExclusiveOr:
					op = " ^= ";
					break;
				case AssignmentOperatorType.Modulus:
					op = " %= ";
					break;
				case AssignmentOperatorType.BitwiseAnd:
					op = " &= ";
					break;
				case AssignmentOperatorType.BitwiseOr:
					op = " |= ";
					break;
			}
			return String.Concat(left,
			                     op,
			                     right);
		}
		
		public object Visit(CastExpression castExpression, object data)
		{
			DebugOutput(castExpression);
			string type     = ConvertTypeString(castExpression.CastTo.Type);
			string castExpr = castExpression.Expression.AcceptVisitor(this, data).ToString();
			
			if (castExpression.IsSpecializedCast) {
				switch (type) {
					case "System.Object":
						break;
					default:
						string convToType = type.Substring("System.".Length);
						return String.Format("System.Convert.To{0}({1})", convToType, castExpr);
				}
			}
			return String.Format("(({0})({1}))", type, castExpr);
		}
		
		public object Visit(ThisReferenceExpression thisReferenceExpression, object data)
		{
			DebugOutput(thisReferenceExpression);
			return "this";
		}
		
		public object Visit(BaseReferenceExpression baseReferenceExpression, object data)
		{
			DebugOutput(baseReferenceExpression);
			return "base";
		}
		
		public object Visit(ObjectCreateExpression objectCreateExpression, object data)
		{
			string type = GetTypeString(objectCreateExpression.CreateType);
			
			if ((objectCreateExpression.Parameters == null || objectCreateExpression.Parameters.Count == 0) && type.EndsWith("]")) {
				return String.Format("new {0}",
				                     type);
				
			}
			return String.Format("new {0}{1}",
			                     type,
			                     GetParameters(objectCreateExpression.Parameters)
			                     );
		}
		
		public object Visit(ParameterDeclarationExpression parameterDeclarationExpression, object data)
		{
			DebugOutput(parameterDeclarationExpression);
			// Is handled in the AppendParameters method
			return "// should never happen" + parameterDeclarationExpression;
		}
		
		public object Visit(FieldReferenceOrInvocationExpression fieldReferenceOrInvocationExpression, object data)
		{
			DebugOutput(fieldReferenceOrInvocationExpression);
			INode target = fieldReferenceOrInvocationExpression.TargetObject;
			if (target == null && withExpressionStack.Count > 0) {
				target = withExpressionStack.Peek() as INode;
			}
			return String.Concat(target.AcceptVisitor(this, data),
			                     '.',
			                     fieldReferenceOrInvocationExpression.FieldName);
		}
		
		public object Visit(ArrayInitializerExpression arrayInitializerExpression, object data)
		{
			DebugOutput(arrayInitializerExpression);
			if (arrayInitializerExpression.CreateExpressions.Count > 0) {
				return String.Concat("{",
				                     GetExpressionList(arrayInitializerExpression.CreateExpressions),
				                     "}");
			}
			return String.Empty;
		}
		
		public object Visit(GetTypeExpression getTypeExpression, object data)
		{
			DebugOutput(getTypeExpression);
			return String.Concat("typeof(",
			                     this.GetTypeString(getTypeExpression.Type),
			                     ")");
		}
		
		public object Visit(ClassReferenceExpression classReferenceExpression, object data)
		{
			// ALMOST THE SAME AS '.this' but ignores all overridings from virtual
			// members. How can this done in C# ?
			DebugOutput(classReferenceExpression);
			return "TODO : " + classReferenceExpression;
		}
		
		public object Visit(LoopControlVariableExpression loopControlVariableExpression, object data)
		{
			// I think the LoopControlVariableExpression is only used in the for statement
			// and there it is handled
			DebugOutput(loopControlVariableExpression);
			return "Should Never happen : " + loopControlVariableExpression;
		}
		
		public object Visit(NamedArgumentExpression namedArgumentExpression, object data)
		{
			return String.Concat(namedArgumentExpression.Parametername,
			                     "=",
			                    namedArgumentExpression.Expression.AcceptVisitor(this, data));
		}
		
		public object Visit(AddressOfExpression addressOfExpression, object data)
		{
			DebugOutput(addressOfExpression);
			string procedureName    = addressOfExpression.Procedure.AcceptVisitor(this, data).ToString();
			string eventHandlerType = "EventHandler";
			bool   foundEventHandler = false;
			// try to resolve the type of the eventhandler using a little trick :)
			foreach (INode node in currentType.Children) {
				MethodDeclaration md = node as MethodDeclaration;
				if (md != null && md.Parameters != null && md.Parameters.Count > 0) {
					if (procedureName == md.Name || procedureName.EndsWith("." + md.Name)) {
						ParameterDeclarationExpression pde = (ParameterDeclarationExpression)md.Parameters[md.Parameters.Count - 1];
						string typeName = GetTypeString(pde.TypeReference);
						if (typeName.EndsWith("Args")) {
							eventHandlerType = typeName.Substring(0, typeName.Length - "Args".Length) + "Handler";
							foundEventHandler = true;
						}
					}
				}
			}
			return String.Concat(foundEventHandler ? "new " : "/* might be wrong, please check */ new ",
			                     eventHandlerType,
			                     "(",
			                     procedureName,
			                     ")");
		}
		
		public object Visit(TypeOfExpression typeOfExpression, object data)
		{
			DebugOutput(typeOfExpression);
			return String.Concat(typeOfExpression.Expression.AcceptVisitor(this, data),
			                     " is ",
			                     GetTypeString(typeOfExpression.Type));
		}
		
		public object Visit(ArrayCreateExpression ace, object data)
		{
			DebugOutput(ace);
			
			string type = GetTypeString(ace.CreateType);
			
			if (type.EndsWith("]")) {
				return String.Concat("new ",
				                     type);
			}
			
			return String.Concat("new ",
			                     type,
			                     "[",
			                     GetExpressionList(ace.Parameters),
			                     "]",
			                     ace.ArrayInitializer.AcceptVisitor(this, data));
		}
#endregion
#endregion
		
		public void AppendAttributes(ArrayList attr)
		{
			if (attr != null) {
				foreach (AttributeSection section in attr) {
					section.AcceptVisitor(this, null);
				}
			}
		}
		
		public void AppendParameters(ArrayList parameters)
		{
			if (parameters == null) {
				return;
			}
			for (int i = 0; i < parameters.Count; ++i) {
				ParameterDeclarationExpression pde = (ParameterDeclarationExpression)parameters[i];
				AppendAttributes(pde.Attributes);
				
				if ((pde.ParamModifiers.Modifier & ParamModifier.ByRef) == ParamModifier.ByRef) {
					sourceText.Append("ref ");
				} else if ((pde.ParamModifiers.Modifier & ParamModifier.ParamArray) == ParamModifier.ParamArray) {
					sourceText.Append("params ");
				}
				
				sourceText.Append(GetTypeString(pde.TypeReference));
				sourceText.Append(" ");
				sourceText.Append(pde.ParameterName);
				if (i + 1 < parameters.Count) {
					sourceText.Append(", ");
				}
			}
		}
		
		string ConvertTypeString(string typeString)
		{
			switch (typeString.ToLower(System.Globalization.CultureInfo.InvariantCulture)) {
				case "boolean":
					return "bool";
				case "string":
					return "string";
				case "char":
					return "char";
				case "double":
					return "double";
				case "single":
					return "float";
				case "decimal":
					return "decimal";
				case "date":
					return "System.DateTime";
				case "long":
					return "long";
				case "integer":
					return "int";
				case "short":
					return "short";
				case "byte":
					return "byte";
				case "void":
					return "void";
				case "system.object":
				case "object":
					return "object";
				case "system.uint64":
					return "ulong";
				case "system.uint32":
					return "uint";
				case "system.uint16":
					return "ushort";
			}
			return typeString;
		}
		
		string GetTypeString(TypeReference typeRef)
		{
			if (typeRef == null) {
				return "void";
			}
			
			string typeStr = ConvertTypeString(typeRef.Type);
		
			StringBuilder arrays = new StringBuilder();

			if (typeRef.RankSpecifier != null) {
				for (int i = 0; i < typeRef.RankSpecifier.Count; ++i) {
					if (typeRef.RankSpecifier[i] is int) {
						arrays.Append("[");
						arrays.Append(new String(',', (int)typeRef.RankSpecifier[i]));
						arrays.Append("]");
					} else if (typeRef.RankSpecifier[i] is ICollection) {
						foreach (object o in (ICollection)typeRef.RankSpecifier[i]) {
							arrays.Append("[");
							if (o is INode) {
								arrays.Append(((INode)o).AcceptVisitor(this, "").ToString());
							} else {
								arrays.Append(o.ToString());
							}
							arrays.Append("]");
						}
					} else {
						arrays.Append("[");
						arrays.Append(typeRef.RankSpecifier[i].ToString());
						arrays.Append("]");
					}
				}
			} else {
				if (typeRef.Dimension != null) {
					arrays.Append("[");
					if (typeRef.Dimension.Count > 0) {
						arrays.Append(new String(',', typeRef.Dimension.Count - 1));
					}
					arrays.Append("]");
				}
			}
			
			return typeStr + arrays.ToString();
		}
		
		string GetModifier(Modifier modifier)
		{
			StringBuilder builder = new StringBuilder();
			
			if ((modifier & Modifier.Public) == Modifier.Public) {
				builder.Append("public ");
			} else if ((modifier & Modifier.Private) == Modifier.Private) {
				builder.Append("private ");
			} else if ((modifier & (Modifier.Protected | Modifier.Friend)) == (Modifier.Protected | Modifier.Friend)) {
				builder.Append("protected internal ");
			} else if ((modifier & Modifier.Friend) == Modifier.Friend) {
				builder.Append("internal ");
			} else if ((modifier & Modifier.Protected) == Modifier.Protected) {
				builder.Append("protected ");
			}
			
			if ((modifier & Modifier.MustInherit) == Modifier.MustInherit) {
				builder.Append("abstract ");
			}
			if ((modifier & Modifier.Shared) == Modifier.Shared) {
				builder.Append("static ");
			}
			if ((modifier & Modifier.Overridable) == Modifier.Overridable) {
				builder.Append("virtual ");
			}
			if ((modifier & Modifier.MustOverride) == Modifier.MustOverride) {
				builder.Append("abstract ");
			}
			if ((modifier & Modifier.Overrides) == Modifier.Overrides) {
				builder.Append("override ");
			}
			if ((modifier & Modifier.Shadows) == Modifier.Shadows) {
				builder.Append("new ");
			}
			
			if ((modifier & Modifier.NotInheritable) == Modifier.NotInheritable) {
				builder.Append("sealed ");
			}
			
			if ((modifier & Modifier.Constant) == Modifier.Constant) {
				builder.Append("const ");
			}
			if ((modifier & Modifier.ReadOnly) == Modifier.ReadOnly) {
				builder.Append("readonly ");
			}
			return builder.ToString();
		}

		string GetParameters(ArrayList list)
		{
			return String.Concat("(",
			                     GetExpressionList(list),
			                     ")");
		}
		
		string GetExpressionList(ArrayList list)
		{
			StringBuilder sb = new StringBuilder();
			if (list != null) {
				for (int i = 0; i < list.Count; ++i) {
					Expression exp = (Expression)list[i];
					if (exp != null) {
						sb.Append(exp.AcceptVisitor(this, null));
						if (i + 1 < list.Count) {
							sb.Append(", ");
						}
					}
				}
			}
			return sb.ToString();
		}
		
	}
}	

⌨️ 快捷键说明

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