public MetadataImporter(IErrorReporter errorReporter, ICompilation compilation, CompilerOptions options) {
			_errorReporter = errorReporter;
			_compilation = compilation;
			_minimizeNames = options.MinimizeScript;
			_systemObject = compilation.MainAssembly.Compilation.FindType(KnownTypeCode.Object);
			_typeSemantics = new Dictionary<ITypeDefinition, TypeSemantics>();
			_delegateSemantics = new Dictionary<ITypeDefinition, DelegateScriptSemantics>();
			_instanceMemberNamesByType = new Dictionary<ITypeDefinition, HashSet<string>>();
			_staticMemberNamesByType = new Dictionary<ITypeDefinition, HashSet<string>>();
			_methodSemantics = new Dictionary<IMethod, MethodScriptSemantics>();
			_propertySemantics = new Dictionary<IProperty, PropertyScriptSemantics>();
			_fieldSemantics = new Dictionary<IField, FieldScriptSemantics>();
			_eventSemantics = new Dictionary<IEvent, EventScriptSemantics>();
			_constructorSemantics = new Dictionary<IMethod, ConstructorScriptSemantics>();
			_propertyBackingFieldNames = new Dictionary<IProperty, string>();
			_eventBackingFieldNames = new Dictionary<IEvent, string>();
			_backingFieldCountPerType = new Dictionary<ITypeDefinition, int>();
			_internalTypeCountPerAssemblyAndNamespace = new Dictionary<Tuple<IAssembly, string>, int>();
			_ignoredMembers = new HashSet<IMember>();

			var sna = compilation.MainAssembly.AssemblyAttributes.SingleOrDefault(a => a.AttributeType.FullName == typeof(ScriptNamespaceAttribute).FullName);
			if (sna != null) {
				var data = AttributeReader.ReadAttribute<ScriptNamespaceAttribute>(sna);
				if (data.Name == null || (data.Name != "" && !data.Name.IsValidNestedJavaScriptIdentifier())) {
					Message(Messages._7002, sna.Region, "assembly");
				}
			}
		}
예제 #2
0
		protected string Process(string source, string[] typeNames = null, string entryPoint = null, IEnumerable<IAssemblyResource> resources = null, IErrorReporter errorReporter = null) {
			bool assertNoErrors = errorReporter == null;
			errorReporter = errorReporter ?? new MockErrorReporter(true);
			var sourceFile = new MockSourceFile("file.cs", source);
			var n = new Namer();
			var references = new[] { Files.Mscorlib };
			var compilation = PreparedCompilation.CreateCompilation("x", new[] { sourceFile }, references, null, resources);
			var md = new MetadataImporter(errorReporter, compilation.Compilation, new CompilerOptions());
			var rtl = new RuntimeLibrary(md, errorReporter, compilation.Compilation, n);
			var l = new MockLinker();
			md.Prepare(compilation.Compilation.GetAllTypeDefinitions());
			var compiler = new Compiler(md, n, rtl, errorReporter);
			var compiledTypes = compiler.Compile(compilation).ToList();
			var obj = new OOPEmulator(compilation.Compilation, md, rtl, n, l, errorReporter);
			IMethod ep;
			if (entryPoint != null) {
				var type = compiledTypes.Single(c => c.CSharpTypeDefinition.FullName == entryPoint.Substring(0, entryPoint.IndexOf('.')));
				ep = type.CSharpTypeDefinition.Methods.Single(m => m.FullName == entryPoint);
			}
			else {
				ep = null;
			}
			var rewritten = obj.Process(compiledTypes.Where(t => typeNames == null || typeNames.Contains(t.CSharpTypeDefinition.FullName)), ep);

			if (assertNoErrors)
				Assert.That(((MockErrorReporter)errorReporter).AllMessages, Is.Empty, "Should not have errors");

			return string.Join("", rewritten.Select(s => OutputFormatter.Format(s, allowIntermediates: true)));
		}
 public ScriptSharpRuntimeLibrary(IScriptSharpMetadataImporter metadataImporter, IErrorReporter errorReporter, Func<ITypeParameter, string> getTypeParameterName, Func<ITypeReference, JsExpression> createTypeReferenceExpression)
 {
     _metadataImporter = metadataImporter;
     _errorReporter = errorReporter;
     _getTypeParameterName = getTypeParameterName;
     _createTypeReferenceExpression = createTypeReferenceExpression;
 }
예제 #4
0
 public DispatcherEngine(ISequenceEventSelector sequencedEventSelector, IErrorQueueLoader errorQueueLoader, IHandlerExecutor handlerExecutor, IErrorReporter errorReporter)
 {
     _sequencedEventSelector = sequencedEventSelector;
     _errorQueueLoader = errorQueueLoader;
     _handlerExecutor = handlerExecutor;
     _errorReporter = errorReporter;
 }
예제 #5
0
파일: Lexer.cs 프로젝트: chenzuo/nquery
 public Lexer(IErrorReporter errorReporter, string source)
 {
     _errorReporter = errorReporter;
     _source = source;
     _reader = new CharReader(source);
     _tokenRange = SourceRange.Empty;
 }
        public override TypeDefinition Generate(IErrorReporter errorReporter)
        {
            var t = new TypeDefinition(
                providedType.Namespace,
                providedType.Name + Internal.Plugins.Codegen.CodegenPlugin.IProviderSuffix,
                TypeAttributes.Public,
                References.Binding);

            var providerOfT = References.IProviderOfT.MakeGenericInstanceType(providedType);

            t.Interfaces.Add(providerOfT);
            t.CustomAttributes.Add(new CustomAttribute(References.CompilerGeneratedAttribute));

            var providerOfT_get = ModuleDefinition.Import(providerOfT.Resolve()
                                                                     .Methods
                                                                     .First(m => m.Name == "Get"))
                                                  .MakeHostInstanceGeneric(providedType);

            var providerKeyField = new FieldDefinition("providerKey", FieldAttributes.Private, References.String);
            var mustBeInjectableField = new FieldDefinition("mustBeInjectable", FieldAttributes.Private, References.Boolean);
            var delegateBindingField = new FieldDefinition("delegateBinding", FieldAttributes.Private, References.Binding);

            t.Fields.Add(providerKeyField);
            t.Fields.Add(mustBeInjectableField);
            t.Fields.Add(delegateBindingField);

            EmitCtor(t, providerKeyField, mustBeInjectableField);
            EmitResolve(t, mustBeInjectableField, providerKeyField, delegateBindingField);
            EmitGet(t, providerOfT_get, delegateBindingField);

            return t;
        }
		public override void ApplyTo(IAssembly assembly, IAttributeStore attributeStore, IErrorReporter errorReporter) {
			foreach (var t in assembly.GetAllTypeDefinitions()) {
				if (!attributeStore.AttributesFor(t).HasAttribute<DefaultMemberReflectabilityAttribute>()) {
					ApplyTo(t, attributeStore, errorReporter);
				}
			}
		}
예제 #8
0
 public Compiler(IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter)
 {
     _metadataImporter = metadataImporter;
     _namer            = namer;
     _errorReporter    = errorReporter;
     _runtimeLibrary   = runtimeLibrary;
 }
		public MetadataImporter(IErrorReporter errorReporter, ICompilation compilation, IAttributeStore attributeStore, CompilerOptions options) {
			_errorReporter = errorReporter;
			_compilation = compilation;
			_attributeStore = attributeStore;
			_minimizeNames = options.MinimizeScript;
			_systemObject = compilation.MainAssembly.Compilation.FindType(KnownTypeCode.Object);
			_typeSemantics = new Dictionary<ITypeDefinition, TypeSemantics>();
			_delegateSemantics = new Dictionary<ITypeDefinition, DelegateScriptSemantics>();
			_instanceMemberNamesByType = new Dictionary<ITypeDefinition, HashSet<string>>();
			_staticMemberNamesByType = new Dictionary<ITypeDefinition, HashSet<string>>();
			_methodSemantics = new Dictionary<IMethod, MethodScriptSemantics>();
			_propertySemantics = new Dictionary<IProperty, PropertyScriptSemantics>();
			_fieldSemantics = new Dictionary<IField, FieldScriptSemantics>();
			_eventSemantics = new Dictionary<IEvent, EventScriptSemantics>();
			_constructorSemantics = new Dictionary<IMethod, ConstructorScriptSemantics>();
			_propertyBackingFieldNames = new Dictionary<IProperty, Tuple<string, bool>>();
			_eventBackingFieldNames = new Dictionary<IEvent, Tuple<string, bool>>();
			_backingFieldCountPerType = new Dictionary<ITypeDefinition, int>();
			_internalTypeCountPerAssemblyAndNamespace = new Dictionary<Tuple<IAssembly, string>, int>();
			_ignoredMembers = new HashSet<IMember>();

			var sna = _attributeStore.AttributesFor(compilation.MainAssembly).GetAttribute<ScriptNamespaceAttribute>();
			if (sna != null) {
				if (sna.Name == null || (sna.Name != "" && !sna.Name.IsValidNestedJavaScriptIdentifier())) {
					Message(Messages._7002, default(DomRegion), "assembly");
				}
			}
		}
예제 #10
0
        public SymbolTableBuilder(Program node, IErrorReporter errorReporter)
        {
            _errorReporter = errorReporter;
            _syntaxTree = node;
            _globalScope = new GlobalScope();

            _scopeStack = new Stack<IScope>();
        }
		public RuntimeLibrary(IMetadataImporter metadataImporter, IErrorReporter errorReporter, ICompilation compilation, INamer namer) {
			_metadataImporter = metadataImporter;
			_errorReporter = errorReporter;
			_compilation = compilation;
			_namer = namer;
			_omitDowncasts = MetadataUtils.OmitDowncasts(compilation);
			_omitNullableChecks = MetadataUtils.OmitNullableChecks(compilation);
		}
예제 #12
0
 public Compiler(IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, bool allowUserDefinedStructs)
 {
     _metadataImporter        = metadataImporter;
     _namer                   = namer;
     _errorReporter           = errorReporter;
     _runtimeLibrary          = runtimeLibrary;
     _allowUserDefinedStructs = allowUserDefinedStructs;
 }
예제 #13
0
 /// <summary>
 /// Adds <paramref name="reporter"/> to the list of error reporters.
 /// </summary>
 /// <param name="reporter"></param>
 /// <exception cref="ArgumentNullException"><paramref name="reporter"/> is <c>null</c>.</exception>
 public void Add(IErrorReporter reporter)
 {
     lock (reporters)
     {
         foreach (var asm in reporter.AssembliesHandled)
             reporters.Add (asm, reporter);
     }
 }
예제 #14
0
 public SemanticsChecker(Program program, IErrorReporter errorReporter)
 {
     if (program.Scope == null)
         throw new ArgumentException("Global scope is undefined.");
     _programRoot = program;
     _symbolTable = (GlobalScope)program.Scope;
     _errors = errorReporter;
 }
		protected OOPEmulator CreateEmulator(ICompilation compilation, IErrorReporter errorReporter = null) {
			var n = new Namer();
			errorReporter = errorReporter ?? new MockErrorReporter();
			var md = new MetadataImporter(errorReporter, compilation, new CompilerOptions());
			md.Prepare(compilation.GetAllTypeDefinitions());
			var rtl = new RuntimeLibrary(md, errorReporter, compilation, n);
			return new OOPEmulator(compilation, md, rtl, n, new MockLinker(), errorReporter);
		}
예제 #16
0
파일: Resolver.cs 프로젝트: chenzuo/nquery
        public Resolver(IErrorReporter errorReporter, Scope scope)
            : base(errorReporter)
        {
            _scope = scope;

            // Needed for IntelliSense. This ensures
            // That CurrentScope always returns a legal scope.
            PushNewScope(null);
        }
예제 #17
0
 public ConnectionFactory(
     IErrorReporter errorReporter,
     IDataEnumeratorFactory dataEnumeratorFactory,
     IDataReaderFactory dataReaderFactory)
 {
     _errorReporter = errorReporter;
     _dataEnumeratorFactory = dataEnumeratorFactory;
     _dataReaderFactory = dataReaderFactory;
 }
예제 #18
0
 public ContextFactory(
     IDataEnumeratorFactory dataEnumeratorFactory,
     IRepositoryFactory repositoryFactory,
     IErrorReporter errorReporter)
 {
     _dataEnumeratorFactory = dataEnumeratorFactory;
     _repositoryFactory = repositoryFactory;
     _errorReporter = errorReporter;
 }
		private static CompilerSettings MapSettings(CompilerOptions options, string outputAssemblyPath, string outputDocFilePath, IErrorReporter er) {
			var allPaths = options.AdditionalLibPaths.Concat(new[] { Environment.CurrentDirectory }).ToList();

			var result = new CompilerSettings {
				Target                    = (options.HasEntryPoint ? Target.Exe : Target.Library),
				Platform                  = Platform.AnyCPU,
				TargetExt                 = (options.HasEntryPoint ? ".exe" : ".dll"),
				MainClass                 = options.EntryPointClass,
				VerifyClsCompliance       = false,
				Optimize                  = false,
				Version                   = LanguageVersion.V_5,
				EnhancedWarnings          = false,
				LoadDefaultReferences     = false,
				TabSize                   = 1,
				WarningsAreErrors         = options.TreatWarningsAsErrors,
				FatalCounter              = 100,
				WarningLevel              = options.WarningLevel,
				Encoding                  = Encoding.UTF8,
				DocumentationFile         = !string.IsNullOrEmpty(options.DocumentationFile) ? outputDocFilePath : null,
				OutputFile                = outputAssemblyPath,
				AssemblyName              = GetAssemblyName(options),
				StdLib                    = false,
				StdLibRuntimeVersion      = RuntimeVersion.v4,
				StrongNameKeyContainer    = options.KeyContainer,
				StrongNameKeyFile         = options.KeyFile,
			};
			result.SourceFiles.AddRange(options.SourceFiles.Select((f, i) => new SourceFile(f, f, i + 1)));
			foreach (var r in options.References) {
				string resolvedPath = ResolveReference(r.Filename, allPaths, er);
				if (r.Alias == null) {
					if (!result.AssemblyReferences.Contains(resolvedPath))
						result.AssemblyReferences.Add(resolvedPath);
				}
				else
					result.AssemblyReferencesAliases.Add(Tuple.Create(r.Alias, resolvedPath));
			}
			foreach (var c in options.DefineConstants)
				result.AddConditionalSymbol(c);
			foreach (var w in options.DisabledWarnings)
				result.SetIgnoreWarning(w);
			foreach (var w in options.WarningsAsErrors)
				result.AddWarningAsError(w);
			foreach (var w in options.WarningsNotAsErrors)
				result.AddWarningOnly(w);
			if (options.EmbeddedResources.Count > 0)
				result.Resources = options.EmbeddedResources.Select(r => new AssemblyResource(r.Filename, r.ResourceName, isPrivate: !r.IsPublic) { IsEmbeded = true }).ToList();

			if (result.AssemblyReferencesAliases.Count > 0) {	// NRefactory does currently not support reference aliases, this check will hopefully go away in the future.
				er.Region = DomRegion.Empty;
				er.Message(Messages._7998, "aliased reference");
			}

			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, 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 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.");
		}
예제 #22
0
 public Validator(
     IErrorReporter errorReporter,
     IEnumerable<InjectBindingGenerator> injectBindings,
     IEnumerable<LazyBindingGenerator> lazyBindings,
     IEnumerable<ProviderBindingGenerator> providerBindings,
     IEnumerable<ModuleGenerator> modules)
 {
     modulesByTypeName = modules.ToDictionary(m => m.ModuleType.FullName, m => m);
     moduleGenerators = modulesByTypeName.Values;
     plugin = new CompilerPlugin(injectBindings, lazyBindings, providerBindings);
     this.errorReporter = errorReporter;
 }
        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");
        }
예제 #24
0
        public CompilerLoader(
            IEnumerable<InjectBindingGenerator> bindings,
            IEnumerable<LazyBindingGenerator> lazyBindings,
            IEnumerable<ProviderBindingGenerator> providerBindings,
            IErrorReporter errorReporter)
        {
            var comparer = StringComparer.Ordinal;

            this.bindings = new Dictionary<string, Binding>(comparer);
            foreach (var gen in bindings)
            {
                try
                {
                    this.bindings.Add(gen.Key, new CompilerBinding(gen));
                }
                catch (ArgumentException)
                {
                    const string format = "The inject binding {0} is erroneously duplicated - please report this, with a repro if possible!";
                    errorReporter.LogError(string.Format(format, gen.Key));
                    HasError = true;
                }
            }

            this.lazyBindings = new Dictionary<string, CompilerParameterizedBinding>(comparer);
            foreach (var gen in lazyBindings)
            {
                try
                {
                    this.lazyBindings.Add(gen.Key, new CompilerParameterizedBinding(gen));
                }
                catch (ArgumentException)
                {
                    var message = string.Format("The lazy binding {0} is erroneously duplicated - please report this, with a repro if possible!", gen.Key);
                    errorReporter.LogError(message);
                    HasError = true;
                }
            }

            this.providerBindings = new Dictionary<string, CompilerParameterizedBinding>(comparer);
            foreach (var gen in providerBindings)
            {
                try
                {
                    this.providerBindings.Add(gen.Key, new CompilerParameterizedBinding(gen));
                }
                catch (ArgumentException)
                {
                    var message = string.Format("The IProvider binding {0} is erroneously duplicated - please report this, with a repro if possible!", gen.Key);
                    errorReporter.LogError(message);
                    HasError = true;
                }
            }
        }
		public override void ApplyTo(IEntity entity, IAttributeStore attributeStore, IErrorReporter errorReporter) {
			var type = entity as ITypeDefinition;
			if (type == null)
				return;

			foreach (var m in type.Members) {
				var attributes = attributeStore.AttributesFor(m);
				if (!attributes.HasAttribute<ReflectableAttribute>()) {
					if (IsMemberReflectable(m)) {
						attributes.Add(new ReflectableAttribute(true));
					}
				}
			}
		}
		protected TypeOOPEmulation EmulateType(string source, string typeName, IErrorReporter errorReporter = null) {
			bool assertNoErrors = errorReporter == null;
			errorReporter = errorReporter ?? new MockErrorReporter(true);

			var compiled = Compile(source, errorReporter: errorReporter);

			var emulated = compiled.Item2.EmulateType(compiled.Item3.Single(t => t.CSharpTypeDefinition.FullName == typeName));

			if (assertNoErrors) {
				Assert.That(((MockErrorReporter)errorReporter).AllMessages, Is.Empty, "Should not have errors");
			}

			return emulated;
		}
예제 #27
0
		public override void ApplyTo(IEntity entity, IAttributeStore attributeStore, IErrorReporter errorReporter) {
			foreach (var p in ((ITypeDefinition)entity).GetProperties(options: GetMemberOptions.IgnoreInheritedMembers)) {
				if (attributeStore.AttributesFor(p).HasAttribute<KnockoutPropertyAttribute>())
					continue;
				if (p.IsStatic)
					continue;

				if (MetadataUtils.IsAutoProperty(p) == false) {
					errorReporter.Message(MessageSeverity.Error, 8001, "The property {0} is not an auto-property so because its containing type has a [KnockoutModelAttribute], the property must be decorated with [KnockoutPropertyAttribute(false)]", p.FullName);
					continue;
				}

				KnockoutPropertyAttribute.MakeKnockoutProperty(p, attributeStore);
			}
		}
예제 #28
0
		public override void ApplyTo(IEntity entity, IAttributeStore attributeStore, IErrorReporter errorReporter) {
			if (IsKnockoutProperty) {
				var p = (IProperty)entity;

				if (p.IsStatic) {
					errorReporter.Message(MessageSeverity.Error, 8000, "The property {0} cannot have a [KnockoutPropertyAttribute] because it is static", p.FullName);
				}
				else if (MetadataUtils.IsAutoProperty(p) == false) {
					errorReporter.Message(MessageSeverity.Error, 8001, "The property {0} cannot be a knockout property because it is not an auto-property", p.FullName);
				}
				else {
					MakeKnockoutProperty((IProperty)entity, attributeStore);
				}
			}
		}
        protected string Process(IEnumerable<JsType> types, IScriptSharpMetadataImporter metadataImporter = null, IErrorReporter errorReporter = null, IMethod entryPoint = null)
        {
            metadataImporter = metadataImporter ?? new MockScriptSharpMetadataImporter();

            IProjectContent proj = new CSharpProjectContent();
            proj = proj.AddAssemblyReferences(new[] { Common.Mscorlib });
            var comp = proj.CreateCompilation();
            bool verifyNoErrors = errorReporter == null;
            errorReporter = errorReporter ?? new MockErrorReporter();
            var obj = new OOPEmulator.ScriptSharpOOPEmulator(comp, metadataImporter, new MockRuntimeLibrary(), new MockNamer(), errorReporter);
            if (verifyNoErrors)
                Assert.That(((MockErrorReporter)errorReporter).AllMessages, Is.Empty, "Should not have errors");

            var rewritten = obj.Process(types, comp, entryPoint);
            return string.Join("", rewritten.Select(s => OutputFormatter.Format(s, allowIntermediates: true)));
        }
		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");
			}
		}
예제 #31
0
 public Parser(IErrorReporter errorReporter)
 {
     _errorReporter = errorReporter;
 }
예제 #32
0
 public ScriptSharpRuntimeLibrary(IScriptSharpMetadataImporter metadataImporter, IErrorReporter errorReporter, Func <ITypeParameter, string> getTypeParameterName, Func <ITypeReference, JsExpression> createTypeReferenceExpression)
 {
     _metadataImporter              = metadataImporter;
     _errorReporter                 = errorReporter;
     _getTypeParameterName          = getTypeParameterName;
     _createTypeReferenceExpression = createTypeReferenceExpression;
 }
예제 #33
0
        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);
        }
예제 #34
0
        private void DeserializeMetrics(YamlMappingNode node, MetricDefinitionV1 metricDefinition, IErrorReporter errorReporter)
        {
            if (metricDefinition.ResourceType == null)
            {
                return;
            }

            var resourceTypeNode = node.Children["resourceType"];

            if (metricDefinition.ResourceType == ResourceType.NotSpecified)
            {
                errorReporter.ReportError(resourceTypeNode, "'resourceType' must not be set to 'NotSpecified'.");
                return;
            }

            if (node.Children.TryGetValue(ResourceDiscoveryGroupsTag, out var resourceDiscoveryGroupNode))
            {
                metricDefinition.ResourceDiscoveryGroups = _azureResourceDiscoveryGroupDeserializer.Deserialize((YamlSequenceNode)resourceDiscoveryGroupNode, errorReporter);
            }

            if (node.Children.TryGetValue(ResourcesTag, out var metricsNode))
            {
                var resourceDeserializer = _azureResourceDeserializerFactory.GetDeserializerFor(metricDefinition.ResourceType.Value);
                if (resourceDeserializer != null)
                {
                    metricDefinition.Resources = resourceDeserializer.Deserialize((YamlSequenceNode)metricsNode, errorReporter);
                }
                else
                {
                    errorReporter.ReportError(resourceTypeNode, $"Could not find a deserializer for resource type '{metricDefinition.ResourceType}'.");
                }
            }

            if ((metricDefinition.Resources == null || !metricDefinition.Resources.Any()) &&
                (metricDefinition.ResourceDiscoveryGroups == null || !metricDefinition.ResourceDiscoveryGroups.Any()))
            {
                errorReporter.ReportError(node, "Either 'resources' or 'resourceDiscoveryGroups' must be specified.");
            }
        }
예제 #35
0
 public DataReader(IErrorReporter errorReporter)
 {
     _errorReporter = errorReporter;
 }
예제 #36
0
        public void Validate(IErrorReporter errorReporter)
        {
            {
                var list = elements.FindAll(x => x.GetType() == typeof(A2ML));
                if (list != null)
                {
                    if (list.Count > 1)
                    {
                        list[list.Count - 1].reportErrorOrWarning("Second A2ML found, shall only be one", false, errorReporter);
                    }
                }
            }
            {
                var list = elements.FindAll(x => x.GetType() == typeof(MOD_COMMON));
                if (list != null)
                {
                    if (list.Count > 1)
                    {
                        list[list.Count - 1].reportErrorOrWarning("Second MOD_COMMON found, shall only be one", false, errorReporter);
                    }
                }
            }
            {
                var list = elements.FindAll(x => x.GetType() == typeof(MOD_PAR));
                if (list != null)
                {
                    if (list.Count > 1)
                    {
                        list[list.Count - 1].reportErrorOrWarning("Second MOD_PAR found, shall only be one", false, errorReporter);
                    }
                }
            }
            {
                var list = elements.FindAll(x => x.GetType() == typeof(VARIANT_CODING));
                if (list != null)
                {
                    if (list.Count > 1)
                    {
                        list[list.Count - 1].reportErrorOrWarning("Second VARIANT_CODING found, shall only be one", false, errorReporter);
                    }
                }
            }

            {
                {
                    var measurements = elements.FindAll(x => x.GetType() == typeof(MEASUREMENT));
                    foreach (var item in measurements)
                    {
                        (item as MEASUREMENT).Validate(errorReporter, this);
                    }
                }
                {
                    var measurements = elements.FindAll(x => x.GetType() == typeof(CHARACTERISTIC));
                    foreach (var item in measurements)
                    {
                        (item as CHARACTERISTIC).Validate(errorReporter, this);
                    }
                }
                {
                    var axis_pts = elements.FindAll(x => x.GetType() == typeof(AXIS_PTS));
                    foreach (var item in axis_pts)
                    {
                        (item as AXIS_PTS).Validate(errorReporter, this);
                    }
                }
                {
                    var compu_method = elements.FindAll(x => x.GetType() == typeof(COMPU_METHOD));
                    foreach (var item in compu_method)
                    {
                        (item as COMPU_METHOD).Validate(errorReporter, this);
                    }
                }
            }
        }
예제 #37
0
 void IMetadataImporter.Prepare(IEnumerable <ITypeDefinition> allTypes, IAssembly mainAssembly, IErrorReporter errorReporter)
 {
 }
예제 #38
0
 public DefaultRuntimeContext(ITypeDefinition currentType, IMetadataImporter metadataImporter, IErrorReporter errorReporter, INamer namer)
 {
     _currentType      = currentType;
     _metadataImporter = metadataImporter;
     _errorReporter    = errorReporter;
     _namer            = namer;
 }
예제 #39
0
        public OOPEmulator(ICompilation compilation, IMetadataImporter metadataImporter, IRuntimeLibrary runtimeLibrary, INamer namer, ILinker linker, IAttributeStore attributeStore, 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;
            _linker           = linker;
            _attributeStore   = attributeStore;
            _errorReporter    = errorReporter;
            _defaultReflectionRuntimeContext = new ReflectionRuntimeContext(false, _systemObject, _namer);
            _genericSpecializationReflectionRuntimeContext = new ReflectionRuntimeContext(true, _systemObject, _namer);
        }
예제 #40
0
 public static void InternalError(this IErrorReporter reporter, Exception ex, string additionalText = null)
 {
     reporter.InternalError(ex, additionalText);
 }
예제 #41
0
 public static void Message(this IErrorReporter reporter, Tuple <int, MessageSeverity, string> message, params object[] args)
 {
     reporter.Message(message.Item2, message.Item1, message.Item3, args);
 }
예제 #42
0
            private static object InvertBooleanString(string value, KeyValuePair <YamlNode, YamlNode> nodePair, IErrorReporter errorReporter)
            {
                var boolValue = bool.Parse(value);

                return(!boolValue);
            }
예제 #43
0
 public override void CheckSemantic(Scope scope, IErrorReporter logger)
 {
 }
예제 #44
0
 public static void AddWarning(IErrorReporter reporter, ICharRange token, string format, params object[] args)
 {
     AddWarning(reporter, token, string.Format(CultureInfo.CurrentCulture, format, args));
 }
예제 #45
0
 public Resolver(Interpreter interpreter, IErrorReporter errors)
 {
     _interpreter = interpreter;
     _errors      = errors;
 }
예제 #46
0
        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));
        }
        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, 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(metadataImporter ?? new MockMetadataImporter(), namer ?? new MockNamer(), runtimeLibrary ?? new MockRuntimeLibrary(), errorReporter, allowUserDefinedStructs: allowUserDefinedStructs);

            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");
            }
        }
예제 #48
0
 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));
 }
예제 #49
0
파일: Parser.cs 프로젝트: vvromanov/Asap2
 public Parser(string fileName, IErrorReporter errorHandler)
 {
     this.fileName     = fileName;
     this.errorHandler = errorHandler;
     this.indentType   = "    ";
 }
예제 #50
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="gitGetter">The IGitGetter object of your choice. It connects the Engine to the branches stored in Git.</param>
 /// <param name="reporter">The IErrorReporter object that both the Engine and the IGitGetter will use to show any kinds of problems to the End User.</param>
 public Engine(IGitGetter gitGetter, IErrorReporter reporter)
 {
     GitGetter = gitGetter;
     Reporter  = reporter;
 }
예제 #51
0
        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], new JsBlockStatement(constructorResult.AdditionalStatements.Concat(new[] { new JsReturnStatement(constructorResult.Expression) })))));
            }
            else
            {
                return(constructorResult.Expression);
            }
        }
예제 #52
0
 public Interpreter(Environment globals, IErrorReporter errors)
 {
     _globals     = globals;
     _environment = _globals;
     _errors      = errors;
 }
예제 #53
0
 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));
 }
예제 #54
0
        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.");
        }
예제 #55
0
 public static void SetReporter(IErrorReporter pError)
 {
     _error = pError;
 }
 public TestRewriter(IErrorReporter errorReporter, IRuntimeLibrary runtimeLibrary)
 {
     _errorReporter  = errorReporter;
     _runtimeLibrary = runtimeLibrary;
 }
예제 #57
0
        public static JsExpression ConstructMemberInfo(IMember m, ICompilation compilation, IMetadataImporter metadataImporter, INamer namer, IRuntimeLibrary runtimeLibrary, IErrorReporter errorReporter, Func <IType, JsExpression> instantiateType, bool includeDeclaringType)
        {
            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    = 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(new CSharpInvocationResolveResult(new ThisResolveResult(method.DeclaringType), method, arguments), method.DeclaringTypeDefinition, method, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, true, variables, usedNames);
                    var definition    = JsExpression.FunctionDefinition(parameters.Select(p => variables[p].Name), new JsBlockStatement(compileResult.AdditionalStatements.Concat(new[] { new JsReturnStatement(compileResult.Expression) })));

                    if (tokens.Any(t => t.Type == InlineCodeToken.TokenType.TypeParameter && t.OwnerType == EntityType.Method))
                    {
                        definition = JsExpression.FunctionDefinition(method.TypeParameters.Select(namer.GetTypeParameterName), new JsReturnStatement(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)));
                    }
                    if (sem.SetMethod != null)
                    {
                        properties.Add(new JsObjectLiteralProperty("setter", ConstructMemberInfo(prop.Setter, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType)));
                    }
                    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)));
                properties.Add(new JsObjectLiteralProperty("remover", ConstructMemberInfo(evt.RemoveAccessor, compilation, metadataImporter, namer, runtimeLibrary, errorReporter, instantiateType, includeDeclaringType)));
            }
            else
            {
                throw new ArgumentException("Invalid member " + m);
            }

            return(JsExpression.ObjectLiteral(properties));
        }
예제 #58
0
        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), new JsBlockStatement(compileResult.AdditionalStatements.Concat(new[] { new JsReturnStatement(compileResult.Expression) })));
                properties.Add(new JsObjectLiteralProperty("def", definition));
            }
            return(JsExpression.ObjectLiteral(properties));
        }
예제 #59
0
 public static void InternalError(this IErrorReporter reporter, string text)
 {
     reporter.InternalError(text);
 }
예제 #60
0
 public override void Validate(IErrorReporter errorReporter)
 {
 }