public virtual AssemblyNode ResolveReference(AssemblyReference reference, Module module) {

            if (reference == null) throw new ArgumentNullException("reference");

            //Console.WriteLine("resolving {0}", reference.StrongName);

            // try to get it from the cache
            string name = reference.StrongName;
            if (cache.ContainsKey(name)) return (cache[name]);

            // try to get it from the gac
            if (useGac) {
                string location = GlobalAssemblyCache.GetLocation(reference);
                if (location != null) {
                    AssemblyNode assembly = AssemblyNode.GetAssembly(location, null, false, false, false, false);
                    if (assembly != null) {
                        Add(assembly);
                        return (assembly);
                    }
                }
            }

            // couldn't find it; return null
            // Console.WriteLine("returning null on request for {0}", reference.StrongName);
            //OnUnresolvedAssemblyReference(reference, module);
            return (null);

        }
Exemple #2
0
    //IDebugExpressionEvaluator
    public  HRESULT Parse( 
      [In,MarshalAs(UnmanagedType.LPWStr)]
      string                    pszExpression,
      PARSEFLAGS                  flags,
      uint                        radix,
      out string                  pbstrErrorMessages,
      out uint                    perrorCount,
      out IDebugParsedExpression  ppparsedExpression
      ) 
    {
      
      HRESULT hr = (HRESULT)HResult.S_OK;
      perrorCount = 0;
      pbstrErrorMessages = null;
      ppparsedExpression = null;
      ErrorNodeList errors =  new ErrorNodeList();
      Module symbolTable = new Module();
      Document doc = this.cciEvaluator.ExprCompiler.CreateDocument(null, 1, pszExpression);
      IParser exprParser = this.cciEvaluator.ExprCompiler.CreateParser(doc.Name, doc.LineNumber, doc.Text, symbolTable, errors, null);
      Expression parsedExpression = exprParser.ParseExpression();

      perrorCount = (uint)errors.Count;
      if (perrorCount > 0)
        pbstrErrorMessages = errors[0].GetMessage();
      else
        ppparsedExpression = new BaseParsedExpression(pszExpression, parsedExpression, this);

      return hr;
    }
 public CollectOldExpressions(Module module, Method method, ContractNodes contractNodes, Dictionary<TypeNode, Local> closureLocals, 
     int localCounterStart, Class initialClosureClass)
     : this(module, method, contractNodes, closureLocals, localCounterStart)
 {
     this.topLevelClosureClass = initialClosureClass;
     this.currentClosureClass = initialClosureClass;
 }
Exemple #4
0
 public Specializer(Module targetModule, TypeNodeList pars, TypeNodeList args)
 {
     Debug.Assert(pars != null && pars.Count > 0);
     Debug.Assert(args != null && args.Count > 0);
     this.pars = pars;
     this.args = args;
     this.TargetModule = targetModule;
 }
Exemple #5
0
 /// <param name="module">The module into which the duplicate IR will be grafted.</param>
 /// <param name="type">The type into which the duplicate Member will be grafted. Ignored if entire type, or larger unit is duplicated.</param>
 public Duplicator(Module/*!*/ module, TypeNode type)
 {
     this.TargetModule = module;
     this.TargetType = this.OriginalTargetType = type;
     this.DuplicateFor = new TrivialHashtable();
     this.TypesToBeDuplicated = new TrivialHashtable();
     //^ base();
 }
        public DuplicatorForContractsAndClosures(Module module, Method sourceMethod, Method targetMethod,
            ContractNodes contractNodes, bool mapParameters)
            : base(module, targetMethod.DeclaringType)
        {
            this.sourceMethod = sourceMethod;
            this.targetMethod = targetMethod;

            this.RemoveNameForLocals = true;

            Duplicator dup = this;

            if (mapParameters)
            {
                if (sourceMethod.ThisParameter != null)
                {
                    if (targetMethod.ThisParameter != null)
                    {
                        dup.DuplicateFor[sourceMethod.ThisParameter.UniqueKey] = targetMethod.ThisParameter;
                    }
                    else
                    {
                        // target is a static wrapper. But duplicator cannot handle This -> Parameter conversion
                        // so we handle it explicitly here in this visitor.
                        replaceThisWithParameter = targetMethod.Parameters[0];
                    }
                }

                if (sourceMethod.Parameters != null && targetMethod.Parameters != null
                    && sourceMethod.Parameters.Count == targetMethod.Parameters.Count)
                {
                    for (int i = 0, n = sourceMethod.Parameters.Count; i < n; i++)
                    {
                        dup.DuplicateFor[sourceMethod.Parameters[i].UniqueKey] = targetMethod.Parameters[i];
                    }
                }
            }

            var originalType = HelperMethods.IsContractTypeForSomeOtherType(sourceMethod.DeclaringType, contractNodes);
            if (originalType != null)
            {
                var contractType = this.contractClass = sourceMethod.DeclaringType;
                while (contractType.Template != null)
                {
                    contractType = contractType.Template;
                }
                    
                while (originalType.Template != null)
                {
                    originalType = originalType.Template;
                }

                // forward ContractType<A,B> -> originalType<A',B'>
                this.contractClassToForward = contractType;
                this.targetTypeToForwardTo = originalType;

                //dup.DuplicateFor[contractType.UniqueKey] = originalType;
            }
        }
        private AssemblyNode OnAssemblyNotFound(AssemblyReference reference,
                                                System.Compiler.Module module)
        {
            _logger.WriteLine(String.Format(
                                  "Unresolved assembly reference: {0} ({1}) required by {2}",
                                  reference.Name, reference.StrongName, module.Name),
                              BuildLoggerLevel.Error);

            return(null);
        }
        public CollectOldExpressions(Module module, Method method, ContractNodes contractNodes, Dictionary<TypeNode, Local> closureLocals,
            int localCounterStart)
        {
            this.contractNodes = contractNodes;
            this.prestateValuesOfOldExpressions = new Block(new StatementList());
            this.closureLocals = closureLocals;

            this.stackOfMethods = new List<MethodCall>();
            this.stackOfBoundVariables = new List<Parameter>();

            this.module = module;
            this.currentMethod = method;
            this.counter = localCounterStart;
        }
    public static void Write(Compilation compilation, Module module, CompilerParameters options) {
      XmlTextWriter writer = new XmlTextWriter(module.Name + ".source.xml", Encoding.Default);

      SourceContextWriter scw = new SourceContextWriter(writer);

      writer.WriteStartDocument();
      writer.WriteStartElement("Module");
      writer.WriteAttributeString("name", module.Name);

      scw.VisitCompilation(compilation);

      writer.WriteEndElement(); // Module
      writer.WriteEndDocument();
      writer.Flush();
      writer.Close();
    }
Exemple #10
0
    readonly private TypeNode declaringType; // needed to copy anonymous delegates into

    public ReplaceResult(Method containingMethod, Local r, Module assemblyBeingRewritten) {
      Contract.Requires(containingMethod != null);
      
      this.assemblyBeingRewritten = assemblyBeingRewritten;
      this.declaringType = containingMethod.DeclaringType;
      this.topLevelMethodFormals = containingMethod.TemplateParameters;
      this.originalLocalForResult = r;
      this.delegateNestingLevel = 0;
    }
Exemple #11
0
 /// <summary>
 /// Resolves assembly references based on the library paths specified.
 /// Tries to resolve to ".dll" or ".exe". First found wins.
 /// </summary>
 /// <param name="assemblyReference">Reference to resolve.</param>
 /// <param name="referencingModule">Referencing module.</param>
 /// <returns>The resolved assembly node (null if not found).</returns>
 private static AssemblyNode AssemblyReferenceResolution (AssemblyReference assemblyReference, Module referencingModule) {
   AssemblyNode a = ProbeForAssembly(assemblyReference.Name, referencingModule.Directory, DllAndExeExt);
   return a;
 }
        public DuplicatorForContractsAndClosures(Module module, Method sourceMethod, Method targetMethod,
            ContractNodes contractNodes, bool mapParameters)
            : base(module, targetMethod.DeclaringType)
        {
            this.sourceMethod = sourceMethod;
            this.targetMethod = targetMethod;

            this.RemoveNameForLocals = true;

            Duplicator dup = this;

            if (mapParameters)
            {
                if (sourceMethod.ThisParameter != null)
                {
                    if (targetMethod.ThisParameter != null)
                    {
                        dup.DuplicateFor[sourceMethod.ThisParameter.UniqueKey] = targetMethod.ThisParameter;
                    }
                    else
                    {
                        // target is a static wrapper. But duplicator cannot handle This -> Parameter conversion
                        // so we handle it explicitly here in this visitor.
                        replaceThisWithParameter = targetMethod.Parameters[0];
                    }
                }

                if (sourceMethod.Parameters != null && targetMethod.Parameters != null
                    && sourceMethod.Parameters.Count == targetMethod.Parameters.Count)
                {
                    for (int i = 0, n = sourceMethod.Parameters.Count; i < n; i++)
                    {
                        dup.DuplicateFor[sourceMethod.Parameters[i].UniqueKey] = targetMethod.Parameters[i];
                    }
                }

                // This code makes sure that generic method parameters used by contracts inherited from contract class
                // are correctly replaced by the one defined in the target method.
                // Without this mapping <c>CheckPost</c> method in generated async closure class would contain an invalid
                // reference to a generic contract method parameter instead of generic async closure type parameter.
                // For more about this problem see comments for Microsoft.Contracts.Foxtrot.EmitAsyncClosure.GenericTypeMapper class
                // and issue #380.
                if (sourceMethod.TemplateParameters != null && targetMethod.TemplateParameters != null
                    && sourceMethod.TemplateParameters.Count == targetMethod.TemplateParameters.Count)
                {
                    for (int i = 0, n = sourceMethod.TemplateParameters.Count; i < n; i++)
                    {
                        dup.DuplicateFor[sourceMethod.TemplateParameters[i].UniqueKey] = targetMethod.TemplateParameters[i];
                    }
                }
            }

            var originalType = HelperMethods.IsContractTypeForSomeOtherType(sourceMethod.DeclaringType, contractNodes);
            if (originalType != null)
            {
                var contractType = this.contractClass = sourceMethod.DeclaringType;
                while (contractType.Template != null)
                {
                    contractType = contractType.Template;
                }
                    
                while (originalType.Template != null)
                {
                    originalType = originalType.Template;
                }

                // forward ContractType<A,B> -> originalType<A',B'>
                this.contractClassToForward = contractType;
                this.targetTypeToForwardTo = originalType;

                //dup.DuplicateFor[contractType.UniqueKey] = originalType;
            }
        }
 public DuplicatorForContractsAndClosures(Module module, Method sourceMethod, Method targetMethod,
     ContractNodes contractNodes)
     : this(module, sourceMethod, targetMethod, contractNodes, true)
 {
 }
 private void WriteLibraryReference(Module module) {
     AssemblyNode assembly = module.ContainingAssembly;
     writer.WriteStartElement("library");
     WriteStringAttribute("assembly", assembly.Name);
     WriteStringAttribute("module", module.Name);
     WriteStringAttribute("kind", module.Kind.ToString());
     writer.WriteEndElement();
 }
Exemple #15
0
 private void ProvideTypeMembers(TypeNode/*!*/ dup, object/*!*/ handle)
 {
     TypeNode template = (TypeNode)handle;
     Debug.Assert(!template.membersBeingPopulated);
     TypeNode savedTargetType = this.TargetType;
     Module savedTargetModule = this.TargetModule;
     this.TargetType = dup;
     //^ assume dup.DeclaringModule != null;
     this.TargetModule = dup.DeclaringModule;
     this.FindTypesToBeDuplicated(template.NestedTypes);
     dup.Members = this.VisitMemberList(template.Members);
     DelegateNode delegateNode = dup as DelegateNode;
     if (delegateNode != null && delegateNode.IsNormalized)
     {
         Debug.Assert(dup.Members != null && dup.Members.Count > 0 && dup.Members[0] != null);
         delegateNode.Parameters = this.VisitParameterList(delegateNode.Parameters);
         delegateNode.ReturnType = this.VisitTypeReference(delegateNode.ReturnType);
     }
     this.TargetModule = savedTargetModule;
     this.TargetType = savedTargetType;
 }
 public MyMethodBodySpecializer(Module module, TypeNodeList source, TypeNodeList target)
     : base(module, source, target)
 {
 }
Exemple #17
0
    CompilationUnit CreateCompilationUnit(Module module, TypeNode type) {
      
      CompilationUnit cu = new CompilationUnit();
      cu.Namespaces = new NamespaceList();      
      cu.TargetModule = module;
      this.cunit = cu;
      this.module = module;

      Namespace ns = new Namespace(Identifier.Empty, Identifier.Empty, new AliasDefinitionList(), new UsedNamespaceList(), new NamespaceList(), new TypeNodeList());
      cu.Namespaces.Add(ns);      

      ns.UsedNamespaces.Add(new UsedNamespace(Identifier.For("System")));
      ns.UsedNamespaces.Add(new UsedNamespace(Identifier.For("System.Xml")));
      ns.UsedNamespaces.Add(new UsedNamespace(Identifier.For("Microsoft.Comega"))); // XmlSerializationWriter

      CreateSerializerFor(type);
      return cu;
    }
        /// <summary>
        /// This is called if assembly reference resolution fails after probing
        /// </summary>
        /// <param name="reference">The assembly reference</param>
        /// <param name="module">The module</param>
        /// <returns>Always returns null</returns>
        private AssemblyNode UnresolvedReference(AssemblyReference reference, Module module)
        {
            // Don't raise the event if ignored
            if(!ignoreIfUnresolved.Contains(reference.Name))
                OnUnresolvedAssemblyReference(reference, module);
            else
                ConsoleApplication.WriteMessage(LogLevel.Warn, "Ignoring unresolved assembly " +
                    "reference: {0} ({1}) required by {2}", reference.Name, reference.StrongName,
                    module.Name);

            return null;
        }
        /// <summary>
        /// This is used to try and resolve an assembly reference
        /// </summary>
        /// <param name="reference">The assembly reference</param>
        /// <param name="referrer">The module requiring the reference</param>
        /// <returns>The assembly node if resolved or null if not resolved</returns>
        public virtual AssemblyNode ResolveReference(AssemblyReference reference, Module referrer)
        {
            AssemblyNode assembly;

            if(reference == null)
                throw new ArgumentNullException("reference");

            // Try to get it from the cache
            string name = reference.StrongName;

            if(cache.ContainsKey(name))
                return cache[name];

            // Try to get it from the GAC if so indicated
            if(this.UseGac)
            {
                string location = GlobalAssemblyCache.GetLocation(reference);

                if(location != null)
                {
                    assembly = AssemblyNode.GetAssembly(location, null, false, false, false, false);

                    if(assembly != null)
                    {
                        this.Add(assembly);
                        return assembly;
                    }
                }
            }

            // Try the redirects if not found
            foreach(BindingRedirectSettings brs in redirects)
                if(brs.IsRedirectFor(name) && cache.ContainsKey(brs.StrongName))
                {
                    ConsoleApplication.WriteMessage(LogLevel.Info, "Using redirect '{0}' in place of '{1}'",
                        brs.StrongName, name);

                    assembly = cache[brs.StrongName];

                    // Add the same assembly under the current name
                    cache.Add(name, assembly);
                    return assembly;
                }

            // Couldn't find it; return null
            return null;
        }
        /// <summary>
        /// This raises the <see cref="UnresolvedAssemblyReference" event/>
        /// </summary>
        /// <param name="reference">The assembly reference</param>
        /// <param name="referrer">The module requiring the reference</param>
        protected virtual void OnUnresolvedAssemblyReference(AssemblyReference reference, Module referrer)
        {
            var handler = UnresolvedAssemblyReference;

            if(handler != null)
                handler(this, new AssemblyReferenceEventArgs(reference, referrer));
        }
Exemple #21
0
 public virtual Module VisitModuleReference(Module module)
 {
     if (module == null) return null;
     Module dup = (Module)this.DuplicateFor[module.UniqueKey];
     if (dup != null) return dup;
     for (int i = 0, n = this.TargetModule.ModuleReferences == null ? 0 : this.TargetModule.ModuleReferences.Count; i < n; i++)
     {
         //^ assert this.TargetModule.ModuleReferences != null;
         ModuleReference modRef = this.TargetModule.ModuleReferences[i];
         if (modRef == null) continue;
         if (string.Compare(module.Name, modRef.Name, true, System.Globalization.CultureInfo.InvariantCulture) != 0) continue;
         this.DuplicateFor[module.UniqueKey] = modRef.Module; return modRef.Module;
     }
     if (this.TargetModule.ModuleReferences == null)
         this.TargetModule.ModuleReferences = new ModuleReferenceList();
     this.TargetModule.ModuleReferences.Add(new ModuleReference(module.Name, module));
     this.DuplicateFor[module.UniqueKey] = module;
     return module;
 }
Exemple #22
0
 public override Module VisitModule(Module module)
 {
     if (module == null) return null;
     Module dup = (Module)module.Clone();
     if (this.TargetModule == null) this.TargetModule = dup;
     this.FindTypesToBeDuplicated(module.Types);
     return base.VisitModule(dup);
 }
Exemple #23
0
    public override void VisitAssembly(AssemblyNode assembly)
    {
      // Don't rewrite assemblies twice.
      if (ContractNodes.IsAlreadyRewritten(assembly)) {
        throw new RewriteException("Cannot rewrite an assembly that has already been rewritten!");
      }

      this.module = assembly;

      this.AdaptRuntimeOptionsBasedOnAttributes(assembly.Attributes);

      // Extract all inline foxtrot contracts and place them in the object model.
      //if (this.extractContracts) {
      //  new Extractor(rewriterNodes, this.Verbose, this.Decompile).Visit(assembly);
      //}
      base.VisitAssembly(assembly);

      this.runtimeContracts.Commit();

      // Set the flag that indicates the assembly has been rewritten.
      SetRuntimeContractFlag(assembly);

      // Add wrapper types for call-site requires. We do it here to avoid visiting them multiple times
      foreach (TypeNode t in this.wrapperTypes.Values)
      {
        assembly.Types.Add(t);
      }

      // in principle we shouldn't have old and result left over, but because of the call-site requires copying
      // we end up having them in closures that were used in ensures but not needed at call site requires
#if !DEBUG || true
      CleanUpOldAndResult cuoar = new CleanUpOldAndResult();
      assembly = cuoar.VisitAssembly(assembly);
#endif
      RemoveContractClasses rcc = new RemoveContractClasses();
      rcc.VisitAssembly(assembly);
    }
Exemple #24
0
 internal SerializationProvider(Module module) {
   this.module = module;
   Init();
 }
 public virtual Module VisitModule(Module module)
 {
     if (module == null) return null;
     module.Attributes = this.VisitAttributeList(module.Attributes);
     module.Types = this.VisitTypeNodeList(module.Types);
     return module;
 }
Exemple #26
0
 public IParser CreateParser(string fileName, int lineNumber, DocumentText text, Module symbolTable, ErrorNodeList errorNodes, CompilerParameters options){
   return new XamlParserStub(errorNodes, options as CompilerOptions);
 }
        public static bool ContractOption(Module module, string category, string setting)
        {
            if (module == null) return true; // default

            if (module.ContainingAssembly == null) return true; // default
            
            var tv = ContractOption(module.ContainingAssembly.Attributes, category, setting);
            
            switch (tv)
            {
                case ThreeValued.False:
                    return false;
                default:
                    return true;
            }
        }
Exemple #28
0
 private void ProvideNestedTypes(TypeNode/*!*/ dup, object/*!*/ handle)
 {
     TypeNode template = (TypeNode)handle;
     TypeNode savedTargetType = this.TargetType;
     Module savedTargetModule = this.TargetModule;
     this.TargetType = dup;
     //^ assume dup.DeclaringModule != null;
     this.TargetModule = dup.DeclaringModule;
     this.FindTypesToBeDuplicated(template.NestedTypes);
     dup.NestedTypes = this.VisitNestedTypes(dup, template.NestedTypes);
     this.TargetModule = savedTargetModule;
     this.TargetType = savedTargetType;
 }
Exemple #29
0
 internal SerializationProvider(CompilationUnit cunit) {
   this.cunit = cunit;
   this.module = cunit.TargetModule;
   Init();
 }
 public AsyncContractDuplicator(TypeNode parentType, Module module)
     : base(module, parentType)
 {
     this.parentType = parentType;
 }
Exemple #31
0
 /// <param name="module">The module into which the duplicate IR will be grafted.</param>
 /// <param name="type">The type into which the duplicate Member will be grafted. Ignored if entire type, or larger unit is duplicated.</param>
 public Duplicator(Module module, TypeNode type)
     : base(module, type)
 {
 }
Exemple #32
0
 private static AssemblyNode AssemblyNotFound(AssemblyReference reference, System.Compiler.Module module)
 {
     ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("Unresolved assembly reference: {0} ({1}) required by {2}", reference.Name, reference.StrongName, module.Name));
     Environment.Exit(1);
     return(null);
 }