/// <summary> /// Helper method to mark an error in the UI. /// </summary> /// <param name="id">ID of the error to mark. Used for marking in the CAML textbox.</param> /// <param name="error">Error object of the error to mark. Used for marking in the LINQ expression textbox.</param> /// <param name="selected">Indicates whether the error is currently selected or not.</param> private void MarkError(int id, ParseError error, bool selected) { // // Select the expression part indicated by the error and mark it. // txtLinq.Select(error.StartIndex, error.EndIndex - error.StartIndex + 1); txtLinq.SelectionColor = Color.Red; if (selected) { txtLinq.SelectionFont = new Font(txtLinq.SelectionFont, FontStyle.Underline); } // // Locate the ParseError placeholder in the CAML query and mark it. // string tag = "<ParseError ID=\"" + id + "\" />"; int iCaml = txtCaml.Text.IndexOf(tag, StringComparison.Ordinal); if (iCaml >= 0) { txtCaml.Select(iCaml, tag.Length); txtCaml.SelectionColor = Color.Red; if (selected) { txtCaml.SelectionFont = new Font(txtCaml.SelectionFont, FontStyle.Underline); } else { _camlPositions.Add(id, new Position() { Start = iCaml, End = iCaml + tag.Length - 1 }); } } }
public override int GetHashCode() { int hash = 1; if (resultCase_ == ResultOneofCase.ParseError) { hash ^= ParseError.GetHashCode(); } if (resultCase_ == ResultOneofCase.SerializeError) { hash ^= SerializeError.GetHashCode(); } if (resultCase_ == ResultOneofCase.RuntimeError) { hash ^= RuntimeError.GetHashCode(); } if (resultCase_ == ResultOneofCase.ProtobufPayload) { hash ^= ProtobufPayload.GetHashCode(); } if (resultCase_ == ResultOneofCase.JsonPayload) { hash ^= JsonPayload.GetHashCode(); } if (resultCase_ == ResultOneofCase.Skipped) { hash ^= Skipped.GetHashCode(); } hash ^= (int)resultCase_; return(hash); }
private List <FlashElement> GetFlashElementsNoArguents(Runtime.Structures.Units.Function function, SourceLineInstruction line, out ParseError error) { Integer currentInstructionProgramIndex = (Integer)function.CompileCache.InstructionIndex++; var result = new List <FlashElement>(); error = null; if (line.Instruction.ParameterCount != 0) { error = new ParseError( ParseErrorType.Syntax_Instruction_WrongParameterCount, line.LineIndex, (line.Comment != null ? line.Comment.Length : 0) + line.Instruction.NameString.Length, line.FileName); return(null); } if (!string.IsNullOrEmpty(line.Label)) { RegisterConstant(function, line.Label, (ulong)currentInstructionProgramIndex); } result.Add(new FlashElementInstruction(line.Instruction, null, currentInstructionProgramIndex)); return(result); }
protected void SetSingleError(ParseError error) { MakeErrorsLike(new List <ParseError>() { error }); }
internal bool ParseInt(int max, out int i) { i = 0; int pos = this.pos; while ((this.ch >= '0') && (this.ch <= '9')) { if ((((long)i) & 0xf0000000L) != 0L) { this.error = ParseError.Overflow; return(false); } i = ((i * 10) + this.ch) - 0x30; if (i < 0) { this.error = ParseError.Overflow; return(false); } this.NextChar(); } if (pos == this.pos) { this.error = ParseError.Format; return(false); } if (i > max) { this.error = ParseError.Overflow; return(false); } return(true); }
/// <summary> /// RuleBasedCollator constructor. /// This takes the table rules and builds a collation table out of them. /// </summary> /// <param name="rules">the collation rules to build the collation table from</param> /// <param name="normalizationMode">the normalization mode to use</param> /// <param name="collationStrength">the collation strength to use</param> public RuleBasedCollator(string rules, NormalizationMode normalizationMode, CollationStrength collationStrength) { ErrorCode status; var parseError = new ParseError(); _collatorHandle = NativeMethods.ucol_openRules(rules, rules.Length, normalizationMode, collationStrength, ref parseError, out status); try { ExceptionFromErrorCode.ThrowIfError(status, parseError.ToString(rules)); } catch { if (_collatorHandle != default(SafeRuleBasedCollatorHandle)) { _collatorHandle.Dispose(); } _collatorHandle = default(SafeRuleBasedCollatorHandle); throw; } }
public static void Display(this IInteractivity interactivity, ParseError error, String source) { var start = error.Start.Index - 1; var end = error.End.Index - 1; var lines = source.Split(new[] { Environment.NewLine }, StringSplitOptions.None); source = String.Join(" ", lines).Replace('\t', ' '); if (end == start) { end++; } var range = 48; var middle = (end + start) / 2; var ss = Math.Min(source.Length, Math.Max(middle - range / 2, 0)); var se = Math.Min(Math.Max(0, middle + range / 2), source.Length); var snippet = source.Substring(ss, se - ss); interactivity.Error(snippet); interactivity.Error(Environment.NewLine); interactivity.Error(new String(' ', Math.Max(0, start - ss))); interactivity.Error(new String('^', Math.Max(0, end - start))); interactivity.Error(Environment.NewLine); interactivity.Display(error); }
/// <param name="message">the error message. /// </param> /// <param name="cause">the exception that causes this. /// </param> /// <param name="err">the ParseError object. /// </param> /// <param name="mname">the module name. /// </param> /// <param name="pos">the position. /// </param> //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'" public ParserException(string message, System.Exception cause, ParseError err, string mname, Pos pos) : base(message, cause) { this.err = err; this.pos = pos; this.module = mname; }
public void FatalError(ParseError error) { #if DEBUG Debugger.Break(); #endif // DEBUG error.Throw(); }
/// <summary> /// Helper method to clear selections in the LINQ and CAML textboxes. /// </summary> private void ClearSelections() { // // Select all and undo marking. // txtLinq.Select(0, txtLinq.Text.Length); txtLinq.SelectionFont = new Font(txtLinq.Font, FontStyle.Regular); txtCaml.Select(0, txtCaml.Text.Length); txtCaml.SelectionFont = new Font(txtCaml.Font, FontStyle.Regular); // // Unselect for pretty display. // txtLinq.Select(0, 0); txtCaml.Select(0, 0); // // Hide tooltip. // linqTip.RemoveAll(); camlTip.RemoveAll(); // // Set default cursor. // txtLinq.Cursor = Cursors.Default; txtCaml.Cursor = Cursors.Default; // // Set to no current error. // currentError = null; }
public static void Display(this IInteractivity interactivity, ParseError error) { var message = error.Code.GetMessage(); var hint = String.Format("Line {1}, Column {2}: {0}", message, error.Start.Row, error.Start.Column); interactivity.Error(hint); }
public virtual void FatalError(ParseError error) { if (errorHandler != null) { errorHandler.FatalError(error); } }
protected void InnerEnd(ParseError error) { EndTime = DateTime.Now; Length = TimeSpan.FromMilliseconds((EndTime - StartTime).TotalMilliseconds); Status = ParseTaskStatus.Failed; Error = error; }
public static IDictionary AnalyzeAst(Ast ast) { // Build string list of all AST object values that will be later sent to StringMetricCalculator. List <String> stringList = new List <String>(); // Create required variables for tokenization. Token[] tokens = new Token[] {}; ParseError[] parseErrors = new ParseError[] {}; // Tokenize the entire input script. We must tokenize (instead of AST) to retrieve function values with obfuscation (like ticks) intact. Parser.ParseInput(ast.Extent.Text, out tokens, out parseErrors); // Iterate each token returned from above tokenization. foreach (Token token in tokens) { // If token is a function name then add to stringList. if ((token.Kind.ToString() == "Generic") && (token.TokenFlags.ToString() == "None")) { stringList.Add(token.Text); } } // Return character distribution and additional string metrics across all targeted AST objects across the entire input AST object. return(RevokeObfuscationHelpers.StringMetricCalculator(stringList, "AstFunctionNameMetrics")); }
/* IErrorHandler */ public virtual void Warning(ParseError error) { if (errorHandler != null) { errorHandler.Warning(error); } }
public void Parser_Received_Empty_String() { // Arrange var inputString = ""; var recipeParserConfiguration = new ParserConfiguration { ReportExceptions = true }; var recipeParser = new RecipeParser(recipeParserConfiguration); var parseError = new ParseError { Character = -1, Line = -1, Description = "Empty String was provided. No Content to Parse", ErrorCode = ParseErrorCode.NoInput, ErrorType = ErrorType.Fatal, UnparsedLine = "" }; // Act var output = recipeParser.Parse(inputString); // Assert Assert.NotNull(output); Assert.Equal(ParseStatus.Failed, output.Status); Assert.NotEmpty(output.Errors); Assert.Single(output.Errors); Assert.Matches(parseError.ToString(), output.Errors.FirstOrDefault().ToString()); }
public void Parser_Received_Recipe_With_No_Instructions() { // Arrange var inputString = @" Puppies Kittens Bunnies "; var recipeParserConfiguration = new ParserConfiguration { ReportExceptions = true }; var recipeParser = new RecipeParser(recipeParserConfiguration); var parseError = new ParseError { Character = -1, Line = -1, Description = "Could Not find any instructions", ErrorCode = ParseErrorCode.NoInstructions, ErrorType = ErrorType.MissingSection, UnparsedLine = "" }; // Act var output = recipeParser.Parse(inputString); // Assert Assert.NotNull(output); Assert.Equal(ParseStatus.ParsedWithErrors, output.Status); Assert.NotEmpty(output.Errors); Assert.Matches(parseError.ToString(), output.Errors.Single(c => c.ErrorCode == ParseErrorCode.NoInstructions).ToString()); }
protected void RunSql(string sql, object[] parameters) { if (DbConnectionType == typeof(SQLiteConnection)) { using (new DbContextTest()) { int i = 0; using (DatabaseContext ctx = new DatabaseContext()) { if (parameters != null) { ctx.Database.ExecuteSqlCommand(sql, parameters); } else { ctx.Database.ExecuteSqlCommand(sql); } i++; } } } else { TSql140Parser parser = new TSql140Parser(true, SqlEngineType.Standalone); IList <ParseError> errors; TSqlFragment result = parser.Parse(new StringReader(sql), out errors); ParseError error = errors.FirstOrDefault(); if (error != null) { throw new QueryParseException(error.Message); } } }
/// <summary> /// Initializes a new instance of the <see cref="ParseResult{T}"/> class. /// </summary> /// <param name="startPosition">The start position.</param> /// <param name="position">The position.</param> /// <param name="error">The parse error that occured.</param> public ParseResult(int startPosition, int position, ParseError error) { StartPosition = startPosition; Position = position; Error = error; Success = false; }
ParseException( ParseError cause, Exception innerException) : base("Configuration error", innerException) { this.cause = cause; }
private void Display(ParseError error, String source) { var start = error.Start.Index - 1; var end = error.End.Index - 1; var lines = source.Split(new[] { Environment.NewLine }, StringSplitOptions.None); source = String.Join(" ", lines).Replace('\t', ' '); if (end == start) { end++; } var range = 80; var message = error.Code.GetMessage(); var middle = (end + start) / 2; var ss = Math.Max(middle - range / 2, 0); var se = Math.Min(middle + range / 2, source.Length); var snippet = source.Substring(ss, se - ss); _interactivity.Error(snippet); _interactivity.Error(Environment.NewLine); _interactivity.Error(new String(' ', start - ss)); _interactivity.Error(new String('^', end - start)); _interactivity.Error(Environment.NewLine); _interactivity.Error("Error: "); _interactivity.Error(message); }
public static string FormatCompileErrors(this ParseError self, ReadOnlyMemory <char> resource) { ErrorSpan span = new(self.Row, self.Slice !.Value.Start.Value, self.Slice.Value.End.Value, self.Position.Start.Value, self.Position.End.Value); return(FormatErrors(self.Message, span, resource)); }
// REVIEW: We might want to integrate the methods below in a better way. /// <summary> /// Test collation rules and return an object with error information if it fails. /// </summary> /// <param name="rules">String containing the collation rules to check</param> /// <returns>A CollationRuleErrorInfo object with error information; or <c>null</c> if /// no errors are found.</returns> public static CollationRuleErrorInfo CheckRules(string rules) { if (rules == null) { return(null); } ErrorCode err; var parseError = new ParseError(); using (NativeMethods.ucol_openRules(rules, rules.Length, NormalizationMode.Default, CollationStrength.Default, ref parseError, out err)) { if (err == ErrorCode.NoErrors) { return(null); } return(new CollationRuleErrorInfo { Line = parseError.Line + 1, Offset = parseError.Offset + 1, PreContext = parseError.PreContext, PostContext = parseError.PostContext }); } }
private void PrintParseError(ParseError parseError, string code) { view.PrintOutput(Colors.DimGray, "> "); view.PrintOutput(Colors.LightGray, string.Format("{0}\n", code)); view.PrintOutput(Colors.DimGray, " Ошибка: "); view.PrintOutput(Colors.White, string.Format("{0}\n", parseError.Message)); }
internal bool ParseInt(int max, out int i) { i = 0; int p = pos; while (ch >= '0' && ch <= '9') { if ((i & 0xF0000000) != 0) { error = ParseError.Overflow; return(false); } i = i * 10 + ch - '0'; if (i < 0) { error = ParseError.Overflow; return(false); } NextChar(); } if (p == pos) { error = ParseError.Format; return(false); } if (i > max) { error = ParseError.Overflow; return(false); } return(true); }
internal override void Apply(StringGroup input, Stack <bool> enableStack, List <Define> defines, out ParseError error) { if (enableStack.Contains(false)) { error = null; return; } string strInput = input.AsSingleLine(); strInput = ClearInput(strInput); if (!PreprocessorIfdef.ArgumentRegex.IsMatch(strInput)) { error = new ParseError(ParseErrorType.Preprocessor_NameExpected); return; } if (!defines.Exists(p => p.Name == strInput)) { error = new ParseError(ParseErrorType.Preprocessor_UnknownDefineName); return; } defines.RemoveAll(p => p.Name == strInput); error = null; }
//加载外接式模型 public void LoadModel(int model) { ModelItem Target = DlcMng.GetPluginModel(model); if (Target == null) { Debug.LogError("cannot load model:" + model); return; } string skc = ""; for (int i = 0; i < Target.resPath.Count; i++) { if (Target.resPath[i].ToLower().EndsWith(".skc")) { skc = Target.resPath[i]; break; } } if (!System.IO.File.Exists(skc)) { errorno = ParseError.Miss; } string text = System.IO.File.ReadAllText(skc); Parse(text); }
/// <summary> /// Parses the current file contents to get the AST, tokens, /// and parse errors. /// </summary> private void ParseFileContents() { ParseError[] parseErrors = null; try { this.ScriptAst = Parser.ParseInput( this.Contents, out this.scriptTokens, out parseErrors); } catch (RuntimeException ex) { var parseError = new ParseError( null, ex.ErrorRecord.FullyQualifiedErrorId, ex.Message); parseErrors = new[] { parseError }; this.scriptTokens = new Token[0]; this.ScriptAst = null; } // Translate parse errors into syntax markers this.SyntaxMarkers = parseErrors .Select(ScriptFileMarker.FromParseError) .ToArray(); //Get all dot sourced referenced files and store them this.ReferencedFiles = AstOperations.FindDotSourcedIncludes(this.ScriptAst); }
public IStatement Parse(ConsideredTokens consideredTokens, Action tweakTokens, out ParseError error) { var letToken = consideredTokens.Current; tweakTokens(); if (consideredTokens.Current.Type != TokenType.IDENT) { error = new ParseError(StatementType.Let, TokenType.IDENT, consideredTokens.Current.Type); tweakTokens(); return(null); } var identifer = new Identifier(consideredTokens.Current); tweakTokens(); if (consideredTokens.Current.Type != TokenType.ASSIGN) { error = new ParseError(StatementType.Let, TokenType.ASSIGN, consideredTokens.Current.Type); tweakTokens(); return(null); } tweakTokens(); var value = ExpressionParser.ParseExpression(consideredTokens, tweakTokens, out var errorExpression); error = value == null ? errorExpression : ParseError.None; return(new LetStatement(letToken, identifer, value)); }
public bool Error(ParseError type, string message) { _success = false; ErrorType = type; _errorMessage = message; return(false); }
static string toErrorStr(ParseError err, Pos? pos) { System.Text.StringBuilder buf = new System.Text.StringBuilder(); if (pos.HasValue) buf.Append("line " + pos.Value.Line + ", column " + pos.Value.Column); if (err != null) { buf.Append(":\n"); showExpecting(buf, err.getExpecting()); showUnexpected(buf, err.getUnexpected()); showMessages(buf, err.getMessages()); showEncountered(buf, err.getEncountered()); } return buf.ToString(); }
//Get data as a boolean public bool asBool() { //If the data was written with words //if true then return true if (m_Data.Contains("true") || m_Data.Contains("TRUE") || m_Data.Contains("True")) { return true; } //if false return false else if (m_Data.Contains("false") || m_Data.Contains("FALSE") || m_Data.Contains("False")) { return false; } //If the data was written as a number //If 0 return false byte byteValue = asByte(); //If there was an error parsing the byte then there was an error parsing the bool if ((m_Error & ParseError.AS_BYTE) == ParseError.AS_BYTE) { m_Error = m_Error | ParseError.AS_BOOL; } if (byteValue == 0) { return false; } //Not 0 return false; else if (byteValue != 0) { return true; } //If we get down here, failed to parse as bool m_Error = m_Error | ParseError.AS_BOOL; return false; }
public string FormatError(ParseError error) { return string.Format("{0}({1}) : ERROR {2} : {3}", input.Path, error.Line, error.Number, error.Message); }
//get string as a byte public byte asByte() { byte byteValue = 0; bool error = byte.TryParse(m_Data, out byteValue); if (error == true) { //Success return byteValue; } //Failure m_Error = m_Error | ParseError.AS_BYTE; return 0; }
public ParseError getError() { //Check the bit fields for an error and then return with the error or return no error if there were none //remove the error from the bit field as the user will have been notified already. if ((m_Error & ParseError.AS_BOOL) == ParseError.AS_BOOL) { m_Error -= ParseError.AS_BOOL; return ParseError.AS_BOOL; } if ((m_Error & ParseError.AS_BYTE) == ParseError.AS_BYTE) { m_Error -= ParseError.AS_BYTE; return ParseError.AS_BYTE; } if ((m_Error & ParseError.AS_INT) == ParseError.AS_INT) { m_Error -= ParseError.AS_INT; return ParseError.AS_INT; } if ((m_Error & ParseError.AS_FLOAT) == ParseError.AS_FLOAT) { m_Error -= ParseError.AS_FLOAT; return ParseError.AS_FLOAT; } if ((m_Error & ParseError.AS_DOUBLE) == ParseError.AS_DOUBLE) { m_Error -= ParseError.AS_DOUBLE; return ParseError.AS_DOUBLE; } //No Errors clear fields m_Error = ParseError.NO_ERROR; return ParseError.NO_ERROR; }
/// <summary> Create a ParserException object.</summary> /// <param name="err">the ParseError object. /// </param> /// <param name="mname">the module name. /// </param> /// <param name="pos">the position. /// </param> public ParserException(ParseError err, string mname, Pos pos) { this.err = err; this.pos = pos; this.module = mname; }
public void FatalError(ParseError error) { if (parentTestSuite != null) parentTestSuite.FatalError(error); seenEvent = true; FlushEndPrefixMappings(); writer.WriteStartElement("fatalError"); writer.WriteEndElement(); }
public void Warning(ParseError error) { writer.WriteLine("<warning line='" + error.LineNumber + "' column='" + error.ColumnNumber + "'>"+ Escape(error.Message) + "</warning>"); warningCount++; }
public void Warning(ParseError error) { // warnings are optional if (parentTestSuite != null) parentTestSuite.Warning(error); }
/* IErrorHandler */ public void Warning(ParseError error) { string msg = "Warning: " + error.Message; if (error.BaseException != null) msg = msg + Environment.NewLine + error.BaseException.Message; msgList.Add(msg); }
public void Error(ParseError error) { // reporting errors is optional if (parentTestSuite != null) parentTestSuite.Error(error); }
internal static string Show(ParseError err, Pos pos) { return toErrorStr(err, pos); }
void IErrorHandler.Error(ParseError error) { FireOnError(new SaxParseException(error)); }
//Get string as a double public double asDouble() { double doubleValue = 0; bool error = double.TryParse(m_Data, out doubleValue); if (error == true) { //Success return doubleValue; } //Failure m_Error = m_Error | ParseError.AS_DOUBLE; return 0.0; }
public void FatalError(ParseError error) { writer.WriteLine("<fatalError line='" + error.LineNumber + "' column='" + error.ColumnNumber + "'>"+ Escape(error.Message) + "</fatalError>"); fatalCount++; }
void IErrorHandler.Warning(ParseError error) { Debug.WriteLine("XML parse warning: " + error.Message + " at line number: " + error.LineNumber); }
//Get string as a float public float asFloat() { float floatValue = 0; bool error = float.TryParse(m_Data, out floatValue); if (error == true) { //Success return floatValue; } //Failure m_Error = m_Error | ParseError.AS_FLOAT; return 0.0f; }
//Get string as an int public int asInt() { int intValue = 0; bool error = int.TryParse(m_Data, out intValue); if (error == true) { //Success return intValue; } //Failure m_Error = m_Error | ParseError.AS_INT; return 0; }
public void FatalError(ParseError error) { error.Throw(); }