protected void AssertCorrect(string csharp, string expected, INamingConventionResolver namingConvention = null, IRuntimeLibrary runtimeLibrary = null, bool addSkeleton = true, bool referenceSystemCore = false) { CompileMethod(csharp, namingConvention: namingConvention ?? new MockNamingConventionResolver { GetPropertySemantics = p => { if (p.DeclaringType.Kind == TypeKind.Anonymous || new Regex("^F[0-9]*$").IsMatch(p.Name) || (p.DeclaringType.FullName == "System.Array" && p.Name == "Length")) return PropertyScriptSemantics.Field("$" + p.Name); else return PropertyScriptSemantics.GetAndSetMethods(MethodScriptSemantics.NormalMethod("get_$" + p.Name), MethodScriptSemantics.NormalMethod("set_$" + p.Name)); }, GetMethodSemantics = m => MethodScriptSemantics.NormalMethod("$" + m.Name), GetEventSemantics = e => EventScriptSemantics.AddAndRemoveMethods(MethodScriptSemantics.NormalMethod("add_$" + e.Name), MethodScriptSemantics.NormalMethod("remove_$" + e.Name)), }, runtimeLibrary: runtimeLibrary, addSkeleton: addSkeleton, referenceSystemCore: referenceSystemCore); string actual = OutputFormatter.Format(CompiledMethod, true); int begin = actual.IndexOf("// BEGIN"); if (begin > -1) { while (begin < (actual.Length - 1) && actual[begin - 1] != '\n') begin++; actual = actual.Substring(begin); } int end = actual.IndexOf("// END"); if (end >= 0) { while (end >= 0 && actual[end] != '\n') end--; actual = actual.Substring(0, end + 1); } Assert.That(actual.Replace("\r\n", "\n"), Is.EqualTo(expected.Replace("\r\n", "\n"))); }
protected void AssertCorrect(string csharp, string expected, IMetadataImporter metadataImporter = null, IRuntimeLibrary runtimeLibrary = null, bool addSkeleton = true, IEnumerable<IAssemblyReference> references = null, string methodName = "M", bool allowUserDefinedStructs = false) { CompileMethod(csharp, metadataImporter: metadataImporter ?? new MockMetadataImporter { GetPropertySemantics = p => { if (p.DeclaringType.Kind == TypeKind.Anonymous || new Regex("^F[0-9]*$").IsMatch(p.Name) || (p.DeclaringType.FullName == "System.Array" && p.Name == "Length")) return PropertyScriptSemantics.Field("$" + p.Name); else return PropertyScriptSemantics.GetAndSetMethods(MethodScriptSemantics.NormalMethod("get_$" + p.Name), MethodScriptSemantics.NormalMethod("set_$" + p.Name)); }, GetMethodSemantics = m => MethodScriptSemantics.NormalMethod("$" + m.Name), GetEventSemantics = e => EventScriptSemantics.AddAndRemoveMethods(MethodScriptSemantics.NormalMethod("add_$" + e.Name), MethodScriptSemantics.NormalMethod("remove_$" + e.Name)), }, runtimeLibrary: runtimeLibrary, methodName: methodName, addSkeleton: addSkeleton, references: references, allowUserDefinedStructs: allowUserDefinedStructs); string actual = OutputFormatter.Format(CompiledMethod, true); int begin = actual.IndexOf("// BEGIN"); if (begin > -1) { while (begin < (actual.Length - 1) && actual[begin - 1] != '\n') begin++; actual = actual.Substring(begin); } int end = actual.IndexOf("// END"); if (end >= 0) { while (end >= 0 && actual[end] != '\n') end--; actual = actual.Substring(0, end + 1); } Assert.That(actual.Replace("\r\n", "\n"), Is.EqualTo(expected.Replace("\r\n", "\n")), "Expected:\n" + expected + "\n\nActual:\n" + actual); }
public ScriptSharpOOPEmulator(ICompilation compilation, IScriptSharpMetadataImporter metadataImporter, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter) { _metadataImporter = metadataImporter; _runtimeLibrary = runtimeLibrary; _errorReporter = errorReporter; _compilation = compilation; }
public Compiler(IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter) { _metadataImporter = metadataImporter; _namer = namer; _errorReporter = errorReporter; _runtimeLibrary = runtimeLibrary; }
public Compiler(IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, bool allowUserDefinedStructs) { _metadataImporter = metadataImporter; _namer = namer; _errorReporter = errorReporter; _runtimeLibrary = runtimeLibrary; _allowUserDefinedStructs = allowUserDefinedStructs; }
public MethodCompiler(IMetadataImporter metadataImporter, INamer namer, IErrorReporter errorReporter, ICompilation compilation, CSharpAstResolver resolver, IRuntimeLibrary runtimeLibrary) { _metadataImporter = metadataImporter; _namer = namer; _errorReporter = errorReporter; _compilation = compilation; _resolver = resolver; _runtimeLibrary = runtimeLibrary; }
public ScriptSharpOOPEmulator(ICompilation compilation, IScriptSharpMetadataImporter metadataImporter, IRuntimeLibrary runtimeLibrary, INamer namer, IErrorReporter errorReporter) { _metadataImporter = metadataImporter; _runtimeLibrary = runtimeLibrary; _namer = namer; _errorReporter = errorReporter; _compilation = compilation; _systemType = new JsTypeReferenceExpression(_compilation.FindType(KnownTypeCode.Type).GetDefinition()); }
public MethodCompiler(IMetadataImporter metadataImporter, INamer namer, IErrorReporter errorReporter, ICompilation compilation, CSharpAstResolver resolver, IRuntimeLibrary runtimeLibrary, ISet <string> definedSymbols) { _metadataImporter = metadataImporter; _namer = namer; _errorReporter = errorReporter; _compilation = compilation; _resolver = resolver; _runtimeLibrary = runtimeLibrary; _definedSymbols = definedSymbols; }
protected void Compile(string source, IMetadataImporter metadataImporter = null, IRuntimeLibrary runtimeLibrary = null, IErrorReporter errorReporter = null, bool useFirstConstructor = false) { Compile(new[] { source }, metadataImporter: metadataImporter, runtimeLibrary: runtimeLibrary, errorReporter: errorReporter, methodCompiled: (m, res, mc) => { if (m.IsConstructor && (m.Attributes.Any() || useFirstConstructor)) { Constructor = m; MethodCompiler = mc; CompiledConstructor = res; } }); Assert.That(Constructor, Is.Not.Null, "No constructors with attributes were compiled."); }
protected void CompileMethod(string source, IMetadataImporter metadataImporter = null, INamer namer = null, IRuntimeLibrary runtimeLibrary = null, IErrorReporter errorReporter = null, string methodName = "M", bool addSkeleton = true, IEnumerable<IAssemblyReference> references = null, bool allowUserDefinedStructs = false) { Compile(new[] { addSkeleton ? "using System; class C { " + source + "}" : source }, metadataImporter: metadataImporter, namer: namer, runtimeLibrary: runtimeLibrary, errorReporter: errorReporter, methodCompiled: (m, res, mc) => { if (m.Name == methodName) { Method = m; MethodCompiler = mc; CompiledMethod = res; } }, references: references, allowUserDefinedStructs: allowUserDefinedStructs); Assert.That(Method, Is.Not.Null, "Method " + methodName + " was not compiled"); }
protected void CompileMethod(string source, INamingConventionResolver namingConvention = null, IRuntimeLibrary runtimeLibrary = null, IErrorReporter errorReporter = null, string methodName = "M", bool addSkeleton = true, bool referenceSystemCore = false) { Compile(new[] { addSkeleton ? "using System; class C { " + source + "}" : source }, namingConvention, runtimeLibrary, errorReporter, (m, res, mc) => { if (m.Name == methodName) { Method = m; MethodCompiler = mc; CompiledMethod = res; } }, referenceSystemCore: referenceSystemCore); Assert.That(Method, Is.Not.Null, "Method " + methodName + " was not compiled"); }
public OOPEmulator(ICompilation compilation, IMetadataImporter metadataImporter, IRuntimeLibrary runtimeLibrary, INamer namer, IErrorReporter errorReporter) { _compilation = compilation; _systemScript = new JsTypeReferenceExpression(compilation.FindType(new FullTypeName("System.Script")).GetDefinition()); _systemObject = new JsTypeReferenceExpression(compilation.FindType(KnownTypeCode.Object).GetDefinition()); _metadataImporter = metadataImporter; _runtimeLibrary = runtimeLibrary; _namer = namer; _errorReporter = errorReporter; _defaultReflectionRuntimeContext = new ReflectionRuntimeContext(false, _systemObject, _namer); _genericSpecializationReflectionRuntimeContext = new ReflectionRuntimeContext(true, _systemObject, _namer); }
protected void Compile(IEnumerable<string> sources, IMetadataImporter metadataImporter = null, INamer namer = null, IRuntimeLibrary runtimeLibrary = null, IErrorReporter errorReporter = null, Action<IMethod, JsFunctionDefinitionExpression, MethodCompiler> methodCompiled = null, IList<string> defineConstants = null, IEnumerable<IAssemblyReference> references = null) { var sourceFiles = sources.Select((s, i) => new MockSourceFile("File" + i + ".cs", s)).ToList(); bool defaultErrorHandling = false; if (errorReporter == null) { defaultErrorHandling = true; errorReporter = new MockErrorReporter(true); } var compiler = new Saltarelle.Compiler.Compiler.Compiler(metadataImporter ?? new MockMetadataImporter(), namer ?? new MockNamer(), runtimeLibrary ?? new MockRuntimeLibrary(), errorReporter); if (methodCompiled != null) compiler.MethodCompiled += methodCompiled; var c = PreparedCompilation.CreateCompilation("x", sourceFiles, references ?? new[] { Common.Mscorlib }, defineConstants); CompiledTypes = compiler.Compile(c).AsReadOnly(); if (defaultErrorHandling) { ((MockErrorReporter)errorReporter).AllMessages.Should().BeEmpty("Compile should not generate errors"); } }
private void Prepare(string source, IRuntimeLibrary runtimeLibrary = null, bool expectErrors = false, bool MinimizeNames = false) { IProjectContent project = new CSharpProjectContent(); var parser = new CSharpParser(); using (var rdr = new StringReader(source)) { var pf = new CSharpUnresolvedFile() { FileName = "File.cs" }; var syntaxTree = parser.Parse(rdr, pf.FileName); syntaxTree.AcceptVisitor(new TypeSystemConvertVisitor(pf)); project = project.AddOrUpdateFiles(pf); } project = project.AddAssemblyReferences(new[] { Files.Mscorlib, Files.Web, Files.Knockout }); _compilation = project.CreateCompilation(); var options = new CompilerOptions { MinimizeScript = MinimizeNames }; _errorReporter = new MockErrorReporter(!expectErrors); var s = new AttributeStore(_compilation, _errorReporter); s.RunAttributeCode(); _metadata = new MetadataImporter(_errorReporter, _compilation, s, options); _metadata.Prepare(_compilation.GetAllTypeDefinitions()); _allErrors = _errorReporter.AllMessages.ToList().AsReadOnly(); if (expectErrors) { Assert.That(_allErrors, Is.Not.Empty, "Compile should have generated errors"); } else { Assert.That(_allErrors, Is.Empty, "Compile should not generate errors"); } var rtl = new RuntimeLibrary(_metadata, _errorReporter, _compilation, new Namer(), s); }
protected void Compile(IEnumerable<string> sources, INamingConventionResolver namingConvention = null, IRuntimeLibrary runtimeLibrary = null, IErrorReporter errorReporter = null, Action<IMethod, JsFunctionDefinitionExpression, MethodCompiler> methodCompiled = null, IList<string> defineConstants = null, bool allowUnsupportedConstructs = true, bool referenceSystemCore = false) { var sourceFiles = sources.Select((s, i) => new MockSourceFile("File" + i + ".cs", s)).ToList(); bool defaultErrorHandling = false; if (errorReporter == null) { defaultErrorHandling = true; errorReporter = new MockErrorReporter(true); } var compiler = new Saltarelle.Compiler.Compiler.Compiler(namingConvention ?? new MockNamingConventionResolver(), runtimeLibrary ?? new MockRuntimeLibrary(), errorReporter) { AllowUnsupportedConstructs = allowUnsupportedConstructs }; if (methodCompiled != null) compiler.MethodCompiled += methodCompiled; var references = referenceSystemCore ? new[] { Common.Mscorlib, Common.Linq } : new[] { Common.Mscorlib }; var c = compiler.CreateCompilation(sourceFiles, references, defineConstants); CompiledTypes = compiler.Compile(c).AsReadOnly(); if (defaultErrorHandling) { ((MockErrorReporter)errorReporter).AllMessagesText.Should().BeEmpty("Compile should not generate errors"); } }
internal StatementCompiler(IMetadataImporter metadataImporter, INamer namer, IErrorReporter errorReporter, ICompilation compilation, CSharpAstResolver resolver, IDictionary<IVariable, VariableData> variables, IDictionary<LambdaResolveResult, NestedFunctionData> nestedFunctions, IRuntimeLibrary runtimeLibrary, string thisAlias, ISet<string> usedVariableNames, NestedFunctionContext nestedFunctionContext, IMethod methodBeingCompiled, ITypeDefinition typeBeingCompiled, ExpressionCompiler expressionCompiler, SharedValue<int> nextLabelIndex, IVariable currentVariableForRethrow, IDictionary<object, string> currentGotoCaseMap) { _metadataImporter = metadataImporter; _namer = namer; _errorReporter = errorReporter; _compilation = compilation; _resolver = resolver; _variables = variables; _nestedFunctions = nestedFunctions; _runtimeLibrary = runtimeLibrary; _thisAlias = thisAlias; _usedVariableNames = usedVariableNames; _nestedFunctionContext = nestedFunctionContext; _methodBeingCompiled = methodBeingCompiled; _typeBeingCompiled = typeBeingCompiled; _currentVariableForRethrow = currentVariableForRethrow; _currentGotoCaseMap = currentGotoCaseMap; _nextLabelIndex = nextLabelIndex ?? new SharedValue<int>(1); _expressionCompiler = expressionCompiler ?? new ExpressionCompiler(compilation, metadataImporter, namer, runtimeLibrary, errorReporter, variables, nestedFunctions, v => CreateTemporaryVariable(v, _region), c => new StatementCompiler(_metadataImporter, _namer, _errorReporter, _compilation, _resolver, _variables, _nestedFunctions, _runtimeLibrary, thisAlias, _usedVariableNames, c, _methodBeingCompiled, _typeBeingCompiled), thisAlias, nestedFunctionContext, null, _methodBeingCompiled, _typeBeingCompiled); _result = new List<JsStatement>(); }
public StatementCompiler(IMetadataImporter metadataImporter, INamer namer, IErrorReporter errorReporter, ICompilation compilation, CSharpAstResolver resolver, IDictionary<IVariable, VariableData> variables, IDictionary<LambdaResolveResult, NestedFunctionData> nestedFunctions, IRuntimeLibrary runtimeLibrary, string thisAlias, ISet<string> usedVariableNames, NestedFunctionContext nestedFunctionContext, IMethod methodBeingCompiled, ITypeDefinition typeBeingCompiled) : this(metadataImporter, namer, errorReporter, compilation, resolver, variables, nestedFunctions, runtimeLibrary, thisAlias, usedVariableNames, nestedFunctionContext, methodBeingCompiled, typeBeingCompiled, null, null, null, null) { }
public static JsExpression MaybeCloneValueType(JsExpression input, ResolveResult csharpInput, IType type, IMetadataImporter metadataImporter, IRuntimeLibrary runtimeLibrary, IRuntimeContext runtimeContext, bool forceClone = false) { if (input is JsConstantExpression) return input; // Primarily the case of null for nullables. forceClone does not matter. if (!forceClone) { if (input is JsInvocationExpression) return input; // The clone was already performed when the callee returned var actualInput = csharpInput; var crr = actualInput as ConversionResolveResult; if (crr != null) { actualInput = crr.Input; } if (actualInput is InvocationResolveResult) { return input; } } type = NullableType.GetUnderlyingType(type); if (!IsMutableValueType(type, metadataImporter)) return input; return runtimeLibrary.CloneValueType(input, type, runtimeContext); }
public ScriptSharpOOPEmulator(IScriptSharpMetadataImporter metadataImporter, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter) { _metadataImporter = metadataImporter; _runtimeLibrary = runtimeLibrary; _errorReporter = errorReporter; }
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); }
protected void CompileMethod(string source, IMetadataImporter metadataImporter = null, INamer namer = null, IRuntimeLibrary runtimeLibrary = null, IErrorReporter errorReporter = null, string methodName = "M", bool addSkeleton = true, IEnumerable <IAssemblyReference> references = null) { Compile(new[] { addSkeleton ? "using System; class C { " + source + "}" : source }, metadataImporter: metadataImporter, namer: namer, runtimeLibrary: runtimeLibrary, errorReporter: errorReporter, methodCompiled: (m, res, mc) => { if (m.Name == methodName) { Method = m; MethodCompiler = mc; CompiledMethod = res; } }, references: references); Assert.That(Method, Is.Not.Null, "Method " + methodName + " was not compiled"); }
private static List <JsObjectLiteralProperty> GetCommonMemberInfoProperties(IMember m, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, Func <IType, JsExpression> instantiateType, bool includeDeclaringType) { var result = new List <JsObjectLiteralProperty>(); var attr = GetScriptableAttributes(m.Attributes, metadataImporter).ToList(); if (attr.Count > 0) { result.Add(new JsObjectLiteralProperty("attr", JsExpression.ArrayLiteral(attr.Select(a => ConstructAttribute(a, m.DeclaringTypeDefinition, compilation, metadataImporter, namer, runtimeLibrary, errorReporter))))); } if (includeDeclaringType) { result.Add(new JsObjectLiteralProperty("typeDef", instantiateType(m.DeclaringType))); } result.Add(new JsObjectLiteralProperty("name", JsExpression.String(m.Name))); return(result); }
public TestRewriter(IErrorReporter errorReporter, IRuntimeLibrary runtimeLibrary, IAttributeStore attributeStore) { _errorReporter = errorReporter; _runtimeLibrary = runtimeLibrary; _attributeStore = attributeStore; }
public TestRewriter(IErrorReporter errorReporter, IRuntimeLibrary runtimeLibrary) { _errorReporter = errorReporter; _runtimeLibrary = runtimeLibrary; }
public StatementCompiler(INamingConventionResolver namingConvention, IErrorReporter errorReporter, ICompilation compilation, CSharpAstResolver resolver, IDictionary<IVariable, VariableData> variables, IDictionary<LambdaResolveResult, NestedFunctionData> nestedFunctions, IRuntimeLibrary runtimeLibrary, string thisAlias, ISet<string> usedVariableNames, NestedFunctionContext nestedFunctionContext, IMethod methodBeingCompiled, ISet<string> definedSymbols) : this(namingConvention, errorReporter, compilation, resolver, variables, nestedFunctions, runtimeLibrary, thisAlias, usedVariableNames, nestedFunctionContext, methodBeingCompiled, definedSymbols, null, null, null, null) { }
private static ExpressionCompileResult Compile(ResolveResult rr, ITypeDefinition currentType, IMethod currentMethod, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, bool returnValueIsImportant, Dictionary <IVariable, VariableData> variables, ISet <string> usedVariableNames) { variables = variables ?? new Dictionary <IVariable, VariableData>(); usedVariableNames = usedVariableNames ?? new HashSet <string>(); return(new ExpressionCompiler(compilation, metadataImporter, namer, runtimeLibrary, errorReporter, variables, new Dictionary <LambdaResolveResult, NestedFunctionData>(), t => { string name = namer.GetVariableName(null, usedVariableNames); IVariable variable = new SimpleVariable(t, "temporary", DomRegion.Empty); variables[variable] = new VariableData(name, null, false); usedVariableNames.Add(name); return variable; }, _ => { throw new Exception("Cannot compile nested functions here"); }, null, new NestedFunctionContext(EmptyList <IVariable> .Instance), null, currentMethod, currentType ).Compile(rr, returnValueIsImportant)); }
public static JsExpression ConstructAttribute(IAttribute attr, ITypeDefinition currentType, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter) { errorReporter.Region = attr.Region; var initializerStatements = attr.NamedArguments.Select(a => new OperatorResolveResult(a.Key.ReturnType, ExpressionType.Assign, new MemberResolveResult(new InitializedObjectResolveResult(attr.AttributeType), a.Key), a.Value)).ToList <ResolveResult>(); var constructorResult = CompileConstructorInvocation(attr.Constructor, initializerStatements, currentType, null, attr.PositionalArguments, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, null, null); if (constructorResult.AdditionalStatements.Count > 0) { return(JsExpression.Invocation(JsExpression.FunctionDefinition(new string[0], JsStatement.Block(constructorResult.AdditionalStatements.Concat(new[] { JsStatement.Return(constructorResult.Expression) }))))); } else { return(constructorResult.Expression); } }
protected RuntimeLibraryDecoratorBase(IRuntimeLibrary prev) { _prev = prev; }
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 JsExpression MaybeCloneValueType(JsExpression input, ResolveResult csharpInput, IType type, IMetadataImporter metadataImporter, IRuntimeLibrary runtimeLibrary, IRuntimeContext runtimeContext, bool forceClone = false) { if (input is JsConstantExpression) { return(input); // Primarily the case of null for nullables. forceClone does not matter. } if (!forceClone) { if (input is JsInvocationExpression) { return(input); // The clone was already performed when the callee returned } var actualInput = csharpInput; var crr = actualInput as ConversionResolveResult; if (crr != null) { actualInput = crr.Input; } if (actualInput is InvocationResolveResult) { return(input); } } type = NullableType.GetUnderlyingType(type); if (!IsMutableValueType(type, metadataImporter)) { return(input); } return(runtimeLibrary.CloneValueType(input, type, runtimeContext)); }
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); }
public static JsExpression ConstructMemberInfo(IMember m, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, Func<IType, JsExpression> instantiateType, bool includeDeclaringType) { MethodScriptSemantics semanticsIfAccessor = null; if (m is IMethod && ((IMethod)m).IsAccessor) { var owner = ((IMethod)m).AccessorOwner; if (owner is IProperty) { var sem = metadataImporter.GetPropertySemantics((IProperty)owner); if (sem.Type == PropertyScriptSemantics.ImplType.GetAndSetMethods) { if (ReferenceEquals(m, ((IProperty)owner).Getter)) semanticsIfAccessor = sem.GetMethod; else if (ReferenceEquals(m, ((IProperty)owner).Setter)) semanticsIfAccessor = sem.SetMethod; else throw new ArgumentException("Invalid member " + m); } } else if (owner is IEvent) { var sem = metadataImporter.GetEventSemantics((IEvent)owner); if (sem.Type == EventScriptSemantics.ImplType.AddAndRemoveMethods) { if (ReferenceEquals(m, ((IEvent)owner).AddAccessor)) semanticsIfAccessor = sem.AddMethod; else if (ReferenceEquals(m, ((IEvent)owner).RemoveAccessor)) semanticsIfAccessor = sem.RemoveMethod; else throw new ArgumentException("Invalid member " + m); } } else throw new ArgumentException("Invalid owner " + owner); } return ConstructMemberInfo(m, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType, semanticsIfAccessor); }
protected void Compile(IEnumerable <string> sources, IMetadataImporter metadataImporter = null, INamer namer = null, IRuntimeLibrary runtimeLibrary = null, IErrorReporter errorReporter = null, Action <IMethod, JsFunctionDefinitionExpression, MethodCompiler> methodCompiled = null, IList <string> defineConstants = null, bool allowUserDefinedStructs = true, IEnumerable <IAssemblyReference> references = null) { var sourceFiles = sources.Select((s, i) => new MockSourceFile("File" + i + ".cs", s)).ToList(); bool defaultErrorHandling = false; if (errorReporter == null) { defaultErrorHandling = true; errorReporter = new MockErrorReporter(true); } var compiler = new Saltarelle.Compiler.Compiler.Compiler(metadataImporter ?? new MockMetadataImporter(), namer ?? new MockNamer(), runtimeLibrary ?? new MockRuntimeLibrary(), errorReporter); compiler.AllowUserDefinedStructs = allowUserDefinedStructs; if (methodCompiled != null) { compiler.MethodCompiled += methodCompiled; } var c = PreparedCompilation.CreateCompilation(sourceFiles, references ?? new[] { Common.Mscorlib }, defineConstants); CompiledTypes = compiler.Compile(c).AsReadOnly(); if (defaultErrorHandling) { ((MockErrorReporter)errorReporter).AllMessages.Should().BeEmpty("Compile should not generate errors"); } }
protected void Compile(string source, INamingConventionResolver namingConvention = null, IRuntimeLibrary runtimeLibrary = null, IErrorReporter errorReporter = null, bool useFirstConstructor = false) { Compile(new[] { source }, namingConvention, runtimeLibrary, errorReporter, (m, res, mc) => { if (m.IsConstructor && (m.Attributes.Any() || useFirstConstructor)) { Constructor = m; MethodCompiler = mc; CompiledConstructor = res; } }); Assert.That(Constructor, Is.Not.Null, "No constructors with attributes were compiled."); }
public Compiler(INamingConventionResolver namingConvention, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter) { _namingConvention = namingConvention; _errorReporter = errorReporter; _runtimeLibrary = runtimeLibrary; }
private void AssertCorrect(string csharp, string expected, IRuntimeLibrary runtimeLibrary = null, IMetadataImporter metadataImporter = null, string methodName = "M") { base.AssertCorrect("using System; using System.Linq.Expressions; using System.Collections.Generic; class C { " + csharp + "}", expected, references: _referencesLazy.Value, methodName: methodName, metadataImporter: metadataImporter, addSkeleton: false, runtimeLibrary: runtimeLibrary); }
private static ExpressionCompileResult Compile(ResolveResult rr, ITypeDefinition currentType, IMethod currentMethod, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, bool returnValueIsImportant, Dictionary<IVariable, VariableData> variables, ISet<string> usedVariableNames) { variables = variables ?? new Dictionary<IVariable, VariableData>(); usedVariableNames = usedVariableNames ?? new HashSet<string>(); return new ExpressionCompiler(compilation, metadataImporter, namer, runtimeLibrary, errorReporter, variables, new Dictionary<LambdaResolveResult, NestedFunctionData>(), t => { string name = namer.GetVariableName(null, usedVariableNames); IVariable variable = new SimpleVariable(t, "temporary", DomRegion.Empty); variables[variable] = new VariableData(name, null, false); usedVariableNames.Add(name); return variable; }, _ => { throw new Exception("Cannot compile nested functions here"); }, null, new NestedFunctionContext(EmptyList<IVariable>.Instance), null, currentMethod, currentType ).Compile(rr, returnValueIsImportant); }
public static ExpressionCompileResult CompileConstructorInvocation(IMethod constructor, IList<ResolveResult> initializerStatements, ITypeDefinition currentType, IMethod currentMethod, IList<ResolveResult> arguments, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, Dictionary<IVariable, VariableData> variables, ISet<string> usedVariableNames) { return Compile(new CSharpInvocationResolveResult(new TypeResolveResult(constructor.DeclaringType), constructor, arguments, initializerStatements: initializerStatements), currentType, currentMethod, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, true, variables, usedVariableNames); }
public static ExpressionCompileResult CompileConstructorInvocation(IMethod constructor, IList <ResolveResult> initializerStatements, ITypeDefinition currentType, IMethod currentMethod, IList <ResolveResult> arguments, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, Dictionary <IVariable, VariableData> variables, ISet <string> usedVariableNames) { return(Compile(new CSharpInvocationResolveResult(new TypeResolveResult(constructor.DeclaringType), constructor, arguments, initializerStatements: initializerStatements), currentType, currentMethod, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, true, variables, usedVariableNames)); }
public static JsExpression ConstructAttribute(IAttribute attr, ITypeDefinition currentType, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter) { errorReporter.Region = attr.Region; var initializerStatements = attr.NamedArguments.Select(a => new OperatorResolveResult(a.Key.ReturnType, ExpressionType.Assign, new MemberResolveResult(new InitializedObjectResolveResult(attr.AttributeType), a.Key), a.Value)).ToList<ResolveResult>(); var constructorResult = CompileConstructorInvocation(attr.Constructor, initializerStatements, currentType, null, attr.PositionalArguments, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, null, null); if (constructorResult.AdditionalStatements.Count > 0) { return JsExpression.Invocation(JsExpression.FunctionDefinition(new string[0], JsStatement.Block(constructorResult.AdditionalStatements.Concat(new[] { JsStatement.Return(constructorResult.Expression) })))); } else { return constructorResult.Expression; } }
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 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); }
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 static List<JsObjectLiteralProperty> GetCommonMemberInfoProperties(IMember m, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, Func<IType, JsExpression> instantiateType, bool includeDeclaringType) { var result = new List<JsObjectLiteralProperty>(); var attr = GetScriptableAttributes(m.Attributes, metadataImporter).ToList(); if (attr.Count > 0) result.Add(new JsObjectLiteralProperty("attr", JsExpression.ArrayLiteral(attr.Select(a => ConstructAttribute(a, m.DeclaringTypeDefinition, compilation, metadataImporter, namer, runtimeLibrary, errorReporter))))); if (includeDeclaringType) result.Add(new JsObjectLiteralProperty("typeDef", instantiateType(m.DeclaringType))); result.Add(new JsObjectLiteralProperty("name", JsExpression.String(m.Name))); return result; }
public static JsExpression ConstructMemberInfo(IMember m, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, Func <IType, JsExpression> instantiateType, bool includeDeclaringType) { MethodScriptSemantics semanticsIfAccessor = null; if (m is IMethod && ((IMethod)m).IsAccessor) { var owner = ((IMethod)m).AccessorOwner; if (owner is IProperty) { var sem = metadataImporter.GetPropertySemantics((IProperty)owner); if (sem.Type == PropertyScriptSemantics.ImplType.GetAndSetMethods) { if (ReferenceEquals(m, ((IProperty)owner).Getter)) { semanticsIfAccessor = sem.GetMethod; } else if (ReferenceEquals(m, ((IProperty)owner).Setter)) { semanticsIfAccessor = sem.SetMethod; } else { throw new ArgumentException("Invalid member " + m); } } } else if (owner is IEvent) { var sem = metadataImporter.GetEventSemantics((IEvent)owner); if (sem.Type == EventScriptSemantics.ImplType.AddAndRemoveMethods) { if (ReferenceEquals(m, ((IEvent)owner).AddAccessor)) { semanticsIfAccessor = sem.AddMethod; } else if (ReferenceEquals(m, ((IEvent)owner).RemoveAccessor)) { semanticsIfAccessor = sem.RemoveMethod; } else { throw new ArgumentException("Invalid member " + m); } } } else { throw new ArgumentException("Invalid owner " + owner); } } return(ConstructMemberInfo(m, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType, semanticsIfAccessor)); }
protected void AssertCorrect(string csharp, string expected, IMetadataImporter metadataImporter = null, IRuntimeLibrary runtimeLibrary = null, bool addSkeleton = true, IEnumerable <IAssemblyReference> references = null, string methodName = "M", bool mutableValueTypes = false) { CompileMethod(csharp, metadataImporter: metadataImporter ?? new MockMetadataImporter { GetPropertySemantics = p => { if (p.DeclaringType.Kind == TypeKind.Anonymous || new Regex("^F[0-9]*$").IsMatch(p.Name) || (p.DeclaringType.FullName == "System.Array" && p.Name == "Length")) { return(PropertyScriptSemantics.Field("$" + p.Name)); } else { return(PropertyScriptSemantics.GetAndSetMethods(MethodScriptSemantics.NormalMethod("get_$" + p.Name), MethodScriptSemantics.NormalMethod("set_$" + p.Name))); } }, GetMethodSemantics = m => MethodScriptSemantics.NormalMethod("$" + m.Name), GetEventSemantics = e => EventScriptSemantics.AddAndRemoveMethods(MethodScriptSemantics.NormalMethod("add_$" + e.Name), MethodScriptSemantics.NormalMethod("remove_$" + e.Name)), GetTypeSemantics = t => { return(mutableValueTypes && t.Kind == TypeKind.Struct ? TypeScriptSemantics.MutableValueType(t.FullName) : TypeScriptSemantics.NormalType(t.FullName)); } }, runtimeLibrary: runtimeLibrary, methodName: methodName, addSkeleton: addSkeleton, references: references); string actual = OutputFormatter.Format(CompiledMethod, true); int begin = actual.IndexOf("// BEGIN"); if (begin > -1) { while (begin < (actual.Length - 1) && actual[begin - 1] != '\n') { begin++; } actual = actual.Substring(begin); } int end = actual.IndexOf("// END"); if (end >= 0) { while (end >= 0 && actual[end] != '\n') { end--; } actual = actual.Substring(0, end + 1); } Assert.That(actual.Replace("\r\n", "\n"), Is.EqualTo(expected.Replace("\r\n", "\n")), "Expected:\n" + expected + "\n\nActual:\n" + actual); }
private static List<JsObjectLiteralProperty> GetCommonMemberInfoProperties(IMember m, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, Func<IType, JsExpression> instantiateType, bool includeDeclaringType) { var result = new List<JsObjectLiteralProperty>(); var attr = m.Attributes.Where(a => !a.IsConditionallyRemoved && metadataImporter.GetTypeSemantics(a.AttributeType.GetDefinition()).Type == TypeScriptSemantics.ImplType.NormalType).ToList(); if (attr.Count > 0) result.Add(new JsObjectLiteralProperty("attr", JsExpression.ArrayLiteral(attr.Select(a => ConstructAttribute(a, m.DeclaringTypeDefinition, compilation, metadataImporter, namer, runtimeLibrary, errorReporter))))); if (includeDeclaringType) result.Add(new JsObjectLiteralProperty("typeDef", instantiateType(m.DeclaringType))); result.Add(new JsObjectLiteralProperty("name", JsExpression.String(m.Name))); return result; }
protected void CompileMethod(string source, IMetadataImporter metadataImporter = null, INamer namer = null, IRuntimeLibrary runtimeLibrary = null, IErrorReporter errorReporter = null, string methodName = "M", bool addSkeleton = true, bool referenceSystemCore = false, bool allowUserDefinedStructs = false) { Compile(new[] { addSkeleton ? "using System; class C { " + source + "}" : source }, metadataImporter: metadataImporter, namer: namer, runtimeLibrary: runtimeLibrary, errorReporter: errorReporter, methodCompiled: (m, res, mc) => { if (m.Name == methodName) { Method = m; MethodCompiler = mc; CompiledMethod = res; } }, referenceSystemCore: referenceSystemCore, allowUserDefinedStructs: allowUserDefinedStructs); Assert.That(Method, Is.Not.Null, "Method " + methodName + " was not compiled"); }