public void ObjectLiteralWithFunctionValuesAreNotOutputOnMultipleLines() { AssertCorrect(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("x", JsExpression.Number(1)), new JsObjectLiteralProperty("y", JsExpression.FunctionDefinition(new string[0], new JsReturnStatement())), new JsObjectLiteralProperty("z", JsExpression.Number(3))), "{x:1,y:function(){return;},z:3}"); }
private JsExpression CreateDefaultConstructorInvocation(IMethod defaultConstructor, JsExpression typeRef) { var sem = _metadataImporter.GetConstructorSemantics(defaultConstructor); switch (sem.Type) { case ConstructorScriptSemantics.ImplType.UnnamedConstructor: // default behavior is good enough. case ConstructorScriptSemantics.ImplType.NotUsableFromScript: // Can't be invoked so we don't need to create it. return(null); case ConstructorScriptSemantics.ImplType.NamedConstructor: return(JsExpression.New(JsExpression.Member(typeRef, sem.Name))); case ConstructorScriptSemantics.ImplType.StaticMethod: return(JsExpression.Invocation(JsExpression.Member(typeRef, sem.Name))); case ConstructorScriptSemantics.ImplType.InlineCode: var prevRegion = _errorReporter.Region; try { _errorReporter.Region = defaultConstructor.Region; return(InlineCodeMethodCompiler.CompileInlineCodeMethodInvocation(defaultConstructor, sem.LiteralCode, null, EmptyList <JsExpression> .Instance, r => r.Resolve(_compilation), _runtimeLibrary.GetScriptType, false, s => _errorReporter.Message(7525, s))); } finally { _errorReporter.Region = prevRegion; } case ConstructorScriptSemantics.ImplType.Json: return(JsExpression.ObjectLiteral()); default: throw new Exception("Invalid constructor implementation type: " + sem.Type); } }
private JsExpression CreateInitEnumCall(JsEnum type, string ctorName) { var values = new List <JsObjectLiteralProperty>(); foreach (var v in type.CSharpTypeDefinition.Fields) { if (v.ConstantValue != null) { var sem = _metadataImporter.GetFieldSemantics(v); if (sem.Type == FieldScriptSemantics.ImplType.Field) { values.Add(new JsObjectLiteralProperty(sem.Name, JsExpression.Number(Convert.ToDouble(v.ConstantValue)))); } else if (sem.Type == FieldScriptSemantics.ImplType.Constant && sem.Name != null) { values.Add(new JsObjectLiteralProperty(sem.Name, sem.Value is string?JsExpression.String((string)sem.Value) : JsExpression.Number(Convert.ToDouble(sem.Value)))); } } else { _errorReporter.Region = v.Region; _errorReporter.InternalError("Enum field " + v.FullName + " is not constant."); } } var args = new List <JsExpression> { JsExpression.Identifier(ctorName), JsExpression.ObjectLiteral(values) }; return(JsExpression.Invocation(JsExpression.Member(_systemScript, InitEnum), args)); }
public void ObjectLiteralIsOutputCorrectly() { AssertCorrect(JsExpression.ObjectLiteral(), "{}"); AssertCorrect(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("x", JsExpression.Number(1))), "{ x: 1 }"); AssertCorrect(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("x", JsExpression.Number(1)), new JsObjectLiteralProperty("y", JsExpression.Number(2)), new JsObjectLiteralProperty("z", JsExpression.Number(3))), "{ x: 1, y: 2, z: 3 }"); }
public void ObjectLiteralsContainNoEmbeddedSpaces() { AssertCorrect(JsExpression.ObjectLiteral(), "{}"); AssertCorrect(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("x", JsExpression.Number(1))), "{x:1}"); AssertCorrect(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("x", JsExpression.Number(1)), new JsObjectLiteralProperty("y", JsExpression.Number(2)), new JsObjectLiteralProperty("z", JsExpression.Number(3))), "{x:1,y:2,z:3}"); }
public void ExpressionStatementIsParenthesizedWhenItStartsWithAnObjectLiteral() { AssertCorrect((JsStatement)JsExpression.ObjectLiteral(new JsObjectLiteralProperty("a", JsExpression.Number(0))), "({ a: 0 });\n"); AssertCorrect((JsStatement)JsExpression.Invocation(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("a", JsExpression.Number(0)))), "({ a: 0 }());\n"); AssertCorrect((JsStatement)JsExpression.Member(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("a", JsExpression.Number(0))), "a"), "({ a: 0 }.a);\n"); AssertCorrect((JsStatement)JsExpression.Comma(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("a", JsExpression.Number(0))), JsExpression.Null), "({ a: 0 }, null);\n"); AssertCorrect((JsStatement)JsExpression.Conditional(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("a", JsExpression.Number(0))), JsExpression.Number(0), JsExpression.Number(1)), "({ a: 0 } ? 0 : 1);\n"); AssertCorrect((JsStatement)JsExpression.PrefixPlusPlus(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("a", JsExpression.Number(0)))), "++{ a: 0 };\n"); AssertCorrect((JsStatement)JsExpression.PostfixPlusPlus(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("a", JsExpression.Number(0)))), "({ a: 0 }++);\n"); AssertCorrect((JsStatement)JsExpression.PostfixMinusMinus(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("a", JsExpression.Number(0)))), "({ a: 0 }--);\n"); AssertCorrect((JsStatement)JsExpression.Index(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("a", JsExpression.Number(0))), JsExpression.Number(0)), "({ a: 0 }[0]);\n"); AssertCorrect((JsStatement)JsExpression.Member(JsExpression.Invocation(JsExpression.Member(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("a", JsExpression.Number(0))), "a")), "b"), "({ a: 0 }.a().b);\n"); }
public JsStatement MakeInitAssemblyCall() { var args = new List <JsExpression> { _linker.CurrentAssemblyExpression, JsExpression.String(_compilation.MainAssembly.AssemblyName) }; var includedResources = GetIncludedResources().ToList(); if (includedResources.Count > 0) { args.Add(JsExpression.ObjectLiteral(includedResources.Select(r => new JsObjectLiteralProperty(r.Name, JsExpression.String(Convert.ToBase64String(ReadResource(r))))))); } return(JsExpression.Invocation(JsExpression.Member(_systemScript, InitAssembly), args)); }
public static JsExpression ConstructFieldPropertyAccessor(IMethod m, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, string fieldName, Func <IType, JsExpression> instantiateType, bool isGetter, bool includeDeclaringType) { var properties = GetCommonMemberInfoProperties(m, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType); properties.Add(new JsObjectLiteralProperty("type", JsExpression.Number((int)MemberTypes.Method))); properties.Add(new JsObjectLiteralProperty("params", JsExpression.ArrayLiteral(m.Parameters.Select(p => instantiateType(p.Type))))); properties.Add(new JsObjectLiteralProperty("returnType", instantiateType(m.ReturnType))); properties.Add(new JsObjectLiteralProperty(isGetter ? "fget" : "fset", JsExpression.String(fieldName))); if (m.IsStatic) { properties.Add(new JsObjectLiteralProperty("isStatic", JsExpression.True)); } return(JsExpression.ObjectLiteral(properties)); }
public static IList <JsStatement> Process(IMetadataImporter metadataImporter, INamer namer, ICompilation compilation, IList <JsStatement> statements) { var usedSymbols = UsedSymbolsGatherer.Analyze(statements); var importer = new ImportVisitor(metadataImporter, namer, compilation.MainAssembly, usedSymbols); var body = statements.Select(s => importer.VisitStatement(s, null)).ToList(); if (MetadataUtils.IsAsyncModule(compilation.MainAssembly)) { body.Insert(0, new JsVariableDeclarationStatement("exports", JsExpression.ObjectLiteral())); body.Add(new JsReturnStatement(JsExpression.Identifier("exports"))); var pairs = new[] { new KeyValuePair <string, string>("mscorlib", namer.GetVariableName("_", usedSymbols)) }.Concat(importer._moduleAliases.OrderBy(x => x.Key)).ToList(); body = new List <JsStatement> { new JsExpressionStatement( JsExpression.Invocation( JsExpression.Identifier("define"), JsExpression.ArrayLiteral(pairs.Select(p => JsExpression.String(p.Key))), JsExpression.FunctionDefinition( pairs.Select(p => p.Value), new JsBlockStatement(body) ) ) ) }; } else if (importer._moduleAliases.Count > 0) { // If we require any module, we require mscorlib. This should work even if we are a leaf module that doesn't include any other module because our parent script will do the mscorlib require for us. body.InsertRange(0, new[] { (JsStatement) new JsExpressionStatement(JsExpression.Invocation(JsExpression.Identifier("require"), JsExpression.String("mscorlib"))) } .Concat(importer._moduleAliases.OrderBy(x => x.Key) .Select(x => new JsVariableDeclarationStatement( x.Value, JsExpression.Invocation( JsExpression.Identifier("require"), JsExpression.String(x.Key)))) .ToList())); } else { body = new List <JsStatement> { new JsExpressionStatement(JsExpression.Invocation(JsExpression.FunctionDefinition(new string[0], new JsBlockStatement(body)))) }; } return(body); }
private JsExpression GetMetadataDescriptor(ITypeDefinition type, bool isGenericSpecialization) { var properties = new List <JsObjectLiteralProperty>(); var scriptableAttributes = MetadataUtils.GetScriptableAttributes(type.Attributes, _metadataImporter).ToList(); if (scriptableAttributes.Count != 0) { properties.Add(new JsObjectLiteralProperty("attr", JsExpression.ArrayLiteral(scriptableAttributes.Select(a => MetadataUtils.ConstructAttribute(a, type, _compilation, _metadataImporter, _namer, _runtimeLibrary, _errorReporter))))); } if (type.Kind == TypeKind.Interface && MetadataUtils.IsJsGeneric(type, _metadataImporter) && type.TypeParameters != null && type.TypeParameters.Any(typeParameter => typeParameter.Variance != VarianceModifier.Invariant)) { properties.Add(new JsObjectLiteralProperty("variance", JsExpression.ArrayLiteral(type.TypeParameters.Select(typeParameter => JsExpression.Number(ConvertVarianceToInt(typeParameter.Variance)))))); } if (type.Kind == TypeKind.Class || type.Kind == TypeKind.Struct || type.Kind == TypeKind.Interface) { var members = type.Members.Where(m => MetadataUtils.IsReflectable(m, _attributeStore)) .OrderBy(m => m, MemberOrderer.Instance) .Select(m => { _errorReporter.Region = m.Region; return(MetadataUtils.ConstructMemberInfo(m, _compilation, _metadataImporter, _namer, _runtimeLibrary, _errorReporter, t => _runtimeLibrary.InstantiateType(t, isGenericSpecialization ? _genericSpecializationReflectionRuntimeContext : _defaultReflectionRuntimeContext), includeDeclaringType: false)); }) .ToList(); if (members.Count > 0) { properties.Add(new JsObjectLiteralProperty("members", JsExpression.ArrayLiteral(members))); } var aua = _attributeStore.AttributesFor(type).GetAttribute <AttributeUsageAttribute>(); if (aua != null) { if (!aua.Inherited) { properties.Add(new JsObjectLiteralProperty("attrNoInherit", JsExpression.True)); } if (aua.AllowMultiple) { properties.Add(new JsObjectLiteralProperty("attrAllowMultiple", JsExpression.True)); } } } if (type.Kind == TypeKind.Enum && _attributeStore.AttributesFor(type).HasAttribute <FlagsAttribute>()) { properties.Add(new JsObjectLiteralProperty("enumFlags", JsExpression.True)); } return(properties.Count > 0 ? JsExpression.ObjectLiteral(properties) : null); }
private JsExpression CreateInstanceMembers(JsClass c, string typeVariableName) { var members = c.InstanceMethods.Select(m => new JsObjectLiteralProperty(m.Name, m.Definition != null ? RewriteMethod(m) : JsExpression.Null)); if (c.CSharpTypeDefinition.Kind == TypeKind.Struct) { if (!c.InstanceMethods.Any(m => m.Name == "getHashCode")) { members = members.Concat(new[] { new JsObjectLiteralProperty("getHashCode", GenerateStructGetHashCodeMethod(c.CSharpTypeDefinition)) }); } if (!c.InstanceMethods.Any(m => m.Name == "equals")) { members = members.Concat(new[] { new JsObjectLiteralProperty("equals", GenerateStructEqualsMethod(c.CSharpTypeDefinition, typeVariableName)) }); } } return(JsExpression.ObjectLiteral(members)); }
public JsExpression GetExpressionForLocal(string name, JsExpression accessor, IType type, IRuntimeContext context) { var scriptType = TypeOf(type, context); JsExpression getterDefinition = JsExpression.FunctionDefinition(new string[0], JsStatement.Return(accessor)); JsExpression setterDefinition = JsExpression.FunctionDefinition(new[] { "$" }, JsExpression.Assign(accessor, JsExpression.Identifier("$"))); if (UsesThisVisitor.Analyze(accessor)) { getterDefinition = JsExpression.Invocation(JsExpression.Member(getterDefinition, "bind"), JsExpression.This); setterDefinition = JsExpression.Invocation(JsExpression.Member(setterDefinition, "bind"), JsExpression.This); } return(JsExpression.ObjectLiteral( new JsObjectLiteralProperty("ntype", JsExpression.Number((int)ExpressionType.MemberAccess)), new JsObjectLiteralProperty("type", scriptType), new JsObjectLiteralProperty("expression", JsExpression.ObjectLiteral( new JsObjectLiteralProperty("ntype", JsExpression.Number((int)ExpressionType.Constant)), new JsObjectLiteralProperty("type", scriptType), new JsObjectLiteralProperty("value", JsExpression.ObjectLiteral()) )), new JsObjectLiteralProperty("member", JsExpression.ObjectLiteral( new JsObjectLiteralProperty("typeDef", new JsTypeReferenceExpression(_compilation.FindType(KnownTypeCode.Object).GetDefinition())), new JsObjectLiteralProperty("name", JsExpression.String(name)), new JsObjectLiteralProperty("type", JsExpression.Number((int)MemberTypes.Property)), new JsObjectLiteralProperty("returnType", scriptType), new JsObjectLiteralProperty("getter", JsExpression.ObjectLiteral( new JsObjectLiteralProperty("typeDef", new JsTypeReferenceExpression(_compilation.FindType(KnownTypeCode.Object).GetDefinition())), new JsObjectLiteralProperty("name", JsExpression.String("get_" + name)), new JsObjectLiteralProperty("type", JsExpression.Number((int)MemberTypes.Method)), new JsObjectLiteralProperty("returnType", scriptType), new JsObjectLiteralProperty("params", JsExpression.ArrayLiteral()), new JsObjectLiteralProperty("def", getterDefinition) )), new JsObjectLiteralProperty("setter", JsExpression.ObjectLiteral( new JsObjectLiteralProperty("typeDef", new JsTypeReferenceExpression(_compilation.FindType(KnownTypeCode.Object).GetDefinition())), new JsObjectLiteralProperty("name", JsExpression.String("set_" + name)), new JsObjectLiteralProperty("type", JsExpression.Number((int)MemberTypes.Method)), new JsObjectLiteralProperty("returnType", new JsTypeReferenceExpression(_compilation.FindType(KnownTypeCode.Void).GetDefinition())), new JsObjectLiteralProperty("params", JsExpression.ArrayLiteral(scriptType)), new JsObjectLiteralProperty("def", setterDefinition) )) )) )); }
private JsExpression GetMetadataDescriptor(ITypeDefinition type, bool isGenericSpecialization) { var properties = new List <JsObjectLiteralProperty>(); var scriptableAttributes = type.Attributes.Where(a => !a.IsConditionallyRemoved && _metadataImporter.GetTypeSemantics(a.AttributeType.GetDefinition()).Type == TypeScriptSemantics.ImplType.NormalType).ToList(); if (scriptableAttributes.Count != 0) { properties.Add(new JsObjectLiteralProperty("attr", JsExpression.ArrayLiteral(scriptableAttributes.Select(a => MetadataUtils.ConstructAttribute(a, type, _compilation, _metadataImporter, _namer, _runtimeLibrary, _errorReporter))))); } if (type.Kind == TypeKind.Class) { var members = type.Members.Where(m => MetadataUtils.IsReflectable(m, _metadataImporter)) .OrderBy(m => m, MemberOrderer.Instance) .Select(m => { _errorReporter.Region = m.Region; return(MetadataUtils.ConstructMemberInfo(m, _compilation, _metadataImporter, _namer, _runtimeLibrary, _errorReporter, t => _runtimeLibrary.InstantiateType(t, isGenericSpecialization ? _genericSpecializationReflectionRuntimeContext : _defaultReflectionRuntimeContext), includeDeclaringType: false)); }) .ToList(); if (members.Count > 0) { properties.Add(new JsObjectLiteralProperty("members", JsExpression.ArrayLiteral(members))); } var aua = AttributeReader.ReadAttribute <AttributeUsageAttribute>(type); if (aua != null) { if (!aua.Inherited) { properties.Add(new JsObjectLiteralProperty("attrNoInherit", JsExpression.True)); } if (aua.AllowMultiple) { properties.Add(new JsObjectLiteralProperty("attrAllowMultiple", JsExpression.True)); } } } if (type.Kind == TypeKind.Enum && AttributeReader.HasAttribute <FlagsAttribute>(type)) { properties.Add(new JsObjectLiteralProperty("enumFlags", JsExpression.True)); } return(properties.Count > 0 ? JsExpression.ObjectLiteral(properties) : null); }
public IList <JsStatement> Process(IEnumerable <JsType> types, IMethod entryPoint) { var result = new List <JsStatement>(); var orderedTypes = OrderByNamespace(types, t => _metadataImporter.GetTypeSemantics(t.CSharpTypeDefinition).Name).ToList(); foreach (var t in orderedTypes) { try { string name = _metadataImporter.GetTypeSemantics(t.CSharpTypeDefinition).Name; bool isGlobal = string.IsNullOrEmpty(name); bool isMixin = MetadataUtils.IsMixin(t.CSharpTypeDefinition); result.Add(new JsComment("//////////////////////////////////////////////////////////////////////////////" + Environment.NewLine + " " + t.CSharpTypeDefinition.FullName)); var typeRef = JsExpression.Identifier(_namer.GetTypeVariableName(name)); if (t is JsClass) { var c = (JsClass)t; if (isGlobal) { result.AddRange(c.StaticMethods.Select(m => new JsExpressionStatement(JsExpression.Binary(ExpressionNodeType.Assign, JsExpression.Member(GetRoot(t.CSharpTypeDefinition, exportNonPublic: true), m.Name), m.Definition)))); } else if (isMixin) { result.AddRange(c.StaticMethods.Select(m => new JsExpressionStatement(JsExpression.Assign(MakeNestedMemberAccess(name + "." + m.Name), m.Definition)))); } else if (MetadataUtils.IsResources(c.CSharpTypeDefinition)) { result.Add(GenerateResourcesClass(c)); } else { var unnamedCtor = c.UnnamedConstructor ?? JsExpression.FunctionDefinition(new string[0], JsBlockStatement.EmptyStatement); if (MetadataUtils.IsJsGeneric(c.CSharpTypeDefinition, _metadataImporter)) { var typeParameterNames = c.CSharpTypeDefinition.TypeParameters.Select(tp => _namer.GetTypeParameterName(tp)).ToList(); var stmts = new List <JsStatement> { new JsVariableDeclarationStatement(InstantiatedGenericTypeVariableName, unnamedCtor) }; AddClassMembers(c, JsExpression.Identifier(InstantiatedGenericTypeVariableName), stmts); stmts.AddRange(c.StaticInitStatements); stmts.Add(new JsReturnStatement(JsExpression.Identifier(InstantiatedGenericTypeVariableName))); var replacer = new GenericSimplifier(c.CSharpTypeDefinition, typeParameterNames, JsExpression.Identifier(InstantiatedGenericTypeVariableName)); for (int i = 0; i < stmts.Count; i++) { stmts[i] = replacer.Process(stmts[i]); } result.Add(new JsVariableDeclarationStatement(typeRef.Name, JsExpression.FunctionDefinition(typeParameterNames, new JsBlockStatement(stmts)))); var args = new List <JsExpression> { GetRoot(t.CSharpTypeDefinition), JsExpression.String(name), typeRef, JsExpression.Number(c.CSharpTypeDefinition.TypeParameterCount) }; var metadata = GetMetadataDescriptor(t.CSharpTypeDefinition, false); if (metadata != null) { args.Add(metadata); } result.Add(new JsExpressionStatement(JsExpression.Invocation(JsExpression.Member(_systemScript, c.CSharpTypeDefinition.Kind == TypeKind.Interface ? RegisterGenericInterface : RegisterGenericClass), args))); } else { result.Add(new JsVariableDeclarationStatement(typeRef.Name, unnamedCtor)); AddClassMembers(c, typeRef, result); } } } else if (t is JsEnum) { var e = (JsEnum)t; result.Add(new JsVariableDeclarationStatement(typeRef.Name, JsExpression.FunctionDefinition(new string[0], JsBlockStatement.EmptyStatement))); var values = new List <JsObjectLiteralProperty>(); foreach (var v in e.CSharpTypeDefinition.Fields) { if (v.ConstantValue != null) { var sem = _metadataImporter.GetFieldSemantics(v); if (sem.Type == FieldScriptSemantics.ImplType.Field) { values.Add(new JsObjectLiteralProperty(sem.Name, JsExpression.Number(Convert.ToDouble(v.ConstantValue)))); } else if (sem.Type == FieldScriptSemantics.ImplType.Constant && sem.Name != null) { values.Add(new JsObjectLiteralProperty(sem.Name, sem.Value is string?JsExpression.String((string)sem.Value) : JsExpression.Number(Convert.ToDouble(sem.Value)))); } } else { _errorReporter.Region = v.Region; _errorReporter.InternalError("Enum field " + v.FullName + " is not constant."); } } result.Add(new JsExpressionStatement(JsExpression.Assign(JsExpression.Member(typeRef, Prototype), JsExpression.ObjectLiteral(values)))); } } catch (Exception ex) { _errorReporter.Region = t.CSharpTypeDefinition.Region; _errorReporter.InternalError(ex, "Error formatting type " + t.CSharpTypeDefinition.FullName); } } var typesToRegister = orderedTypes .Where(c => !(c is JsClass && MetadataUtils.IsJsGeneric(c.CSharpTypeDefinition, _metadataImporter)) && !string.IsNullOrEmpty(_metadataImporter.GetTypeSemantics(c.CSharpTypeDefinition).Name) && (!MetadataUtils.IsResources(c.CSharpTypeDefinition) || c.CSharpTypeDefinition.IsExternallyVisible()) && // Resources classes are only exported if they are public. !MetadataUtils.IsMixin(c.CSharpTypeDefinition)) .ToList(); result.AddRange(TopologicalSortTypesByInheritance(typesToRegister) .Select(c => { try { string name = _metadataImporter.GetTypeSemantics(c.CSharpTypeDefinition).Name; if (c.CSharpTypeDefinition.Kind == TypeKind.Enum) { return(CreateRegisterEnumCall(c.CSharpTypeDefinition, name, JsExpression.Identifier(_namer.GetTypeVariableName(name)))); } if (MetadataUtils.IsResources(c.CSharpTypeDefinition)) { return(JsExpression.Invocation(JsExpression.Member(_systemScript, RegisterType), GetRoot(c.CSharpTypeDefinition), JsExpression.String(name), JsExpression.Identifier(_namer.GetTypeVariableName(name)))); } if (c.CSharpTypeDefinition.Kind == TypeKind.Interface) { return(CreateRegisterInterfaceCall(c.CSharpTypeDefinition, name, JsExpression.Identifier(_namer.GetTypeVariableName(name)), GetImplementedInterfaces(c.CSharpTypeDefinition.GetDefinition()).ToList())); } else { return(CreateRegisterClassCall(c.CSharpTypeDefinition, name, JsExpression.Identifier(_namer.GetTypeVariableName(name)), GetBaseClass(c.CSharpTypeDefinition), GetImplementedInterfaces(c.CSharpTypeDefinition).ToList())); } } catch (Exception ex) { _errorReporter.Region = c.CSharpTypeDefinition.Region; _errorReporter.InternalError(ex, "Error formatting type " + c.CSharpTypeDefinition.FullName); return(JsExpression.Number(0)); } }) .Select(expr => new JsExpressionStatement(expr))); result.AddRange(GetStaticInitializationOrder(orderedTypes.OfType <JsClass>(), 1) .Where(c => !MetadataUtils.IsJsGeneric(c.CSharpTypeDefinition, _metadataImporter) && !MetadataUtils.IsResources(c.CSharpTypeDefinition)) .SelectMany(c => c.StaticInitStatements)); if (entryPoint != null) { if (entryPoint.Parameters.Count > 0) { _errorReporter.Region = entryPoint.Region; _errorReporter.Message(Messages._7800, entryPoint.FullName); } else { var sem = _metadataImporter.GetMethodSemantics(entryPoint); if (sem.Type != MethodScriptSemantics.ImplType.NormalMethod) { _errorReporter.Region = entryPoint.Region; _errorReporter.Message(Messages._7801, entryPoint.FullName); } else { result.Add(new JsExpressionStatement(JsExpression.Invocation(JsExpression.Member(new JsTypeReferenceExpression(entryPoint.DeclaringTypeDefinition), sem.Name)))); } } } return(result); }
private JsStatement GenerateResourcesClass(JsClass c) { var fields = c.StaticInitStatements .OfType <JsExpressionStatement>() .Select(s => s.Expression) .OfType <JsBinaryExpression>() .Where(expr => expr.NodeType == ExpressionNodeType.Assign && expr.Left is JsMemberAccessExpression) .Select(expr => new { Name = ((JsMemberAccessExpression)expr.Left).MemberName, Value = expr.Right }); return(new JsVariableDeclarationStatement(_namer.GetTypeVariableName(_metadataImporter.GetTypeSemantics(c.CSharpTypeDefinition).Name), JsExpression.ObjectLiteral(fields.Select(f => new JsObjectLiteralProperty(f.Name, f.Value))))); }
private void AddClassMembers(JsClass c, JsExpression typeRef, List <JsStatement> stmts) { if (c.InstanceMethods.Count > 0) { stmts.Add(new JsExpressionStatement(JsExpression.Assign(JsExpression.Member(typeRef, Prototype), JsExpression.ObjectLiteral(c.InstanceMethods.Select(m => new JsObjectLiteralProperty(m.Name, m.Definition != null ? RewriteMethod(m) : JsExpression.Null)))))); } if (c.NamedConstructors.Count > 0) { stmts.AddRange(c.NamedConstructors.Select(m => new JsExpressionStatement(JsExpression.Assign(JsExpression.Member(typeRef, m.Name), m.Definition)))); stmts.Add(new JsExpressionStatement(c.NamedConstructors.Reverse().Aggregate((JsExpression)JsExpression.Member(typeRef, Prototype), (right, ctor) => JsExpression.Assign(JsExpression.Member(JsExpression.Member(typeRef, ctor.Name), Prototype), right)))); // This generates a statement like {C}.ctor1.prototype = {C}.ctor2.prototype = {C}.prototoype } var defaultConstructor = Saltarelle.Compiler.Utils.SelfParameterize(c.CSharpTypeDefinition).GetConstructors().SingleOrDefault(x => x.Parameters.Count == 0 && x.IsPublic); if (defaultConstructor != null) { var sem = _metadataImporter.GetConstructorSemantics(defaultConstructor); if (sem.Type != ConstructorScriptSemantics.ImplType.UnnamedConstructor && sem.Type != ConstructorScriptSemantics.ImplType.NotUsableFromScript) { var createInstance = MetadataUtils.CompileConstructorInvocation(defaultConstructor, null, c.CSharpTypeDefinition, null, EmptyList <ResolveResult> .Instance, _compilation, _metadataImporter, _namer, _runtimeLibrary, _errorReporter, null, null); stmts.Add(new JsExpressionStatement( JsExpression.Assign( JsExpression.Member(typeRef, "createInstance"), JsExpression.FunctionDefinition(new string[0], new JsBlockStatement(createInstance.AdditionalStatements.Concat(new[] { new JsReturnStatement(createInstance.Expression) })))))); } } stmts.AddRange(c.StaticMethods.Select(m => new JsExpressionStatement(JsExpression.Assign(JsExpression.Member(typeRef, m.Name), RewriteMethod(m))))); if (MetadataUtils.IsSerializable(c.CSharpTypeDefinition)) { string typeCheckCode = MetadataUtils.GetSerializableTypeCheckCode(c.CSharpTypeDefinition); if (!string.IsNullOrEmpty(typeCheckCode)) { var oldReg = _errorReporter.Region; _errorReporter.Region = c.CSharpTypeDefinition.Attributes.Single(a => a.AttributeType.FullName == typeof(SerializableAttribute).FullName).Region; var method = MetadataUtils.CreateTypeCheckMethod(Saltarelle.Compiler.Utils.SelfParameterize(c.CSharpTypeDefinition), _compilation); var errors = new List <string>(); var tokens = InlineCodeMethodCompiler.Tokenize(method, typeCheckCode, errors.Add); if (errors.Count == 0) { var context = new DefaultRuntimeContext(c.CSharpTypeDefinition, _metadataImporter, _errorReporter, _namer); var result = InlineCodeMethodCompiler.CompileInlineCodeMethodInvocation(method, tokens, JsExpression.Identifier("obj"), new JsExpression[0], n => { var type = ReflectionHelper.ParseReflectionName(n).Resolve(_compilation); if (type.Kind == TypeKind.Unknown) { errors.Add("Unknown type '" + n + "' specified in inline implementation"); return(JsExpression.Null); } return(_runtimeLibrary.InstantiateType(type, context)); }, t => _runtimeLibrary.InstantiateTypeForUseAsTypeArgumentInInlineCode(t, context), errors.Add); stmts.Add(new JsExpressionStatement( JsExpression.Assign( JsExpression.Member(typeRef, "isInstanceOfType"), JsExpression.FunctionDefinition(new[] { "obj" }, new JsReturnStatement(result))))); foreach (var e in errors) { _errorReporter.Message(Messages._7157, c.CSharpTypeDefinition.FullName, e); } } _errorReporter.Region = oldReg; } } if (MetadataUtils.IsJsGeneric(c.CSharpTypeDefinition, _metadataImporter)) { var args = new List <JsExpression> { typeRef, new JsTypeReferenceExpression(c.CSharpTypeDefinition), JsExpression.ArrayLiteral(c.CSharpTypeDefinition.TypeParameters.Select(tp => JsExpression.Identifier(_namer.GetTypeParameterName(tp)))) }; if (c.CSharpTypeDefinition.Kind == TypeKind.Class) { args.Add(JsExpression.FunctionDefinition(new string[0], new JsReturnStatement(GetBaseClass(c.CSharpTypeDefinition) ?? JsExpression.Null))); } args.Add(JsExpression.FunctionDefinition(new string[0], new JsReturnStatement(JsExpression.ArrayLiteral(GetImplementedInterfaces(c.CSharpTypeDefinition))))); var metadata = GetMetadataDescriptor(c.CSharpTypeDefinition, true); if (metadata != null) { args.Add(metadata); } stmts.Add(new JsExpressionStatement(JsExpression.Invocation(JsExpression.Member(_systemScript, c.CSharpTypeDefinition.Kind == TypeKind.Class ? RegisterGenericClassInstance : RegisterGenericInterfaceInstance), args))); } }
public virtual JsExpression VisitObjectLiteralExpression(JsObjectLiteralExpression expression, TData data) { var values = VisitObjectLiteralProperties(expression.Values, data); return(ReferenceEquals(values, expression.Values) ? expression : JsExpression.ObjectLiteral(values)); }
private static JsExpression ConstructConstructorInfo(IMethod constructor, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, Func <IType, JsExpression> instantiateType, bool includeDeclaringType) { var properties = GetCommonMemberInfoProperties(constructor, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType); var sem = metadataImporter.GetConstructorSemantics(constructor); if (sem.Type == ConstructorScriptSemantics.ImplType.NotUsableFromScript) { errorReporter.Message(Messages._7200, constructor.FullName); return(JsExpression.Null); } properties.Add(new JsObjectLiteralProperty("type", JsExpression.Number((int)MemberTypes.Constructor))); properties.Add(new JsObjectLiteralProperty("params", JsExpression.ArrayLiteral(constructor.Parameters.Select(p => instantiateType(p.Type))))); if (sem.Type == ConstructorScriptSemantics.ImplType.NamedConstructor || sem.Type == ConstructorScriptSemantics.ImplType.StaticMethod) { properties.Add(new JsObjectLiteralProperty("sname", JsExpression.String(sem.Name))); } if (sem.Type == ConstructorScriptSemantics.ImplType.StaticMethod) { properties.Add(new JsObjectLiteralProperty("sm", JsExpression.True)); } if ((sem.Type == ConstructorScriptSemantics.ImplType.UnnamedConstructor || sem.Type == ConstructorScriptSemantics.ImplType.NamedConstructor || sem.Type == ConstructorScriptSemantics.ImplType.StaticMethod) && sem.ExpandParams) { properties.Add(new JsObjectLiteralProperty("exp", JsExpression.True)); } if (sem.Type == ConstructorScriptSemantics.ImplType.Json || sem.Type == ConstructorScriptSemantics.ImplType.InlineCode) { var usedNames = new HashSet <string>(); var parameters = new List <IVariable>(); var variables = new Dictionary <IVariable, VariableData>(); IList <ResolveResult> constructorParameters = null; IList <ResolveResult> initializerStatements = null; if (sem.Type == ConstructorScriptSemantics.ImplType.Json && constructor.DeclaringType.Kind == TypeKind.Anonymous) { initializerStatements = new List <ResolveResult>(); foreach (var p in constructor.DeclaringType.GetProperties()) { string paramName = MakeCamelCase(p.Name); string name = namer.GetVariableName(paramName, usedNames); usedNames.Add(name); var variable = new SimpleVariable(p.ReturnType, paramName, DomRegion.Empty); parameters.Add(variable); variables.Add(variable, new VariableData(name, null, false)); initializerStatements.Add(new OperatorResolveResult(p.ReturnType, ExpressionType.Assign, new MemberResolveResult(new InitializedObjectResolveResult(constructor.DeclaringType), p), new LocalResolveResult(variable))); } } else { constructorParameters = new List <ResolveResult>(); foreach (var p in constructor.Parameters) { string name = namer.GetVariableName(p.Name, usedNames); usedNames.Add(name); var variable = new SimpleVariable(p.Type, p.Name, DomRegion.Empty); parameters.Add(variable); variables.Add(variable, new VariableData(name, null, false)); constructorParameters.Add(new LocalResolveResult(variable)); } } var compileResult = CompileConstructorInvocation(constructor, initializerStatements, constructor.DeclaringTypeDefinition, constructor, constructorParameters, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, variables, usedNames); var definition = JsExpression.FunctionDefinition(parameters.Select(p => variables[p].Name), JsStatement.Block(compileResult.AdditionalStatements.Concat(new[] { JsStatement.Return(compileResult.Expression) }))); properties.Add(new JsObjectLiteralProperty("def", definition)); } return(JsExpression.ObjectLiteral(properties)); }
private IEnumerable <JsStatement> CreateNamespaces(JsExpression root, IEnumerable <string> requiredNamespaces) { return(requiredNamespaces.SelectMany(EntireNamespaceHierarchy) .Distinct() .OrderBy(ns => ns) .Select(ns => { var access = MakeNestedMemberAccess(ns, root); return (JsStatement)JsExpression.Assign(access, JsExpression.LogicalOr(access, JsExpression.ObjectLiteral())); })); }
private void AddClassMembers(JsClass c, JsExpression typeRef, ICompilation compilation, List <JsStatement> stmts) { ICollection <JsMethod> instanceMethods; if (_metadataImporter.IsTestFixture(c.CSharpTypeDefinition)) { var tests = new List <Tuple <string, string, bool, int?, JsFunctionDefinitionExpression> >(); var instanceMethodList = new List <JsMethod>(); foreach (var m in c.InstanceMethods) { var td = (m.CSharpMember is IMethod ? _metadataImporter.GetTestData((IMethod)m.CSharpMember) : null); if (td != null) { tests.Add(Tuple.Create(td.Description, td.Category, td.IsAsync, td.ExpectedAssertionCount, m.Definition)); } else { instanceMethodList.Add(m); } } var testInvocations = new List <JsExpression>(); foreach (var category in tests.GroupBy(t => t.Item2).Select(g => new { Category = g.Key, Tests = g.Select(x => new { Description = x.Item1, IsAsync = x.Item3, ExpectedAssertionCount = x.Item4, Function = x.Item5 }) }).OrderBy(x => x.Category)) { if (category.Category != null) { testInvocations.Add(JsExpression.Invocation(JsExpression.Identifier("module"), JsExpression.String(category.Category))); } testInvocations.AddRange(category.Tests.Select(t => JsExpression.Invocation(JsExpression.Identifier(t.IsAsync ? "asyncTest" : "test"), t.ExpectedAssertionCount != null ? new JsExpression[] { JsExpression.String(t.Description), JsExpression.Number(t.ExpectedAssertionCount.Value), _runtimeLibrary.Bind(t.Function, JsExpression.This) } : new JsExpression[] { JsExpression.String(t.Description), _runtimeLibrary.Bind(t.Function, JsExpression.This) }))); } instanceMethodList.Add(new JsMethod(null, "runTests", null, JsExpression.FunctionDefinition(new string[0], new JsBlockStatement(testInvocations.Select(t => new JsExpressionStatement(t)))))); instanceMethods = instanceMethodList; } else { instanceMethods = c.InstanceMethods; } if (instanceMethods.Count > 0) { stmts.Add(new JsExpressionStatement(JsExpression.Assign(JsExpression.MemberAccess(typeRef, Prototype), JsExpression.ObjectLiteral(instanceMethods.Select(m => new JsObjectLiteralProperty(m.Name, m.Definition != null ? RewriteMethod(m) : JsExpression.Null)))))); } if (c.NamedConstructors.Count > 0) { stmts.AddRange(c.NamedConstructors.Select(m => new JsExpressionStatement(JsExpression.Assign(JsExpression.MemberAccess(typeRef, m.Name), m.Definition)))); stmts.Add(new JsExpressionStatement(c.NamedConstructors.Reverse().Aggregate((JsExpression)JsExpression.MemberAccess(typeRef, Prototype), (right, ctor) => JsExpression.Assign(JsExpression.MemberAccess(JsExpression.MemberAccess(typeRef, ctor.Name), Prototype), right)))); // This generates a statement like {C}.ctor1.prototype = {C}.ctor2.prototype = {C}.prototoype } var defaultConstructor = c.CSharpTypeDefinition.GetConstructors().SingleOrDefault(x => x.Parameters.Count == 0 && x.IsPublic); if (defaultConstructor != null) { JsExpression createInstance = CreateDefaultConstructorInvocation(defaultConstructor, typeRef); if (createInstance != null) { stmts.Add(new JsExpressionStatement( JsExpression.Assign( JsExpression.MemberAccess(typeRef, "createInstance"), JsExpression.FunctionDefinition(new string[0], new JsReturnStatement(createInstance))))); } } stmts.AddRange(c.StaticMethods.Select(m => new JsExpressionStatement(JsExpression.Assign(JsExpression.MemberAccess(typeRef, m.Name), RewriteMethod(m))))); if (c.TypeArgumentNames.Count > 0) { if (c.ClassType == JsClass.ClassTypeEnum.Interface) { stmts.Add(new JsExpressionStatement(JsExpression.Invocation(JsExpression.MemberAccess(typeRef, RegisterGenericInterfaceInstance), typeRef, new JsTypeReferenceExpression(compilation.MainAssembly, c.Name), JsExpression.ArrayLiteral(c.TypeArgumentNames.Select(JsExpression.Identifier)), JsExpression.FunctionDefinition(new string[0], new JsReturnStatement(JsExpression.ArrayLiteral(c.ImplementedInterfaces)))))); } else { stmts.Add(new JsExpressionStatement(JsExpression.Invocation(JsExpression.MemberAccess(typeRef, RegisterGenericClassInstance), typeRef, new JsTypeReferenceExpression(compilation.MainAssembly, c.Name), JsExpression.ArrayLiteral(c.TypeArgumentNames.Select(JsExpression.Identifier)), JsExpression.FunctionDefinition(new string[0], new JsReturnStatement(c.BaseClass)), JsExpression.FunctionDefinition(new string[0], new JsReturnStatement(JsExpression.ArrayLiteral(c.ImplementedInterfaces)))))); } } }
public IList <JsStatement> Process(IEnumerable <JsType> types, ICompilation compilation, IMethod entryPoint) { var result = new List <JsStatement>(); var orderedTypes = OrderByNamespace(types, t => _metadataImporter.GetTypeSemantics(t.CSharpTypeDefinition).Name).ToList(); foreach (var t in orderedTypes) { try { string name = _metadataImporter.GetTypeSemantics(t.CSharpTypeDefinition).Name; bool isGlobal = string.IsNullOrEmpty(name); bool isMixin = _metadataImporter.IsMixin(t.CSharpTypeDefinition); result.Add(new JsComment("//////////////////////////////////////////////////////////////////////////////" + Environment.NewLine + " " + t.CSharpTypeDefinition.FullName)); var typeRef = JsExpression.Identifier(_namer.GetTypeVariableName(name)); if (t is JsClass) { var c = (JsClass)t; if (isGlobal) { result.AddRange(c.StaticMethods.Select(m => new JsExpressionStatement(JsExpression.Binary(ExpressionNodeType.Assign, JsExpression.Member(GetRoot(t.CSharpTypeDefinition, exportNonPublic: true), m.Name), m.Definition)))); } else if (isMixin) { result.AddRange(c.StaticMethods.Select(m => new JsExpressionStatement(JsExpression.Assign(MakeNestedMemberAccess(name + "." + m.Name), m.Definition)))); } else if (_metadataImporter.IsResources(t.CSharpTypeDefinition)) { result.Add(GenerateResourcesClass(c)); } else { var unnamedCtor = c.UnnamedConstructor ?? JsExpression.FunctionDefinition(new string[0], JsBlockStatement.EmptyStatement); if (c.TypeArgumentNames.Count == 0) { result.Add(new JsVariableDeclarationStatement(typeRef.Name, unnamedCtor)); AddClassMembers(c, typeRef, compilation, result); } else { var stmts = new List <JsStatement> { new JsVariableDeclarationStatement(InstantiatedGenericTypeVariableName, unnamedCtor) }; AddClassMembers(c, JsExpression.Identifier(InstantiatedGenericTypeVariableName), compilation, stmts); stmts.AddRange(c.StaticInitStatements); stmts.Add(new JsReturnStatement(JsExpression.Identifier(InstantiatedGenericTypeVariableName))); result.Add(new JsVariableDeclarationStatement(typeRef.Name, JsExpression.FunctionDefinition(c.TypeArgumentNames, new JsBlockStatement(stmts)))); result.Add(new JsExpressionStatement(JsExpression.Invocation(JsExpression.Member(_systemType, c.ClassType == JsClass.ClassTypeEnum.Interface ? RegisterGenericInterface : RegisterGenericClass), GetRoot(t.CSharpTypeDefinition), JsExpression.String(name), typeRef, JsExpression.Number(c.TypeArgumentNames.Count)))); } } } else if (t is JsEnum) { var e = (JsEnum)t; bool flags = GetAttributePositionalArgs(t.CSharpTypeDefinition, FlagsAttribute, "System") != null; result.Add(new JsVariableDeclarationStatement(typeRef.Name, JsExpression.FunctionDefinition(new string[0], JsBlockStatement.EmptyStatement))); result.Add(new JsExpressionStatement(JsExpression.Assign(JsExpression.Member(typeRef, Prototype), JsExpression.ObjectLiteral(e.Values.Select(v => new JsObjectLiteralProperty(v.Name, (_metadataImporter.IsNamedValues(t.CSharpTypeDefinition) ? JsExpression.String(v.Name) : JsExpression.Number(v.Value)))))))); result.Add(new JsExpressionStatement(JsExpression.Invocation(JsExpression.Member(_systemType, RegisterEnum), GetRoot(t.CSharpTypeDefinition), JsExpression.String(name), typeRef, JsExpression.Boolean(flags)))); } } catch (Exception ex) { _errorReporter.Region = t.CSharpTypeDefinition.Region; _errorReporter.InternalError(ex, "Error formatting type " + t.CSharpTypeDefinition.FullName); } } var typesToRegister = orderedTypes.OfType <JsClass>() .Where(c => c.TypeArgumentNames.Count == 0 && !string.IsNullOrEmpty(_metadataImporter.GetTypeSemantics(c.CSharpTypeDefinition).Name) && (!_metadataImporter.IsResources(c.CSharpTypeDefinition) || Utils.IsPublic(c.CSharpTypeDefinition)) && // Resources classes are only exported if they are public. !_metadataImporter.IsMixin(c.CSharpTypeDefinition)) .ToList(); result.AddRange(TopologicalSortTypesByInheritance(typesToRegister) .Select(c => { try { string name = _metadataImporter.GetTypeSemantics(c.CSharpTypeDefinition).Name; if (_metadataImporter.IsResources(c.CSharpTypeDefinition)) { return(JsExpression.Invocation(JsExpression.Member(_systemType, RegisterType), GetRoot(c.CSharpTypeDefinition), JsExpression.String(name), JsExpression.Identifier(_namer.GetTypeVariableName(name)))); } if (c.ClassType == JsClass.ClassTypeEnum.Interface) { return(JsExpression.Invocation(JsExpression.Member(_systemType, RegisterInterface), GetRoot(c.CSharpTypeDefinition), JsExpression.String(name), JsExpression.Identifier(_namer.GetTypeVariableName(name)), JsExpression.ArrayLiteral(c.ImplementedInterfaces))); } else { return(CreateRegisterClassCall(GetRoot(c.CSharpTypeDefinition), name, JsExpression.Identifier(_namer.GetTypeVariableName(name)), c.BaseClass, c.ImplementedInterfaces)); } } catch (Exception ex) { _errorReporter.Region = c.CSharpTypeDefinition.Region; _errorReporter.InternalError(ex, "Error formatting type " + c.CSharpTypeDefinition.FullName); return(JsExpression.Number(0)); } }) .Select(expr => new JsExpressionStatement(expr))); result.AddRange(orderedTypes.OfType <JsClass>().Where(c => c.TypeArgumentNames.Count == 0 && !_metadataImporter.IsResources(c.CSharpTypeDefinition)).SelectMany(t => t.StaticInitStatements)); if (entryPoint != null) { if (entryPoint.Parameters.Count > 0) { _errorReporter.Region = entryPoint.Region; _errorReporter.Message(7800, entryPoint.FullName); } else { var sem = _metadataImporter.GetMethodSemantics(entryPoint); if (sem.Type != MethodScriptSemantics.ImplType.NormalMethod) { _errorReporter.Region = entryPoint.Region; _errorReporter.Message(7801, entryPoint.FullName); } else { result.Add(new JsExpressionStatement(JsExpression.Invocation(JsExpression.Member(new JsTypeReferenceExpression(entryPoint.DeclaringTypeDefinition), sem.Name)))); } } } return(result); }
public void ObjectLiteralWithInvalidIdentifierPropertyWorks() { AssertCorrect(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("a\\b", JsExpression.Number(1))), "{ 'a\\\\b': 1 }"); }
public JsFunctionDefinitionExpression CompileConstructor(ConstructorDeclaration ctor, IMethod constructor, List <JsStatement> instanceInitStatements, ConstructorScriptSemantics impl) { var region = _errorReporter.Region = ctor != null?ctor.GetRegion() : constructor.DeclaringTypeDefinition.Region; try { CreateCompilationContext(ctor, constructor, (impl.Type == ConstructorScriptSemantics.ImplType.StaticMethod ? _namer.ThisAlias : null)); IList <JsStatement> body = new List <JsStatement>(); body.AddRange(FixByRefParameters(constructor.Parameters, variables)); var systemObject = _compilation.FindType(KnownTypeCode.Object); if (impl.Type == ConstructorScriptSemantics.ImplType.StaticMethod) { if (ctor != null && !ctor.Initializer.IsNull) { body.AddRange(_statementCompiler.CompileConstructorInitializer(ctor.Initializer, true)); } else if (!constructor.DeclaringType.DirectBaseTypes.Any(t => t.Equals(systemObject))) { body.AddRange(_statementCompiler.CompileImplicitBaseConstructorCall(constructor.DeclaringTypeDefinition, true)); } else { body.Add(new JsVariableDeclarationStatement(_namer.ThisAlias, JsExpression.ObjectLiteral())); } } if (ctor == null || ctor.Initializer.IsNull || ctor.Initializer.ConstructorInitializerType != ConstructorInitializerType.This) { if (impl.Type == ConstructorScriptSemantics.ImplType.StaticMethod) { // The compiler one step up has created the statements as "this.a = b;", but we need to replace that with "$this.a = b;" (or whatever name the this alias has). var replacer = new ThisReplacer(JsExpression.Identifier(_namer.ThisAlias)); instanceInitStatements = instanceInitStatements.Select(s => replacer.VisitStatement(s, null)).ToList(); } body.AddRange(instanceInitStatements); // Don't initialize fields when we are chaining, but do it when we 1) compile the default constructor, 2) don't have an initializer, or 3) when the initializer is not this(...). } if (impl.Type != ConstructorScriptSemantics.ImplType.StaticMethod) { if (ctor != null && !ctor.Initializer.IsNull) { body.AddRange(_statementCompiler.CompileConstructorInitializer(ctor.Initializer, false)); } else if (!constructor.DeclaringType.DirectBaseTypes.Any(t => t.Equals(systemObject))) { body.AddRange(_statementCompiler.CompileImplicitBaseConstructorCall(constructor.DeclaringTypeDefinition, false)); } } if (ctor != null) { body.AddRange(_statementCompiler.Compile(ctor.Body).Statements); } if (impl.Type == ConstructorScriptSemantics.ImplType.StaticMethod) { if (body.Count == 0 || !(body[body.Count - 1] is JsReturnStatement)) { body.Add(new JsReturnStatement()); } body = StaticMethodConstructorReturnPatcher.Process(body, _namer.ThisAlias).AsReadOnly(); } var compiled = JsExpression.FunctionDefinition(constructor.Parameters.Select(p => variables[p].Name), new JsBlockStatement(body)); return(_statementCompiler.StateMachineRewriteNormalMethod(compiled)); } catch (Exception ex) { _errorReporter.Region = region; _errorReporter.InternalError(ex); return(JsExpression.FunctionDefinition(new string[0], JsBlockStatement.EmptyStatement)); } }
public static List <JsStatement> PrepareParameters(IList <IParameter> parameters, IDictionary <IVariable, VariableData> variables, bool expandParams, bool staticMethodWithThisAsFirstArgument) { List <JsStatement> result = null; if (expandParams && parameters.Count > 0) { result = result ?? new List <JsStatement>(); result.Add(JsStatement.Var(variables[parameters[parameters.Count - 1]].Name, JsExpression.Invocation(JsExpression.Member(JsExpression.Member(JsExpression.Member(JsExpression.Identifier("Array"), "prototype"), "slice"), "call"), JsExpression.Identifier("arguments"), JsExpression.Number(parameters.Count - 1 + (staticMethodWithThisAsFirstArgument ? 1 : 0))))); } foreach (var p in parameters) { if (!p.IsOut && !p.IsRef && variables[p].UseByRefSemantics) { result = result ?? new List <JsStatement>(); result.Add(JsExpression.Assign(JsExpression.Identifier(variables[p].Name), JsExpression.ObjectLiteral(new JsObjectLiteralProperty("$", JsExpression.Identifier(variables[p].Name))))); } } return(result ?? new List <JsStatement>()); }
public void ObjectLiteralWithNumericPropertyWorks() { AssertCorrect(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("1", JsExpression.Number(2))), "{ '1': 2 }"); }
private JsStatement GenerateResourcesClass(JsClass c) { var fields = c.StaticInitStatements .OfType <JsExpressionStatement>() .Select(s => s.Expression) .OfType <JsBinaryExpression>() .Where(expr => expr.NodeType == ExpressionNodeType.Assign && expr.Left is JsMemberAccessExpression) .Select(expr => new { Name = ((JsMemberAccessExpression)expr.Left).Member, Value = expr.Right }); return(new JsExpressionStatement(JsExpression.Assign(new JsTypeReferenceExpression(c.CSharpTypeDefinition.ParentAssembly, c.Name), JsExpression.ObjectLiteral(fields.Select(f => new JsObjectLiteralProperty(f.Name, f.Value)))))); }
public IList <JsStatement> Rewrite(IEnumerable <JsType> types, ICompilation compilation) { var netSystemType = compilation.FindType(KnownTypeCode.Type).GetDefinition(); var systemType = new JsTypeReferenceExpression(netSystemType.ParentAssembly, _metadataImporter.GetTypeSemantics(netSystemType).Name); var result = new List <JsStatement>(); var orderedTypes = OrderByNamespace(types, t => t.Name).ToList(); string currentNs = ""; foreach (var t in orderedTypes) { try { var globalMethodsPrefix = _metadataImporter.GetGlobalMethodsPrefix(t.CSharpTypeDefinition); string ns = GetNamespace(t.Name); if (ns != currentNs && globalMethodsPrefix == null) { result.Add(new JsExpressionStatement(JsExpression.Invocation(JsExpression.MemberAccess(systemType, RegisterNamespace), JsExpression.String(ns)))); currentNs = ns; } result.Add(new JsComment("//////////////////////////////////////////////////////////////////////////////" + Environment.NewLine + " " + t.CSharpTypeDefinition.FullName)); var typeRef = new JsTypeReferenceExpression(compilation.MainAssembly, t.Name); if (t is JsClass) { var c = (JsClass)t; if (globalMethodsPrefix != null) { if (globalMethodsPrefix == "") { result.AddRange(c.StaticMethods.Select(m => new JsExpressionStatement(JsExpression.Binary(ExpressionNodeType.Assign, JsExpression.MemberAccess(JsExpression.Identifier("window"), m.Name), m.Definition)))); } else { result.AddRange(c.StaticMethods.Select(m => new JsExpressionStatement(JsExpression.Assign(MakeNestedMemberAccess(globalMethodsPrefix + "." + m.Name), m.Definition)))); } } else if (_metadataImporter.IsResources(t.CSharpTypeDefinition)) { result.Add(GenerateResourcesClass(c)); } else { var unnamedCtor = c.UnnamedConstructor ?? JsExpression.FunctionDefinition(new string[0], JsBlockStatement.EmptyStatement); if (c.TypeArgumentNames.Count == 0) { result.Add(new JsExpressionStatement(JsExpression.Assign(typeRef, unnamedCtor))); AddClassMembers(c, typeRef, compilation, result); } else { var stmts = new List <JsStatement> { new JsVariableDeclarationStatement(InstantiatedGenericTypeVariableName, unnamedCtor) }; AddClassMembers(c, JsExpression.Identifier(InstantiatedGenericTypeVariableName), compilation, stmts); stmts.AddRange(c.StaticInitStatements); stmts.Add(new JsReturnStatement(JsExpression.Identifier(InstantiatedGenericTypeVariableName))); result.Add(new JsExpressionStatement(JsExpression.Assign(typeRef, JsExpression.FunctionDefinition(c.TypeArgumentNames, new JsBlockStatement(stmts))))); result.Add(new JsExpressionStatement(JsExpression.Invocation(JsExpression.MemberAccess(typeRef, c.ClassType == JsClass.ClassTypeEnum.Interface ? RegisterGenericInterface : RegisterGenericClass), JsExpression.String(c.Name), JsExpression.Number(c.TypeArgumentNames.Count)))); } } } else if (t is JsEnum) { var e = (JsEnum)t; bool flags = GetAttributePositionalArgs(t.CSharpTypeDefinition, FlagsAttribute, "System") != null; result.Add(new JsExpressionStatement(JsExpression.Assign(typeRef, JsExpression.FunctionDefinition(new string[0], JsBlockStatement.EmptyStatement)))); result.Add(new JsExpressionStatement(JsExpression.Assign(JsExpression.MemberAccess(typeRef, Prototype), JsExpression.ObjectLiteral(e.Values.Select(v => new JsObjectLiteralProperty(v.Name, (_metadataImporter.IsNamedValues(t.CSharpTypeDefinition) ? JsExpression.String(v.Name) : JsExpression.Number(v.Value)))))))); result.Add(new JsExpressionStatement(JsExpression.Invocation(JsExpression.MemberAccess(typeRef, RegisterEnum), JsExpression.String(t.Name), JsExpression.Boolean(flags)))); } } catch (Exception ex) { _errorReporter.Region = t.CSharpTypeDefinition.Region; _errorReporter.InternalError(ex, "Error formatting type " + t.CSharpTypeDefinition.FullName); } } var typesToRegister = orderedTypes.OfType <JsClass>() .Where(c => c.TypeArgumentNames.Count == 0 && _metadataImporter.GetGlobalMethodsPrefix(c.CSharpTypeDefinition) == null && !_metadataImporter.IsResources(c.CSharpTypeDefinition)) .ToList(); result.AddRange(TopologicalSortTypesByInheritance(typesToRegister) .Select(c => { try { var typeRef = new JsTypeReferenceExpression(compilation.MainAssembly, c.Name); if (c.ClassType == JsClass.ClassTypeEnum.Interface) { return(JsExpression.Invocation(JsExpression.MemberAccess(typeRef, RegisterInterface), JsExpression.String(c.Name), JsExpression.ArrayLiteral(c.ImplementedInterfaces))); } else { return(CreateRegisterClassCall(JsExpression.String(c.Name), c.BaseClass, c.ImplementedInterfaces, typeRef)); } } catch (Exception ex) { _errorReporter.Region = c.CSharpTypeDefinition.Region; _errorReporter.InternalError(ex, "Error formatting type " + c.CSharpTypeDefinition.FullName); return(JsExpression.Number(0)); } }) .Select(expr => new JsExpressionStatement(expr))); result.AddRange(orderedTypes.OfType <JsClass>().Where(c => c.TypeArgumentNames.Count == 0 && !_metadataImporter.IsResources(c.CSharpTypeDefinition)).SelectMany(t => t.StaticInitStatements)); return(result); }
public void CommaExpressionIsParenthesizedInsideObjectLiteral() { AssertCorrect(JsExpression.ObjectLiteral(new JsObjectLiteralProperty("x", JsExpression.Comma(JsExpression.Number(1), JsExpression.Number(2))), new JsObjectLiteralProperty("y", JsExpression.Number(3))), "{ x: (1, 2), y: 3 }"); }
private static JsExpression ConstructMemberInfo(IMember m, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, Func <IType, JsExpression> instantiateType, bool includeDeclaringType, MethodScriptSemantics semanticsIfAccessor) { if (m is IMethod && ((IMethod)m).IsConstructor) { return(ConstructConstructorInfo((IMethod)m, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType)); } var properties = GetCommonMemberInfoProperties(m, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType); if (m.IsStatic) { properties.Add(new JsObjectLiteralProperty("isStatic", JsExpression.True)); } if (m is IMethod) { var method = (IMethod)m; var sem = semanticsIfAccessor ?? metadataImporter.GetMethodSemantics(method); if (sem.Type != MethodScriptSemantics.ImplType.NormalMethod && sem.Type != MethodScriptSemantics.ImplType.StaticMethodWithThisAsFirstArgument && sem.Type != MethodScriptSemantics.ImplType.InlineCode) { errorReporter.Message(Messages._7201, m.FullName, "method"); return(JsExpression.Null); } if ((sem.Type == MethodScriptSemantics.ImplType.NormalMethod || sem.Type == MethodScriptSemantics.ImplType.StaticMethodWithThisAsFirstArgument) && sem.ExpandParams) { properties.Add(new JsObjectLiteralProperty("exp", JsExpression.True)); } properties.Add(new JsObjectLiteralProperty("type", JsExpression.Number((int)MemberTypes.Method))); if (sem.Type == MethodScriptSemantics.ImplType.InlineCode) { var usedNames = new HashSet <string>(); var parameters = new List <IVariable>(); var variables = new Dictionary <IVariable, VariableData>(); var arguments = new List <ResolveResult>(); foreach (var p in method.Parameters) { string name = namer.GetVariableName(p.Name, usedNames); usedNames.Add(name); var variable = new SimpleVariable(p.Type, p.Name, DomRegion.Empty); parameters.Add(variable); variables.Add(variable, new VariableData(name, null, false)); arguments.Add(new LocalResolveResult(variable)); } var tokens = InlineCodeMethodCompiler.Tokenize(method, sem.LiteralCode, _ => {}); var compileResult = Compile(CreateMethodInvocationResolveResult(method, method.IsStatic ? (ResolveResult) new TypeResolveResult(method.DeclaringType) : new ThisResolveResult(method.DeclaringType), arguments), method.DeclaringTypeDefinition, method, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, true, variables, usedNames); var definition = JsExpression.FunctionDefinition(parameters.Select(p => variables[p].Name), JsStatement.Block(compileResult.AdditionalStatements.Concat(new[] { JsStatement.Return(compileResult.Expression) }))); if (tokens.Any(t => t.Type == InlineCodeToken.TokenType.TypeParameter && t.OwnerType == SymbolKind.Method)) { definition = JsExpression.FunctionDefinition(method.TypeParameters.Select(namer.GetTypeParameterName), JsStatement.Return(definition)); properties.Add(new JsObjectLiteralProperty("tpcount", JsExpression.Number(method.TypeParameters.Count))); } properties.Add(new JsObjectLiteralProperty("def", definition)); } else { if (IsJsGeneric(method, metadataImporter)) { properties.Add(new JsObjectLiteralProperty("tpcount", JsExpression.Number(method.TypeParameters.Count))); } if (sem.Type == MethodScriptSemantics.ImplType.StaticMethodWithThisAsFirstArgument) { properties.Add(new JsObjectLiteralProperty("sm", JsExpression.True)); } properties.Add(new JsObjectLiteralProperty("sname", JsExpression.String(sem.Name))); } properties.Add(new JsObjectLiteralProperty("returnType", instantiateType(method.ReturnType))); properties.Add(new JsObjectLiteralProperty("params", JsExpression.ArrayLiteral(method.Parameters.Select(p => instantiateType(p.Type))))); } else if (m is IField) { var field = (IField)m; var sem = metadataImporter.GetFieldSemantics(field); if (sem.Type != FieldScriptSemantics.ImplType.Field) { errorReporter.Message(Messages._7201, m.FullName, "field"); return(JsExpression.Null); } properties.Add(new JsObjectLiteralProperty("type", JsExpression.Number((int)MemberTypes.Field))); properties.Add(new JsObjectLiteralProperty("returnType", instantiateType(field.ReturnType))); properties.Add(new JsObjectLiteralProperty("sname", JsExpression.String(sem.Name))); } else if (m is IProperty) { var prop = (IProperty)m; var sem = metadataImporter.GetPropertySemantics(prop); properties.Add(new JsObjectLiteralProperty("type", JsExpression.Number((int)MemberTypes.Property))); properties.Add(new JsObjectLiteralProperty("returnType", instantiateType(prop.ReturnType))); if (prop.Parameters.Count > 0) { properties.Add(new JsObjectLiteralProperty("params", JsExpression.ArrayLiteral(prop.Parameters.Select(p => instantiateType(p.Type))))); } switch (sem.Type) { case PropertyScriptSemantics.ImplType.GetAndSetMethods: if (sem.GetMethod != null && sem.GetMethod.Type != MethodScriptSemantics.ImplType.NormalMethod && sem.GetMethod.Type != MethodScriptSemantics.ImplType.StaticMethodWithThisAsFirstArgument && sem.GetMethod.Type != MethodScriptSemantics.ImplType.InlineCode) { errorReporter.Message(Messages._7202, m.FullName, "property", "getter"); return(JsExpression.Null); } if (sem.SetMethod != null && sem.SetMethod.Type != MethodScriptSemantics.ImplType.NormalMethod && sem.SetMethod.Type != MethodScriptSemantics.ImplType.StaticMethodWithThisAsFirstArgument && sem.SetMethod.Type != MethodScriptSemantics.ImplType.InlineCode) { errorReporter.Message(Messages._7202, m.FullName, "property", "setter"); return(JsExpression.Null); } if (sem.GetMethod != null) { properties.Add(new JsObjectLiteralProperty("getter", ConstructMemberInfo(prop.Getter, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType, sem.GetMethod))); } if (sem.SetMethod != null) { properties.Add(new JsObjectLiteralProperty("setter", ConstructMemberInfo(prop.Setter, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType, sem.SetMethod))); } break; case PropertyScriptSemantics.ImplType.Field: if (prop.CanGet) { properties.Add(new JsObjectLiteralProperty("getter", ConstructFieldPropertyAccessor(prop.Getter, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, sem.FieldName, instantiateType, isGetter: true, includeDeclaringType: includeDeclaringType))); } if (prop.CanSet) { properties.Add(new JsObjectLiteralProperty("setter", ConstructFieldPropertyAccessor(prop.Setter, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, sem.FieldName, instantiateType, isGetter: false, includeDeclaringType: includeDeclaringType))); } properties.Add(new JsObjectLiteralProperty("fname", JsExpression.String(sem.FieldName))); break; default: errorReporter.Message(Messages._7201, m.FullName, "property"); return(JsExpression.Null); } } else if (m is IEvent) { var evt = (IEvent)m; var sem = metadataImporter.GetEventSemantics(evt); if (sem.Type != EventScriptSemantics.ImplType.AddAndRemoveMethods) { errorReporter.Message(Messages._7201, m.FullName, "event"); return(JsExpression.Null); } if (sem.AddMethod.Type != MethodScriptSemantics.ImplType.NormalMethod && sem.AddMethod.Type != MethodScriptSemantics.ImplType.StaticMethodWithThisAsFirstArgument && sem.AddMethod.Type != MethodScriptSemantics.ImplType.InlineCode) { errorReporter.Message(Messages._7202, m.FullName, "event", "add accessor"); return(JsExpression.Null); } if (sem.RemoveMethod.Type != MethodScriptSemantics.ImplType.NormalMethod && sem.RemoveMethod.Type != MethodScriptSemantics.ImplType.StaticMethodWithThisAsFirstArgument && sem.RemoveMethod.Type != MethodScriptSemantics.ImplType.InlineCode) { errorReporter.Message(Messages._7202, m.FullName, "event", "remove accessor"); return(JsExpression.Null); } properties.Add(new JsObjectLiteralProperty("type", JsExpression.Number((int)MemberTypes.Event))); properties.Add(new JsObjectLiteralProperty("adder", ConstructMemberInfo(evt.AddAccessor, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType, sem.AddMethod))); properties.Add(new JsObjectLiteralProperty("remover", ConstructMemberInfo(evt.RemoveAccessor, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType, sem.RemoveMethod))); } else { throw new ArgumentException("Invalid member " + m); } return(JsExpression.ObjectLiteral(properties)); }
public static List <JsStatement> FixByRefParameters(IEnumerable <IParameter> parameters, IDictionary <IVariable, VariableData> variables) { List <JsStatement> result = null; foreach (var p in parameters) { if (!p.IsOut && !p.IsRef && variables[p].UseByRefSemantics) { result = result ?? new List <JsStatement>(); result.Add(new JsExpressionStatement(JsExpression.Assign(JsExpression.Identifier(variables[p].Name), JsExpression.ObjectLiteral(new JsObjectLiteralProperty("$", JsExpression.Identifier(variables[p].Name)))))); } } return(result ?? new List <JsStatement>()); }