public void ParseException_with_message() { var e = new ParseException(_parseReason, _message); Assert.AreEqual(_message, e.Message); Assert.IsNull(e.InnerException); Assert.AreEqual(_parseReason, e.Reason); }
public override void Parse(Reader @in) { LineNumberReader br = new LineNumberReader(@in); try { string line = null; string lastSynSetID = ""; CharsRef[] synset = new CharsRef[8]; int synsetSize = 0; while ((line = br.readLine()) != null) { string synSetID = line.Substring(2, 9); if (!synSetID.Equals(lastSynSetID)) { addInternal(synset, synsetSize); synsetSize = 0; } if (synset.Length <= synsetSize+1) { CharsRef[] larger = new CharsRef[synset.Length * 2]; Array.Copy(synset, 0, larger, 0, synsetSize); synset = larger; } synset[synsetSize] = parseSynonym(line, synset[synsetSize]); synsetSize++; lastSynSetID = synSetID; } // final synset in the file addInternal(synset, synsetSize); } catch (System.ArgumentException e) { ParseException ex = new ParseException("Invalid synonym rule at line " + br.LineNumber, 0); ex.initCause(e); throw ex; } finally { br.close(); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public void parse(java.io.Reader in) throws java.io.IOException, java.text.ParseException public override void parse(Reader @in) { LineNumberReader br = new LineNumberReader(@in); try { addInternal(br); } catch (System.ArgumentException e) { ParseException ex = new ParseException("Invalid synonym rule at line " + br.LineNumber, 0); ex.initCause(e); throw ex; } finally { br.close(); } }
public void DisplayParseExceptionMessage(ParseException e) { Console.WriteLine($"\n{string.Join(", ", e.InvalidColourInput)} is not a valid colour."); }
public static FluidInput ParseFluidInput(XmlNode node, DFG <Block> dfg, ParserInfo parserInfo, string id, string nodeName, ParseException exception) { XmlNode inputFluidNode = node.GetInnerBlockNode(nodeName, parserInfo, exception); if (inputFluidNode != null) { return(XmlParser.ParseFluidInput(inputFluidNode, dfg, parserInfo)); } return(null); }
/// <summary> /// Assembles the given code. /// </summary> /// <param name="outputPath"> /// Path to output file. /// </param> /// <returns> /// Binary code of assembled program. /// </returns> public byte[] Assemble(string outputPath = "out.o") { try { if (!code.EndsWith("\n")) { code += "\r\n"; } var provider = CSharpCodeProvider.CreateProvider("c#"); var options = new CompilerParameters(); var assemblyContainingNotDynamicClass = Path.GetFileName(Assembly.GetExecutingAssembly().Location); options.ReferencedAssemblies.Add(assemblyContainingNotDynamicClass); string parserCode = File.ReadAllText("Grammar/cs/" + ((SystemComponent)cpu).Name + "Parser.cs"); string constantsCode = File.ReadAllText("Grammar/cs/" + ((SystemComponent)cpu).Name + "Constants.cs"); string tokenizerCode = File.ReadAllText("Grammar/cs/" + ((SystemComponent)cpu).Name + "Tokenizer.cs"); string analyzerCode = File.ReadAllText("Grammar/cs/" + ((SystemComponent)cpu).Name + "Analyzer.cs"); var results = provider.CompileAssemblyFromSource(options, new[] { parserCode, constantsCode, tokenizerCode, analyzerCode }); if (results.Errors.Count > 0) { foreach (var error in results.Errors) { File.AppendAllText("error.txt", error + "\n"); } return(null); } else { Parser parser = null; var t = results.CompiledAssembly.GetType("MultiArc_Compiler." + cpu.Name + "Parser", true); object instance = Activator.CreateInstance(t, new[] { new StringReader(code) }); parser = (Parser)instance; try { Node n = parser.Parse(); instructions.Clear(); labels.Clear(); symbolTable.Clear(); getInstructionsFromTree(n); getOriginFromTree(n); binaryCode = new byte[instructions.Count * cpu.Constants.MAX_BYTES]; // THIS MUST BE TESTED. count = 0; separators.Clear(); separators = new LinkedList <int>(); // First passing: for (int i = 0; i < instructions.Count; i++) { Instruction inst = cpu.Constants.GetInstruction(instructions.ElementAt(i).GetName()); if (labels.ContainsKey(instructions.ElementAt(i))) { Symbol symbol = new Symbol(labels[instructions.ElementAt(i)], 0, count, true); if (symbolTable.Contains(symbol)) { throw new Exception("Label already defined"); } else { symbolTable.AddLast(symbol); } } for (int j = inst.Mask.Length - 1; j >= 0; j--) { binaryCode[count + j] = inst.Mask[j]; } LinkedList <AddressingMode> addrModes = new LinkedList <AddressingMode>(); LinkedList <int> argumentsIndexes = new LinkedList <int>(); for (int j = 0; j < instructions.ElementAt(i).GetChildCount(); j++) { AddressingMode am = null; am = cpu.Constants.GetAddressingMode(instructions.ElementAt(i).GetChildAt(j).Name); if (!object.ReferenceEquals(am, null)) { addrModes.AddLast(am); argumentsIndexes.AddLast(j); } } for (int j = 0; j < inst.Arguments.Count; j++) { int argcodeValue = inst.Arguments.ElementAt(j).CodeValues[addrModes.ElementAt(j).Name]; int argcodeStart = inst.Arguments.ElementAt(j).CodeStarts[addrModes.ElementAt(j).Name]; int argcodeEnd = inst.Arguments.ElementAt(j).CodeEnds[addrModes.ElementAt(j).Name]; int argcodeSize = 1; for (int k = argcodeStart; k >= argcodeEnd; k--) { if (k % 8 == 0 && k != argcodeEnd) { argcodeSize++; } } int argcodeCount = argcodeStart - argcodeEnd; int byteCount = argcodeSize - 1; for (int k = argcodeStart; k >= argcodeEnd; k--) { int semiValue = (argcodeValue & (1 << argcodeCount)) << argcodeEnd % 8; binaryCode[count + inst.Size - 1 - argcodeEnd / 8 - byteCount] |= (byte)((semiValue & (1 << (argcodeEnd % 8 + argcodeCount))) >> byteCount * 8); // This might be a problem. if ((argcodeEnd + argcodeCount) % 8 == 0) { byteCount--; } argcodeCount--; } AddressingMode am = addrModes.ElementAt(j); int argumentIndex = argumentsIndexes.ElementAt(j); int operandValue = 0; bool shouldBeWritten = false; if (am.OperandInValues) { shouldBeWritten = true; string expr = ""; if (instructions.ElementAt(i).GetChildAt(argumentIndex).GetChildAt(0) is Production) { expr = ((Production)instructions.ElementAt(i).GetChildAt(argumentIndex).GetChildAt(0)).Name; } else { for (int l = 0; l < instructions.ElementAt(i).GetChildAt(argumentIndex).GetChildCount(); l++) { expr += ((Token)instructions.ElementAt(i).GetChildAt(argumentIndex).GetChildAt(l)).Image; } } if (am.Values.ContainsKey(expr.ToLower())) { operandValue = am.Values[expr.ToLower()]; } } else if (am.OperandReadFromExpression) { Node node = (instructions.ElementAt(i).GetChildAt(argumentIndex)); int childCount = node.GetChildCount(); Node child = node; int sign = 1; while (!(child.GetChildAt(0) is Token)) { child = child.GetChildAt(0); } for (int l = 0; l < node.GetChildCount() && !child.Name.Equals("DEC_NUMBER") && !child.Name.Equals("HEX_NUMBER") && !child.Name.Equals("OCT_NUMBER") && !child.Name.Equals("BIN_NUMBER") && !child.Name.Equals("IDENTIFIER"); l++) { child = node.GetChildAt(l); if (l != 0 && node.GetChildAt(l - 1).Name.Equals("SIGN")) { if (((Token)node.GetChildAt(l - 1)).Image.Equals("+")) { sign = 1; } else { sign = -1; } } } if (child.Name.Equals("DEC_NUMBER")) { operandValue = Convert.ToInt32(((Token)child).Image.ToLower()) * sign; shouldBeWritten = true; } else if (child.Name.Equals("HEX_NUMBER")) { operandValue = Convert.ToInt32(((Token)child).Image.ToLower().Substring(0, ((Token)child).Image.Length - 1), 16) * sign; shouldBeWritten = true; } else if (child.Name.Equals("OCT_NUMBER")) { operandValue = Convert.ToInt32(((Token)child).Image.ToLower().Substring(0, ((Token)child).Image.Length - 1), 8) * sign; shouldBeWritten = true; } else if (child.Name.Equals("BIN_NUMBER")) { operandValue = Convert.ToInt32(((Token)child).Image.ToLower().Substring(0, ((Token)child).Image.Length - 1), 2) * sign; shouldBeWritten = true; } else if (child.Name.Equals("IDENTIFIER")) { string label = ((Token)child).Image; operandValue = 0; foreach (Symbol s in symbolTable) { if (s.Label.ToLower().Equals(label)) { operandValue = s.Offset; break; } } } if (am.OperandType.ToLower().Equals("relative")) { operandValue = operandValue - inst.Size - count; } } else if (am.OperandValueDefinedByUser) { Node node = (instructions.ElementAt(i).GetChildAt(argumentIndex)); int childCount = node.GetChildCount(); Node child = node; bool labelNotYet = false; int sign = 1; while (!(child.GetChildAt(0) is Token)) { child = child.GetChildAt(0); } for (int l = 0; l < node.GetChildCount() && !child.Name.Equals("DEC_NUMBER") && !child.Name.Equals("HEX_NUMBER") && !child.Name.Equals("OCT_NUMBER") && !child.Name.Equals("BIN_NUMBER") && !child.Name.Equals("IDENTIFIER"); l++) { child = node.GetChildAt(l); if (l != 0 && node.GetChildAt(l - 1).Name.Equals("SIGN")) { if (((Token)node.GetChildAt(l - 1)).Image.Equals("+")) { sign = 1; } else { sign = -1; } } } if (child.Name.Equals("DEC_NUMBER")) { operandValue = Convert.ToInt32(((Token)child).Image.ToLower()) * sign; } else if (child.Name.Equals("HEX_NUMBER")) { operandValue = Convert.ToInt32(((Token)child).Image.ToLower().Substring(0, ((Token)child).Image.Length - 1), 16) * sign; } else if (child.Name.Equals("OCT_NUMBER")) { operandValue = Convert.ToInt32(((Token)child).Image.ToLower().Substring(0, ((Token)child).Image.Length - 1), 8) * sign; } else if (child.Name.Equals("BIN_NUMBER")) { operandValue = Convert.ToInt32(((Token)child).Image.ToLower().Substring(0, ((Token)child).Image.Length - 1), 2) * sign; } else if (child.Name.Equals("IDENTIFIER")) { string label = ((Token)child).Image; operandValue = 0; bool found = false; foreach (Symbol s in symbolTable) { if (s.Label.ToLower().Equals(label)) { operandValue = s.Offset; found = true; break; } } if (found == false) { labelNotYet = true; } } int relativeOperandValue = operandValue - inst.Size - count; string image = getExpression(instructions.ElementAt(i), ""); if (labelNotYet == false) { operandValue = am.GetOperandValue(image, count + inst.Size, relativeOperandValue, operandValue); shouldBeWritten = true; } } if (shouldBeWritten == true) { int operandStart = inst.Arguments.ElementAt(j).OperandStarts[am.Name]; int operandEnd = inst.Arguments.ElementAt(j).OperandEnds[am.Name]; int operandSize = 1; for (int k = operandStart; k >= operandEnd; k--) { if (k % 8 == 0 && k != operandEnd) { operandSize++; } } int operandCount = operandStart - operandEnd; byteCount = operandSize - 1; for (int k = operandStart; k >= operandEnd; k--) { int semiValue = (operandValue & (1 << operandCount)) << operandEnd % 8; binaryCode[count + inst.Size - 1 - operandEnd / 8 - byteCount] |= (byte)((semiValue & (1 << (operandEnd % 8 + operandCount))) >> byteCount * 8); // This might be a problem. if ((operandEnd + operandCount) % 8 == 0) { byteCount--; } operandCount--; } } } separators.AddLast(count); count += inst.Size; } separators.AddLast(count); count = 0; // Second passing: for (int i = 0; i < instructions.Count; i++) { Instruction inst = cpu.Constants.GetInstruction(instructions.ElementAt(i).GetName()); LinkedList <AddressingMode> addrModes = new LinkedList <AddressingMode>(); LinkedList <int> argumentsIndexes = new LinkedList <int>(); for (int j = 0; j < instructions.ElementAt(i).GetChildCount(); j++) { AddressingMode am = null; am = cpu.Constants.GetAddressingMode(instructions.ElementAt(i).GetChildAt(j).Name); if (!object.ReferenceEquals(am, null)) { addrModes.AddLast(am); argumentsIndexes.AddLast(j); } } for (int j = 0; j < inst.Arguments.Count; j++) { AddressingMode am = addrModes.ElementAt(j); int argumentIndex = argumentsIndexes.ElementAt(j); int operandValue = 0; bool shouldBeOverwriten = false; if (am.OperandReadFromExpression) { Node node = (instructions.ElementAt(i).GetChildAt(argumentIndex)); int childCount = node.GetChildCount(); Node child = node; while (!(child.GetChildAt(0) is Token)) { child = child.GetChildAt(0); } for (int l = 0; l < node.GetChildCount() && !child.Name.Equals("DEC_NUMBER") && !child.Name.Equals("HEX_NUMBER") && !child.Name.Equals("OCT_NUMBER") && !child.Name.Equals("BIN_NUMBER") && !child.Name.Equals("IDENTIFIER"); l++) { child = node.GetChildAt(l); } if (child.Name.Equals("IDENTIFIER")) { string label = ((Token)child).Image; operandValue = 0; shouldBeOverwriten = true; bool found = false; foreach (Symbol s in symbolTable) { if (s.Label.ToLower().Equals(label)) { operandValue = s.Offset; found = true; break; } } if (found == false) { operandValue = Program.Mem.FirstFreeInRAM(am.Result.Size / 8); if (operandValue == -1) { throw new Exception("Memory full"); } Symbol newSymbol = new Symbol(label, 0, operandValue, true); symbolTable.AddLast(newSymbol); Program.Mem.Allocate(operandValue, am.Result.Size / 8); } } if (am.OperandType.ToLower().Equals("relative")) { operandValue = operandValue - inst.Size - count; } } else if (am.OperandValueDefinedByUser) { Node node = (instructions.ElementAt(i).GetChildAt(argumentIndex)); int childCount = node.GetChildCount(); Node child = node; while (!(child.GetChildAt(0) is Token)) { child = child.GetChildAt(0); } for (int l = 0; l < node.GetChildCount() && !child.Name.Equals("DEC_NUMBER") && !child.Name.Equals("HEX_NUMBER") && !child.Name.Equals("OCT_NUMBER") && !child.Name.Equals("BIN_NUMBER") && !child.Name.Equals("IDENTIFIER"); l++) { child = node.GetChildAt(l); } if (child.Name.Equals("IDENTIFIER")) { string label = ((Token)child).Image; bool found = false; shouldBeOverwriten = true; foreach (Symbol s in symbolTable) { if (s.Label.ToLower().Equals(label)) { operandValue = s.Offset; found = true; break; } } if (found == false) { operandValue = Program.Mem.FirstFree(Program.Mem.AuSize); Program.Mem.Allocate(operandValue, Program.Mem.AuSize); // This must be improved. } } int relativeOperandValue = operandValue - inst.Size - count; string image = getExpression(instructions.ElementAt(i), ""); operandValue = am.GetOperandValue(image, count + inst.Size, relativeOperandValue, operandValue); } if (shouldBeOverwriten == true) { int operandStart = inst.Arguments.ElementAt(j).OperandStarts[am.Name]; int operandEnd = inst.Arguments.ElementAt(j).OperandEnds[am.Name]; int operandSize = 1; for (int k = operandStart; k >= operandEnd; k--) { if (k % 8 == 0 && k != operandEnd) { operandSize++; } } int operandCount = operandStart - operandEnd; int byteCount = operandSize - 1; for (int k = operandStart; k >= operandEnd; k--) { int semiValue = (operandValue & (1 << operandCount)) << operandEnd % 8; binaryCode[count + inst.Size - 1 - operandEnd / 8 - byteCount] |= (byte)((semiValue & (1 << (operandEnd % 8 + operandCount))) >> byteCount * 8); // This might be a problem. if ((operandEnd + operandCount) % 8 == 0) { byteCount--; } operandCount--; } } } count += inst.Size; } output.Text += DateTime.Now.ToString() + " Compile successfull.\n"; output.ScrollToCaret(); byte[] ret = new byte[count]; for (int i = 0; i < count; i++) { ret[i] = binaryCode[i]; } for (int i = 0; i < count; i += Program.Mem.AuSize) { byte[] toWrite = new byte[Program.Mem.AuSize]; for (int j = 0; j < Program.Mem.AuSize && i + j < count; j++) { toWrite[j] = ret[j + i]; } Program.Mem[(uint)(i + origin)] = toWrite; } return(ret); } catch (ParserLogException ex) { string o = "Error(s) in code existed. Compile unsuccessfull.\r\nList of errors:\r\n"; for (int j = 0; j < ex.Count; j++) { ParseException pe = ex[j]; o += (j + 1) + ": Syntax error " + '\'' + pe.ErrorMessage + '\'' + " in line " + pe.Line + " and column " + pe.Column + "\n"; } output.Text += DateTime.Now.ToString() + " " + o; output.ScrollToCaret(); return(null); } } } catch (Exception ex) { File.AppendAllText("error.txt", ex.ToString()); return(null); } }
public override void Done(IList <ParseObject> objects, ParseException e) { action(objects, e); }
private YMapping GetMappingValueDependent(ITokenizer tokenizer) { switch (tokenizer.Current.Value.Kind) { case TokenKind.Indent when tokenizer.Current.Next?.Value.Kind == TokenKind.MappingKey: { var mappingNode = new YMapping(tokenizer.Current.Value.IndentLevel); var items = new YKeyValueList(); tokenizer.MoveNext(); while (tokenizer.Current.Value.Kind == TokenKind.MappingKey) { var keyValueNode = this.ParseMappingKey(tokenizer); items.AddNode(keyValueNode); } while (tokenizer.Current.Value.Kind == TokenKind.Unindent) { tokenizer.MoveNext(); } mappingNode.Add(items.ToNodes()); return(mappingNode); } case TokenKind.MappingValue: { var mappingNode = new YMapping(tokenizer.Current.Value.IndentLevel); tokenizer.MoveNext(); var value = this.GetNodeValue(tokenizer); mappingNode.Add(value); return(mappingNode); } case TokenKind.Indent when tokenizer.Current.Next?.Next?.Value.Kind == TokenKind.MappingValue: { var mappingNode = new YMapping(tokenizer.Current.Value.IndentLevel); var items = new YKeyValueList(); tokenizer.MoveNext(); // Добавлеяем элементы в список do { var keyValueNode = this.ParseMappingKey(tokenizer); items.AddNode(keyValueNode); } while (tokenizer.Current.Value.Kind != TokenKind.Unindent && tokenizer.Current.Value.Kind != TokenKind.Eof && tokenizer.Current.Value.Kind != TokenKind.Indent && tokenizer.Current.Value.IndentLevel >= mappingNode.IndentLevel); // Удаляем ненужные отступы while (tokenizer.Current.Value.Kind == TokenKind.Unindent) { tokenizer.MoveNext(); } // Проверяем уровень вложенности if (tokenizer.Current.Value.IndentLevel != 0 && tokenizer.Current.Value.Kind == TokenKind.Indent) { while (tokenizer.Current.Value.IndentLevel == mappingNode.IndentLevel && tokenizer.Current.Value.Kind != TokenKind.Eof) { if (tokenizer.Current.Value.Kind == TokenKind.Indent) { tokenizer.MoveNext(); } var keyValueNode = this.ParseMappingKey(tokenizer); items.AddNode(keyValueNode); } } mappingNode.Add(items.ToNodes()); return(mappingNode); } case TokenKind.MappingBegin: { var mappingNode = new YMapping(tokenizer.Current.Value.IndentLevel); var items = new YKeyValueList(); tokenizer.MoveNext(); do { if (tokenizer.Current.Value.Kind == TokenKind.MappingEnd) { break; } var keyValueNode = this.ParseMappingKey(tokenizer); items.AddNode(keyValueNode); } while (tokenizer.Current.Value.Kind == TokenKind.ItemDelimiter && tokenizer.MoveNext()); if (tokenizer.Current.Value.Kind != TokenKind.MappingEnd) { throw ParseException.UnexpectedToken(tokenizer, TokenKind.MappingEnd); } tokenizer.MoveNext(); mappingNode.Add(items.ToNodes()); return(mappingNode); } default: return(null); } }
public override void Done(ParseUser p0, ParseException p1) { action (p0, p1); }
/// <inheritdoc/> public ExcelPackage GetExcelPackage(dynamic excelFile, string password = "") { ParseException exception = null; //Make sure we have a file if (excelFile == null) { exception = new() { ExceptionType = ParseExceptionType.NoFileFound, Severity = ParseExceptionSeverity.Error, }; throw new ImportException(exception); } if (PropertyExist(excelFile, "ContentType") == false || PropertyExist(excelFile, "FileName") == false) { throw new FormatException("file must be type IFormFile or HttpPostedFileBase"); } //TODO: accept more formats later (https://github.com/domshyra/ExcelExtensions/issues/10) //Make sure the file is a xlsx type if (excelFile.ContentType != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { exception = new() { Message = "Wrong file type uploaded. Please upload an excel file", ExceptionType = ParseExceptionType.Generic, Severity = ParseExceptionSeverity.Error, }; } if (exception != null) { throw new ImportException(exception); } //Core if (PropertyExist(excelFile, "InputStream") == false) { try { if (!string.IsNullOrEmpty(password)) { //We need to create a read/write memory stream that is needed to read a password protected file MemoryStream readWrite = new(); excelFile.CopyTo(readWrite); return(new ExcelPackage(readWrite, password)); } else { return(new ExcelPackage(excelFile.OpenReadStream())); } } catch (InvalidDataException) { //the password is not supplied to a password protected file throw new ImportException(PasswordError("not supplied")); } catch (System.Security.SecurityException) { //the password supplied is invalid throw new ImportException(PasswordError("invalid")); } } //MVC else { try { if (!string.IsNullOrEmpty(password)) { return(new ExcelPackage(excelFile.InputStream, password)); } else { return(new ExcelPackage(excelFile.InputStream)); } } catch (InvalidDataException) { throw new ImportException(PasswordError("invalid")); } } }
/// <summary> /// Creates the evaluator for a single calculated field. /// </summary> /// <param name="calculatedField">Entity for the calculated field.</param> /// <param name="settings">Settings.</param> /// <returns></returns> private CalculatedFieldMetadata GetSingleCalculatedFieldMetadata(Field calculatedField, CalculatedFieldSettings settings) { string calculation = null; IExpression expression = null; ParseException exception = null; BuilderSettings builderSettings; try { // Get calculation calculation = calculatedField.FieldCalculation; if (string.IsNullOrEmpty(calculation)) { throw new ArgumentException("The field has no calculation script. It may not be a calculated field."); } // Get settings builderSettings = CreateBuilderSettingsForField(calculatedField, settings); // Compile expression = _expressionCompiler.Compile(calculation, builderSettings); // Register cache invalidations if (CacheContext.IsSet()) { CalculationDependencies dependencies = _expressionCompiler.GetCalculationDependencies(expression); using (CacheContext cacheContext = CacheContext.GetContext()) { cacheContext.Entities.Add(calculatedField.Id); cacheContext.Entities.Add(dependencies.IdentifiedEntities); cacheContext.Entities.Add(builderSettings.RootContextType.EntityTypeId); } } } catch (InvalidMemberParseException ex) { exception = ex; // If a parse-exception resulted from being unable to look up a member name, then it may be corrected by renaming some arbitrary field or relationship // that could not be otherwise detected by dependencies.IdentifiedEntities. So invalidate parse exceptions if any field/relationship changes. if (CacheContext.IsSet()) { using (CacheContext cacheContext = CacheContext.GetContext()) { cacheContext.Entities.Add(ex.TypeId); // TODO: ideally just listen for all fields/relationships attached to type var fieldTypes = PerTenantEntityTypeCache.Instance.GetDescendantsAndSelf(new EntityRef("core:field").Id); cacheContext.EntityTypes.Add(fieldTypes); cacheContext.EntityTypes.Add(new EntityRef("core:relationship").Id); } } } catch (ParseException ex) { exception = ex; } // Build metadata CalculatedFieldMetadata metadata = new CalculatedFieldMetadata(calculatedField.Id, calculation, expression, exception); return(metadata); }
public override void Done(int count, ParseException e) { callback (count, e); }
public void DecrementPowerUp(PowerTypes powerType, Action doIfHasPower) { if (!isLocalPlayer) { return; } switch (powerType) { case PowerTypes.Mirror: var currentMirrors = CurrentMirrors(); Debug.LogError("ANZAHL VON MIRRORS: " + currentMirrors); //if (currentMirrors == 0) return; user["mirrors"] = currentMirrors - 1; break; case PowerTypes.Noiz: var currentNoiz = CurrentNoiz(); //if (currentNoiz == 0) return; user["noiz"] = currentNoiz - 1; break; case PowerTypes.Boom: var currentBooms = CurrentBooms(); if (currentBooms == 0) { return; } user["booms"] = currentBooms - 1; break; default: break; } if (!user.IsAuthenticated) { GuiManager.Instance.message.For(2).Show("NOT AUTHENTICATED"); Debug.LogError("ERROR: " + "NOT AUTHENTICATED"); } user.SaveAsync() .ContinueWith(task => { if (task.IsCompleted && (task.IsFaulted || task.IsCanceled)) { GuiManager.Instance.message.For(2).ShowOnMainThread("Cant add -1 powerUp"); Debug.LogError("Cant substract powerup"); GuiManager.Instance.loading.HideOnMainThread(); // Errors from Parse Cloud and network interactions using (IEnumerator <System.Exception> enumerator = task.Exception.InnerExceptions.GetEnumerator()) { if (enumerator.MoveNext()) { ParseException error = (ParseException)enumerator.Current; GuiManager.Instance.message.For(2).ShowOnMainThread(error.Message); Debug.LogError("ERROR: " + error.Message + " " + error.Code); } } } else { MainThread.Call(() => { doIfHasPower.Invoke(); UpdateUi(); }); GuiManager.Instance.message.For(2).ShowOnMainThread("PowerUp -1 :)"); Debug.LogError("Substacted power up"); } }); }
public void ConstructorWorks() { var exception = new ParseException("foo"); }
internal static XmlNode GetInnerBlockNode(this XmlNode node, string nodeAttribName, ParserInfo parserInfo, ParseException exception) { XmlNode innerNode = node.TryGetNodeWithAttributeValue(nodeAttribName); if (innerNode == null) { parserInfo.ParseExceptions.Add(exception); return(null); } return(innerNode.FirstChild); }
public override void Done(ParseObject pobject, ParseException pexception) { action(pobject, pexception); }
public override void Done(ParseException p0) { action(user, p0); }
public InvalidSortException(ParseException exception) : base("Invalid sort", exception) { }
internal IEnumerator SaveHighScore(GameMode currentGameMode, TaskResult result) { if (!FB.IsLoggedIn) { yield break; } var query = ParseObject.GetQuery("HighScore") .WhereEqualTo("facebookUserID", FB.UserId) .WhereEqualTo("gameMode", currentGameMode.ModeName); var task = query.FirstOrDefaultAsync(); while (!task.IsCompleted) { yield return(null); } if (task.IsFaulted) { foreach (var e in task.Exception.InnerExceptions) { ParseException parseException = (ParseException)e; Debug.Log("Error getting high score.\r\nError message: " + parseException.Message + "\r\nErrorCode: " + parseException.Code); } result.IsCompleted = true; result.IsFaulted = true; yield break; } if (task.Result == null) { //Create and send new score var highScore = new ParseObject("HighScore"); highScore["gameVersion"] = GlobalData.Instance.version; highScore["score"] = currentGameMode.Score; highScore["facebookUserID"] = FB.UserId; highScore["gameMode"] = currentGameMode.ModeName; if (currentGameMode.ModeName == "PeriodicMode") { highScore["seedUsed"] = GlobalData.Instance.periodicModeSeed; highScore["rawSeedUsed"] = GlobalData.Instance.rawSeed; } var saveTask = highScore.SaveAsync(); while (!saveTask.IsCompleted) { yield return(null); } if (saveTask.IsFaulted) { foreach (var e in task.Exception.InnerExceptions) { ParseException parseException = (ParseException)e; Debug.Log("Error saving high score.\r\nError message: " + parseException.Message + "\r\nErrorCode: " + parseException.Code); } result.IsCompleted = true; result.IsFaulted = true; yield break; } result.IsCompleted = true; PlayerPrefs.SetInt(currentGameMode.ModeName + "HighScore", currentGameMode.Score); GlobalData.Instance.highScores[currentGameMode.ModeName] = currentGameMode.Score; } else { //Update high score if recorded one is lower than the obtained one (or if the game changed versions in the meantime) var previousHighScore = task.Result; if (previousHighScore.Get <string>("gameVersion") != GlobalData.Instance.version || previousHighScore.Get <long>("score") < currentGameMode.Score || (previousHighScore.Get <string>("gameMode") == "PeriodicMode" && previousHighScore.Get <string>("rawSeedUsed") != GlobalData.Instance.rawSeed)) { previousHighScore["gameVersion"] = GlobalData.Instance.version; previousHighScore["score"] = currentGameMode.Score; if (currentGameMode.ModeName == "PeriodicMode") { previousHighScore["seedUsed"] = GlobalData.Instance.periodicModeSeed; previousHighScore["rawSeedUsed"] = GlobalData.Instance.rawSeed; } var saveTask = previousHighScore.SaveAsync(); if (saveTask.IsFaulted) { foreach (var e in task.Exception.InnerExceptions) { ParseException parseException = (ParseException)e; Debug.Log("Error updating high score.\r\nError message: " + parseException.Message + "\r\nErrorCode: " + parseException.Code); } result.IsCompleted = true; result.IsFaulted = true; yield break; } result.IsCompleted = true; PlayerPrefs.SetInt(currentGameMode.ModeName + "HighScore", currentGameMode.Score); GlobalData.Instance.highScores[currentGameMode.ModeName] = currentGameMode.Score; } } /* Facebook score saving was here * var formData = new Dictionary<string, string>(); * formData.Add("score", currentGameMode.Score.ToString()); * FB.API("/me/scores", Facebook.HttpMethod.POST, PostScoreCallback, formData); //TODO-> Add callback and error handling*/ }
/// <summary> /// 记录异常,并再次返回这个异常 /// </summary> private ParseException Error(ParseException e) { return(_exceptions.AddLast(e).Value); }
/// <summary> /// Constructor /// </summary> /// <param name="fieldId"></param> /// <param name="calculation"></param> /// <param name="expression"></param> /// <param name="exception"></param> public CalculatedFieldMetadata(long fieldId, string calculation, IExpression expression, ParseException exception) { CalculatedFieldId = fieldId; Calculation = calculation; // may be null if fieldId wasn't a valid calculation. Expression = expression; // may be null if calculation wasn't valid. Exception = exception; }
public override void Done(ParseException p0) { action (user, p0); }
public void AddError(ParseException e) { this.errors.Add(e); }
public override void Done(byte[] data, ParseException e) { action(data, e); }
IEnumerator GetSelfScores() { if (!FB.IsLoggedIn) { yield break; } while (GlobalData.Instance.FriendsInfo == null) { yield return(null); } HashSet <string> friendsIDs = new HashSet <string>(); foreach (var friend in GlobalData.Instance.FriendsInfo) { friendsIDs.Add(friend.Key); } var gameModes = new List <string> { "ClassicMode", "GrowthMode", "PeriodicMode" }; var parameters = new Dictionary <string, object> { { "userID", FB.UserId }, { "gameVersion", GlobalData.Instance.version }, { "friendsIDs", friendsIDs.ToList() }, { "gameModes", gameModes } }; var playerScoresAndRanksTask = ParseCloud.CallFunctionAsync <Dictionary <string, object> >("PlayerScoresAndRanks", parameters); while (!playerScoresAndRanksTask.IsCompleted) { yield return(null); } if (playerScoresAndRanksTask.IsFaulted) { foreach (var e in playerScoresAndRanksTask.Exception.InnerExceptions) { ParseException parseException = (ParseException)e; Debug.Log("Error getting your score.\r\nError message: " + parseException.Message + "\r\nErrorCode: " + parseException.Code); } } else { Dictionary <string, object> playerScoresAndRanks = playerScoresAndRanksTask.Result; foreach (var gameMode in gameModes) { selfScoresRanks.Add(new DTOSelfScoreRank { GameMode = gameMode, Rank = Convert.ToInt32(playerScoresAndRanks[gameMode + "Rank"]), Score = (long)playerScoresAndRanks[gameMode + "Score"] }); playerNameplates[GetModeIndex(gameMode)].score.Text = playerScoresAndRanks[gameMode + "Score"].ToString(); GlobalData.Instance.highScores[gameMode] = (long)playerScoresAndRanks[gameMode + "Score"]; } try { playerRank.Text = playerScoresAndRanks[currentMode + "Rank"].ToString(); } catch { Debug.Log("Tried to access " + currentMode + "Rank"); } } }
public object Parse(INamedParameterNode np, string value) { IClassNode iface = null; try { iface = (IClassNode)GetNode(np.GetFullArgName()); } catch (NameResolutionException e) { Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Caught(e, Level.Error, LOGGER); var ex = new IllegalStateException("Could not parse validated named parameter argument type. NamedParameter is " + np.GetFullName() + " argument type is " + np.GetFullArgName(), e); Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER); } Type clazz; string fullName; try { clazz = (Type)ClassForName(iface.GetFullName()); fullName = null; } catch (TypeLoadException e) { Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Caught(e, Level.Warning, LOGGER); clazz = null; fullName = iface.GetFullName(); } object result = null; if (clazz != null) { result = Parameterparser.Parse(clazz, value); } else { result = Parameterparser.Parse(fullName, value); } if (result == null) { try { INode impl = GetNode(value); if (impl is IClassNode) { if (IsImplementation(iface, (IClassNode)impl)) { return(impl); } } var ex = new ParseException( "Name<" + iface.GetFullName() + "> " + np.GetFullName() + " cannot take non-subclass " + impl.GetFullName()); Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER); } catch (NameResolutionException ec) { Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Caught(ec, Level.Error, LOGGER); var ex = new ParseException( "Name<" + iface.GetFullName() + "> " + np.GetFullName() + " cannot take non-class " + value, ec); Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER); } } return(result); }
public static T ParseBlock <T>(XmlNode node, DFG <Block> dfg, ParserInfo parserInfo, string id, string nodeName, ParseException exception) where T : Block { XmlNode leftNode = node.GetInnerBlockNode(nodeName, parserInfo, exception); if (leftNode != null) { return((T)XmlParser.ParseBlock(leftNode, dfg, parserInfo, false, false)); } return(null); }
private void TestDataGeneration(string sourcePath, string dataPath, bool useAsyncMethods = false) { string fileLogPath = Path.Combine(dataPath, "parse.log"); string callLogPath = Path.Combine(dataPath, "methodcalls.log"); bool regenerateSrcML = shouldRegenerateSrcML; if (!Directory.Exists(sourcePath)) { Assert.Ignore("Source code for is missing"); } if (File.Exists(callLogPath)) { File.Delete(callLogPath); } if (File.Exists(fileLogPath)) { File.Delete(fileLogPath); } if (!Directory.Exists(dataPath)) { regenerateSrcML = true; } else if (shouldRegenerateSrcML) { Directory.Delete(dataPath, true); } var archive = new SrcMLArchive(dataPath, regenerateSrcML); archive.XmlGenerator.ExtensionMapping[".cxx"] = Language.CPlusPlus; archive.XmlGenerator.ExtensionMapping[".c"] = Language.CPlusPlus; archive.XmlGenerator.ExtensionMapping[".cc"] = Language.CPlusPlus; int numberOfFailures = 0; int numberOfSuccesses = 0; int numberOfFiles = 0; Dictionary <string, List <string> > errors = new Dictionary <string, List <string> >(); using (var fileLog = new StreamWriter(fileLogPath)) { using (var monitor = new FileSystemFolderMonitor(sourcePath, dataPath, new LastModifiedArchive(dataPath), archive)) { DateTime start, end = DateTime.MinValue; bool startupCompleted = false; start = DateTime.Now; if (useAsyncMethods) { var task = monitor.UpdateArchivesAsync().ContinueWith((t) => { end = DateTime.Now; startupCompleted = true; }); task.Wait(); } else { monitor.UpdateArchives(); end = DateTime.Now; startupCompleted = true; } if (!startupCompleted) { end = DateTime.Now; } Console.WriteLine("{0} to {1} srcML", end - start, (regenerateSrcML ? "generate" : "verify")); Assert.That(startupCompleted); using (var data = new DataRepository(archive)) { start = DateTime.Now; data.FileProcessed += (o, e) => { if (e.EventType == FileEventType.FileAdded) { numberOfFiles++; numberOfSuccesses++; if (numberOfFiles % 100 == 0) { Console.WriteLine("{0,5:N0} files completed in {1} with {2,5:N0} failures", numberOfFiles, DateTime.Now - start, numberOfFailures); } fileLog.WriteLine("OK {0}", e.FilePath); } }; data.ErrorRaised += (o, e) => { numberOfFiles++; numberOfFailures++; if (numberOfFiles % 100 == 0) { Console.WriteLine("{0,5:N0} files completed in {1} with {2,5:N0} failures", numberOfFiles, DateTime.Now - start, numberOfFailures); } ParseException pe = e.Exception as ParseException; if (pe != null) { fileLog.WriteLine("ERROR {0}", pe.FileName); fileLog.WriteLine(e.Exception.InnerException.StackTrace); var key = e.Exception.InnerException.StackTrace.Split('\n')[0].Trim(); if (!errors.ContainsKey(key)) { errors[key] = new List <string>(); } int errorLineNumber = (pe.LineNumber < 1 ? 1 : pe.LineNumber); int errorColumnNumber = (pe.ColumnNumber < 1 ? 1 : pe.ColumnNumber); var errorLocation = String.Format("{0}({1},{2})", pe.FileName, errorLineNumber, errorColumnNumber); errors[key].Add(errorLocation); } }; if (useAsyncMethods) { data.InitializeDataAsync().Wait(); } else { data.InitializeData(); } end = DateTime.Now; Console.WriteLine("{0,5:N0} files completed in {1} with {2,5:N0} failures", numberOfFiles, end - start, numberOfFailures); Console.WriteLine("{0} to generate data", end - start); Console.WriteLine("\nSummary"); Console.WriteLine("==================="); Console.WriteLine("{0,10:N0} failures ({1,8:P2})", numberOfFailures, ((float)numberOfFailures) / numberOfFiles); Console.WriteLine("{0,10:N0} successes ({1,8:P2})", numberOfSuccesses, ((float)numberOfSuccesses) / numberOfFiles); Console.WriteLine("{0} to generate data", end - start); Console.WriteLine(fileLogPath); IScope globalScope; Assert.That(data.TryLockGlobalScope(Timeout.Infinite, out globalScope)); try { PrintScopeReport(globalScope); PrintMethodCallReport(globalScope, callLogPath); PrintErrorReport(errors); } finally { data.ReleaseGlobalScopeLock(); } } } } }
public static Either <ParseException, Pair <List <IToken>, RoutineDeclarationNode> > Parse(List <IToken> tokens, SymT symT, IScopedTable <IEntityType, string> parentTypeTable) { var NewSymT = new SymT(symT); Console.WriteLine("RoutineDeclarationNode"); if (tokens.Count <= 3) { return(NotARoutineException); } var maybeRoutine = tokens[0]; var maybeIdentifier = tokens[1]; var maybeLp = tokens[2]; if ( !(maybeRoutine is RoutineKeywordToken) || !(maybeIdentifier is IdentifierToken) || !(maybeLp is LeftParenthSymbolToken) ) { return(NotARoutineException); } IdentifierToken identifier = (IdentifierToken)maybeIdentifier; tokens = tokens.Skip(3).ToList(); var parameters = new List <ParameterNode>(); var typeTable = new Dictionary <string, IEntityType>(); while (true) { var maybeParameter = ParameterNode.Parse(tokens, NewSymT, parentTypeTable); if (maybeParameter.IsLeft) { break; } var parameter = maybeParameter.RightToList()[0].Second; parameters.Add(parameter); typeTable.TryAdd(parameter.Name.Lexeme, new VariableType(parameter.Type.ToTypeRepresentation())); tokens = maybeParameter.RightToList()[0].First; if (tokens.Count < 1) { return(NotARoutineException); } if (tokens[0] is ComaSymbolToken) { tokens = tokens.Skip(1).ToList(); continue; } break; } if (tokens[0] is RightParenthSymbolToken) { tokens = tokens.Skip(1).ToList(); } else { return(NotARoutineException); } if (tokens.Count < 2) { return(NotARoutineException); } Either <ParseException, Pair <List <IToken>, TypeNode> > maybeType = new ParseException("Dummy"); if (tokens[0] is ColonSymbolToken) { tokens = tokens.Skip(1).ToList(); maybeType = TypeNode.Parse(tokens, symT, parentTypeTable); if (maybeType.IsLeft) { return(NotARoutineException); } tokens = maybeType.RightToList()[0].First; } if (tokens.Count < 1) { return(NotARoutineException); } if (!(tokens[0] is IsKeywordToken)) { return(NotARoutineException); } tokens = tokens.Skip(1).ToList(); var result = new RoutineDeclarationNode( identifier, parameters, maybeType.Map <TypeNode>(pr => pr.Second).ToOption(), null, NewSymT, typeTable, parentTypeTable ); var maybeBody = BodyNode.Parse(tokens, NewSymT, result); if (maybeBody.IsLeft) { return(maybeBody.LeftToList()[0]); } tokens = maybeBody.RightToList()[0].First; if (tokens.Count < 1) { return(NotARoutineException); } if (!(tokens[0] is EndKeywordToken)) { return(NotARoutineException); } tokens = tokens.Skip(1).ToList(); while (tokens.Count > 0) { if (tokens[0] is NewLineSymbolToken || tokens[0] is CommentToken || tokens[0] is SemicolonSymbolToken) { tokens = tokens.Skip(1).ToList(); } else { break; } } result.Body = maybeBody.RightToList()[0].Second; return(new Pair <List <IToken>, RoutineDeclarationNode>(tokens, result)); }
public void Test_ParseException() { long[] fieldIds = new long[] { 11, 22 }; long[] entityIds = new long[] { 33, 44, 55 }; CalculatedFieldSettings settings = new CalculatedFieldSettings { TimeZone = "Australia/Sydney" }; CalculatedFieldProvider provider; Mock <ICalculatedFieldMetadataProvider> mockMetadataProvider; Mock <IEntityRepository> mockEntityRepository; Mock <IExpressionRunner> mockExpressionRunner; IReadOnlyCollection <CalculatedFieldMetadata> mockMetadata; IReadOnlyCollection <CalculatedFieldResult> actualResult; IReadOnlyCollection <IEntity> mockEntities; int mockFirstResult = 100; Mock <IExpression> mockExpression; ParseException exception = new ParseException("Test error"); // Mock metadata provider mockExpression = new Mock <IExpression>(); mockMetadata = new[] { new CalculatedFieldMetadata(11, "abc", null, exception), new CalculatedFieldMetadata(22, "abc", mockExpression.Object, null) }; mockMetadataProvider = new Mock <ICalculatedFieldMetadataProvider>(MockBehavior.Strict); mockMetadataProvider .Setup(p => p.GetCalculatedFieldMetadata(fieldIds, settings)) .Returns(mockMetadata); // Mock entity repository mockEntities = entityIds.Select(id => new Mock <IEntity>().Object).ToArray(); mockEntityRepository = new Mock <IEntityRepository>(MockBehavior.Strict); mockEntityRepository.Setup(er => er.Get(entityIds)).Returns(mockEntities); // Mock expression runner mockExpressionRunner = new Mock <IExpressionRunner>(MockBehavior.Strict); int runResult = mockFirstResult; foreach (IEntity entity in mockEntities) { mockExpressionRunner .Setup(exprRun => exprRun.Run( mockExpression.Object, It.Is <EvaluationSettings>(evalSetting => evalSetting.ContextEntity == entity))) .Returns(() => new ExpressionRunResult(runResult++)); } // Run test provider = new CalculatedFieldProvider(mockMetadataProvider.Object, mockExpressionRunner.Object, mockEntityRepository.Object); actualResult = provider.GetCalculatedFieldValues(fieldIds, entityIds, settings); // Verify Assert.That(actualResult, Has.Count.EqualTo(2)); var firstField = actualResult.First(); Assert.That(firstField, Is.Not.Null); Assert.That(firstField.FieldId, Is.EqualTo(fieldIds.First())); Assert.That(firstField.ParseException, Is.EqualTo(exception)); Assert.That(firstField.Entities, Is.Null); var lastField = actualResult.Last(); var lastResult = lastField.Entities.Last(); Assert.That(lastResult, Is.Not.Null); Assert.That(lastResult.EvaluationException, Is.Null); Assert.That(lastResult.Result, Is.EqualTo(mockFirstResult + 2)); mockMetadataProvider.VerifyAll(); mockEntityRepository.VerifyAll(); mockExpressionRunner.VerifyAll(); }
/// <summary> /// Displays a ParseException /// </summary> /// <param name="ex">The exception</param> private static void ShowException(ParseException ex) { PrepareToShow(); //string errorMessage = LocalizeMessage(Strings.UNEXPECTED_TOKEN, ex.UnexpectedToken.Text); string errorMessage = Util.GetComprehensiveExceptionMessage(ex); ShowError(errorMessage, false); }
private void NextToken() { while (char.IsWhiteSpace(_parseChar)) { NextChar(); } TokenId t; var tokenPos = _parsePosition; switch (_parseChar) { case '!': NextChar(); if (_parseChar == '=') { NextChar(); t = TokenId.ExclamationEqual; } else { t = TokenId.Exclamation; } break; case '%': NextChar(); t = TokenId.Percent; break; case '&': NextChar(); if (_parseChar == '&') { NextChar(); t = TokenId.DoubleAmphersand; } else { t = TokenId.Amphersand; } break; case '(': NextChar(); t = TokenId.OpenParen; break; case ')': NextChar(); t = TokenId.CloseParen; break; case '*': NextChar(); t = TokenId.Asterisk; break; case '+': NextChar(); t = TokenId.Plus; break; case ',': NextChar(); t = TokenId.Comma; break; case '-': NextChar(); t = TokenId.Minus; break; case '.': NextChar(); if (char.IsDigit(_parseChar)) { t = TokenId.RealLiteral; do { NextChar(); } while (char.IsDigit(_parseChar)); if (_parseChar == 'E' || _parseChar == 'e') { t = TokenId.RealLiteral; NextChar(); if (_parseChar == '+' || _parseChar == '-') { NextChar(); } ValidateDigit(); do { NextChar(); } while (char.IsDigit(_parseChar)); } if (_parseChar == 'F' || _parseChar == 'f' || _parseChar == 'M' || _parseChar == 'm') { NextChar(); } break; } t = TokenId.Dot; break; case '/': NextChar(); t = TokenId.Slash; break; case ':': NextChar(); t = TokenId.Colon; break; case '<': NextChar(); if (_parseChar == '=') { NextChar(); t = TokenId.LessThanEqual; } else { t = TokenId.LessThan; } break; case '=': NextChar(); if (_parseChar == '=') { NextChar(); t = TokenId.DoubleEqual; } else { t = TokenId.Equal; } break; case '>': NextChar(); if (_parseChar == '=') { NextChar(); t = TokenId.GreaterThanEqual; } else { t = TokenId.GreaterThan; } break; case '?': NextChar(); if (_parseChar == '.') { NextChar(); t = TokenId.QuestionDot; } else if (_parseChar == '?') { NextChar(); t = TokenId.QuestionQuestion; } else { t = TokenId.Question; } break; case '[': NextChar(); t = TokenId.OpenBracket; break; case ']': NextChar(); t = TokenId.CloseBracket; break; case '|': NextChar(); if (_parseChar == '|') { NextChar(); t = TokenId.DoubleBar; } else { t = TokenId.Bar; } break; case '"': NextChar(); bool isEscapeS = false; bool isEndS = _parseChar == '\"'; while (_parsePosition < _expressionTextLength && !isEndS) { isEscapeS = _parseChar == '\\' && !isEscapeS; NextChar(); isEndS = (_parseChar == '\"' && !isEscapeS); } if (_parsePosition == _expressionTextLength) { throw ParseException.Create(_parsePosition, ErrorMessages.UnterminatedStringLiteral); } NextChar(); t = TokenId.StringLiteral; break; case '\'': NextChar(); bool isEscapeC = false; bool isEndC = false; while (_parsePosition < _expressionTextLength && !isEndC) { isEscapeC = _parseChar == '\\' && !isEscapeC; NextChar(); isEndC = (_parseChar == '\'' && !isEscapeC); } if (_parsePosition == _expressionTextLength) { throw ParseException.Create(_parsePosition, ErrorMessages.UnterminatedStringLiteral); } NextChar(); t = TokenId.CharLiteral; break; case '^': NextChar(); t = TokenId.Caret; break; default: if (char.IsLetter(_parseChar) || _parseChar == '@' || _parseChar == '_') { do { NextChar(); } while (char.IsLetterOrDigit(_parseChar) || _parseChar == '_'); t = TokenId.Identifier; break; } if (char.IsDigit(_parseChar)) { t = TokenId.IntegerLiteral; do { NextChar(); } while (char.IsDigit(_parseChar)); if (_parseChar == '.') { NextChar(); if (char.IsDigit(_parseChar)) { t = TokenId.RealLiteral; do { NextChar(); } while (char.IsDigit(_parseChar)); } else { PreviousChar(); break; } } if (_parseChar == 'E' || _parseChar == 'e') { t = TokenId.RealLiteral; NextChar(); if (_parseChar == '+' || _parseChar == '-') { NextChar(); } ValidateDigit(); do { NextChar(); } while (char.IsDigit(_parseChar)); } if (_parseChar == 'F' || _parseChar == 'f' || _parseChar == 'M' || _parseChar == 'm') { t = TokenId.RealLiteral; NextChar(); } break; } if (_parsePosition == _expressionTextLength) { t = TokenId.End; break; } throw ParseException.Create(_parsePosition, ErrorMessages.InvalidCharacter, _parseChar); } _token.id = t; _token.text = _expressionText.Substring(tokenPos, _parsePosition - tokenPos); _token.pos = tokenPos; }
public Task TestDeleteAllFailSome() { var states = new List <IObjectState>(); for (int i = 0; i < 30; ++i) { states.Add(new MutableObjectState { ClassName = "Corgi", ObjectId = ((i % 2 == 0) ? null : "st4nl3yW" + i), ServerData = new Dictionary <string, object>() { { "corgi", "isNotDoge" }, } }); } var results = new List <IDictionary <string, object> >(); for (int i = 0; i < 15; ++i) { if (i % 2 == 0) { results.Add(new Dictionary <string, object> { { "error", new Dictionary <string, object>() { { "code", (long)ParseException.ErrorCode.ObjectNotFound }, { "error", "Object not found." } } } }); } else { results.Add(new Dictionary <string, object> { { "success", null } }); } } var responseDict = new Dictionary <string, object>() { { "results", results } }; var response = new Tuple <HttpStatusCode, IDictionary <string, object> >(HttpStatusCode.OK, responseDict); var mockRunner = CreateMockRunner(response); var controller = new ParseObjectController(mockRunner.Object); var tasks = controller.DeleteAllAsync(states, null, CancellationToken.None); return(Task.WhenAll(tasks).ContinueWith(_ => { for (int i = 0; i < 15; ++i) { if (i % 2 == 0) { Assert.True(tasks[i].IsFaulted); Assert.IsInstanceOf <ParseException>(tasks[i].Exception.InnerException); ParseException exception = tasks[i].Exception.InnerException as ParseException; Assert.AreEqual(ParseException.ErrorCode.ObjectNotFound, exception.Code); } else { Assert.True(tasks[i].IsCompleted); Assert.False(tasks[i].IsFaulted || tasks[i].IsCanceled); } } mockRunner.Verify(obj => obj.RunCommandAsync(It.Is <ParseCommand>(command => command.Uri.AbsolutePath == "/1/batch"), It.IsAny <IProgress <ParseUploadProgressEventArgs> >(), It.IsAny <IProgress <ParseDownloadProgressEventArgs> >(), It.IsAny <CancellationToken>()), Times.Exactly(1)); })); }
public override void Done(ParseObject pobject, ParseException pexception) { action (pobject, pexception); }
public override void ErrorNode( ITokenStream input, IToken start, IToken stop, RecognitionException e) { HasErrors = true; LastException = new ParseException(e); }
public void ParseException_with_message_and_inner_exception() { var e = new ParseException(_parseReason, _message, _innerException); Assert.AreEqual(_message, e.Message); Assert.AreSame(_innerException, e.InnerException); Assert.AreEqual(_parseReason, e.Reason); }
public ErrorInfo(ErrorType type, ParseException.ErrorCode code) { ErrorType = type; ErrorCode = code; }
public override void Done(ParseObject obj, ParseException error) { callback(obj, error); }
public override void Done(ParseObject obj, ParseException error) { callback (obj, error); }
public void at_least_one_char() { var e = new ParseException("operator", new string[0], new SourceSpan(new SourceLocation(11, 1, 3), 0)); Assert.AreEqual(new SourceSpan(new SourceLocation(11, 1, 3), 1), e.Location); }
void SignUpCallback(ParseUser user, ParseException e) { if (isDead) { user.DeleteInBackground (); return; } progress.Visibility = ViewStates.Invisible; if (user != null && e == null) { informativeText.Text = "Verification email sent. Waiting for confirmation..."; RefreshLoop (user); } else { SetResult (Result.Canceled); actionButton.Text = "< Go Back"; informativeText.Text = "Error: the username likely exists already"; } }
/// <inheritdoc/> public ExcelWorksheet GetExcelWorksheet(ExcelPackage package, string sheetName, out ParseException exception) { ExcelWorksheet worksheet = package.Workbook.Worksheets[sheetName]; if (worksheet == null) { //We don't have a valid sheet exception = new() { Sheet = sheetName, ExceptionType = ParseExceptionType.SheetMissingError, Severity = ParseExceptionSeverity.Error, }; return(null); } exception = null; return(worksheet); }
private static TomlObject ToTomlValue(ITomlRoot root, ValueNode node) { switch (node.Value.SyntaxNode()) { case TerminalNode tn: return(CreateValueFromTerminal(tn.Terminal)); case ArrayNode an: return(CreateArrayOrTableArray(an)); case InlineTableNode it: return(CreateInlineTable(it)); default: throw new Exception($"Cannot create TomlValue from node with type '{node.GetType()}'."); } TomlValue CreateValueFromTerminal(Token terminal) { switch (terminal.Type) { case TokenType.Integer: return(new TomlInt(root, Convert.ToInt64(Cleanup(terminal.Value, 0)), TomlInt.IntTypes.Decimal)); case TokenType.HexInteger: return(new TomlInt(root, Convert.ToInt64(Cleanup(terminal.Value, 2), 16), TomlInt.IntTypes.Hex)); case TokenType.BinaryInteger: return(new TomlInt(root, Convert.ToInt64(Cleanup(terminal.Value, 2), 2), TomlInt.IntTypes.Binary)); case TokenType.OctalInteger: return(new TomlInt(root, Convert.ToInt64(Cleanup(terminal.Value, 2), 8), TomlInt.IntTypes.Octal)); case TokenType.Bool: return(new TomlBool(root, Convert.ToBoolean(terminal.Value))); case TokenType.String: return(new TomlString(root, terminal.Value.Unescape(terminal))); case TokenType.LiteralString: return(new TomlString(root, terminal.Value, TomlString.TypeOfString.Literal)); case TokenType.MultilineLiteralString: return(new TomlString(root, terminal.Value, TomlString.TypeOfString.MultilineLiteral)); case TokenType.MultilineString: return(new TomlString(root, terminal.Value, TomlString.TypeOfString.Multiline)); case TokenType.Float: return(TomlFloat.FromTerminal(root, terminal)); case TokenType.OffsetDateTime: return(TomlOffsetDateTime.Parse(root, terminal.Value)); case TokenType.LocalTime: return(TomlLocalTime.Parse(root, terminal.Value)); case TokenType.Duration: return(TomlDuration.Parse(root, terminal.Value)); case TokenType.LocalDate: return(TomlLocalDate.Parse(root, terminal.Value)); case TokenType.LocalDateTime: return(TomlLocalDateTime.Parse(root, terminal.Value)); default: throw new NotSupportedException(); } string Cleanup(string s, int sub) => s.Substring(sub).Replace("_", string.Empty); } TomlObject CreateArrayOrTableArray(ArrayNode array) { var values = CreateValues(array.GetValues()).ToList(); var tables = values.OfType <TomlTable>().ToList(); if (tables.Count > 0 && tables.Count == values.Count) { var ta = new TomlTableArray(root, tables); ta.AddComments(array); return(ta); } else if (tables.Count == 0) { var arr = new TomlArray(root, values.Cast <TomlValue>().ToArray()); arr.AddComments(array); return(arr); } else { throw new InvalidOperationException("Array is a mixture of a value array and a TOML table array."); } IEnumerable <TomlObject> CreateValues(IEnumerable <ValueNode> nodes) { var linked = nodes.Select(n => Tuple.Create(n, ToTomlValue(root, n))).ToList(); var expectedType = linked.DistinctBy(n => n.Item2.GetType()).FirstOrDefault(); var wrongType = linked.DistinctBy(n => n.Item2.GetType()).Skip(1).FirstOrDefault(); if (wrongType != null) { string msg = $"Expected array value of type '{expectedType.Item2.ReadableTypeName}' " + $"but value of type '{wrongType.Item2.ReadableTypeName}' was found.'"; throw ParseException.MessageForNode(wrongType.Item1, msg); } return(linked.Select(l => l.Item2)); } } TomlTable CreateInlineTable(InlineTableNode it) { TomlTable table = new TomlTable(root, TomlTable.TableTypes.Inline); table.AddComments(it); System.Collections.Generic.IEnumerable <KeyValueExpressionNode> expressions = it.GetExpressions(); foreach (KeyValueExpressionNode e in expressions) { table.AddRow(e.Key.SyntaxNode().ExpressionKey(), ToTomlValue(root, e.Value.SyntaxNode())); } return(table); } }
public override void Done(ParseException e) { callback (e); }