public override IPyValue TranslateToPython(IExternalTranslationContext ctx, CsharpMethodCallExpression src) { var dt = src.GenericDeclaringType; if (!IsDictionary(dt)) { return(null); } switch (src.MethodName) { case nameof(DictionaryReplacer <int, int> .Remove): // del myDict['key'] var args = MapNamedParameters(src); var key = ctx.TranslateValue(args.GetArgumentValue(0)); var target = ctx.TranslateValue(src.TargetObject); IPyValue arg = new PyArrayAccessExpression(target, key); var m = new PyMethodCallExpression("del", arg); m.OnSkipBracketRequest += (mce, args2) => { args2.CanSkipBrackets = GeneralRulesForMetodBrackets.Bla(mce); }; return(m); } return(null); }
public void CopyArguments(IEnumerable <FunctionArgument> srcParameters, PyMethodCallExpression dstMethod) { foreach (var functionArgument in srcParameters) { dstMethod.Arguments.Add(VisitFunctionArgument(functionArgument) as PyMethodInvokeValue); } }
public static bool Bla(PyMethodCallExpression q) { if (q.Arguments.Count != 1) { return(false); // many arguments } var firstArg = q.Arguments[0]; if (!string.IsNullOrEmpty(firstArg.Name)) { return(false); // named argument } var expression = firstArg.Expression; if (expression is PyMethodCallExpression) { return(true); } if (expression is PyArrayAccessExpression) { return(true); } if (expression is PyVariableExpression) { return(true); } if (expression is PyClassFieldAccessExpression) { return(false); } return(false); }
public override IPyValue TranslateToPython(IExternalTranslationContext ctx, CsharpMethodCallExpression src) { if (src.MethodInfo.DeclaringType == typeof(Console)) { var info = MapNamedParameters(src); if (src.MethodInfo.Name == nameof(Console.WriteLine)) { if (info.MethodParameters.Length == 1) { var v = ctx.TranslateValue(info.CallArguments[0].MyValue); var result = new PyMethodCallExpression(null, "print", v); // In Python 3, print is a function, whereas it used to be a statement in previous versions. /* * result.OnSkipBracketRequest += (mce, args) => * { * args.CanSkipBrackets = GeneralRulesForMetodBrackets.Bla(mce); * }; */ return(result); } } var mn = src.MethodInfo.ToString(); throw new NotImplementedException(mn); } return(null); }
protected virtual T VisitPyMethodCallExpression(PyMethodCallExpression node) { if (ThrowNotImplementedException) { throw new NotImplementedException(string.Format("Method {0} is not supported in class {1}", "VisitPyMethodCallExpression", this.GetType().FullName)); } return(default(T)); }
public IPyValue TranslateToPython(IExternalTranslationContext ctx, CsharpMethodCallExpression src) { if (src.IsDelegate) { return(TranspileDelegateToPyton(ctx, src)); } var principles = ctx.GetTranslationInfo(); src = SubstituteByReplacerMethod(ctx, src); { var value = Try_DirectCallAttribute(ctx, src); if (value != null) { return(value); } value = Try_UseExpressionAttribute(ctx, src); if (value != null) { return(value); } } ctx.GetTranslationInfo().CheckAccesibility(src); var declaringType = src.MethodInfo.DeclaringType; if (declaringType.IsGenericType) { declaringType = declaringType.GetGenericTypeDefinition(); } var cti = principles.FindClassTranslationInfo(declaringType); if (cti == null) { throw new NotSupportedException(); } var mti = principles.GetOrMakeTranslationInfo(src.MethodInfo); { var pyMethod = new PyMethodCallExpression(mti.ScriptName); if (src.MethodInfo.IsStatic) { var a = principles.GetPyType(src.MethodInfo.DeclaringType, true, principles.CurrentType); pyMethod.SetClassName(a, mti); } pyMethod.TargetObject = ctx.TranslateValue(src.TargetObject); CopyArguments(ctx, src.Arguments, pyMethod, null); if (cti.DontIncludeModuleForClassMembers) { pyMethod.DontIncludeClass = true; } return(pyMethod); } throw new Exception(string.Format("bright cow, {0}", src.MethodInfo.DeclaringType.FullName)); }
public static PyMethodCallExpression TrySetTargetObjectFromModule(this PyMethodCallExpression self, Type methodInfoDeclaringType) { var ar = methodInfoDeclaringType?.GetCustomAttribute <PyModuleAttribute>(); if (ar != null) { self.TargetObject = new PyModuleExpression(PyCodeModuleName.FromAttribute(ar), "?"); } return(self); }
public static IPyValue MakePathValueRelatedToFile(string path) { path = MakeUnixPath(path + UNIX_SEP); if (!path.StartsWith(UNIX_SEP)) { path = UNIX_SEP + path; } var _FILE_ = new PyDefinedConstExpression("__FILE__", null); var dirinfo = new PyMethodCallExpression("dirname", _FILE_); var a2 = new PyConstValue(path); var concat = new PyBinaryOperatorExpression(".", dirinfo, a2); return(concat); }
// Private Methods private IEnumerable <IPyStatement> ConvertDefinedConstToCode() { var result = new List <IPyStatement>(); var alreadyDefined = new List <string>(); if (!DefinedConsts.Any()) { return(result.ToArray()); } var grouped = DefinedConsts.GroupBy(u => GetNamespace(u.Key)).ToArray(); var useNamespaces = grouped.Length > 1 || grouped[0].Key != PathUtil.UNIX_SEP; foreach (var group in grouped) { List <IPyStatement> container; if (useNamespaces) { var ns1 = new PyNamespaceStatement((PyNamespace)group.Key); container = ns1.Code.Statements; result.Add(ns1); } else { container = result; } foreach (var item in group) { var shortName = GetShortName(item.Key); if (alreadyDefined.Contains(item.Key)) { continue; } alreadyDefined.Add(item.Key); var defined = new PyMethodCallExpression("defined", new PyConstValue(shortName)); var notDefined = new PyUnaryOperatorExpression(defined, "!"); var define = new PyMethodCallExpression("define", new PyConstValue(shortName), item.Value); var ifStatement = new PyIfStatement(notDefined, new PyExpressionStatement(define), null); container.Add(ifStatement); } } return(result.ToArray()); }
// Private Methods private static IPyValue TranspileDelegateToPyton(IExternalTranslationContext ctx, CsharpMethodCallExpression src) { if (src.TargetObject == null) { throw new NotSupportedException(); } var args = new List <IPyValue> { ctx.TranslateValue(src.TargetObject) }; foreach (var i in src.Arguments) { args.Add(ctx.TranslateValue(i.MyValue)); } var a = new PyMethodCallExpression("call_user_func", args.ToArray()); return(a); }
private void TranslateClass( ClassTranslationInfo classTranslationInfo, FullInterfaceDeclaration[] interfaces, FullClassDeclaration[] classes) { if (classTranslationInfo.Skip) { Debug.Write(""); } var pyModule = GetOrMakeModuleByName(classTranslationInfo.ModuleName); // var assemblyTI = _info.GetOrMakeTranslationInfo(_info.CurrentAssembly); PyQualifiedName GetBaseClassName() { var netBaseType = classTranslationInfo.Type.BaseType; if ((object)netBaseType == null || netBaseType == typeof(object)) { return(PyQualifiedName.Empty); } var baseTypeTranslationInfo = _state.Principles.GetOrMakeTranslationInfo(netBaseType); if (baseTypeTranslationInfo.Skip) { return(PyQualifiedName.Empty); } return(_state.Principles.GetPyType(netBaseType, true, null)); } var pyClass = classTranslationInfo.ExportAsModule ? null : pyModule.FindOrCreateClass(classTranslationInfo.PyName, GetBaseClassName()); Console.WriteLine(classTranslationInfo.ModuleName); _state.Principles.CurrentType = classTranslationInfo.Type; try { _state.Principles.CurrentAssembly = _state.Principles.CurrentType.Assembly; var fullname = classTranslationInfo.Type.FullName; var srcs = classTranslationInfo.Type.IsInterface ? interfaces .Where(q => q.FullName == fullname) .Select(q => q.ClassDeclaration) .OfType <IClassOrInterface>().ToArray() : classes .Where(q => q.FullName == fullname) .Select(q => q.ClassDeclaration) .OfType <IClassOrInterface>().ToArray(); var members = srcs.SelectMany(i => i.Members).ToArray(); { var constructors = members.OfType <ConstructorDeclaration>().ToArray(); if (pyClass == null && constructors.Length > 0) { throw new Exception("Class exported as module cannot have constructors"); } if (constructors.Length > 1) { throw new Exception("Python supports only one constructor per class"); } if (constructors.Any()) { TranslateConstructor(pyClass, constructors.First()); } } foreach (var methodDeclaration in members.OfType <MethodDeclaration>()) { TranslateMethod(pyModule, pyClass, methodDeclaration); } foreach (var pDeclaration in members.OfType <CsharpPropertyDeclaration>()) { TranslateProperty(pyModule, pyClass, pDeclaration); } foreach (var constDeclaration in members.OfType <FieldDeclaration>()) { TranslateField(pyModule, pyClass, constDeclaration); } } finally { _state.Principles.CurrentType = null; } { if (classTranslationInfo.IsPage) { var mti = MethodTranslationInfo.FromMethodInfo(classTranslationInfo.PageMethod, classTranslationInfo); var callMain = new PyMethodCallExpression(mti.ScriptName); callMain.SetClassName( classTranslationInfo.PyName, mti ); pyModule.BottomCode.Statements.Add(new PyExpressionStatement(callMain)); } } TranslateClass_AddModuleRequests(classTranslationInfo, pyModule); }
protected override IPyStatement VisitPyCodeBlock(PyCodeBlock node) { var newNode = new PyCodeBlock(); foreach (var i in node.GetPlain()) { newNode.Statements.Add(Simplify(i)); } if (op.JoinEchoStatements) { for (var i = 1; i < newNode.Statements.Count; i++) { var e1 = GetPyNativeMethodCall(newNode.Statements[i - 1], "echo"); if (e1 == null) { continue; } var e2 = GetPyNativeMethodCall(newNode.Statements[i], "echo"); if (e2 == null) { continue; } Func <IPyValue, IPyValue> AddBracketsIfNecessary = ee => { if (ee is PyParenthesizedExpression || ee is PyConstValue || ee is PyPropertyAccessExpression) { return(ee); } if (ee is PyBinaryOperatorExpression && ((PyBinaryOperatorExpression)ee).Operator == ".") { return(ee); } return(new PyParenthesizedExpression(ee)); }; var a1 = AddBracketsIfNecessary(e1.Arguments[0].Expression); var a2 = AddBracketsIfNecessary(e2.Arguments[0].Expression); IPyValue e = new PyBinaryOperatorExpression(".", a1, a2); e = Simplify(e); IPyValue echo = new PyMethodCallExpression("echo", e); newNode.Statements[i - 1] = new PyExpressionStatement(echo); newNode.Statements.RemoveAt(i); i--; } for (var i = 0; i < newNode.Statements.Count; i++) { var a = newNode.Statements[i]; if (a is PySourceBase) { newNode.Statements[i] = Visit(a as PySourceBase); } } } return(PySourceBase.EqualCode_List(node.Statements, newNode.Statements) ? node : newNode); }
protected override IPyValue VisitInstancePropertyAccessExpression(CsharpInstancePropertyAccessExpression src) { var pri = PropertyTranslationInfo.FromPropertyInfo(src.Member); var ownerInfo = _state.Principles.GetOrMakeTranslationInfo(src.Member.DeclaringType); if (src.TargetObject == null) { throw new NotImplementedException("statyczny"); } var translatedByExternalNodeTranslator = _state.Principles.NodeTranslators.Translate(_state, src); if (translatedByExternalNodeTranslator != null) { return(SimplifyPyExpression(translatedByExternalNodeTranslator)); } var pyTargetObject = TransValue(src.TargetObject); if (ownerInfo.IsArray) { var idx = new PyConstValue(pri.FieldScriptName); var arrayExpr = new PyArrayAccessExpression(pyTargetObject, idx); return(arrayExpr); } { var propertyInfo = src.Member; var classReplacer = _state.FindOneClassReplacer(propertyInfo.DeclaringType); if (classReplacer != null) { var newPropertyInfo = classReplacer.ReplaceBy.GetProperty(src.Member.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (newPropertyInfo == null) { throw new Exception(string.Format("Klasa {0} nie zawiera własności {1}", classReplacer.ReplaceBy, src.Member)); } if (newPropertyInfo.GetIndexParameters().Length > 0) { throw new NotSupportedException("energetic gecko, Property with index"); } propertyInfo = newPropertyInfo; } { var ats = propertyInfo.GetCustomAttribute <DirectCallAttribute>(true); if (ats != null) { if (string.IsNullOrEmpty(ats.Name)) { var tmp = ats.MapArray; if (tmp == null || tmp.Length <= 0) { return(pyTargetObject); } if (tmp.Length > 1 || tmp[0] != DirectCallAttribute.This) { throw new NotSupportedException(string.Format( "Property {1}.{0} has invalid 'Map' parameter in DirectCallAttribute", propertyInfo.Name, propertyInfo.DeclaringType)); } return(pyTargetObject); } switch (ats.MemberToCall) { case ClassMembers.Method: if (ats.Name == "this") { return(pyTargetObject); } var pyMethodCall = new PyMethodCallExpression(ats.Name); switch (ats.CallType) { case MethodCallStyles.Procedural: pyMethodCall.Arguments.Add(new PyMethodInvokeValue(pyTargetObject)); return(pyMethodCall); case MethodCallStyles.Instance: pyMethodCall.TargetObject = pyTargetObject; return(pyMethodCall); } throw new NotImplementedException(); case ClassMembers.Field: switch (ats.CallType) { case MethodCallStyles.Instance: if (ats.Name == "this") { return(pyTargetObject); } var includeModule = ownerInfo.IncludeModule; var field = new PyInstanceFieldAccessExpression(ats.Name, pyTargetObject, includeModule); return(field); default: throw new NotSupportedException(); } //var f = new PyMethodCallExpression(ats.Name); //method.Arguments.Add(new PyMethodInvokeValue(PyTargetObject)); //return method; default: throw new NotSupportedException(); } } } { var ats = propertyInfo.GetCustomAttribute <UseBinaryExpressionAttribute>(true); if (ats != null) { var left = GetValueForExpression(pyTargetObject, ats.Left); var right = GetValueForExpression(pyTargetObject, ats.Right); var method = new PyBinaryOperatorExpression(ats.Operator, left, right); return(method); } } { pri = PropertyTranslationInfo.FromPropertyInfo(src.Member); var to = TransValue(src.TargetObject); var a = new PyPropertyAccessExpression(pri, to); return(a); } } }
/// <summary> /// Creates expression based on DirectCallAttribute /// </summary> /// <param name="ctx"></param> /// <param name="directCallAttribute"></param> /// <param name="targetObject"></param> /// <param name="arguments"></param> /// <returns></returns> public static IPyValue CreateExpressionFromDirectCallAttribute(IExternalTranslationContext ctx, DirectCallAttribute directCallAttribute, IValue targetObject, FunctionArgument[] arguments, MethodBase methodInfo) { if (directCallAttribute.CallType == MethodCallStyles.Static) { throw new NotSupportedException(); } if (directCallAttribute.MemberToCall != ClassMembers.Method) { throw new NotSupportedException(); } if (string.IsNullOrEmpty(directCallAttribute.Name)) { var ma = directCallAttribute.MapArray; if (ma.Length != 1) { throw new NotSupportedException("gray horse 1"); } if (ma[0] == DirectCallAttribute.This) { if (targetObject == null) { throw new NotSupportedException("gray horse 2"); } return(ctx.TranslateValue(targetObject)); } // return PyMethod.Arguments[ma[0]].Expression return(ctx.TranslateValue(arguments[ma[0]].MyValue)); } var name = directCallAttribute.Name; var PyMethod = new PyMethodCallExpression(name); if (directCallAttribute.CallType == MethodCallStyles.Instance) { if (targetObject == null) { throw new NotSupportedException("gray horse 3"); } PyMethod.TargetObject = ctx.TranslateValue(targetObject); } { List <int> skipRefIndexList = null; if (methodInfo != null) { var skipRefOrOutArray = directCallAttribute.SkipRefOrOutArray; if (skipRefOrOutArray.Any()) { var parameters = methodInfo.GetParameters(); for (var index = 0; index < parameters.Length; index++) { if (!skipRefOrOutArray.Contains(parameters[index].Name)) { continue; } if (skipRefIndexList == null) { skipRefIndexList = new List <int>(); } skipRefIndexList.Add(index); } } } CopyArguments(ctx, arguments, PyMethod, skipRefIndexList); } if (directCallAttribute.HasMapping) { var PyArguments = PyMethod.Arguments.ToArray(); PyMethod.Arguments.Clear(); foreach (var argNr in directCallAttribute.MapArray) { if (argNr == DirectCallAttribute.This) { if (targetObject == null) { throw new NotSupportedException(); } var v = ctx.TranslateValue(targetObject); PyMethod.Arguments.Add(new PyMethodInvokeValue(v)); } else { if (argNr < PyArguments.Length) { PyMethod.Arguments.Add(PyArguments[argNr]); } } } } if (directCallAttribute.OutNr >= 0) { var nr = directCallAttribute.OutNr; var movedExpression = PyMethod.Arguments[nr].Expression; PyMethod.Arguments.RemoveAt(nr); var a = new PyAssignExpression(movedExpression, PyMethod); return(a); } return(PyMethod); }
// Private Methods private static void CopyArguments(IExternalTranslationContext ctx, IEnumerable <FunctionArgument> srcParameters, PyMethodCallExpression dstMethod, List <int> skipRefIndexList) { var parameterIdx = 0; foreach (var functionArgument in srcParameters) { var a = ctx.TranslateValue(functionArgument); if (!(a is PyMethodInvokeValue b)) { throw new NotImplementedException(); } if (b.Expression is PyParenthesizedExpression) { Debug.Write(""); } if (skipRefIndexList != null && skipRefIndexList.Contains(parameterIdx)) { b.ByRef = false; } dstMethod.Arguments.Add(b); parameterIdx++; } }
public override IPyValue TranslateToPython(IExternalTranslationContext ctx, CsharpMethodCallExpression src) { string GetOperatorName() { if (!src.MethodInfo.IsSpecialName) { return(null); } switch (src.MethodInfo.Name) { case "op_Addition": return("+"); case "op_Subtraction": return("-"); case "op_Multiply": return("*"); case "op_Division": return("/"); case "op_Equality": return("=="); case "op_Inequality ": return("!="); case "op_Implicit": return("i"); } return(null); } var ats = src.MethodInfo.GetCustomAttribute <DirectCallAttribute>(); if (ats == null) { return(null); } var name = ats.Name; var opName = GetOperatorName(); if (string.IsNullOrEmpty(name)) { name = src.MethodInfo.Name; } if (opName != null) { name = opName; } var cSharpParameters = src.MethodInfo.GetParameters(); var agrsIndexByName = Enumerable.Range(0, cSharpParameters.Length) .ToDictionary(a => cSharpParameters[a].Name, a => a); var argsValues = new Argument[cSharpParameters.Length]; var info = MapNamedParameters(src); for (var index = 0; index < src.Arguments.Length; index++) { var i = src.Arguments[index]; var pythonArgName = cSharpParameters[index].Name; if (!string.IsNullOrEmpty(i.ExplicitName)) { pythonArgName = i.ExplicitName; } var b = ctx.TranslateValue(i.MyValue); var pyIndex = agrsIndexByName[pythonArgName]; argsValues[pyIndex] = new Argument { Value = b, Name = cSharpParameters[pyIndex].Name }; } if (opName != null) { if (opName == "i" && argsValues.Length == 1) { return(argsValues[0].Value); } switch (argsValues.Length) { case 2: return(new PyBinaryOperatorExpression(opName, argsValues[0].Value, argsValues[1].Value)); case 1: return(new PyUnaryOperatorExpression(argsValues[0].Value, opName)); } throw new NotSupportedException("Unable to convert operator " + opName + " with " + argsValues.Length + " arguments"); } var result = new PyMethodCallExpression(name); var setName = false; foreach (var i in argsValues) { if (i == null) { setName = true; continue; } var item = new PyMethodInvokeValue(i.Value); if (setName) { item.Name = i.Name; } result.Arguments.Add(item); } result.TrySetTargetObjectFromModule(src.MethodInfo.DeclaringType); return(result); }
/// <summary> /// try to resolve simple case like for(int i=0; i<10; i++) /// </summary> private static IPyStatement[] TrySimpleForLoop( PyAssignExpression[] pyDeclarations, IPyStatement[] incrementors, IPyValue condition, IPyStatement statement) { if (pyDeclarations.Length != 1 || incrementors.Length != 1) { return(null); } var dec = pyDeclarations[0]; if (!(dec.Left is PyVariableExpression controlVariable)) { return(null); } if (!(condition is PyBinaryOperatorExpression binCondition)) { return(null); } binCondition = VariableOnLeft(binCondition, controlVariable.VariableName); var loopIncrement = FindIncrement(controlVariable, incrementors[0]); if (loopIncrement == null) { return(null); } var loopStart = pyDeclarations[0].Right; IPyStatement[] Q(object incrementValue) { var range = new PyMethodCallExpression("range"); var isOneIncrement = ValueHelper.EqualsNumericOne(incrementValue) ?? false; if (!IsConstZero(loopStart) || !isOneIncrement) { range.Arguments.Add(new PyMethodInvokeValue(loopStart)); } range.Arguments.Add(new PyMethodInvokeValue(binCondition.Right)); if (!isOneIncrement) { range.Arguments.Add( new PyMethodInvokeValue(new PyConstValue(incrementValue))); } var foreachStatement = new PyForEachStatement(controlVariable.VariableName, range, statement); return(new IPyStatement[] { foreachStatement }); } if (loopIncrement is PyConstValue constLoopIncrement) { switch (binCondition.Operator) { case "<": { if (ValueHelper.IsGreaterThanZero(constLoopIncrement.Value) ?? false) { return(Q(constLoopIncrement.Value)); } } break; case ">": { if (ValueHelper.IsLowerThanZero(constLoopIncrement.Value) ?? false) { return(Q(constLoopIncrement.Value)); } } break; } } var result = new PyForStatement(pyDeclarations.ToArray(), condition, statement, incrementors); return(new IPyStatement[] { result }); }
protected override IPyValue VisitCallConstructor(CallConstructor src) { var tmp = _state.Principles.NodeTranslators.Translate(_state, src); if (tmp != null) { return(SimplifyPyExpression(tmp)); } var r = new PyMethodCallExpression(PyMethodCallExpression.ConstructorMethodName); if (src.Info.ReflectedType != src.Info.DeclaringType) { throw new NotSupportedException(); } // we can use "state.Principles.CurrentType" as third parameter if we prefer "new self()" or "new parent()" contructor calls r.SetClassName( _state.Principles.GetPyType(src.Info.ReflectedType, true, null), _state.Principles.GetOrMakeTranslationInfo(src.Info) ); // class name for constructor { // var a = src.Info.GetCustomAttribute(); } var cti = _state.Principles.GetTi(src.Info.ReflectedType, true); if (cti.DontIncludeModuleForClassMembers) { r.DontIncludeClass = true; } if (cti.IsArray) { if (src.Initializers != null && src.Initializers.Any()) { var ggg = src.Initializers.Select(TransValue).ToArray(); var h = new PyArrayCreateExpression(ggg); return(SimplifyPyExpression(h)); } else { var h = new PyArrayCreateExpression(); return(SimplifyPyExpression(h)); } } { // cti = state.Principles.GetTi(src.Info.ReflectedType); // if (cti.IsReflected) { var replacer = _state.FindOneClassReplacer(src.Info.ReflectedType); if (replacer != null) { var translationMethods = replacer.ReplaceBy .GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) .Where(m => m.IsDefined(typeof(TranslatorAttribute))).ToArray(); foreach (var m in translationMethods) { var translated = m.Invoke(null, new object[] { _state, src }); if (translated is IPyValue) { return(translated as IPyValue); } } //throw new Exception(string.Format("Klasa {0} nie umie przetłumaczyć konstruktora {1}",replacer.ReplaceBy.FullName, replacer.SourceType.FullName)); } } } foreach (var functionArgument in src.Arguments) { r.Arguments.Add(TransFunctionArgument(functionArgument)); } return(r); }