Ejemplo n.º 1
0
  Expression IContractDeserializer.ParseContract (MethodContract mc, string text, ErrorNodeList errs)
  {
    Expression expression = null;
    currentMethodContract = mc;
    currentMethod = null;
    currentType = null;
    if (mc != null){
      currentMethod = mc.DeclaringMethod;
      currentType = currentMethod.DeclaringType;
    }
    try{
      Parser.ParseContract(this.assembly, text, out expression);
    }catch (Exception e){
      ErrorNodeList eList = errs != null ? errs : this.ErrorList;
      if (eList != null){
#if OLDERRORS
        ErrorHandler eh = new ErrorHandler(eList);
        eh.HandleError(mc,System.Compiler.Error.GenericError,"Deserializer error: " + e.Message);
#else
        this.assembly.MetadataImportErrors.Add(e);
#endif
      }
      throw e;
    }
    return expression;
  }
Ejemplo n.º 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;
    }
Ejemplo n.º 3
0
 public override CompilerResults CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] compilationUnits, ErrorNodeList errorNodes)
 {
     if (options == null) { Debug.Assert(false); return null; }
     this.Options = options;
     int n = compilationUnits == null ? 0 : compilationUnits.Length;
     if (options.OutputAssembly == null || options.OutputAssembly.Length == 0)
     {
         for (int i = 0; i < n; i++)
         {
             CodeSnippetCompileUnit csu = compilationUnits[i] as CodeSnippetCompileUnit;
             if (csu == null || csu.LinePragma == null || csu.LinePragma.FileName == null) continue;
             this.SetOutputFileName(options, csu.LinePragma.FileName);
             break;
         }
     }
     CompilerResults results = new CompilerResults(options.TempFiles);
     AssemblyNode assem = this.CreateAssembly(options, errorNodes);
     Compilation compilation = new Compilation(assem, new CompilationUnitList(n), options, this.GetGlobalScope(assem));
     CodeDomTranslator cdt = new CodeDomTranslator();
     SnippetParser sp = new SnippetParser(this, assem, errorNodes, options);
     for (int i = 0; i < n; i++)
     {
         CompilationUnit cu = cdt.Translate(this, compilationUnits[i], assem, errorNodes);
         sp.Visit(cu);
         compilation.CompilationUnits.Add(cu);
         cu.Compilation = compilation;
     }
     this.CompileParseTree(compilation, errorNodes);
     this.ProcessErrors(options, results, errorNodes);
     if (results.NativeCompilerReturnValue == 0)
         this.SetEntryPoint(compilation, results);
     // The following line is different from the base class method...
     this.SaveOrLoadAssembly(this.targetModule as AssemblyNode, options, results, errorNodes);
     return results;
 }
Ejemplo n.º 4
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);
        }
Ejemplo n.º 5
0
 public Parser(Document doc, ErrorNodeList errors)
 {
     this.doc          = doc;
     this.errors       = errors;
     this.errorHandler = new ErrorHandler(errors);
     this.scanner      = this.CreateScanner(doc, errors);
 }
Ejemplo n.º 6
0
 private void Init(){
   ErrorNodeList tempErrors = new ErrorNodeList();
   ErrorHandler tempErrorHandler = new ErrorHandler(tempErrors);
   tempTypeSystem = new TypeSystem(tempErrorHandler);
   // Here we ignore the errors generated by this temporary checker on purpose!
   tempChecker = new Checker(tempErrorHandler, tempTypeSystem, null, null, null);
   if (errorHandler == null) {
     errors = new ErrorNodeList();
     errorHandler = new ErrorHandler(errors);
   }
 }
Ejemplo n.º 7
0
 public Checker(ErrorHandler errorHandler, TypeSystem typeSystem, TrivialHashtable scopeFor, TrivialHashtable ambiguousTypes, TrivialHashtable referencedLabels)
   : base(errorHandler) {
   this.typeSystem = typeSystem;
   this.Errors = errorHandler == null ? null : errorHandler.Errors;
   this.scopeFor = scopeFor;
   this.ambiguousTypes = ambiguousTypes;
   this.referencedLabels = referencedLabels;
   this.MayNotReferenceThisFromFieldInitializer = true;
   this.allowedExceptions = new TypeNodeList();
   this.useGenerics = TargetPlatform.UseGenerics;
   this.AllowPropertiesIndexersAsRef = true;
 }
Ejemplo n.º 8
0
 void WriteOutAnyErrors()
 {
     for (int i = 0, n = this.errors == null ? 0 : this.errors.Count; i < n; i++)
     {
         ErrorNode e = this.errors[i];
         if (e != null)
         {
             Console.WriteLine(e.GetMessage());
         }
     }
     this.errors = new ErrorNodeList();
 }
Ejemplo n.º 9
0
        /// <summary>
        /// return the level of the most severe error.
        /// </summary>
        /// <param name="errors"></param>
        /// <returns></returns>
        static public int ErrorSeverity(ErrorNodeList errors)
        {
            int severity = int.MaxValue;

            for (int i = 0; i < errors.Count; i++)
            {
                ErrorNode e = errors[i];
                if (e == null)
                {
                    continue;
                }
                if (e.Severity < 0)
                {
                    continue;
                }
                severity = severity > e.Severity ? e.Severity : severity;
            }
            return(severity);
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Walks the supplied System.CodeDom.CodeCompileUnit and produces a corresponding CompilationUnit.
 /// Enters declarations into the supplied Module and errors into the supplied ErrorNodeList. 
 /// Calls back to the supplied compiler to resolve assembly references and to create appropriate documents for code snippets.
 /// </summary>
 /// <param name="compiler">Called upon to resolve assembly references and to create Documents for snippets.</param>
 /// <param name="compilationUnit">The root of the CodeDOM tree to be translated into an IR CompileUnit.</param>
 /// <param name="targetModule">The module or assembly to which the compilation unit will be compiled.</param>
 /// <param name="errorNodes">Errors in the CodeDOM tree that are found during translation are added to this list.</param>
 /// <returns></returns>
 public CompilationUnit Translate(Compiler compiler, CodeCompileUnit compilationUnit, Module targetModule, ErrorNodeList errorNodes){
   Debug.Assert(compiler != null); 
   Debug.Assert(compilationUnit != null); 
   Debug.Assert(targetModule != null); 
   Debug.Assert(errorNodes != null);
   this.compiler = compiler;
   this.errorNodes = errorNodes;
   this.targetModule = targetModule;
   CodeSnippetCompileUnit cscu = compilationUnit as CodeSnippetCompileUnit;
   CompilationUnit cunit = cscu != null ? new CompilationUnitSnippet() : new CompilationUnit();
   this.Translate(compilationUnit.AssemblyCustomAttributes, targetModule.Attributes);
   StringCollection references = compilationUnit.ReferencedAssemblies;
   if (references != null && references.Count > 0){
     AssemblyReferenceList arefs = targetModule.AssemblyReferences;
     TrivialHashtable alreadyReferencedAssemblies = new TrivialHashtable();
     for (int i = 0, n = arefs.Count; i < n; i++)
       alreadyReferencedAssemblies[arefs[i].Assembly.UniqueKey] = this;
     foreach (string rAssemblyName in references)
       compiler.AddAssemblyReferenceToModule(null, targetModule, rAssemblyName, null, errorNodes, alreadyReferencedAssemblies, false);
   }
   Namespace defaultNamespace = new Namespace(Identifier.Empty, Identifier.Empty, null, null, new NamespaceList(), null);
   NamespaceList nspaceList = defaultNamespace.NestedNamespaces;
   CodeNamespaceCollection nspaces = compilationUnit.Namespaces;
   if (nspaces != null) 
     foreach (CodeNamespace cns in nspaces) 
       nspaceList.Add(this.Translate(cns));
   if (cscu == null) return cunit;
   Document doc = null;
   if (cscu.LinePragma == null)
     doc = compiler.CreateDocument(targetModule.Name, 1, cscu.Value);
   else{
     doc = compiler.CreateDocument(cscu.LinePragma.FileName, cscu.LinePragma.LineNumber, cscu.Value);
     cunit.Name = Identifier.For(cscu.LinePragma.FileName);
   }
   cunit.SourceContext = new SourceContext(doc);
   defaultNamespace.SourceContext = cunit.SourceContext;
   return cunit;
 }
Ejemplo n.º 11
0
 public CompilationUnit ParseCompilationUnit(string source, string fname, CompilerParameters parameters, ErrorNodeList errors, AuthoringSink sink){
   Guid dummy = Parser.dummyGuid;
   Document document = new Document(fname, 1, source, dummy, dummy, dummy);
   this.errors = errors;
   this.scanner = new Scanner(document, errors, parameters as SpecSharpCompilerOptions);
   this.currentToken = Token.None;
   this.errors = errors;
   this.ProcessOptions(parameters as SpecSharpCompilerOptions);
   CompilationUnit cu = new CompilationUnit(Identifier.For(fname));
   cu.Compilation = new Compilation(this.module, new CompilationUnitList(cu), parameters, null);
   cu.SourceContext = new SourceContext(document);
   this.ParseCompilationUnit(cu, false, true, sink);//This overload is only called for intellisense, not the background error check.
   cu.PragmaWarnInformation = this.scanner.pragmaInformation;
   this.errors = null;
   this.scanner = null;
   return cu;
 }
Ejemplo n.º 12
0
        private IDebugProperty EvaluateExpression(uint evalFlags, uint timeout, IDebugContext context, String resultType)
        {
            if (this.debugContext == null)
            {
                this.debugContext = new DebugEnvironment();
            }
            this.debugContext.context = context;
            BlockScope    scope  = new DebugBlockScope(this.debugContext);
            ErrorNodeList errors = new ErrorNodeList();

            if (this.cciExpr.compiledExpression == null)
            {
                this.cciExpr.compiledExpression = (Expression)this.cciExpr.EE.ExprCompiler.CompileParseTree(this.cciExpr.ParsedExpr, scope, new Module(), errors);
                if (errors.Count > 0)
                {
                    this.cciExpr.compiledExpression = null;
                }
            }
            if (this.cciExpr.compiledExpression != null)
            {
                StackFrame         currentFrame = new StackFrame();
                IDebugMethodSymbol methodSym    = this.debugContext.context.GetContainer() as CDebugMethodSymbol;
                if (methodSym != null)
                {
                    IDebugFieldSymbol thisSymbol = methodSym.GetThis();
                    if (thisSymbol != null)
                    {
                        currentFrame.thisObject = new Literal(thisSymbol.GetValue(null), ((MethodScope )scope.BaseClass).ThisType);
                    }
                    else
                    {
                        currentFrame.thisObject = null;
                    }
                    currentFrame.parameters[0] = currentFrame.thisObject;
                    IEnumSymbol locals = methodSym.GetLocals();
                    if (locals != null)
                    {
                        for (int i = 0; ; i++)
                        {
                            if (locals.Current == null)
                            {
                                break;
                            }
                            Field localField = new DebugFieldNode(this.debugContext, locals.Current, new Identifier(locals.Current.Name), null, null, i);
                            currentFrame.locals[i] = localField.GetValue(null);
                            locals.MoveNext();
                        }
                    }
                    IEnumSymbol param = methodSym.GetParameters();
                    if (param != null)
                    {
                        for (int i = 1; ; i++)
                        {
                            if (param.Current == null)
                            {
                                break;
                            }
                            Field paramField = new DebugFieldNode(this.debugContext, param.Current, new Identifier(param.Current.Name), null, null, i);
                            currentFrame.parameters[i] = paramField.GetValue(null);
                            param.MoveNext();
                        }
                    }
                }
                if (this.cciExpr.EE.ExprEvaluator == null)
                {
                    this.cciExpr.EE.ExprEvaluator = new Evaluator();
                }
                this.cciExpr.EE.ExprEvaluator.stackFrame = currentFrame;
                Literal resultExpr = this.cciExpr.EE.ExprEvaluator.VisitExpression(this.cciExpr.compiledExpression) as Literal;
                if (resultExpr != null)
                {
                    if (resultExpr.Value is IDebugValue && resultExpr.Type is IDebugInfo) //already wrapped for use by debugger
                    {
                        return(this.cciExpr.EE.MakeProperty(this.cciExpr.Expr, ((IDebugInfo)resultExpr.Type).GetDebugType, (IDebugValue)resultExpr.Value, null));
                    }
                    else if (resultExpr.Value is IDebugValue)
                    {
                        return(this.cciExpr.EE.MakeProperty(this.cciExpr.Expr, ((IDebugValue)resultExpr.Value).RuntimeType(), (IDebugValue)resultExpr.Value, null));
                    }
                    if (resultExpr.Value != null)
                    {
                        return(new ExpressionEvalProperty(this.cciExpr.Expr, resultExpr.Type.FullName, resultExpr.Value.ToString(), resultExpr, this.cciExpr.EE));
                    }
                }
                else
                {
                    return(new ExpressionEvalProperty(this.cciExpr.Expr, String.Empty, "Error Evaluating Expression.", null, this.cciExpr.EE));
                }
            }
            else if (errors.Count > 0)
            {
                return(new ExpressionEvalProperty(this.cciExpr.Expr, String.Empty, errors[0].GetMessage(), null, this.cciExpr.EE));
            }
            return(new ExpressionEvalProperty(this.cciExpr.Expr, String.Empty, "Unknown Compiler Error.", null, this.cciExpr.EE));
        }
Ejemplo n.º 13
0
 public ErrorHandler(ErrorNodeList errors){
   Debug.Assert(errors != null);
   this.Errors = errors;
 }
Ejemplo n.º 14
0
    internal void ReportErrors(ErrorNodeList errors) {
      TextSpan firstError = new TextSpan();
      
      int errorMax = this.service.Preferences.MaxErrorMessages;
      this.taskProvider.ClearErrors();

      for (int i = 0, n = errors.Length; i < n; i++ ) {
        ErrorNode enode = errors[i];
        SourceContext ctx = enode.SourceContext;

        Severity severity = enode.Severity > 0 ? Severity.SevError : Severity.SevWarning;
        string message = enode.GetMessage(this.service.culture);
        if (message == null)  return;        
  
        //set error
        TextSpan span;
        span.iStartLine  = ctx.StartLine-1;
        span.iStartIndex = ctx.StartColumn-1;
        span.iEndLine    = ctx.EndLine-1;
        span.iEndIndex   = ctx.EndColumn-1;

        // Don't do multi-line squiggles, instead just squiggle to the
        // end of the first line.
        if (span.iEndLine > span.iStartLine) {
          span.iEndLine = span.iStartLine;
          this.textLines.GetLengthOfLine(span.iStartLine, out span.iEndIndex);
        }

        if (TextSpanHelper.TextSpanIsEmpty( firstError) && (severity > Severity.SevWarning)) {
          firstError = span;
        }

        this.taskProvider.AddTask(this.CreateErrorTaskItem(span, message, severity));
  
        //check error count
        if (i == errorMax) {
          string maxMsg = UIStrings.GetString(UIStringNames.MaxErrorsReached);
          TaskItem error = this.CreateErrorTaskItem(span, maxMsg, Severity.SevWarning);
          this.taskProvider.AddTask(error);
          break;
        }
      }
      this.taskProvider.RefreshTaskWindow();

    }
Ejemplo n.º 15
0
    private static int RunTest(string suiteName, string test, StringBuilder actualOutput, ArrayList compilerParameters, ArrayList testCaseParameters, bool xamlSuite)
    {
        Microsoft.SpecSharp.Compiler compiler = new Microsoft.SpecSharp.Compiler();
        compiler.CompileAsXaml = xamlSuite;
        CompilerOptions options = new Microsoft.SpecSharp.SpecSharpCompilerOptions();

        if (compilerParameters != null)
        {
            ErrorNodeList compilerParameterErrors = new ErrorNodeList(0);
            compiler.ParseCompilerParameters(options, (string[])compilerParameters.ToArray(typeof(string)), compilerParameterErrors, false);
            for (int i = 0, n = compilerParameterErrors.Count; i < n; i++)
            {
                ErrorNode err = compilerParameterErrors[i];
                Console.WriteLine(err.GetMessage());
            }
        }
        options.OutputAssembly     = "assembly for suite " + suiteName + " test case " + main.assemblyNameCounter++;
        options.GenerateExecutable = true;
        options.MayLockFiles       = true;
        options.GenerateInMemory   = true;
        // Code that is not marked as unsafe should be verifiable. This catches cases where the compiler generates bad IL.
        if (!options.AllowUnsafeCode)
        {
            options.Evidence = new System.Security.Policy.Evidence(new object[] { new System.Security.Policy.Zone(System.Security.SecurityZone.Internet) }, null);
        }
        CompilerResults results = compiler.CompileAssemblyFromSource(options, test);

        foreach (CompilerError e in results.Errors)
        {
            Console.Write('(');
            Console.Write(e.Line);
            Console.Write(',');
            Console.Write(e.Column);
            Console.Write("): ");
            string warningString = null;
            string errorString   = null;
            if (e.IsWarning)
            {
                if (!e.ErrorNumber.StartsWith("CS") || e.ErrorNumber.Length == 6)
                {
                    if (warningString == null)
                    {
                        warningString = compiler.GetWarningString();
                    }
                    Console.Write(warningString, e.ErrorNumber);
                }
            }
            else
            {
                if (!e.ErrorNumber.StartsWith("CS") || e.ErrorNumber.Length == 6)
                {
                    if (errorString == null)
                    {
                        errorString = compiler.GetErrorString();
                    }
                    Console.Write(errorString, e.ErrorNumber);
                }
            }
            Console.WriteLine(e.ErrorText);
        }
        if (results.NativeCompilerReturnValue != 0)
        {
            return(0);
        }
        object returnVal = null;

        try{
            if (testCaseParameters == null)
            {
                if (results.CompiledAssembly.EntryPoint.GetParameters().Length == 0)
                {
                    returnVal = results.CompiledAssembly.EntryPoint.Invoke(null, null);
                }
                else
                {
                    returnVal = results.CompiledAssembly.EntryPoint.Invoke(null, new object[] { new string[0] });
                }
            }
            else
            {
                returnVal = results.CompiledAssembly.EntryPoint.Invoke(null, new object[] { (string[])testCaseParameters.ToArray(typeof(string)) });
            }
        }catch (System.Reflection.TargetInvocationException e) {
            throw e.InnerException;
        }
        if (returnVal is int)
        {
            return((int)returnVal);
        }
        return(0);
    }
Ejemplo n.º 16
0
 public IParser CreateParser(string fileName, int lineNumber, DocumentText text, Module symbolTable, ErrorNodeList errorNodes, CompilerParameters options){
   return new XamlParserStub(errorNodes, options as CompilerOptions);
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Parses all of the CompilationUnitSnippets in the given compilation, ignoring method bodies. Then resolves all type expressions.
 /// The resulting types can be retrieved from the module in compilation.TargetModule. The base types, interfaces and 
 /// member signatures will all be resolved and on an equal footing with imported, already compiled modules and assemblies.
 /// </summary>
 public override void ConstructSymbolTable(Compilation compilation, ErrorNodeList errors){
   this.ConstructSymbolTable(compilation, errors, new TrivialHashtable());
 }
Ejemplo n.º 18
0
 public abstract CompilationUnit ParseCompilationUnit(String source, string fname, CompilerParameters parameters, ErrorNodeList errors, AuthoringSink sink);
Ejemplo n.º 19
0
 private IDebugProperty EvaluateExpression(uint evalFlags, uint timeout, IDebugContext context, String resultType){
   if (this.debugContext == null) this.debugContext = new DebugEnvironment();
   this.debugContext.context = context;  
   BlockScope scope = new DebugBlockScope(this.debugContext);
   ErrorNodeList errors = new ErrorNodeList();
   if (this.cciExpr.compiledExpression == null){
     this.cciExpr.compiledExpression = (Expression)this.cciExpr.EE.ExprCompiler.CompileParseTree(this.cciExpr.ParsedExpr, scope, new Module(), errors);
     if (errors.Count > 0)
       this.cciExpr.compiledExpression = null;
   }
   if (this.cciExpr.compiledExpression != null){
     StackFrame currentFrame = new StackFrame();
     IDebugMethodSymbol methodSym = this.debugContext.context.GetContainer() as CDebugMethodSymbol;
     if (methodSym != null){
       IDebugFieldSymbol thisSymbol = methodSym.GetThis();
       if (thisSymbol != null)
         currentFrame.thisObject = new Literal(thisSymbol.GetValue(null), ((MethodScope ) scope.BaseClass).ThisType);
       else
         currentFrame.thisObject = null;
       currentFrame.parameters[0] = currentFrame.thisObject;
       IEnumSymbol locals = methodSym.GetLocals();
       if (locals != null){
         for (int i=0; ; i++){
           if (locals.Current == null) break;
           Field localField = new DebugFieldNode(this.debugContext, locals.Current, new Identifier(locals.Current.Name), null, null, i);
           currentFrame.locals[i] = localField.GetValue(null);
           locals.MoveNext();
         }
       }
       IEnumSymbol param = methodSym.GetParameters();
       if (param != null){
         for (int i=1; ; i++){
           if (param.Current == null) break;
           Field paramField = new DebugFieldNode(this.debugContext, param.Current, new Identifier(param.Current.Name), null, null, i);
           currentFrame.parameters[i] = paramField.GetValue(null);
           param.MoveNext();
         }
       }
     }
     if (this.cciExpr.EE.ExprEvaluator == null)
       this.cciExpr.EE.ExprEvaluator = new Evaluator();
     this.cciExpr.EE.ExprEvaluator.stackFrame = currentFrame;
     Literal resultExpr = this.cciExpr.EE.ExprEvaluator.VisitExpression(this.cciExpr.compiledExpression) as Literal;
     if (resultExpr != null){
       if (resultExpr.Value is IDebugValue && resultExpr.Type is IDebugInfo) //already wrapped for use by debugger
         return this.cciExpr.EE.MakeProperty(this.cciExpr.Expr, ((IDebugInfo)resultExpr.Type).GetDebugType, (IDebugValue)resultExpr.Value, null);
       else if(resultExpr.Value is IDebugValue)
         return this.cciExpr.EE.MakeProperty(this.cciExpr.Expr, ((IDebugValue)resultExpr.Value).RuntimeType(), (IDebugValue)resultExpr.Value, null);
       if (resultExpr.Value != null)
         return new ExpressionEvalProperty(this.cciExpr.Expr, resultExpr.Type.FullName, resultExpr.Value.ToString(), resultExpr, this.cciExpr.EE);
     }
     else
       return new ExpressionEvalProperty(this.cciExpr.Expr, String.Empty, "Error Evaluating Expression.", null, this.cciExpr.EE);
   }
   else if (errors.Count > 0){
     return new ExpressionEvalProperty(this.cciExpr.Expr, String.Empty, errors[0].GetMessage(), null, this.cciExpr.EE);
   }
   return new ExpressionEvalProperty(this.cciExpr.Expr, String.Empty, "Unknown Compiler Error.", null, this.cciExpr.EE);
 }
Ejemplo n.º 20
0
 public virtual void ResolveSymbolTable(Compilation/*!*/ parsedCompilation, ErrorNodeList/*!*/ errors, out TrivialHashtable scopeFor){
   scopeFor = new TrivialHashtable();
   if (parsedCompilation == null) { Debug.Assert(false); return; }
   if (errors == null){Debug.Assert(false); return;}
   Scoper scoper = new Scoper(scopeFor);
   scoper.currentModule = parsedCompilation.TargetModule;
   scoper.VisitCompilation(parsedCompilation);
   ErrorHandler errorHandler = new ErrorHandler(errors);
   TrivialHashtable ambiguousTypes = new TrivialHashtable();
   TrivialHashtable referencedLabels = new TrivialHashtable();
   Looker looker = new Looker(null, errorHandler, scopeFor, ambiguousTypes, referencedLabels);
   // begin change by drunje
   SpecSharpCompilerOptions options = parsedCompilation.CompilerParameters as SpecSharpCompilerOptions;
   if (options != null)
     looker.AllowPointersToManagedStructures = options.AllowPointersToManagedStructures;
   // end change by drunje
   looker.currentAssembly = (looker.currentModule = parsedCompilation.TargetModule) as AssemblyNode;
   looker.VisitCompilation(parsedCompilation);
 }
Ejemplo n.º 21
0
 protected override void SaveCompilation(Compilation compilation, AssemblyNode assem, CompilerParameters options, CompilerResults results, ErrorNodeList errorNodes) {
   CompilerOptions ccioptions = options as CompilerOptions;
   if (ccioptions != null && ccioptions.EmitSourceContextsOnly) {
     SourceContextWriter.Write(compilation, assem, options);
     if (ccioptions.XMLDocFileName != null && ccioptions.XMLDocFileName.Length > 0)
       assem.WriteDocumentation(new StreamWriter(ccioptions.XMLDocFileName));
   }
   else{
     base.SaveCompilation (compilation, assem, options, results, errorNodes);
   }
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Resolves all type expressions in the given (already parsed) compilation.
 /// The base types, interfaces and member signatures will all be on an equal footing with signatures from imported, 
 /// already compiled modules and assemblies.
 /// </summary>
 public override void ResolveSymbolTable(Compilation/*!*/ parsedCompilation, ErrorNodeList/*!*/ errors){
   TrivialHashtable scopeFor;
   this.ResolveSymbolTable(parsedCompilation, errors, out scopeFor);
 }
Ejemplo n.º 23
0
 public override void ProcessErrors(CompilerParameters options, CompilerResults results, ErrorNodeList errorNodes)
 {
     if(errorNodes != null &&
       (options is SpecSharpCompilerOptions && 
       ((SpecSharpCompilerOptions)options).RunProgramVerifier))
         errorNodes.Sort(0, errorNodes.Count);  // sort the Boogie errors to make test deterministic
     base.ProcessErrors(options, results, errorNodes);
 }
Ejemplo n.º 24
0
    public virtual void ConstructSymbolTable(Compilation compilation, ErrorNodeList errors, TrivialHashtable scopeFor){
      if (compilation == null || scopeFor == null){Debug.Assert(false); return;}
      this.CurrentCompilation = compilation;
      Module symbolTable = compilation.TargetModule = this.CreateModule(compilation.CompilerParameters, errors, compilation);
      Scoper scoper = new Scoper(scopeFor);
      scoper.currentModule = symbolTable;
      ErrorHandler errorHandler = new ErrorHandler(errors);
      Looker looker = new Looker(this.GetGlobalScope(symbolTable), errorHandler, scopeFor);
      // begin change by drunje
      SpecSharpCompilerOptions options = compilation.CompilerParameters as SpecSharpCompilerOptions;
      if (options != null)
        looker.AllowPointersToManagedStructures = options.AllowPointersToManagedStructures;
      // end change by drunje
      looker.currentAssembly = (looker.currentModule = symbolTable) as AssemblyNode;
      looker.ignoreMethodBodies = true;
      Scope globalScope = compilation.GlobalScope = this.GetGlobalScope(symbolTable);

      CompilationUnitList sources = compilation.CompilationUnits;
      if (sources == null) return;
      int n = sources.Count;
      for (int i = 0; i < n; i++){
        CompilationUnitSnippet compilationUnitSnippet = sources[i] as CompilationUnitSnippet;
        if (compilationUnitSnippet == null){Debug.Assert(false); continue;}
        compilationUnitSnippet.ChangedMethod = null;
        Document doc = compilationUnitSnippet.SourceContext.Document;
        if (doc == null || doc.Text == null){Debug.Assert(false); continue;}
        IParserFactory factory = compilationUnitSnippet.ParserFactory;
        if (factory == null){Debug.Assert(false); return;}
        IParser p = factory.CreateParser(doc.Name, doc.LineNumber, doc.Text, symbolTable, errors, compilation.CompilerParameters);
        if (p is ResgenCompilerStub) continue;
        if (p == null){Debug.Assert(false); continue;}
        Parser specSharpParser = p as Parser;
        if (specSharpParser == null)
          p.ParseCompilationUnit(compilationUnitSnippet);
        else
          specSharpParser.ParseCompilationUnit(compilationUnitSnippet, true, false);
        //TODO: this following is a good idea only if the files will not be frequently reparsed from source
        //StringSourceText stringSourceText = doc.Text.TextProvider as StringSourceText;
        //if (stringSourceText != null && stringSourceText.IsSameAsFileContents)
        //  doc.Text.TextProvider = new CollectibleSourceText(doc.Name, doc.Text.Length);
        //else if (doc.Text.TextProvider != null)
        //  doc.Text.TextProvider.MakeCollectible();
      }
      CompilationUnitList compilationUnits = new CompilationUnitList();
      for (int i = 0; i < n; i++){
        CompilationUnit cUnit = sources[i];
        compilationUnits.Add(scoper.VisitCompilationUnit(cUnit));
      }
      for (int i = 0; i < n; i++){
        CompilationUnit cUnit = compilationUnits[i];
        if (cUnit == null) continue;
        looker.VisitCompilationUnit(cUnit);
      }
      //Run resolver over symbol table so that custom attributes on member signatures are known and can be used
      //to error check the the given file.
      TypeSystem typeSystem = new TypeSystem(errorHandler);
      Resolver resolver = new Resolver(errorHandler, typeSystem);
      resolver.currentAssembly = (resolver.currentModule = symbolTable) as AssemblyNode;
      for (int i = 0; i < n; i++) {
        CompilationUnit cUnit = compilationUnits[i];
        if (cUnit == null) continue;
        resolver.VisitCompilationUnit(cUnit);
      }
      this.CurrentCompilation = null;
    }
Ejemplo n.º 25
0
 public IParser CreateParser(string fileName, int lineNumber, DocumentText text, Module symbolTable, ErrorNodeList errorNodes, CompilerParameters options){
   Document document = Compiler.CreateSpecSharpDocument(fileName, lineNumber, text);
   return new Parser(document, errorNodes, symbolTable, options as SpecSharpCompilerOptions);
 }
Ejemplo n.º 26
0
 public ErrorHandler(ErrorNodeList errors)
   : base(errors){
 }
Ejemplo n.º 27
0
 public Parser(Document document, ErrorNodeList errors, Module symbolTable, SpecSharpCompilerOptions options){
   this.scanner = new Scanner(document, errors, options);
   this.ProcessOptions(options);
   this.errors = errors;
   this.module = symbolTable;
 }
Ejemplo n.º 28
0
 public ErrorHandler(ErrorNodeList errors)
 {
     Debug.Assert(errors != null);
     this.Errors = errors;
 }
Ejemplo n.º 29
0
 public XamlParserStub(ErrorNodeList errorNodes, CompilerOptions options){
   this.errorNodes = errorNodes;
   this.options = options;
 }
Ejemplo n.º 30
0
 public SnippetParser(Compiler defaultCompiler, ErrorNodeList errorNodes)
 {
     this.DefaultCompiler      = defaultCompiler;
     this.ErrorNodes           = errorNodes;
     this.CurrentStatementList = new StatementList(0);
 }
Ejemplo n.º 31
0
    static int Main(string[] args)
    {
        if (0 < args.Length && args[0] == "/break")
        {
            string[] newArgs = new string[args.Length - 1];
            Array.Copy(args, 1, newArgs, 0, newArgs.Length);
            args = newArgs;
            System.Diagnostics.Debugger.Break();
        }
        int    rc = 0;
        bool   includeStandardResponseFile = true;
        string fileName  = null;
        int    n         = args == null ? 0 : args.Length;
        bool   testsuite = false;

        for (int i = 0; i < n; i++)
        {
            string arg = args[i];
            if (arg == null || arg.Length < 1)
            {
                continue;
            }
            char ch = arg[0];
            if (ch == '/')
            {
                if (arg == "/noconfig" || arg == "/nostdlib")
                {
                    includeStandardResponseFile = false;
                }
            }
            else if (ch == '-')
            {
                if (arg == "-noconfig" || arg == "-nostdlib")
                {
                    includeStandardResponseFile = false;
                }
            }
            else if (ch != '@')
            {
                fileName = arg;
                if (BetterPath.GetExtension(fileName) == ".suite")
                {
                    testsuite = true;
                }
            }
        }
        if (includeStandardResponseFile)
        {
            int    nFiles             = 2;
            string globalPath         = Path.GetDirectoryName(typeof(object).Assembly.Location);
            string globalResponseFile = Path.Combine(globalPath, "csc.rsp");
            if (!File.Exists(globalResponseFile))
            {
                globalResponseFile = null; nFiles--;
            }
            string localPath         = Directory.GetCurrentDirectory();
            string localResponseFile = Path.Combine(localPath, "csc.rsp");
            if (!File.Exists(localResponseFile))
            {
                localResponseFile = null;
                nFiles--;
            }
            if (nFiles > 0)
            {
                string[] newArgs = new string[n + nFiles];
                int      i       = 0;
                if (globalResponseFile != null)
                {
                    newArgs[i++] = "@" + globalResponseFile;
                }
                if (localResponseFile != null)
                {
                    newArgs[i++] = "@" + localResponseFile;
                }
                for (int j = 0; j < n; j++)
                {
                    newArgs[i + j] = args[j];
                }
                args = newArgs;
            }
        }
        Microsoft.SpecSharp.SpecSharpCompilerOptions options = new Microsoft.SpecSharp.SpecSharpCompilerOptions();
        options.TempFiles          = new TempFileCollection(Directory.GetCurrentDirectory(), true);
        options.GenerateExecutable = true;
        options.MayLockFiles       = true;
        options.CompileAndExecute  = testsuite;
        ErrorNodeList errors = new ErrorNodeList(0);

        Microsoft.SpecSharp.Compiler compiler = new Microsoft.SpecSharp.Compiler();
        string[] fileNames = compiler.ParseCompilerParameters(options, args, errors);
        if (options.DisplayCommandLineHelp)
        {
            System.Resources.ResourceManager rm = new System.Resources.ResourceManager("ssc.Messages", typeof(main).Module.Assembly);
            Console.WriteLine(rm.GetString("UsageTitle", null));
            Console.WriteLine(options.GetOptionHelp());
            return(0);
        }
        if (testsuite)
        {
            // fileNames has expanded wildcards.
            bool suiteSuccess = true;
            foreach (string file in fileNames)
            {
                suiteSuccess &= main.RunSuite(file);
            }

            if (suiteSuccess)
            {
                return(0);
            }
            return(1);
        }
        string fatalErrorString = null;

        n = errors.Count;
        for (int i = 0; i < n; i++)
        {
            ErrorNode e = errors[i];
            if (e == null)
            {
                continue;
            }
            rc++;
            if (fatalErrorString == null)
            {
                fatalErrorString = compiler.GetFatalErrorString();
            }
            Console.Write(fatalErrorString, e.Code.ToString("0000"));
            Console.WriteLine(e.GetMessage());
        }
        if (rc > 0)
        {
            return(1);
        }
        switch (options.TargetPlatform)
        {
        case PlatformType.notSpecified:
            if (options.NoStandardLibrary && (options.StandardLibraryLocation == null || options.StandardLibraryLocation.Length == 0))
            {
                Microsoft.SpecSharp.TargetPlatform.SetToV2(options.TargetPlatformLocation);
            }
            break;

        case PlatformType.v1: Microsoft.SpecSharp.TargetPlatform.SetToV1(options.TargetPlatformLocation); break;

        case PlatformType.v11: Microsoft.SpecSharp.TargetPlatform.SetToV1_1(options.TargetPlatformLocation); break;

        case PlatformType.v2: Microsoft.SpecSharp.TargetPlatform.SetToV2(options.TargetPlatformLocation); break;

        default:
            if (options.TargetPlatformLocation != null) //TODO: assert not null
            {
                Microsoft.SpecSharp.TargetPlatform.SetToPostV1_1(options.TargetPlatformLocation);
            }
            break;
        }
        compiler.UpdateRuntimeAssemblyLocations(options);
        CompilerResults results;

        if (fileNames.Length == 1)
        {
            if (options.EmitManifest)
            {
                results = compiler.CompileAssemblyFromFile(options, fileNames[0], new ErrorNodeList(), true);
            }
            else
            {
                results = compiler.CompileModuleFromFile(options, fileNames[0]);
            }
        }
        else
        {
            if (options.EmitManifest)
            {
                results = compiler.CompileAssemblyFromFileBatch(options, fileNames);
            }
            else
            {
                results = compiler.CompileModuleFromFileBatch(options, fileNames);
            }
        }
        string errorString   = null;
        string warningString = null;

        foreach (CompilerError e in results.Errors)
        {
            if (e.FileName != null && e.FileName.Length > 0)
            {
                Console.Write(main.GetPath(e.FileName, options));
                Console.Write('(');
                Console.Write(e.Line);
                Console.Write(',');
                Console.Write(e.Column);
                Console.Write("): ");
            }
            if (e.IsWarning)
            {
                if (!e.ErrorNumber.StartsWith("CS") || e.ErrorNumber.Length == 6)
                {
                    if (warningString == null)
                    {
                        warningString = compiler.GetWarningString();
                    }
                    Console.Write(warningString, e.ErrorNumber);
                }
            }
            else
            {
                if (!e.ErrorNumber.StartsWith("CS") || e.ErrorNumber.Length == 6)
                {
                    rc++; //REVIEW: include related location errors?
                    if (errorString == null)
                    {
                        errorString = compiler.GetErrorString();
                    }
                    Console.Write(errorString, e.ErrorNumber);
                }
            }
            Console.WriteLine(e.ErrorText);
        }
        if (rc > 0)
        {
            return(1);
        }
        if ((rc = results.NativeCompilerReturnValue) == 0 && options.CompileAndExecute &&
            results.CompiledAssembly != null && results.CompiledAssembly.EntryPoint != null)
        {
            if (results.CompiledAssembly.EntryPoint.GetParameters().Length == 0)
            {
                results.CompiledAssembly.EntryPoint.Invoke(null, null);
            }
            else
            {
                results.CompiledAssembly.EntryPoint.Invoke(null, new object[] { new string[0] });
            }
        }
        if (rc > 0)
        {
            return(1);
        }
        return(0);
    }
Ejemplo n.º 32
0
//      public override CompilationUnitSnippet CreateCompilationUnitSnippet(string fileName, int lineNumber, DocumentText text, Compilation compilation)
//      {
//       // return new ZonnonCompilationUnit();
//          return base.CreateCompilationUnitSnippet (fileName, lineNumber, text, compilation);
//      }

        //---------------------------------------------------------------------------------

        #region FrameworkOverrides

        public override CompilerResults CompileAssemblyFromIR(Compilation compilation, ErrorNodeList errorNodes)
        {
            ((ZonnonCompilation)compilation).init();
            return(base.CompileAssemblyFromIR(compilation, errorNodes));
        }
Ejemplo n.º 33
0
 public TypeSystem(ErrorHandler errorHandler){
   this.ErrorHandler = errorHandler;
   if (errorHandler != null) this.Errors = errorHandler.Errors;
   this.useGenerics = TargetPlatform.UseGenerics;
 }
Ejemplo n.º 34
0
        // The function overrides the one from System.Compiler.Copiler class.
        // As written in the comment to the function, it
        //
        // "parses all of the CompilationUnitSnippets in the given compilation, ignoring method bodies.
        // Then resolves all type expressions.                                  ----------------------
        // The resulting types can be retrieved from the module in compilation.TargetModule.
        // The base types, interfaces and member signatures will all be resolved and on an equal footing
        // with imported, already compiled modules and assemblies."

        public override void ConstructSymbolTable(Compilation compilation, ErrorNodeList errors)
        {
            if (compilation == null)
            {
                Debug.Assert(false); return;
            }

            ((ZonnonCompilation)compilation).init(); //////////////////////////////

            // RM: We're using out own tree for all the helpers

            /*RM
             * Module symbolTable = compilation.TargetModule =
             *                     this.CreateModule(compilation.CompilerParameters, errors, compilation);
             *
             * TrivialHashtable scopeFor = new TrivialHashtable();
             * ErrorHandler eh = new ErrorHandler(errors);
             * TypeSystem typeSystem = new TypeSystem(eh);
             *
             * Scoper scoper = new Scoper(scopeFor);
             * scoper.currentModule = symbolTable;
             *
             * Looker looker = new Looker(this.GetGlobalScope(symbolTable), eh, scopeFor, typeSystem, null, null);
             * looker.currentAssembly = (looker.currentModule = symbolTable) as AssemblyNode;
             * looker.ignoreMethodBodies = true;
             *
             * Scope globalScope = compilation.GlobalScope = this.GetGlobalScope(symbolTable);
             *
             * CompilationUnitList sources = compilation.CompilationUnits;
             * if ( sources == null ) { Debug.Assert(false); return; }
             *
             * int n = sources.Length;
             * for (int i = 0; i < n; i++)
             * {
             *  CompilationUnitSnippet compilationUnitSnippet = sources[i] as CompilationUnitSnippet;
             *  if ( compilationUnitSnippet == null ) { Debug.Assert(false); continue; }
             *
             *  compilationUnitSnippet.ChangedMethod = null;
             *  Document doc = compilationUnitSnippet.SourceContext.Document;
             *  if ( doc == null || doc.Text == null ) { Debug.Assert(false); continue; }
             *
             *  IParserFactory factory = compilationUnitSnippet.ParserFactory;
             *  if ( factory == null ) { Debug.Assert(false); return; }
             *
             *  IParser p = factory.CreateParser(doc.Name,doc.LineNumber,doc.Text,
             *                                   symbolTable,errors,compilation.CompilerParameters);
             *
             *  if ( p is ResgenCompilerStub ) continue;
             *  if ( p == null ) { Debug.Assert(false); continue; }
             *
             *  p.ParseCompilationUnit(compilationUnitSnippet);
             *
             *  StringSourceText stringSourceText = doc.Text.TextProvider as StringSourceText;
             *  if ( stringSourceText != null && stringSourceText.IsSameAsFileContents )
             *      doc.Text.TextProvider = new CollectibleSourceText(doc.Name, doc.Text.Length);
             *  else if ( doc.Text.TextProvider != null )
             *      doc.Text.TextProvider.MakeCollectible();
             * }
             *
             * try
             * {
             *
             *  Parser.ConvertTree(compilation.CompilationUnits[0]);
             * }
             * catch (Exception ex)
             * {
             *  ERROR.InternalCompilerError("Compiler has experienced an exception processing the AST\n" +
             *      ex.ToString() +"\n" + ex.StackTrace);
             * }
             * ((ZonnonCompilation)compilation).init(); //////////////////////////////
             *
             * // TODO: need work here. E.g. the loops are not needed.
             * CompilationUnitList compilationUnits = new CompilationUnitList();
             * for (int i = 0; i < n; i++)
             * {
             *  CompilationUnit cUnit = sources[i];
             *  compilationUnits.Add(scoper.VisitCompilationUnit(cUnit));
             * }
             * for (int i = 0; i < n; i++)
             * {
             *  CompilationUnit cUnit = compilationUnits[i];
             *  if ( cUnit == null ) continue;
             *  looker.VisitCompilationUnit(cUnit);
             * }
             * */
        }
Ejemplo n.º 35
0
 internal virtual Scanner CreateScanner(Document doc, ErrorNodeList errors)
 {
     return(new Scanner(doc, errors));
 }
Ejemplo n.º 36
0
 public AuthoringScope ParseSource(string text, int line, int col, string fname, AuthoringSink asink, ParseReason reason){
   this.currentAst = null;
   Compilation compilation = this.GetCompilationFor(fname); 
   Debug.Assert(compilation != null, "no compilation for: "+fname);
   this.currentSymbolTable = compilation.TargetModule;
   switch (reason){
     case ParseReason.CollapsibleRegions:
     case ParseReason.CompleteWord:
     case ParseReason.MatchBraces:
     case ParseReason.HighlightBraces:
     case ParseReason.MemberSelect:
     case ParseReason.MemberSelectExplicit:
     case ParseReason.MethodTip: 
     case ParseReason.QuickInfo:
     case ParseReason.Autos:{
       return this.ParsePartialCompilationUnit(fname, text, line, col, asink, reason);
     }
     case ParseReason.Check:{
       ErrorNodeList errors = new ErrorNodeList();
       this.ParseAndAnalyzeCompilationUnit(fname, text, line, col, errors, compilation, asink);
       this.ReportErrors(fname, errors, asink);
       return this.GetAuthoringScope();
     }
   }
   return null;
 }
Ejemplo n.º 37
0
 public SnippetParser(IParserFactory/*!*/ defaultParserFactory, Module symbolTable, ErrorNodeList errorNodes, CompilerParameters options) {
   this.DefaultParserFactory = defaultParserFactory;
   this.ErrorNodes = errorNodes;
   this.SymbolTable = symbolTable;
   this.Options = options;
   this.CurrentStatementList = new StatementList(0);
   //^ base();
 }
Ejemplo n.º 38
0
 public virtual void ReportErrors(string fileName, ErrorNodeList errors, AuthoringSink sink){
   if (sink == null) return;
   for (int n = errors.Count, i = n-1; i >= 0; i--){ //Scan backwards so that early errors trump later errors
     ErrorNode enode = errors[i];
     if (enode == null || enode.Severity < 0) continue;
     //TODO: suppress warnings of level > set in options
     SourceContext context = enode.SourceContext;
     if (context.Document == null) continue;
     if (context.Document.Name != fileName) continue;
     sink.AddError(enode);
   }
 }
Ejemplo n.º 39
0
        public override void CompileParseTree(Compilation compilation, ErrorNodeList errorNodes)
        {
            if (compilation == null)
            {
                Debug.Assert(false, "wrong compilation"); return;
            }
            CONTEXT.useComputeMath = ((ZonnonCompilerParameters)compilation.CompilerParameters).UseComputeMath;
            // Before the actual back-end compilation takes place,
            // we perform the Zonnon-tree to CCI-tree conversion.
            // Notice that we do that for the overall tree (i.e., for all sources)
            // and store the resulting CCI tree to CompilationUnits[0],
            // but do not spread subtrees to corresponding CompilationUnits.
            ERROR.errCount = 0;
            Parser.ConvertTree(compilation.CompilationUnits[0]);
            bool mainCompilationFailed = ERROR.errCount > 0;

            //    ERROR.EndOfMessages();

            //  Module symbolTable = compilation.TargetModule;
            //  compilation.GlobalScope = this.GetGlobalScope(symbolTable);

            ZonnonCompilerParameters options = compilation.CompilerParameters as ZonnonCompilerParameters;

            if (options == null)
            {
                options = new ZonnonCompilerParameters();
            }
            // Walk IR looking up names
#if DEBUG
            if (options.Debug)
            {
                System.Console.Write("Scoper is working...");
            }
#endif
            ErrorHandler     eh               = new ErrorHandler(errorNodes);
            TrivialHashtable ambiguousTypes   = new TrivialHashtable();
            TrivialHashtable referencedLabels = new TrivialHashtable();
            TrivialHashtable scopeFor         = new TrivialHashtable();
            TypeSystem       typeSystem       = new TypeSystem(eh);

            Scoper scoper = new Scoper(scopeFor);
            scoper.VisitCompilation(compilation);
#if DEBUG
            if (options.Debug)
            {
                System.Console.WriteLine("Done.");
                System.Console.Write("Looker is working... ");
            }
#endif
            Looker looker = new Looker(compilation.GlobalScope, eh, scopeFor, typeSystem, ambiguousTypes, referencedLabels);
            looker.VisitCompilation(compilation);

            // Walk IR inferring types and resolving overloads
            if (!mainCompilationFailed) // Resolve only if no errors
            {
                Resolver resolver = new Resolver(eh, typeSystem);
                resolver.VisitCompilation(compilation);

                // Walk IR checking for semantic errors and repairing it so that it the next walk will work
                Checker checker = new Checker(eh, typeSystem, ambiguousTypes, referencedLabels);
                checker.VisitCompilation(compilation);

                // Walk IR reducing it to nodes that have predefined mappings to MD+IL
                Normalizer normalizer = new Normalizer(typeSystem);
                normalizer.VisitCompilation(compilation);

                Analyzer analyzer = new Analyzer(typeSystem, compilation);
                analyzer.VisitCompilation(compilation);
            }
#if DEBUG
            if (options.Debug)
            {
                System.Console.WriteLine("Done.");
            }
#endif
        }
Ejemplo n.º 40
0
 public abstract void ParseAndAnalyzeCompilationUnit(string fname, string source, int line, int col, ErrorNodeList errors, Compilation compilation, AuthoringSink sink);
Ejemplo n.º 41
0
        public override IParser CreateParser(string fileName, int lineNumber, DocumentText text, Module symbolTable, ErrorNodeList errors, CompilerParameters options)
        {
            //       Document document = this.CreateDocument(fileName, lineNumber, text);
            //       return new Parser(symbolTable, document, errorNodes);
            //
            Document document = this.CreateDocument(fileName, lineNumber, text);
            Parser   parser   = new Parser(document, errors, symbolTable, options as ZonnonCompilerParameters);

            //Parser.debug  = options is ZonnonCompilerParameters ? ((ZonnonCompilerParameters)options).Debug  : false;
            //Parser.debugT = options is ZonnonCompilerParameters ? ((ZonnonCompilerParameters)options).DebugT : false;
            return(parser);
        }
Ejemplo n.º 42
0
 public abstract CompilationUnit ParseCompilationUnit(string fname, string source, ErrorNodeList errors, Compilation compilation, AuthoringSink sink);
Ejemplo n.º 43
0
 internal Class CreateSerializerFor(TypeNode type, ErrorHandler errorHandler) {
   this.errorHandler = errorHandler;
   this.errors = errorHandler.Errors;
   return CreateSerializerFor(type);
 }
Ejemplo n.º 44
0
 void WriteOutAnyErrors(){
   for (int i = 0, n = this.errors == null ? 0 : this.errors.Count; i < n; i++){
     ErrorNode e = this.errors[i];
     if (e != null)
       Console.WriteLine(e.GetMessage());
   }
   this.errors = new ErrorNodeList();
 }
Ejemplo n.º 45
0
    public Type GetSerializer(XmlSerializer caller, Type t, ref string rootName, ref string rootNamespace) {
      // start again with clean error list - do NOT return errors from the temporary checker.
      errors = new ErrorNodeList();
      errorHandler = new ErrorHandler(errors);

      TypeNode type = TypeNode.GetTypeNode(t);

      string nspace = GetSerializerNamespace(type);
      string serializerClassName = GetSerializerName(type);
      string fullName = nspace + ((nspace != "" && nspace != null) ? "." : "") + serializerClassName;

      // Structural types have no container element name.
      if (!IsStructuralType(type) && !(type is EnumNode)) {
        if (rootName == null) {
          Identifier name = Checker.GetDefaultElementName(type);
          rootName = name.Name;
          if (rootNamespace == null && name.Prefix != null) {
            rootNamespace = name.Prefix.Name;
          }
        }
      }
     
      if (caller.GetType().FullName == fullName)
        return caller.GetType();


      AssemblyNode assembly = AssemblyNode.GetAssembly(t.Assembly, cache, false, true);

      // see if we can find a serializer in the same assembly as the given type.
      TypeNode serializerType = assembly.GetType(Identifier.For(nspace), Identifier.For(serializerClassName));
      if (serializerType != null) {
        Type result = serializerType.GetRuntimeType();
        Debug.Assert(result != null, "GetRuntimeType() failed on " + serializerType.FullName);
        return result;
      }

      System.Reflection.Assembly sasm = (System.Reflection.Assembly)genCache[t];
      if (sasm == null) {
        ComegaCompilerOptions options = new ComegaCompilerOptions();
        options.OutputAssembly = type.Name +  "Serializer.dll";
        options.GenerateExecutable = false;
        options.ModuleKind = ModuleKindFlags.DynamicallyLinkedLibrary;
        if (DumpOption == null) {
          DumpOption = System.Environment.GetEnvironmentVariable("DEBUG_SERIALIZER");
          if (DumpOption == null) DumpOption = "";
        }
        options.GenerateInMemory = (DumpOption == "");
        options.DumpTree = (DumpOption != "");
        options.IncludeDebugInformation = (DumpOption != "");
        options.TempFiles = new TempFileCollection(Directory.GetCurrentDirectory(), true);
        string writerAssembly = typeof(XmlSerializationWriter).Assembly.Location;
        options.ReferencedAssemblies.Add(writerAssembly);
        string xmlAssembly = typeof(XmlTextReader).Assembly.Location;
        options.ReferencedAssemblies.Add(xmlAssembly);

        Compiler compiler = new Compiler();
        Module module = compiler.CreateModule(options, errors);
        CompilationUnit cu = CreateCompilationUnit(module, type);
        // so we can find all the structural types already defined in the assembly 
        // associated with the type we are building the serializer for.
        cu.TargetModule.AssemblyReferences.Add(new AssemblyReference(assembly));

        CompilerResults results = compiler.CompileAssemblyFromIR(options, cu, errors);

        if (errors.Length > 0) {
          throw new XmlSerializerException(errors[0].GetMessage());
        } else if (results.Errors.Count>0) {
          throw new XmlSerializerException(results.Errors[0].ErrorText);
        } else {
          sasm = results.CompiledAssembly;
          if (sasm == null) 
            throw new XmlSerializerException(RuntimeError.SerializationAssembly);
          genCache[t] = sasm;
        }
      }

      Type instanceType = sasm.GetType(fullName, false, false);
      if (instanceType == null) 
        throw new XmlSerializerException(RuntimeError.SerializationClass, fullName);

      return instanceType;

    }
Ejemplo n.º 46
0
 public XmlDocument Compile(string text, ErrorNodeList errors)
 {
   return new Parser(new Document("InMemoryString", new DocumentText(text)), errors).ParseDocument();
 }