public void ParserGeneratedStageErrors() { var grammarText = $@"grammar {TestGrammarName}; start: rule1+; rule: DIGIT; CHAR: [a-z]+; DIGIT: [0-9]+; WS: [ \r\n\t]+ -> skip;"; var workflow = new Workflow(GrammarFactory.CreateDefaultCombinedAndFill(grammarText, TestGrammarName, ".")); var state = workflow.Process(); Assert.AreEqual(WorkflowStage.ParserGenerated, state.Stage, state.Exception?.ToString()); var grammarSource = new CodeSource(TestGrammarName + ".g4", File.ReadAllText(TestGrammarName + ".g4")); char separator = Path.DirectorySeparatorChar; string testGrammarFullName = $"{Environment.CurrentDirectory}{separator}.{separator}{TestGrammarName}.g4"; ParserGeneratedState parserGeneratedState = state as ParserGeneratedState; string str = new ParsingError(2, 24, $"error(56): {testGrammarFullName}:2:24: reference to undefined rule: rule1", grammarSource, WorkflowStage.ParserGenerated).ToString(); CollectionAssert.AreEquivalent( new [] { new ParsingError(2, 24, $"error(56): {testGrammarFullName}:2:24: reference to undefined rule: rule1", grammarSource, WorkflowStage.ParserGenerated), }, parserGeneratedState.Errors); }
private static ParsingException GetException(ParsingError error, int lineNo, int columnNo, string line, string message, string path) { message = string.Format("Error E{0:D2}: ", (int)error) + message + Environment.NewLine + string.Format("At {0}{1}:{2}:", path == "" ? "" : path + ':', lineNo + 1, columnNo + 1) + Environment.NewLine + line + Environment.NewLine + new string(' ', columnNo) + "^"; throw new ParsingException(error, message); }
private void HandleDataReceived(object sender, string messageJson) { try { var message = Serializer.DeserializeJson <CodeChangeMessage>(messageJson); if (message.Error == null) { Runtime.HandleCodeChange(message.CodeChange); RequestHandled?.Invoke(); } else if (message.Error.ParsingError != null) { ParsingError?.Invoke(message.Error.ParsingError); } else if (message.Error.CompileError != null) { CompileError?.Invoke(message.Error.CompileError); } } catch (Exception ex) { Debug.WriteLine(ex); ParsingError?.Invoke(ex.Message); } }
private void ParserGeneration_ErrorDataReceived(object sender, DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data) && !e.IsIgnoreJavaError()) { var strs = e.Data.Split(':'); int line = 1, column = 1; int locationIndex = strs.Length > 2 && strs[2].Length > 0 && strs[2][0] == '\\' ? 3 : 2; if (strs.Length > locationIndex) { if (!int.TryParse(strs[locationIndex], out line)) { line = 1; } if (strs.Length > locationIndex + 1) { if (!int.TryParse(strs[locationIndex + 1], out column)) { column = 1; } } } bool isWarning = strs.Length > 0 && strs[0].StartsWith("warning"); ParsingError error = new ParsingError(line, column, e.Data, _currentGrammarSource, WorkflowStage.ParserGenerated, isWarning); ErrorEvent?.Invoke(this, error); _result.Errors.Add(error); } }
private static string FormatParsingErrorMessage19(ParsingError error) { var words = ClpUtils.SentenceBuilder19; var message = new StringBuilder(); bool hasLong = error.BadOption.LongName?.Length > 0; if (error.BadOption.ShortName != null) { message.Append($"-{error.BadOption.ShortName}{(hasLong ? "/" : "")}"); } if (hasLong) { message.Append($"--{error.BadOption.LongName}"); } message.Append($" {(error.ViolatesRequired ? words.RequiredOptionMissingText : words.OptionWord)}"); if (error.ViolatesFormat) { message.Append($" {words.ViolatesFormatText}"); } if (error.ViolatesMutualExclusiveness) { if (error.ViolatesFormat || error.ViolatesRequired) { message.Append($" {words.AndWord}"); } message.Append($" {words.ViolatesMutualExclusivenessText}"); } message.Append('.'); return(message.ToString()); }
public void ParsingErrorSetsMessage() { var expected = "test message"; var error = new ParsingError(expected); Assert.True(expected == error.Message, "ParsingError constructor should set message"); }
public void New() { var message = "foo"; var position = new Position(message); var pattern1 = new Literal("foo", "Hello"); var pattern2 = new Literal("foo"); var err1 = new ParsingError(message, position, pattern1); Assert.AreEqual(message, err1.Message); Assert.AreEqual(position, err1.Position); Assert.AreEqual(pattern1, err1.Pattern); Assert.AreEqual(null, err1.InnerError); var err2 = new ParsingError(message, position, pattern2); Assert.AreEqual(pattern2, err2.Pattern); Assert.AreEqual(null, err2.InnerError); var err3 = new ParsingError(message, position, pattern1, err1); Assert.AreEqual(err1, err3.InnerError); var err4 = new ParsingError(message, position, pattern1, err2); Assert.AreEqual(null, err4.InnerError); }
// // All public ctors go through here // private void CreateThis(string?uri, bool dontEscape, UriKind uriKind) { DebugAssertInCtor(); // if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow // to be used here. if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative) { throw new ArgumentException(SR.Format(SR.net_uri_InvalidUriKind, uriKind)); } _string = uri ?? string.Empty; Debug.Assert(_originalUnicodeString is null && _info is null && _syntax is null && _flags == Flags.Zero); if (dontEscape) { _flags |= Flags.UserEscaped; } ParsingError err = ParseScheme(_string, ref _flags, ref _syntax !); InitializeUri(err, uriKind, out UriFormatException? e); if (e != null) { throw e; } }
private void HandleDataReceived(object sender, string request) { try { var methodRequest = Serializer.DeserializeJson <CodeChangeRequest>(request); if (methodRequest.ParsingError != null) { ParsingError?.Invoke(methodRequest.ParsingError); } else if (methodRequest.CompileError != null) { CompileError?.Invoke(methodRequest.CompileError); } else { CodeChangeHandler.HandleRequest(methodRequest); RequestHandled?.Invoke(); } } catch (Exception ex) { Debug.WriteLine(ex); ParsingError?.Invoke(ex.Message); } }
private ParsingError GenerateError(string data, string codeFileName, int line, int column, string rest, bool isWarning = false) { ParsingError error; TextSpan textSpan; if (_grammarCodeMapping.TryGetValue(codeFileName, out List <TextSpanMapping> textSpanMappings)) { string grammarFileName = GetGrammarFromCodeFileName(_currentRuntimeInfo, codeFileName); textSpan = TextHelpers.GetSourceTextSpanForLine(textSpanMappings, line, grammarFileName); error = new ParsingError(textSpan, $"{grammarFileName}:{textSpan.GetLineColumn().BeginLine}:{rest}", WorkflowStage.ParserCompiled, isWarning); } else { Dictionary <string, CodeSource> grammarFilesData = _result.ParserGeneratedState.GrammarCheckedState.GrammarFilesData; CodeSource codeSource = grammarFilesData.FirstOrDefault(file => file.Key.EndsWith(codeFileName, StringComparison.OrdinalIgnoreCase)).Value; textSpan = codeSource != null ? new LineColumnTextSpan(line, column, codeSource).GetTextSpan() : TextSpan.Empty; error = new ParsingError(textSpan, data, WorkflowStage.ParserCompiled, isWarning); } return(error); }
private void AddCSharpError(string data) { if (data.Contains(": error CS")) { var errorString = Helpers.FixEncoding(data); ParsingError error; CodeSource grammarSource = CodeSource.Empty; try { // Format: // Lexer.cs(106,11): error CS0103: The name 'a' does not exist in the current context var strs = errorString.Split(':'); int leftParenInd = strs[0].IndexOf('('); string codeFileName = strs[0].Remove(leftParenInd); string grammarFileName = GetGrammarFromCodeFileName(_currentRuntimeInfo, codeFileName); string lineColumnString = strs[0].Substring(leftParenInd); lineColumnString = lineColumnString.Substring(1, lineColumnString.Length - 2); // Remove parenthesis. var strs2 = lineColumnString.Split(','); int line = int.Parse(strs2[0]); int column = int.Parse(strs2[1]); string rest = string.Join(":", strs.Skip(1)); error = GenerateError(data, codeFileName, line, column, rest); } catch { error = new ParsingError(errorString, grammarSource, WorkflowStage.ParserCompiled); } AddError(error); } }
public async Task GetConfigForFile_FailedToProcessTsConfig_ParsingError_TsConfigIsSkipped() { const string testedFileName = "tested\\file"; var tsConfigsInSolution = new[] { "config1", "config2" }; var tsConfigsLocator = SetupTsConfigsLocator(testedFileName, tsConfigsInSolution); var eslintBridgeClient = new Mock <ITypeScriptEslintBridgeClient>(); var parsingError = new ParsingError { Code = ParsingErrorCode.UNSUPPORTED_TYPESCRIPT, Message = "some message", Line = 5555 }; SetupEslintBridgeResponse(eslintBridgeClient, new Dictionary <string, TSConfigResponse> { { "config1", new TSConfigResponse { ParsingError = parsingError, Files = new[] { testedFileName } // should be ignored } }, { "config2", new TSConfigResponse() } }); var logger = new TestLogger(); var testSubject = CreateTestSubject(tsConfigsLocator.Object, eslintBridgeClient.Object, logger: logger); var result = await testSubject.GetConfigForFile(testedFileName, CancellationToken.None); result.Should().BeNull(); eslintBridgeClient.Verify(x => x.TsConfigFiles("config1", CancellationToken.None), Times.Once); eslintBridgeClient.Verify(x => x.TsConfigFiles("config2", CancellationToken.None), Times.Once); eslintBridgeClient.VerifyNoOtherCalls(); logger.AssertPartialOutputStringExists(parsingError.Message, parsingError.Code.ToString(), parsingError.Line.ToString()); }
// // All public ctors go through here // private void CreateThis(string uri, bool dontEscape, UriKind uriKind) { // if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow // to be used here. if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative) { throw new ArgumentException(SR.Format(SR.net_uri_InvalidUriKind, uriKind)); } _string = uri == null ? string.Empty : uri; if (dontEscape) { _flags |= Flags.UserEscaped; } ParsingError err = ParseScheme(_string, ref _flags, ref _syntax); UriFormatException e; InitializeUri(err, uriKind, out e); if (e != null) { throw e; } }
internal ParsingException(int charIndex, int row, int column, ParsingError error) : base(FormatMessage(charIndex, row, column, error)) { CharIndex = charIndex; Row = row; Column = column; Error = error; }
public ParsingErrors(ParsingError headError, ParsingErrors tailErrors, TextInput errorLocation, bool isFatal = false) { _headError = headError; _tailErrors = tailErrors; _errorLocation = errorLocation; IsFatal = isFatal; // System.Diagnostics.Trace.WriteLine("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ " + headError + " " + errorLocation); }
public ParsingError(string message, Position position, Pattern pattern, ParsingError innerError = null) : base(position) { Message = message; Pattern = pattern; if (innerError != null && innerError.Pattern.Name != null) { InnerError = innerError; } }
private async Task SetupAnalysisWithParsingError(ParsingError parsingError, ILogger logger) { var response = new AnalysisResponse { ParsingError = parsingError }; var eslintBridgeClient = SetupEslintBridgeClient(response: response); var testSubject = CreateTestSubject(eslintBridgeClient.Object, logger: logger); await testSubject.Analyze("some path", "some config", CancellationToken.None); }
public static ConvertionResult Convert(string code, AlgoType algotype, Model.File[] includeFiles) { string calgoCode = null; IEnumerable <ParsingError> parsingErrors = new ParsingError[0]; var compilerErrors = new CompilerError[0]; var codeBase = CodeBase.Mq4; if (CSharpCodeDetector.IsCSharpCode(code)) { codeBase = CodeBase.CSharp; } else if (MqCodeBaseDetector.IsMq5Code(code)) { codeBase = CodeBase.Mq5; } else if (!MqCodeBaseDetector.IsValidMq4Code(code)) { codeBase = CodeBase.Invalid; } else { var parser = new Mq4Parser(); var indicatorParsingResult = parser.Parse(code, algotype, includeFiles); var algo = indicatorParsingResult.Algo; parsingErrors = indicatorParsingResult.ParsingErrors; if (parsingErrors.All(e => e.ErrorType < ErrorType.Error)) { var presenter = CreatePresenter(algotype); calgoCode = presenter.GenerateCodeFrom(algo); var compiler = new CSharpCompiler(); var fileName = Path.GetTempFileName(); try { var codeToCompile = calgoCode; var indexToInsert = codeToCompile.IndexOf("//Custom Indicators Place Holder"); foreach (var customIndicatorName in algo.CustomIndicators) { codeToCompile = codeToCompile.Insert(indexToInsert, CustomIndicatorTemplate.Replace("CustomIndicatorName", customIndicatorName)); } compilerErrors = compiler.Compile(codeToCompile, fileName); codeBase = MqCodeBaseDetector.GetCodeBaseFromErrors(compilerErrors); } finally { File.Delete(fileName); } } } return(new ConvertionResult(calgoCode, parsingErrors, compilerErrors, codeBase)); }
// // a Uri.TryCreate() method goes through here. // internal static Uri CreateHelper(string uriString, bool dontEscape, UriKind uriKind, ref UriFormatException e) { // if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow // to be used here. if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative) { #if MONO if (uriKind != DotNetRelativeOrAbsolute) #endif throw new ArgumentException(SR.GetString(SR.net_uri_InvalidUriKind, uriKind)); } UriParser syntax = null; Flags flags = Flags.Zero; ParsingError err = ParseScheme(uriString, ref flags, ref syntax); if (dontEscape) { flags |= Flags.UserEscaped; } // We won't use User factory for these errors if (err != ParsingError.None) { // If it looks as a relative Uri, custom factory is ignored if (uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex) { return(new Uri((flags & Flags.UserEscaped), null, uriString)); } return(null); } // Cannot be relative Uri if came here Uri result = new Uri(flags, syntax, uriString); // Validate instance using ether built in or a user Parser try { result.InitializeUri(err, uriKind, out e); if (e == null) { return(result); } return(null); } catch (UriFormatException ee) { Debug.Assert(!syntax.IsSimple, "A UriPraser threw on InitializeAndValidate."); e = ee; // A precaution since custom Parser should never throw in this case. return(null); } }
private void HandleParsingError(ParsingError error) { var errorMessage = string.Format("Failed to get indexing data for the domain {0} with error message: {1}", error.DomainURL, error.ErrorMessage); _logger.Error(errorMessage); var domain = _domainService.GetDomainByUrl(error.DomainURL); Sender.Tell(domain, Self); }
protected void ReportWarning(string message, IToken token, Group group, CodeSource codeSource) { var warningTextSpan = new TextSpan(token.StartIndex + group.Index, group.Length, codeSource); var lineColumn = codeSource.ToLineColumn(warningTextSpan); var error = new ParsingError(warningTextSpan, Helpers.FormatErrorMessage(codeSource, lineColumn.BeginLine, lineColumn.BeginColumn, message, true), WorkflowStage.GrammarChecked, true); ErrorAction(error); }
private async Task SetupAnalysisWithParsingError(ParsingError parsingError, ILogger logger) { var response = new AnalysisResponse { ParsingError = parsingError }; var eslintBridgeClient = SetupEslintBridgeClient(response: response); var consumer = new Mock <IIssueConsumer>(); var testSubject = CreateTestSubject(eslintBridgeClient.Object, logger: logger); await testSubject.ExecuteAnalysis("some path", consumer.Object, CancellationToken.None); consumer.VerifyNoOtherCalls(); }
public void ParserTest_Throws( string template, int row, int column, ParsingError error) { var parser = new Parser(template); var ex = Assert.Throws <ParsingException>( () => parser.Parse()); Assert.Equal(row, ex.Row); Assert.Equal(column, ex.Column); Assert.Equal(error, ex.Error); }
private static IEnumerable <ParsingError> ListErrors(ParsingErrors errors, ParsingError error) { var result = new List <ParsingError> { error }; for (var current = errors; current != null; current = current._tailErrors) { result.Add(current._headError); } result.Reverse(); return(result); }
/// <summary> Add a new error which occurred during parsing to this MARC record object </summary> /// <param name="error"> Error object to add to the list </param> public void AddError(ParsingError error) { // Ensure the list is built if (_errors == null) { _errors = new List <ParsingError>(); } // If no other error of the same type exists, add this if (!_errors.Contains(error)) { _errors.Add(error); } }
public async Task ExecuteAnalysis_ResponseWithParsingError_MissingTypescript_ParsingErrorLogged() { var logger = new TestLogger(); var parsingError = new ParsingError { Code = ParsingErrorCode.MISSING_TYPESCRIPT, Line = 5, Message = "some message" }; await SetupAnalysisWithParsingError(parsingError, logger); logger.AssertPartialOutputStringExists(TypeScript.Analyzer.Resources.ERR_ParsingError_MissingTypescript); }
public async Task Analyze_ResponseWithParsingError_UnsupportedTypescript_ParsingErrorLogged() { var logger = new TestLogger(); var parsingError = new ParsingError { Code = ParsingErrorCode.UNSUPPORTED_TYPESCRIPT, Line = 5, Message = "some message" }; await SetupAnalysisWithParsingError(parsingError, logger); logger.AssertPartialOutputStringExists(TypeScript.Analyzer.Resources.ERR_ParsingError_UnsupportedTypescript); }
/// <summary> /// Java version: https://github.com/SonarSource/SonarJS/blob/1916267988093cb5eb1d0b3d74bb5db5c0dbedec/sonar-javascript-plugin/src/main/java/org/sonar/plugins/javascript/eslint/AbstractEslintSensor.java#L134 /// </summary> private void LogParsingError(string path, ParsingError parsingError) { if (parsingError.Code == ParsingErrorCode.MISSING_TYPESCRIPT) { logger.WriteLine(Resources.ERR_ParsingError_MissingTypescript); } else if (parsingError.Code == ParsingErrorCode.UNSUPPORTED_TYPESCRIPT) { logger.WriteLine(parsingError.Message); logger.WriteLine(Resources.ERR_ParsingError_UnsupportedTypescript); } else { logger.WriteLine(Resources.ERR_ParsingError_General, path, parsingError.Line, parsingError.Code, parsingError.Message); } }
private static void SetParserStateIfNeeded(object options, OptionInfo option, bool?required, bool?mutualExclusiveness) { IList <Pair <PropertyInfo, ParserStateAttribute> > list = ReflectionHelper.RetrievePropertyList <ParserStateAttribute>(options); if (list.Count == 0) { return; } PropertyInfo property = list[0].Left; // This method can be called when parser state is still not intialized if (property.GetValue(options, null) is null) { property.SetValue(options, new ParserState(), null); } var parserState = (IParserState)property.GetValue(options, null); if (parserState is null) { return; } var error = new ParsingError { BadOption = { ShortName = option.ShortName, LongName = option.LongName } }; if (required != null) { error.ViolatesRequired = required.Value; } if (mutualExclusiveness != null) { error.ViolatesMutualExclusiveness = mutualExclusiveness.Value; } parserState.Errors.Add(error); }
public async Task Analyze_ResponseWithParsingError_ParsingErrorLogged(int errorCode) { var logger = new TestLogger(); var parsingError = new ParsingError { Code = (ParsingErrorCode)errorCode, Line = 5, Message = "some message" }; await SetupAnalysisWithParsingError(parsingError, logger); logger.AssertPartialOutputStringExists(parsingError.Code.ToString()); logger.AssertPartialOutputStringExists(parsingError.Message); logger.AssertPartialOutputStringExists(parsingError.Line.ToString()); }
// // verifies the syntax of the scheme part // Checks on implicit File: scheme due to simple Dos/Unc path passed // returns the start of the next component position // throws UriFormatException if invalid scheme // unsafe static private ushort ParseSchemeCheckImplicitFile(char* uriString, ushort length, ref ParsingError err, ref Flags flags, ref UriParser syntax) { ushort idx = 0; //skip whitespace while (idx < length && UriHelper.IsLWS(uriString[idx])) { ++idx; } // sets the recognizer for well known registered schemes // file, ftp, http, https, uuid, etc // Note that we don't support one-letter schemes that will be put into a DOS path bucket ushort end = idx; while (end < length && uriString[end] != ':') { ++end; } // NB: On 64-bits we will use less optimized code from CheckSchemeSyntax() // if (IntPtr.Size == 4) { // long = 4chars: The minimal size of a known scheme is 2 + ':' if (end != length && end >= idx + 2 && CheckKnownSchemes((long*)(uriString + idx), (ushort)(end - idx), ref syntax)) { return (ushort)(end + 1); } } //NB: A string must have at least 3 characters and at least 1 before ':' if (idx + 2 >= length || end == idx) { err = ParsingError.BadFormat; return 0; } //Check for supported special cases like a DOS file path OR a UNC share path //NB: A string may not have ':' if this is a UNC path { char c; if ((c = uriString[idx + 1]) == ':' || c == '|') { //DOS-like path? if (UriHelper.IsAsciiLetter(uriString[idx])) { if ((c = uriString[idx + 2]) == '\\' || c == '/') { flags |= (Flags.DosPath | Flags.ImplicitFile | Flags.AuthorityFound); syntax = UriParser.FileUri; return idx; } err = ParsingError.MustRootedPath; return 0; } if (c == ':') err = ParsingError.BadScheme; else err = ParsingError.BadFormat; return 0; } else if ((c = uriString[idx]) == '/' || c == '\\') { //UNC share ? if ((c = uriString[idx + 1]) == '\\' || c == '/') { flags |= (Flags.UncPath | Flags.ImplicitFile | Flags.AuthorityFound); syntax = UriParser.FileUri; idx += 2; // V1.1 compat this will simply eat any slashes prepended to a UNC path while (idx < length && ((c = uriString[idx]) == '/' || c == '\\')) ++idx; return idx; } err = ParsingError.BadFormat; return 0; } } if (end == length) { err = ParsingError.BadFormat; return 0; } // Here could be a possibly valid, and not well-known scheme // Finds the scheme delimiter // we don;t work with the schemes names > c_MaxUriSchemeName (should be ~1k) if ((end - idx) > c_MaxUriSchemeName) { err = ParsingError.SchemeLimit; return 0; } //Check the syntax, canonicalize and avoid a GC call char* schemePtr = stackalloc char[end - idx]; for (length = 0; idx < end; ++idx) { schemePtr[length++] = uriString[idx]; } err = CheckSchemeSyntax(schemePtr, length, ref syntax); if (err != ParsingError.None) { return 0; } return (ushort)(end + 1); }
// private void InitializeUri(ParsingError err, UriKind uriKind, out UriFormatException e) { if (err == ParsingError.None) { if (IsImplicitFile) { // V1 compat VsWhidbey#252282 // A relative Uri wins over implicit UNC path unless the UNC path is of the form "\\something" and // uriKind != Absolute if ( #if !PLATFORM_UNIX NotAny(Flags.DosPath) && #endif // !PLATFORM_UNIX uriKind != UriKind.Absolute && (uriKind == UriKind.Relative || (m_String.Length >= 2 && (m_String[0] != '\\' || m_String[1] != '\\')))) { m_Syntax = null; //make it be relative Uri m_Flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri e = null; return; // Otheriwse an absolute file Uri wins when it's of the form "\\something" } // // VsWhidbey#423805 and V1 compat issue // We should support relative Uris of the form c:\bla or c:/bla // #if !PLATFORM_UNIX else if (uriKind == UriKind.Relative && InFact(Flags.DosPath)) { m_Syntax = null; //make it be relative Uri m_Flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri e = null; return; // Otheriwse an absolute file Uri wins when it's of the form "c:\something" } #endif // !PLATFORM_UNIX } } else if (err > ParsingError.LastRelativeUriOkErrIndex) { //This is a fatal error based solely on scheme name parsing m_String = null; // make it be invalid Uri e = GetException(err); return; } // // // bool hasUnicode = false; // Is there unicode .. if ((!s_ConfigInitialized) && CheckForConfigLoad(m_String)){ InitializeUriConfig(); } m_iriParsing = (s_IriParsing && ((m_Syntax == null) || m_Syntax.InFact(UriSyntaxFlags.AllowIriParsing))); if (m_iriParsing && (CheckForUnicode(m_String) || CheckForEscapedUnreserved(m_String))) { m_Flags |= Flags.HasUnicode; hasUnicode = true; // switch internal strings m_originalUnicodeString = m_String; // original string location changed } if (m_Syntax != null) { if (m_Syntax.IsSimple) { if ((err = PrivateParseMinimal()) != ParsingError.None) { if (uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex) { // RFC 3986 Section 5.4.2 - http:(relativeUri) may be considered a valid relative Uri. m_Syntax = null; // convert to relative uri e = null; m_Flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri } else e = GetException(err); } else if (uriKind == UriKind.Relative) { // Here we know that we can create an absolute Uri, but the user has requested only a relative one e = GetException(ParsingError.CannotCreateRelative); } else e = null; // will return from here if (m_iriParsing && hasUnicode){ // In this scenario we need to parse the whole string EnsureParseRemaining(); } } else { // offer custom parser to create a parsing context m_Syntax = m_Syntax.InternalOnNewUri(); // incase they won't call us m_Flags |= Flags.UserDrivenParsing; // Ask a registered type to validate this uri m_Syntax.InternalValidate(this, out e); if (e != null) { // Can we still take it as a relative Uri? if (uriKind != UriKind.Absolute && err != ParsingError.None && err <= ParsingError.LastRelativeUriOkErrIndex) { m_Syntax = null; // convert it to relative e = null; m_Flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri } } else // e == null { if (err != ParsingError.None || InFact(Flags.ErrorOrParsingRecursion)) { // User parser took over on an invalid Uri SetUserDrivenParsing(); } else if (uriKind == UriKind.Relative) { // Here we know that custom parser can create an absolute Uri, but the user has requested only a // relative one e = GetException(ParsingError.CannotCreateRelative); } if (m_iriParsing && hasUnicode){ // In this scenario we need to parse the whole string EnsureParseRemaining(); } } // will return from here } } // If we encountered any parsing errors that indicate this may be a relative Uri, // and we'll allow relative Uri's, then create one. else if (err != ParsingError.None && uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex) { e = null; m_Flags &= (Flags.UserEscaped | Flags.HasUnicode); // the only flags that makes sense for a relative uri if (m_iriParsing && hasUnicode) { // Iri'ze and then normalize relative uris m_String = EscapeUnescapeIri(m_originalUnicodeString, 0, m_originalUnicodeString.Length, (UriComponents)0); try { if (UriParser.ShouldUseLegacyV2Quirks) m_String = m_String.Normalize(NormalizationForm.FormC); } catch (ArgumentException) { e = GetException(ParsingError.BadFormat); } } } else { m_String = null; // make it be invalid Uri e = GetException(err); } }
private unsafe void CheckAuthorityHelperHandleDnsIri(char* pString, ushort start, int end, int startInput, bool iriParsing, bool hasUnicode, UriParser syntax, string userInfoString, ref Flags flags, ref bool justNormalized, ref string newHost, ref ParsingError err) { flags |= Flags.DnsHostType; if ((s_IdnScope == 1) && this.IsIntranet(new string(pString, 0, end))) { flags |= Flags.HostNotParsed | Flags.IntranetUri; } if (this.AllowIdnStatic(syntax, flags)) { bool allAscii = true; bool atLeastOneValidIdn = false; string idnHost = DomainNameHelper.IdnEquivalent(pString, start, end, ref allAscii, ref atLeastOneValidIdn); string str2 = DomainNameHelper.UnicodeEquivalent(idnHost, pString, start, end); if (!allAscii) { flags |= Flags.HostNotParsed | Flags.UnicodeHost; } if (atLeastOneValidIdn) { flags |= Flags.HostNotParsed | Flags.IdnHost; } if ((allAscii && atLeastOneValidIdn) && StaticNotAny(flags, Flags.HasUnicode)) { this.m_originalUnicodeString = this.m_String; newHost = this.m_originalUnicodeString.Substring(0, startInput) + (StaticInFact(flags, Flags.HasUserInfo) ? userInfoString : null); justNormalized = true; } else if (!iriParsing && (StaticInFact(flags, Flags.HostNotParsed | Flags.UnicodeHost) || StaticInFact(flags, Flags.HostNotParsed | Flags.IdnHost))) { this.m_originalUnicodeString = this.m_String; newHost = this.m_originalUnicodeString.Substring(0, startInput) + (StaticInFact(flags, Flags.HasUserInfo) ? userInfoString : null); justNormalized = true; } if (!allAscii || atLeastOneValidIdn) { this.m_DnsSafeHost = idnHost; newHost = newHost + str2; justNormalized = true; } else if ((allAscii && !atLeastOneValidIdn) && (iriParsing && hasUnicode)) { newHost = newHost + str2; justNormalized = true; } } else if (hasUnicode) { string str3 = StripBidiControlCharacter(pString, start, end - start); try { newHost = newHost + ((str3 != null) ? str3.Normalize(NormalizationForm.FormC) : null); } catch (ArgumentException) { err = ParsingError.BadHostName; } justNormalized = true; } flags |= Flags.HostNotParsed | Flags.HostUnicodeNormalized; }
private unsafe void CheckAuthorityHelperHandleAnyHostIri(char* pString, int startInput, int end, bool iriParsing, bool hasUnicode, UriParser syntax, ref Flags flags, ref string newHost, ref ParsingError err) { if (StaticNotAny(flags, Flags.HostNotParsed | Flags.HostUnicodeNormalized) && (this.AllowIdnStatic(syntax, flags) || (iriParsing && hasUnicode))) { string str = new string(pString, startInput, end - startInput); if (this.AllowIdnStatic(syntax, flags)) { bool allAscii = true; bool atLeastOneValidIdn = false; string str2 = DomainNameHelper.UnicodeEquivalent(pString, startInput, end, ref allAscii, ref atLeastOneValidIdn); if (((allAscii && atLeastOneValidIdn) || !allAscii) && (!iriParsing || !hasUnicode)) { this.m_originalUnicodeString = this.m_String; newHost = this.m_originalUnicodeString.Substring(0, startInput); flags |= Flags.HasUnicode; } if (atLeastOneValidIdn || !allAscii) { newHost = newHost + str2; string bidiStrippedHost = null; this.m_DnsSafeHost = DomainNameHelper.IdnEquivalent(pString, startInput, end, ref allAscii, ref bidiStrippedHost); if (atLeastOneValidIdn) { flags |= Flags.HostNotParsed | Flags.IdnHost; } if (!allAscii) { flags |= Flags.HostNotParsed | Flags.UnicodeHost; } } else if (iriParsing && hasUnicode) { newHost = newHost + str; } } else { try { newHost = newHost + str.Normalize(NormalizationForm.FormC); } catch (ArgumentException) { err = ParsingError.BadHostName; } } flags |= Flags.HostNotParsed | Flags.HostUnicodeNormalized; } }
private static unsafe ushort ParseSchemeCheckImplicitFile(char* uriString, ushort length, ref ParsingError err, ref Flags flags, ref UriParser syntax) { ushort index = 0; while ((index < length) && IsLWS(uriString[index])) { index = (ushort) (index + 1); } ushort num2 = index; while ((num2 < length) && (uriString[num2] != ':')) { num2 = (ushort) (num2 + 1); } if (((IntPtr.Size != 4) || (num2 == length)) || ((num2 < (index + 3)) || !CheckKnownSchemes((long*) (uriString + index), (ushort) (num2 - index), ref syntax))) { char ch; if (((index + 2) >= length) || (num2 == index)) { err = ParsingError.BadFormat; return 0; } if (((ch = uriString[index + 1]) == ':') || (ch == '|')) { if (IsAsciiLetter(uriString[index])) { if (((ch = uriString[index + 2]) == '\\') || (ch == '/')) { flags |= Flags.AuthorityFound | Flags.DosPath | Flags.ImplicitFile; syntax = UriParser.FileUri; return index; } err = ParsingError.MustRootedPath; return 0; } if (ch == ':') { err = ParsingError.BadScheme; } else { err = ParsingError.BadFormat; } return 0; } if (((ch = uriString[index]) == '/') || (ch == '\\')) { if (((ch = uriString[index + 1]) == '\\') || (ch == '/')) { flags |= Flags.AuthorityFound | Flags.ImplicitFile | Flags.UncPath; syntax = UriParser.FileUri; index = (ushort) (index + 2); while ((index < length) && (((ch = uriString[index]) == '/') || (ch == '\\'))) { index = (ushort) (index + 1); } return index; } err = ParsingError.BadFormat; return 0; } if (num2 == length) { err = ParsingError.BadFormat; return 0; } if ((num2 - index) > 0x400) { err = ParsingError.SchemeLimit; return 0; } char* ptr = (char*) stackalloc byte[(((IntPtr) (num2 - index)) * 2)]; length = 0; while (index < num2) { length = (ushort) (length + 1); ptr[length] = uriString[index]; index = (ushort) (index + 1); } err = CheckSchemeSyntax(ptr, length, ref syntax); if (err != ParsingError.None) { return 0; } } return (ushort) (num2 + 1); }
private void InitializeUri(ParsingError err, UriKind uriKind, out UriFormatException e) { if (err == ParsingError.None) { if (this.IsImplicitFile) { if ((this.NotAny(Flags.DosPath) && (uriKind != UriKind.Absolute)) && ((uriKind == UriKind.Relative) || ((this.m_String.Length >= 2) && ((this.m_String[0] != '\\') || (this.m_String[1] != '\\'))))) { this.m_Syntax = null; this.m_Flags &= Flags.HostNotParsed | Flags.UserEscaped; e = null; return; } if ((uriKind == UriKind.Relative) && this.InFact(Flags.DosPath)) { this.m_Syntax = null; this.m_Flags &= Flags.HostNotParsed | Flags.UserEscaped; e = null; return; } } } else if (err > ParsingError.EmptyUriString) { this.m_String = null; e = GetException(err); return; } bool flag = false; if (!s_ConfigInitialized && this.CheckForConfigLoad(this.m_String)) { InitializeUriConfig(); } this.m_iriParsing = s_IriParsing && ((this.m_Syntax == null) || this.m_Syntax.InFact(UriSyntaxFlags.AllowIriParsing)); if (this.m_iriParsing && this.CheckForUnicode(this.m_String)) { this.m_Flags |= Flags.HasUnicode; flag = true; this.m_originalUnicodeString = this.m_String; } if (this.m_Syntax != null) { if (!this.m_Syntax.IsSimple) { this.m_Syntax = this.m_Syntax.InternalOnNewUri(); this.m_Flags |= Flags.HostNotParsed | Flags.UserDrivenParsing; this.m_Syntax.InternalValidate(this, out e); if (e == null) { if ((err != ParsingError.None) || this.InFact(Flags.ErrorOrParsingRecursion)) { this.SetUserDrivenParsing(); } else if (uriKind == UriKind.Relative) { e = GetException(ParsingError.CannotCreateRelative); } if (this.m_iriParsing && flag) { this.EnsureParseRemaining(); } } else if (((uriKind != UriKind.Absolute) && (err != ParsingError.None)) && (err <= ParsingError.EmptyUriString)) { this.m_Syntax = null; e = null; this.m_Flags &= Flags.HostNotParsed | Flags.UserEscaped; } } else { if ((err = this.PrivateParseMinimal()) != ParsingError.None) { if ((uriKind != UriKind.Absolute) && (err <= ParsingError.EmptyUriString)) { this.m_Syntax = null; e = null; this.m_Flags &= Flags.HostNotParsed | Flags.UserEscaped; } else { e = GetException(err); } } else if (uriKind == UriKind.Relative) { e = GetException(ParsingError.CannotCreateRelative); } else { e = null; } if (this.m_iriParsing && flag) { this.EnsureParseRemaining(); } } } else if (((err != ParsingError.None) && (uriKind != UriKind.Absolute)) && (err <= ParsingError.EmptyUriString)) { e = null; this.m_Flags &= Flags.HasUnicode | Flags.UserEscaped; if (this.m_iriParsing && flag) { this.m_String = this.EscapeUnescapeIri(this.m_originalUnicodeString, 0, this.m_originalUnicodeString.Length, 0); try { this.m_String = this.m_String.Normalize(NormalizationForm.FormC); } catch (ArgumentException) { e = GetException(ParsingError.BadFormat); } } } else { this.m_String = null; e = GetException(err); } }
private static UriFormatException GetException(ParsingError err) { switch (err) { case ParsingError.None: return null; case ParsingError.BadFormat: return ExceptionHelper.BadFormatException; case ParsingError.BadScheme: return ExceptionHelper.BadSchemeException; case ParsingError.BadAuthority: return ExceptionHelper.BadAuthorityException; case ParsingError.EmptyUriString: return ExceptionHelper.EmptyUriException; case ParsingError.SchemeLimit: return ExceptionHelper.SchemeLimitException; case ParsingError.SizeLimit: return ExceptionHelper.SizeLimitException; case ParsingError.MustRootedPath: return ExceptionHelper.MustRootedPathException; case ParsingError.BadHostName: return ExceptionHelper.BadHostNameException; case ParsingError.NonEmptyHost: return ExceptionHelper.BadFormatException; case ParsingError.BadPort: return ExceptionHelper.BadPortException; case ParsingError.BadAuthorityTerminator: return ExceptionHelper.BadAuthorityTerminatorException; case ParsingError.CannotCreateRelative: return ExceptionHelper.CannotCreateRelativeException; } return ExceptionHelper.BadFormatException; }
private static void SetParserStateIfNeeded(object options, OptionInfo option, bool? required, bool? mutualExclusiveness) { var list = ReflectionHelper.RetrievePropertyList<ParserStateAttribute>(options); if (list.Count == 0) { return; } var property = list[0].Left; // This method can be called when parser state is still not intialized if (property.GetValue(options, null) == null) { property.SetValue(options, new ParserState(), null); } var parserState = (IParserState)property.GetValue(options, null); if (parserState == null) { return; } var error = new ParsingError { BadOption = { ShortName = option.ShortName, LongName = option.LongName } }; if (required != null) { error.ViolatesRequired = required.Value; } if (mutualExclusiveness != null) { error.ViolatesMutualExclusiveness = mutualExclusiveness.Value; } parserState.Errors.Add(error); }
private static UriFormatException GetException(ParsingError err) { switch (err) { case ParsingError.None: return null; // Could be OK for Relative Uri case ParsingError.BadFormat: return new UriFormatException(SR.net_uri_BadFormat); case ParsingError.BadScheme: return new UriFormatException(SR.net_uri_BadScheme); case ParsingError.BadAuthority: return new UriFormatException(SR.net_uri_BadAuthority); case ParsingError.EmptyUriString: return new UriFormatException(SR.net_uri_EmptyUri); // Fatal case ParsingError.SchemeLimit: return new UriFormatException(SR.net_uri_SchemeLimit); case ParsingError.SizeLimit: return new UriFormatException(SR.net_uri_SizeLimit); case ParsingError.MustRootedPath: return new UriFormatException(SR.net_uri_MustRootedPath); // Derived class controllable case ParsingError.BadHostName: return new UriFormatException(SR.net_uri_BadHostName); case ParsingError.NonEmptyHost: //unix-only return new UriFormatException(SR.net_uri_BadFormat); case ParsingError.BadPort: return new UriFormatException(SR.net_uri_BadPort); case ParsingError.BadAuthorityTerminator: return new UriFormatException(SR.net_uri_BadAuthorityTerminator); case ParsingError.CannotCreateRelative: return new UriFormatException(SR.net_uri_CannotCreateRelative); default: break; } return new UriFormatException(SR.net_uri_BadFormat); }
private unsafe void CheckAuthorityHelperHandleAnyHostIri(char* pString, int startInput, int end, bool iriParsing, bool hasUnicode, UriParser syntax, ref Flags flags, ref string newHost, ref ParsingError err) { if (StaticNotAny(flags, Flags.HostUnicodeNormalized) && (AllowIdnStatic(syntax, flags) || (iriParsing && hasUnicode))) { // Normalize any other host or do idn string user = new string(pString, startInput, end - startInput); if (AllowIdnStatic(syntax, flags)) { bool allAscii = true; bool atLeastOneIdn = false; string UniEquvlt = DomainNameHelper.UnicodeEquivalent(pString, startInput, end, ref allAscii, ref atLeastOneIdn); if (((allAscii && atLeastOneIdn) || !allAscii) && !(iriParsing && hasUnicode)) { // original string location changed lazily _originalUnicodeString = _string; newHost = _originalUnicodeString.Substring(0, startInput); flags |= Flags.HasUnicode; } if (atLeastOneIdn || !allAscii) { newHost += UniEquvlt; string bidiStrippedHost = null; _dnsSafeHost = DomainNameHelper.IdnEquivalent(pString, startInput, end, ref allAscii, ref bidiStrippedHost); if (atLeastOneIdn) flags |= Flags.IdnHost; if (!allAscii) flags |= Flags.UnicodeHost; } else if (iriParsing && hasUnicode) { newHost += user; } } else { try { newHost += user.Normalize(NormalizationForm.FormC); } catch (ArgumentException) { err = ParsingError.BadHostName; } } flags |= Flags.HostUnicodeNormalized; } }
private unsafe void CheckAuthorityHelperHandleDnsIri(char* pString, ushort start, int end, int startInput, bool iriParsing, bool hasUnicode, UriParser syntax, string userInfoString, ref Flags flags, ref bool justNormalized, ref string newHost, ref ParsingError err) { // comes here only if host has unicode chars and iri is on or idn is allowed flags |= Flags.DnsHostType; // check if intranet // if ((s_IdnScope == UriIdnScope.AllExceptIntranet) && IsIntranet(new string(pString, 0, end))) { flags |= Flags.IntranetUri; } if (AllowIdnStatic(syntax, flags)) { bool allAscii = true; bool atLeastOneIdn = false; string idnValue = DomainNameHelper.IdnEquivalent(pString, start, end, ref allAscii, ref atLeastOneIdn); string UniEquvlt = DomainNameHelper.UnicodeEquivalent(idnValue, pString, start, end); if (!allAscii) flags |= Flags.UnicodeHost; // we have a unicode host if (atLeastOneIdn) flags |= Flags.IdnHost; // we have at least one valid idn label if (allAscii && atLeastOneIdn && StaticNotAny(flags, Flags.HasUnicode)) { // original string location changed lazily _originalUnicodeString = _string; newHost = _originalUnicodeString.Substring(0, startInput) + (StaticInFact(flags, Flags.HasUserInfo) ? userInfoString : null); justNormalized = true; } else if (!iriParsing && (StaticInFact(flags, Flags.UnicodeHost) || StaticInFact(flags, Flags.IdnHost))) { // original string location changed lazily _originalUnicodeString = _string; newHost = _originalUnicodeString.Substring(0, startInput) + (StaticInFact(flags, Flags.HasUserInfo) ? userInfoString : null); justNormalized = true; } if (!(allAscii && !atLeastOneIdn)) { _dnsSafeHost = idnValue; newHost += UniEquvlt; justNormalized = true; } else if (allAscii && !atLeastOneIdn && iriParsing && hasUnicode) { newHost += UniEquvlt; justNormalized = true; } } else { if (hasUnicode) { string temp = UriHelper.StripBidiControlCharacter(pString, start, end - start); try { newHost += ((temp != null) ? temp.Normalize(NormalizationForm.FormC) : null); } catch (ArgumentException) { err = ParsingError.BadHostName; } justNormalized = true; } } flags |= Flags.HostUnicodeNormalized; }
// // Checks the syntax of an authority component. It may also get a userInfo if present // Returns an error if no/mailformed authority found // Does not NOT touch m_Info // Returns position of the Path component // // Must be called in the ctor only private unsafe ushort CheckAuthorityHelper(char* pString, ushort idx, ushort length, ref ParsingError err, ref Flags flags, UriParser syntax, ref string newHost) { int end = length; char ch; int startInput = idx; ushort start = idx; newHost = null; bool justNormalized = false; bool iriParsing = (s_IriParsing && IriParsingStatic(syntax)); // perf bool hasUnicode = ((flags & Flags.HasUnicode) != 0); // perf bool hostNotUnicodeNormalized = ((flags & Flags.HostUnicodeNormalized) == 0); // perf UriSyntaxFlags syntaxFlags = syntax.Flags; // need to build new Iri'zed string if (hasUnicode && iriParsing && hostNotUnicodeNormalized) { newHost = _originalUnicodeString.Substring(0, startInput); } //Special case is an empty authority if (idx == length || ((ch = pString[idx]) == '/' || (ch == '\\' && StaticIsFile(syntax)) || ch == '#' || ch == '?')) { if (syntax.InFact(UriSyntaxFlags.AllowEmptyHost)) { flags &= ~Flags.UncPath; //UNC cannot have an empty hostname if (StaticInFact(flags, Flags.ImplicitFile)) err = ParsingError.BadHostName; else flags |= Flags.BasicHostType; } else err = ParsingError.BadHostName; if (hasUnicode && iriParsing && hostNotUnicodeNormalized) { flags |= Flags.HostUnicodeNormalized;// no host } return idx; } string userInfoString = null; // Attempt to parse user info first if ((syntaxFlags & UriSyntaxFlags.MayHaveUserInfo) != 0) { for (; start < end; ++start) { if (start == end - 1 || pString[start] == '?' || pString[start] == '#' || pString[start] == '\\' || pString[start] == '/') { start = idx; break; } else if (pString[start] == '@') { flags |= Flags.HasUserInfo; // Iri'ze userinfo if (iriParsing || (s_IdnScope != UriIdnScope.None)) { if (iriParsing && hasUnicode && hostNotUnicodeNormalized) { // Normalize user info userInfoString = IriHelper.EscapeUnescapeIri(pString, startInput, start + 1, UriComponents.UserInfo); newHost += userInfoString; } else { userInfoString = new string(pString, startInput, start - startInput + 1); } } ++start; ch = pString[start]; break; } } } // DNS name only optimization // Fo an overridden parsing the optimization is suppressed since hostname can be changed to anything bool dnsNotCanonical = ((syntaxFlags & UriSyntaxFlags.SimpleUserSyntax) == 0); if (ch == '[' && syntax.InFact(UriSyntaxFlags.AllowIPv6Host) && IPv6AddressHelper.IsValid(pString, (int)start + 1, ref end)) { flags |= Flags.IPv6HostType; _iriParsing = (s_IriParsing && IriParsingStatic(syntax)); if (hasUnicode && iriParsing && hostNotUnicodeNormalized) { newHost += new string(pString, start, end - start); flags |= Flags.HostUnicodeNormalized; justNormalized = true; } } else if (ch <= '9' && ch >= '0' && syntax.InFact(UriSyntaxFlags.AllowIPv4Host) && IPv4AddressHelper.IsValid(pString, (int)start, ref end, false, StaticNotAny(flags, Flags.ImplicitFile), syntax.InFact(UriSyntaxFlags.V1_UnknownUri))) { flags |= Flags.IPv4HostType; if (hasUnicode && iriParsing && hostNotUnicodeNormalized) { newHost += new string(pString, start, end - start); flags |= Flags.HostUnicodeNormalized; justNormalized = true; } } else if (((syntaxFlags & UriSyntaxFlags.AllowDnsHost) != 0) && !iriParsing && DomainNameHelper.IsValid(pString, start, ref end, ref dnsNotCanonical, StaticNotAny(flags, Flags.ImplicitFile))) { // comes here if there are only ascii chars in host with original parsing and no Iri flags |= Flags.DnsHostType; if (!dnsNotCanonical) { flags |= Flags.CanonicalDnsHost; } if ((s_IdnScope != UriIdnScope.None)) { // check if intranet // if ((s_IdnScope == UriIdnScope.AllExceptIntranet) && IsIntranet(new string(pString, 0, end))) { flags |= Flags.IntranetUri; } if (AllowIdnStatic(syntax, flags)) { bool allAscii = true; bool atLeastOneIdn = false; string idnValue = DomainNameHelper.UnicodeEquivalent(pString, start, end, ref allAscii, ref atLeastOneIdn); // did we find at least one valid idn if (atLeastOneIdn) { // need to switch string here since we didn't know beforehand there was an idn host if (StaticNotAny(flags, Flags.HasUnicode)) _originalUnicodeString = _string; // lazily switching strings flags |= Flags.IdnHost; // need to build string for this special scenario newHost = _originalUnicodeString.Substring(0, startInput) + userInfoString + idnValue; flags |= Flags.CanonicalDnsHost; _dnsSafeHost = new string(pString, start, end - start); justNormalized = true; } flags |= Flags.HostUnicodeNormalized; } } } else if (((syntaxFlags & UriSyntaxFlags.AllowDnsHost) != 0) && ((syntax.InFact(UriSyntaxFlags.AllowIriParsing) && hostNotUnicodeNormalized) || syntax.InFact(UriSyntaxFlags.AllowIdn)) && DomainNameHelper.IsValidByIri(pString, start, ref end, ref dnsNotCanonical, StaticNotAny(flags, Flags.ImplicitFile))) { CheckAuthorityHelperHandleDnsIri(pString, start, end, startInput, iriParsing, hasUnicode, syntax, userInfoString, ref flags, ref justNormalized, ref newHost, ref err); } else if ((syntaxFlags & UriSyntaxFlags.AllowUncHost) != 0) { // // This must remain as the last check before BasicHost type // if (UncNameHelper.IsValid(pString, start, ref end, StaticNotAny(flags, Flags.ImplicitFile))) { if (end - start <= UncNameHelper.MaximumInternetNameLength) flags |= Flags.UncHostType; } } // The deal here is that we won't allow '\' host terminator except for the File scheme // If we see '\' we try to make it a part of a Basic host if (end < length && pString[end] == '\\' && (flags & Flags.HostTypeMask) != Flags.HostNotParsed && !StaticIsFile(syntax)) { if (syntax.InFact(UriSyntaxFlags.V1_UnknownUri)) { err = ParsingError.BadHostName; flags |= Flags.UnknownHostType; return (ushort)end; } flags &= ~Flags.HostTypeMask; } // Here we have checked the syntax up to the end of host // The only thing that can cause an exception is the port value // Spend some (duplicated) cycles on that. else if (end < length && pString[end] == ':') { if (syntax.InFact(UriSyntaxFlags.MayHavePort)) { int port = 0; int startPort = end; for (idx = (ushort)(end + 1); idx < length; ++idx) { ushort val = (ushort)((ushort)pString[idx] - (ushort)'0'); if ((val >= 0) && (val <= 9)) { if ((port = (port * 10 + val)) > 0xFFFF) break; } else if (val == unchecked((ushort)('/' - '0')) || val == (ushort)('?' - '0') || val == unchecked((ushort)('#' - '0'))) { break; } else { // The second check is to keep compatibility with V1 until the UriParser is registered if (syntax.InFact(UriSyntaxFlags.AllowAnyOtherHost) && syntax.NotAny(UriSyntaxFlags.V1_UnknownUri)) { flags &= ~Flags.HostTypeMask; break; } else { err = ParsingError.BadPort; return idx; } } } // check on 0-ffff range if (port > 0xFFFF) { if (syntax.InFact(UriSyntaxFlags.AllowAnyOtherHost)) { flags &= ~Flags.HostTypeMask; } else { err = ParsingError.BadPort; return idx; } } if (iriParsing && hasUnicode && justNormalized) { newHost += new string(pString, startPort, idx - startPort); } } else { flags &= ~Flags.HostTypeMask; } } // check on whether nothing has worked out if ((flags & Flags.HostTypeMask) == Flags.HostNotParsed) { //No user info for a Basic hostname flags &= ~Flags.HasUserInfo; // Some schemes do not allow HostType = Basic (plus V1 almost never understands this issue) // if (syntax.InFact(UriSyntaxFlags.AllowAnyOtherHost)) { flags |= Flags.BasicHostType; for (end = idx; end < length; ++end) { if (pString[end] == '/' || (pString[end] == '?' || pString[end] == '#')) { break; } } CheckAuthorityHelperHandleAnyHostIri(pString, startInput, end, iriParsing, hasUnicode, syntax, ref flags, ref newHost, ref err); } else { // // ATTN V1 compat: V1 supports hostnames like ".." and ".", and so we do but only for unknown schemes. // if (syntax.InFact(UriSyntaxFlags.V1_UnknownUri)) { // Can assert here that the host is not empty so we will set dotFound // at least once or fail before exiting the loop bool dotFound = false; int startOtherHost = idx; for (end = idx; end < length; ++end) { if (dotFound && (pString[end] == '/' || pString[end] == '?' || pString[end] == '#')) break; else if (end < (idx + 2) && pString[end] == '.') { // allow one or two dots dotFound = true; } else { //failure err = ParsingError.BadHostName; flags |= Flags.UnknownHostType; return idx; } } //success flags |= Flags.BasicHostType; if (iriParsing && hasUnicode && StaticNotAny(flags, Flags.HostUnicodeNormalized)) { // Normalize any other host string user = new string(pString, startOtherHost, startOtherHost - end); try { newHost += user.Normalize(NormalizationForm.FormC); } catch (ArgumentException) { err = ParsingError.BadFormat; return idx; } flags |= Flags.HostUnicodeNormalized; } } else if (syntax.InFact(UriSyntaxFlags.MustHaveAuthority) || (syntax.InFact(UriSyntaxFlags.MailToLikeUri))) { err = ParsingError.BadHostName; flags |= Flags.UnknownHostType; return idx; } } } return (ushort)end; }
private unsafe ushort CheckAuthorityHelper(char* pString, ushort idx, ushort length, ref ParsingError err, ref Flags flags, UriParser syntax, ref string newHost) { char ch; int end = length; int num2 = idx; ushort index = idx; newHost = null; bool justNormalized = false; bool iriParsing = s_IriParsing && IriParsingStatic(syntax); bool hasUnicode = (flags & Flags.HasUnicode) != Flags.HostNotParsed; bool flag4 = (flags & (Flags.HostNotParsed | Flags.HostUnicodeNormalized)) == Flags.HostNotParsed; UriSyntaxFlags flags2 = syntax.Flags; if ((hasUnicode && iriParsing) && flag4) { newHost = this.m_originalUnicodeString.Substring(0, num2); } if ((((idx == length) || ((ch = pString[idx]) == '/')) || ((ch == '\\') && StaticIsFile(syntax))) || ((ch == '#') || (ch == '?'))) { if (syntax.InFact(UriSyntaxFlags.AllowEmptyHost)) { flags &= ~(Flags.HostNotParsed | Flags.UncPath); if (StaticInFact(flags, Flags.HostNotParsed | Flags.ImplicitFile)) { err = ParsingError.BadHostName; } else { flags |= Flags.BasicHostType; } } else { err = ParsingError.BadHostName; } if ((hasUnicode && iriParsing) && flag4) { flags |= Flags.HostNotParsed | Flags.HostUnicodeNormalized; } return idx; } string userInfoString = null; if ((flags2 & UriSyntaxFlags.MayHaveUserInfo) != UriSyntaxFlags.None) { while (index < end) { if (((index == (end - 1)) || (pString[index] == '?')) || (((pString[index] == '#') || (pString[index] == '\\')) || (pString[index] == '/'))) { index = idx; break; } if (pString[index] == '@') { flags |= Flags.HasUserInfo; if (iriParsing || (s_IdnScope != null)) { if ((iriParsing && hasUnicode) && flag4) { userInfoString = this.EscapeUnescapeIri(pString, num2, index + 1, UriComponents.UserInfo); try { userInfoString = userInfoString.Normalize(NormalizationForm.FormC); } catch (ArgumentException) { err = ParsingError.BadFormat; return idx; } newHost = newHost + userInfoString; } else { userInfoString = new string(pString, num2, (index - num2) + 1); } } index = (ushort) (index + 1); ch = pString[index]; break; } index = (ushort) (index + 1); } } bool notCanonical = (flags2 & UriSyntaxFlags.SimpleUserSyntax) == UriSyntaxFlags.None; if (((ch == '[') && syntax.InFact(UriSyntaxFlags.AllowIPv6Host)) && IPv6AddressHelper.IsValid(pString, index + 1, ref end)) { flags |= Flags.HostNotParsed | Flags.IPv6HostType; if (!s_ConfigInitialized) { InitializeUriConfig(); this.m_iriParsing = s_IriParsing && IriParsingStatic(syntax); } if ((hasUnicode && iriParsing) && flag4) { newHost = newHost + new string(pString, index, end - index); flags |= Flags.HostNotParsed | Flags.HostUnicodeNormalized; justNormalized = true; } } else if (((ch <= '9') && (ch >= '0')) && (syntax.InFact(UriSyntaxFlags.AllowIPv4Host) && IPv4AddressHelper.IsValid(pString, index, ref end, false, StaticNotAny(flags, Flags.HostNotParsed | Flags.ImplicitFile)))) { flags |= Flags.HostNotParsed | Flags.IPv4HostType; if ((hasUnicode && iriParsing) && flag4) { newHost = newHost + new string(pString, index, end - index); flags |= Flags.HostNotParsed | Flags.HostUnicodeNormalized; justNormalized = true; } } else if ((((flags2 & UriSyntaxFlags.AllowDnsHost) != UriSyntaxFlags.None) && !iriParsing) && DomainNameHelper.IsValid(pString, index, ref end, ref notCanonical, StaticNotAny(flags, Flags.HostNotParsed | Flags.ImplicitFile))) { flags |= Flags.DnsHostType; if (!notCanonical) { flags |= Flags.CanonicalDnsHost; } if (s_IdnScope != null) { if ((s_IdnScope == 1) && this.IsIntranet(new string(pString, 0, end))) { flags |= Flags.HostNotParsed | Flags.IntranetUri; } if (this.AllowIdnStatic(syntax, flags)) { bool allAscii = true; bool atLeastOneValidIdn = false; string str2 = DomainNameHelper.UnicodeEquivalent(pString, index, end, ref allAscii, ref atLeastOneValidIdn); if (atLeastOneValidIdn) { if (StaticNotAny(flags, Flags.HasUnicode)) { this.m_originalUnicodeString = this.m_String; } flags |= Flags.HostNotParsed | Flags.IdnHost; newHost = this.m_originalUnicodeString.Substring(0, num2) + userInfoString + str2; flags |= Flags.CanonicalDnsHost; this.m_DnsSafeHost = new string(pString, index, end - index); justNormalized = true; } flags |= Flags.HostNotParsed | Flags.HostUnicodeNormalized; } } } else if ((((iriParsing || (s_IdnScope != null)) && ((flags2 & UriSyntaxFlags.AllowDnsHost) != UriSyntaxFlags.None)) && ((iriParsing && flag4) || this.AllowIdnStatic(syntax, flags))) && DomainNameHelper.IsValidByIri(pString, index, ref end, ref notCanonical, StaticNotAny(flags, Flags.HostNotParsed | Flags.ImplicitFile))) { this.CheckAuthorityHelperHandleDnsIri(pString, index, end, num2, iriParsing, hasUnicode, syntax, userInfoString, ref flags, ref justNormalized, ref newHost, ref err); } else if ((((s_IdnScope == null) && !s_IriParsing) && (((flags2 & UriSyntaxFlags.AllowUncHost) != UriSyntaxFlags.None) && UncNameHelper.IsValid(pString, index, ref end, StaticNotAny(flags, Flags.HostNotParsed | Flags.ImplicitFile)))) && ((end - index) <= 0x100)) { flags |= Flags.HostNotParsed | Flags.UncHostType; } if (((end < length) && (pString[end] == '\\')) && (((flags & (Flags.BasicHostType | Flags.IPv4HostType)) != Flags.HostNotParsed) && !StaticIsFile(syntax))) { if (syntax.InFact(UriSyntaxFlags.V1_UnknownUri)) { err = ParsingError.BadHostName; flags |= Flags.BasicHostType | Flags.IPv4HostType; return (ushort) end; } flags &= ~(Flags.BasicHostType | Flags.IPv4HostType); } else if ((end < length) && (pString[end] == ':')) { if (!syntax.InFact(UriSyntaxFlags.MayHavePort)) { flags &= ~(Flags.BasicHostType | Flags.IPv4HostType); } else { int num4 = 0; int startIndex = end; idx = (ushort) (end + 1); while (idx < length) { ushort num6 = pString[idx] - '0'; if ((num6 >= 0) && (num6 <= 9)) { num4 = (num4 * 10) + num6; if (num4 > 0xffff) { break; } } else { if (((num6 == 0xffff) || (num6 == 15)) || (num6 == 0xfff3)) { break; } if (syntax.InFact(UriSyntaxFlags.AllowAnyOtherHost) && syntax.NotAny(UriSyntaxFlags.V1_UnknownUri)) { flags &= ~(Flags.BasicHostType | Flags.IPv4HostType); break; } err = ParsingError.BadPort; return idx; } idx = (ushort) (idx + 1); } if (num4 > 0xffff) { if (!syntax.InFact(UriSyntaxFlags.AllowAnyOtherHost)) { err = ParsingError.BadPort; return idx; } flags &= ~(Flags.BasicHostType | Flags.IPv4HostType); } if ((iriParsing && hasUnicode) && justNormalized) { newHost = newHost + new string(pString, startIndex, idx - startIndex); } } } if ((flags & (Flags.BasicHostType | Flags.IPv4HostType)) == Flags.HostNotParsed) { flags &= ~Flags.HasUserInfo; if (!syntax.InFact(UriSyntaxFlags.AllowAnyOtherHost)) { if (!syntax.InFact(UriSyntaxFlags.V1_UnknownUri)) { if (syntax.InFact(UriSyntaxFlags.MustHaveAuthority)) { err = ParsingError.BadHostName; flags |= Flags.BasicHostType | Flags.IPv4HostType; return idx; } } else { bool flag8 = false; int num7 = idx; for (end = idx; end < length; end++) { if (flag8 && (((pString[end] == '/') || (pString[end] == '?')) || (pString[end] == '#'))) { break; } if ((end < (idx + 2)) && (pString[end] == '.')) { flag8 = true; } else { err = ParsingError.BadHostName; flags |= Flags.BasicHostType | Flags.IPv4HostType; return idx; } } flags |= Flags.BasicHostType; if ((iriParsing && hasUnicode) && StaticNotAny(flags, Flags.HostNotParsed | Flags.HostUnicodeNormalized)) { string str3 = new string(pString, num7, num7 - end); try { newHost = newHost + str3.Normalize(NormalizationForm.FormC); } catch (ArgumentException) { err = ParsingError.BadFormat; return idx; } flags |= Flags.HostNotParsed | Flags.HostUnicodeNormalized; } } } else { flags |= Flags.BasicHostType; end = idx; while (end < length) { if (((pString[end] == '/') || (pString[end] == '?')) || (pString[end] == '#')) { break; } end++; } this.CheckAuthorityHelperHandleAnyHostIri(pString, num2, end, iriParsing, hasUnicode, syntax, ref flags, ref newHost, ref err); } } return (ushort) end; }
/// <summary> /// Gets the string representation of the ParsingError enum. /// </summary> /// <param name="parsingErrorKey"></param> /// <returns>The string representation of the ParsingError enum</returns> public string this[ParsingError parsingErrorKey] { get { return _errors[parsingErrorKey]; } }