Пример #1
0
        private static string GetSeverityString(int severity)
        {
            // From jscriptexception.js:
            //
            //guide: 0 == there will be a run-time error if this code executes
            //       1 == the programmer probably did not intend to do this
            //       2 == this can lead to problems in the future.
            //       3 == this can lead to performance problems
            //       4 == this is just not right
            switch (severity)
            {
            case 0:
                return(StringMgr.GetString("Severity0"));

            case 1:
                return(StringMgr.GetString("Severity1"));

            case 2:
                return(StringMgr.GetString("Severity2"));

            case 3:
                return(StringMgr.GetString("Severity3"));

            case 4:
                return(StringMgr.GetString("Severity4"));

            default:
                return(StringMgr.GetString("SeverityUnknown", severity));
            }
        }
Пример #2
0
        // NAME [SCOPE TYPE] [crunched to CRUNCH]
        //
        // SCOPE: global, local, outer, ''
        // TYPE: var, function, argument, arguments array, possibly undefined
        private void WriteMemberReport(JSVariableField variableField, ActivationObject immediateScope)
        {
            // skip any *unreferenced* named-function-expression fields
            JSNamedFunctionExpressionField namedFuncExpr = variableField as JSNamedFunctionExpressionField;

            if (namedFuncExpr == null || namedFuncExpr.RefCount > 0 || !m_removeFunctionExpressionNames)
            {
                string scope    = string.Empty;
                string type     = string.Empty;
                string crunched = string.Empty;
                string name     = variableField.Name;
                if (variableField.IsLiteral)
                {
                    name = variableField.FieldValue.ToString();
                }

                // calculate the crunched label
                JSLocalField localField = variableField as JSLocalField;
                if (localField != null)
                {
                    if (localField.CrunchedName != null)
                    {
                        crunched = StringMgr.GetString("CrunchedTo", localField.CrunchedName, localField.RefCount);
                    }
                }

                // get the field's default scope and type
                GetFieldScopeType(variableField, immediateScope, out scope, out type);
                if (variableField is JSWithField)
                {
                    // if the field is a with field, we won't be using the crunched field (since
                    // those fields can't be crunched), so let's overload it with what the field
                    // could POSSIBLY be if the with object doesn't have a property of that name
                    string outerScope;
                    string outerType;
                    GetFieldScopeType(variableField.OuterField, immediateScope, out outerScope, out outerType);
                    crunched = StringMgr.GetString("MemberInfoWithPossibly", outerScope, outerType);
                }

                // format the entire string
                WriteProgress(StringMgr.GetString(
                                  "MemberInfoFormat",
                                  name,
                                  scope,
                                  type,
                                  crunched
                                  ));
            }
        }
Пример #3
0
 protected JScriptException(SerializationInfo info, StreamingContext context)
     : base(info, context)
 {
     if (info == null)
     {
         throw new ArgumentException(StringMgr.GetString("InternalCompilerError"));
     }
     m_code        = HResult = info.GetInt32("Code");
     m_valueObject = info.GetValue("Value", typeof(System.Object));
     if (m_valueObject == null)
     {
         m_valueObject = Missing.Value;
     }
     m_isError = info.GetBoolean("IsError");
 }
Пример #4
0
        /// <summary>
        /// Prepare the unknwon surrogate pair for encoding
        /// </summary>
        /// <param name="unknownCharHigh">high surrogate pair character</param>
        /// <param name="unknownCharLow">low surrogate pair character</param>
        /// <param name="index">index of character in the stream</param>
        /// <returns></returns>
        public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)
        {
            // if we're not done with the current buffer, we're being recursive.
            if (m_position < m_fallbackString.Length)
            {
                throw new ArgumentException(StringMgr.GetString("FallbackEncodingFailed"));
            }

            // get the fallback string
            m_fallbackString = GetEncoding((int)charUnknownHigh) + GetEncoding((int)charUnknownLow);
            m_position       = 0;

            // return false if we have no string, indicating we didn't encode it
            return(m_fallbackString.Length > 0);
        }
Пример #5
0
        private void WriteScopeReport(FunctionObject funcObj, ActivationObject scope)
        {
            // output the function header
            if (scope is GlobalScope)
            {
                WriteProgress(StringMgr.GetString("GlobalObjectsHeader"));
            }
            else
            {
                FunctionScope functionScope = scope as FunctionScope;
                if (functionScope != null && funcObj != null)
                {
                    WriteFunctionHeader(funcObj, scope.IsKnownAtCompileTime);
                }
                else
                {
                    BlockScope blockScope = scope as BlockScope;
                    if (blockScope is CatchScope)
                    {
                        WriteBlockHeader(blockScope, StringMgr.GetString("BlockTypeCatch"));
                    }
                    else if (blockScope is WithScope)
                    {
                        WriteBlockHeader(blockScope, StringMgr.GetString("BlockTypeWith"));
                    }
                    else
                    {
                        WriteProgress();
                        WriteProgress(StringMgr.GetString("UnknownScopeType", scope.GetType().ToString()));
                    }
                }
            }

            // get all the fields in the scope
            JSVariableField[] scopeFields = scope.GetFields();
            // sort the fields
            Array.Sort(scopeFields, FieldComparer.Instance);

            // iterate over all the fields
            foreach (JSVariableField variableField in scopeFields)
            {
                // don't report placeholder fields
                if (!variableField.IsPlaceholder)
                {
                    WriteMemberReport(variableField, scope);
                }
            }
        }
Пример #6
0
        private void WriteUnrefedReport()
        {
            if (m_undefined != null && m_undefined.Count > 0)
            {
                // sort the undefined reference exceptions
                m_undefined.Sort(UndefinedComparer.Instance);

                // write the report
                WriteProgress();
                WriteProgress(StringMgr.GetString("UndefinedGlobalHeader"));
                foreach (UndefinedReferenceException ex in m_undefined)
                {
                    WriteProgress(StringMgr.GetString(
                                      "UndefinedInfo",
                                      ex.Name,
                                      ex.Line,
                                      ex.Column,
                                      ex.ReferenceType.ToString()
                                      ));
                }
            }
        }
Пример #7
0
        private void WriteBlockHeader(BlockScope blockScope, string blockType)
        {
            string knownMarker = string.Empty;

            if (!blockScope.IsKnownAtCompileTime)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append('[');
                sb.Append(StringMgr.GetString("NotKnown"));
                sb.Append(']');
                knownMarker = sb.ToString();
            }

            WriteProgress();
            WriteProgress(StringMgr.GetString(
                              "BlockScopeHeader",
                              blockType,
                              blockScope.Context.StartLineNumber,
                              blockScope.Context.StartColumn,
                              knownMarker
                              ));
        }
Пример #8
0
        private int ProcessCssFile(string sourceFileName, ResourceStrings resourceStrings, StringBuilder outputBuilder, ref long sourceLength)
        {
            int retVal = 0;

            try
            {
                // read our chunk of code
                string source;
                if (sourceFileName.Length > 0)
                {
                    using (StreamReader reader = new StreamReader(sourceFileName, m_encodingInput))
                    {
                        WriteProgress(
                            StringMgr.GetString("CrunchingFile", Path.GetFileName(sourceFileName))
                            );
                        source = reader.ReadToEnd();
                    }

                    // add the actual file length in to the input source length
                    FileInfo inputFileInfo = new FileInfo(sourceFileName);
                    sourceLength += inputFileInfo.Length;
                }
                else
                {
                    WriteProgress(StringMgr.GetString("CrunchingStdIn"));
                    try
                    {
                        // try setting the input encoding
                        Console.InputEncoding = m_encodingInput;
                    }
                    catch (IOException e)
                    {
                        // error setting the encoding input; just use whatever the default is
                        Debug.WriteLine(e.ToString());
                    }
                    source = Console.In.ReadToEnd();

                    if (m_analyze)
                    {
                        // calculate the actual number of bytes read using the input encoding
                        // and the string that we just read and
                        // add the number of bytes read into the input length.
                        sourceLength += Console.InputEncoding.GetByteCount(source);
                    }
                    else
                    {
                        // don't bother calculating the actual bytes -- the number of characters
                        // is sufficient if we're not doing the analysis
                        sourceLength += source.Length;
                    }
                }

                // process input source...
                CssParser parser = new CssParser();
                parser.CssError   += new EventHandler <CssErrorEventArgs>(OnCssError);
                parser.FileContext = sourceFileName;

                parser.Settings.CommentMode               = m_cssComments;
                parser.Settings.ExpandOutput              = m_prettyPrint;
                parser.Settings.IndentSpaces              = m_indentSize;
                parser.Settings.Severity                  = m_warningLevel;
                parser.Settings.TermSemicolons            = m_terminateWithSemicolon;
                parser.Settings.ColorNames                = m_colorNames;
                parser.Settings.MinifyExpressions         = m_minifyExpressions;
                parser.Settings.AllowEmbeddedAspNetBlocks = m_allowAspNet;
                parser.ValueReplacements                  = resourceStrings;

                // if the kill switch was set to 1 (don't preserve important comments), then
                // we just want to set the comment mode to none, regardless of what the actual comment
                // mode may be.
                if ((m_killSwitch & 1) != 0)
                {
                    parser.Settings.CommentMode = CssComment.None;
                }

                // crunch the source and output to the string builder we were passed
                string crunchedStyles = parser.Parse(source);
                if (crunchedStyles != null)
                {
                    Debug.WriteLine(crunchedStyles);
                }
                else
                {
                    // there was an error and no output was generated
                    retVal = 1;
                }

                if (m_echoInput)
                {
                    // just echo the input to the output
                    outputBuilder.Append(source);
                }
                else if (!string.IsNullOrEmpty(crunchedStyles))
                {
                    // send the crunched styles to the output
                    outputBuilder.Append(crunchedStyles);
                }
            }
            catch (IOException e)
            {
                // probably an error with the input file
                retVal = 1;
                System.Diagnostics.Debug.WriteLine(e.ToString());
                WriteError(CreateBuildError(
                               null,
                               null,
                               true,
                               "JS-IO",
                               e.Message
                               ));
            }

            return(retVal);
        }
Пример #9
0
        private static void GetFieldScopeType(JSVariableField variableField, ActivationObject immediateScope, out string scope, out string type)
        {
            JSLocalField      localField                 = variableField as JSLocalField;
            JSPredefinedField predefinedField            = variableField as JSPredefinedField;
            JSNamedFunctionExpressionField namedFuncExpr = variableField as JSNamedFunctionExpressionField;

            // default scope is blank
            scope = string.Empty;

            if (variableField is JSArgumentField)
            {
                type = StringMgr.GetString("MemberInfoTypeArgument");
            }
            else if (variableField is JSArgumentsField)
            {
                type = StringMgr.GetString("MemberInfoTypeArguments");
            }
            else if (predefinedField != null)
            {
                switch (predefinedField.GlobalObject)
                {
                case GlobalObjectInstance.GlobalObject:
                    scope = StringMgr.GetString("MemberInfoScopeGlobalObject");
                    break;

                case GlobalObjectInstance.WindowObject:
                    scope = StringMgr.GetString("MemberInfoScopeWindowObject");
                    break;

                case GlobalObjectInstance.Other:
                    scope = StringMgr.GetString("MemberInfoScopeOtherObject");
                    break;
                }
                switch (predefinedField.MemberType)
                {
                case MemberTypes.Method:
                    type = StringMgr.GetString("MemberInfoBuiltInMethod");
                    break;

                case MemberTypes.Property:
                    type = StringMgr.GetString("MemberInfoBuiltInProperty");
                    break;

                default:
                    type = StringMgr.GetString("MemberInfoBuiltInObject");
                    break;
                }
            }
            else if (variableField is JSGlobalField)
            {
                if ((variableField.Attributes & FieldAttributes.RTSpecialName) == FieldAttributes.RTSpecialName)
                {
                    // this is a special "global." It might not be a global, but something referenced
                    // in a with scope somewhere down the line.
                    type = StringMgr.GetString("MemberInfoPossiblyUndefined");
                }
                else if (variableField.FieldValue is FunctionObject)
                {
                    if (variableField.NamedFunctionExpression == null)
                    {
                        type = StringMgr.GetString("MemberInfoGlobalFunction");
                    }
                    else
                    {
                        type = StringMgr.GetString("MemberInfoFunctionExpression");
                    }
                }
                else
                {
                    type = StringMgr.GetString("MemberInfoGlobalVar");
                }
            }
            else if (variableField is JSWithField)
            {
                type = StringMgr.GetString("MemberInfoWithField");
            }
            else if (namedFuncExpr != null)
            {
                type = StringMgr.GetString("MemberInfoSelfFuncExpr");
            }
            else if (localField != null)
            {
                // type string
                if (localField.FieldValue is FunctionObject)
                {
                    if (localField.NamedFunctionExpression == null)
                    {
                        type = StringMgr.GetString("MemberInfoLocalFunction");
                    }
                    else
                    {
                        type = StringMgr.GetString("MemberInfoFunctionExpression");
                    }
                }
                else if (localField.IsLiteral)
                {
                    type = StringMgr.GetString("MemberInfoLocalLiteral");
                }
                else
                {
                    type = StringMgr.GetString("MemberInfoLocalVar");
                }

                // scope string
                // this is a local variable, so there MUST be a non-null function scope passed
                // to us. That function scope will be the scope we are expecting local variables
                // to be defined in. If the field is defined in that scope, it's local -- otherwise
                // it must be an outer variable.
                JSVariableField scopeField = immediateScope[variableField.Name];
                if (scopeField == null || scopeField.OuterField != null)
                {
                    scope = StringMgr.GetString("MemberInfoScopeOuter");
                }
                else
                {
                    scope = StringMgr.GetString("MemberInfoScopeLocal");
                }
            }
            else
            {
                type = StringMgr.GetString("MemberInfoBuiltInObject");
            }
        }
Пример #10
0
        //TYPE "NAME" - Starts at line LINE, col COLUMN STATUS [crunched to CRUNCH]
        //
        //TYPE: Function, Function getter, Function setter
        //STATUS: '', Unknown, Unreachable
        private void WriteFunctionHeader(FunctionObject funcObj, bool isKnown)
        {
            // get the crunched value (if any)
            string       crunched   = string.Empty;
            JSLocalField localField = funcObj.LocalField as JSLocalField;

            if (localField != null && localField.CrunchedName != null)
            {
                crunched = StringMgr.GetString("CrunchedTo", localField.CrunchedName, localField.RefCount);
            }

            // get the status if the function
            StringBuilder statusBuilder = new StringBuilder();

            if (!isKnown)
            {
                statusBuilder.Append('[');
                statusBuilder.Append(StringMgr.GetString("NotKnown"));
            }
            if (funcObj.FunctionScope.Parent is GlobalScope)
            {
                // global function.
                // if this is a named function expression, we still want to know if it's
                // referenced by anyone
                if (funcObj.FunctionType == FunctionType.Expression &&
                    !string.IsNullOrEmpty(funcObj.Name))
                {
                    // output a comma separator if not the first item, otherwise
                    // open the square bracket
                    if (statusBuilder.Length > 0)
                    {
                        statusBuilder.Append(", ");
                    }
                    else
                    {
                        statusBuilder.Append('[');
                    }
                    statusBuilder.Append(StringMgr.GetString(
                                             "FunctionInfoReferences",
                                             funcObj.RefCount
                                             ));
                }
            }
            else if (!funcObj.FunctionScope.IsReferenced(null))
            {
                // local function that isn't referenced -- unreachable!
                // output a comma separator if not the first item, otherwise
                // open the square bracket
                if (statusBuilder.Length > 0)
                {
                    statusBuilder.Append(", ");
                }
                else
                {
                    statusBuilder.Append('[');
                }
                statusBuilder.Append(StringMgr.GetString("Unreachable"));
            }
            if (statusBuilder.Length > 0)
            {
                statusBuilder.Append(']');
            }
            string status = statusBuilder.ToString();

            string functionType;

            switch (funcObj.FunctionType)
            {
            case FunctionType.Getter:
                functionType = "FunctionTypePropGet";
                break;

            case FunctionType.Setter:
                functionType = "FunctionTypePropSet";
                break;

            case FunctionType.Expression:
                functionType = "FunctionTypeExpression";
                break;

            default:
                functionType = "FunctionTypeFunction";
                break;
            }

            // output
            WriteProgress();
            WriteProgress(StringMgr.GetString(
                              "FunctionHeader",
                              StringMgr.GetString(functionType),
                              funcObj.Name,
                              funcObj.Context.StartLineNumber,
                              funcObj.Context.StartColumn,
                              status,
                              crunched
                              ));
        }
Пример #11
0
        private bool m_preprocessOnly; // = false;

        #endregion

        #region file processing

        private int ProcessJSFile(string sourceFileName, ResourceStrings resourceStrings, StringBuilder outputBuilder, ref bool lastEndedSemicolon, ref long sourceLength)
        {
            int retVal = 0;

            // read our chunk of code
            string source;

            if (sourceFileName.Length > 0)
            {
                using (StreamReader reader = new StreamReader(sourceFileName, m_encodingInput))
                {
                    WriteProgress(
                        StringMgr.GetString("CrunchingFile", Path.GetFileName(sourceFileName))
                        );
                    source = reader.ReadToEnd();
                }
            }
            else
            {
                WriteProgress(StringMgr.GetString("CrunchingStdIn"));
                try
                {
                    // try setting the input encoding
                    Console.InputEncoding = m_encodingInput;
                }
                catch (IOException e)
                {
                    // error setting the encoding input; just use whatever the default is
                    Debug.WriteLine(e.ToString());
                }
                source = Console.In.ReadToEnd();

                if (m_analyze)
                {
                    // calculate the actual number of bytes read using the input encoding
                    // and the string that we just read and
                    // add the number of bytes read into the input length.
                    sourceLength += Console.InputEncoding.GetByteCount(source);
                }
                else
                {
                    // don't bother calculating the actual bytes -- the number of characters
                    // is sufficient if we're not doing the analysis
                    sourceLength += source.Length;
                }
            }

            // add the input length to the running total
            sourceLength += source.Length;

            // create the a parser object for our chunk of code
            JSParser parser = new JSParser(source);

            // set up the file context for the parser
            parser.FileContext = sourceFileName;

            // hook the engine events
            parser.CompilerError      += OnCompilerError;
            parser.UndefinedReference += OnUndefinedReference;

            // put the resource strings object into the parser
            parser.ResourceStrings = resourceStrings;

            // set our flags
            CodeSettings settings = new CodeSettings();

            settings.ManualRenamesProperties  = m_renameProperties;
            settings.CollapseToLiteral        = m_collapseToLiteral;
            settings.CombineDuplicateLiterals = m_combineDuplicateLiterals;
            settings.EvalLiteralExpressions   = m_evalLiteralExpressions;
            settings.EvalTreatment            = m_evalTreatment;
            settings.IndentSize                    = m_indentSize;
            settings.InlineSafeStrings             = m_safeForInline;
            settings.LocalRenaming                 = m_localRenaming;
            settings.MacSafariQuirks               = m_macSafariQuirks;
            settings.OutputMode                    = (m_prettyPrint ? OutputMode.MultipleLines : OutputMode.SingleLine);
            settings.PreserveFunctionNames         = m_preserveFunctionNames;
            settings.RemoveFunctionExpressionNames = m_removeFunctionExpressionNames;
            settings.RemoveUnneededCode            = m_removeUnneededCode;
            settings.StripDebugStatements          = m_stripDebugStatements;
            settings.AllowEmbeddedAspNetBlocks     = m_allowAspNet;
            settings.SetKnownGlobalNames(m_globals == null ? null : m_globals.ToArray());
            settings.SetNoAutoRename(m_noAutoRename == null ? null : m_noAutoRename.ToArray());
            settings.IgnoreConditionalCompilation = m_ignoreConditionalCompilation;

            // if there are defined preprocessor names
            if (m_defines != null && m_defines.Count > 0)
            {
                // set the list of defined names to our array of names
                settings.SetPreprocessorDefines(m_defines.ToArray());
            }

            // if there are rename entries...
            if (m_renameMap != null && m_renameMap.Count > 0)
            {
                // add each of them to the parser
                foreach (var sourceName in m_renameMap.Keys)
                {
                    settings.AddRenamePair(sourceName, m_renameMap[sourceName]);
                }
            }

            // cast the kill switch numeric value to the appropriate TreeModifications enumeration
            settings.KillSwitch = (TreeModifications)m_killSwitch;

            string resultingCode = null;

            if (m_preprocessOnly)
            {
                // we only want to preprocess the code. Call that api on the parser
                resultingCode = parser.PreprocessOnly(settings);
            }
            else
            {
                Block scriptBlock = parser.Parse(settings);
                if (scriptBlock != null)
                {
                    if (m_analyze)
                    {
                        // output our report
                        CreateReport(parser.GlobalScope);
                    }

                    // crunch the output and write it to debug stream
                    resultingCode = scriptBlock.ToCode();
                }
                else
                {
                    // no code?
                    WriteProgress(StringMgr.GetString("NoParsedCode"));
                }
            }

            if (!string.IsNullOrEmpty(resultingCode))
            {
                // always output the crunched code to debug stream
                System.Diagnostics.Debug.WriteLine(resultingCode);

                // if the last block of code didn't end in a semi-colon,
                // then we need to add one now
                if (!lastEndedSemicolon)
                {
                    outputBuilder.Append(';');
                }

                // we'll output either the crunched code (normal) or
                // the raw source if we're just echoing the input
                string outputCode = (m_echoInput ? source : resultingCode);

                // send the output code to the output stream
                outputBuilder.Append(outputCode);

                // check if this string ended in a semi-colon so we'll know if
                // we need to add one between this code and the next block (if any)
                lastEndedSemicolon = (outputCode[outputCode.Length - 1] == ';');
            }
            else
            {
                // resulting code is null or empty
                Debug.WriteLine(StringMgr.GetString("OutputEmpty"));
            }

            return(retVal);
        }
Пример #12
0
        private static string GetLocalizedMsg()
        {
            string code = ((int)JSError.SyntaxError).ToString(CultureInfo.InvariantCulture);

            return(StringMgr.GetString(code));
        }