public StylesheetParseError(ParserError error, string errorMessage, int line, int column)
 {
     ParserError = error;
     Message = errorMessage;
     Line = line;
     Column = column;
 }
示例#2
0
        private void Run()
        {
            string input = this._template.Content;

                // Ask thread pool for a new thread to do the work.
                Thread thread = null;
                Task<StringBuilder> task = Task.Factory.StartNew<StringBuilder> (() =>
                {
                      //Capture the thread, so we can abort worker thread if it hangs.
                      thread = Thread.CurrentThread;

                      // Setup error reporting.
                      using (StringWriter reportwriter = new StringWriter ())
                      {
                            try
                            {
                                string evalcode = string.Empty;

                                Report report = new Report (new Mono.CSharp.StreamReportPrinter (reportwriter));

                                // Create new evaluator instance.
                                var evaluator = new Evaluator (new CompilerSettings (), report);

                                // Reference current assembly.
                                evaluator.ReferenceAssembly (Assembly.GetExecutingAssembly ());

                        evaluator.ReferenceAssembly (typeof (SNDK.Convert).Assembly);

                                // Using.
                                evaluator.Run ("using System; using System.Collections.Generic; using SorentoLib; using SNDK");

                                foreach (SorentoLib.Addins.IRuntime runtime in AddinManager.GetExtensionObjects (typeof(SorentoLib.Addins.IRuntime)))
                                {
                                      evaluator.ReferenceAssembly (runtime.Assembly);
                                      evaluator.Run ("using " + runtime.Assembly.GetName ().Name + ";");
                                }

                                // Anonymous methods.
                                evalcode += "SorentoLib.Parser.Hooks.Commands.Print.Delegate Print = delegate (object Value) { SorentoLib.Parser.Hooks.Commands.Print.Method (Value);};\n";

                                // Variables
                                int counter = 0;
                                Parser.Hooks.Variables = this._variables;

                                foreach (ParserVariable variable in this._variables)
                                {
                                      evalcode += variable.Value.GetType ().FullName + " " + variable.Name + " = (" + variable.Value.GetType ().FullName + ")SorentoLib.Parser.Hooks.Variables[" + counter + "].Value;\n";
                                      counter++;
                                }

                                evalcode += input;

                                // Output.
                                Parser.Hooks.Errors = null;
                                Parser.Hooks.Output = new StringBuilder ();

                                // Run evaluation.
                                evaluator.Run (evalcode);

                                // Cleanup.
                                evaluator = null;
                                report = null;
                                evalcode = null;

                                if (reportwriter.ToString () != string.Empty)
                                {
                                      Console.WriteLine ("!!!!" + reportwriter.ToString ());

                                      Parser.Hooks.Errors = new ParserError (reportwriter.ToString ());
                                }
                            } catch (Exception e)
                            {
                                Console.WriteLine (e);

                                string interactive = string.Empty;
                                interactive += "{interactive}(0,0): error SE0000: " + e.Message;
                                interactive += reportwriter.ToString ();

                                Parser.Hooks.Errors = new ParserError (interactive);
                            }

                            this._errors = Hooks.Errors;
            //					this._output = Parser.Hooks.Output;

                            return Parser.Hooks.Output;
                      }
                }
                );

            if (!task.IsCompleted)
            {
                if (!task.Wait (25000))
                {
                    thread.Abort ();
                    throw new Exceptions.Parser ("TEMPLATE PARSER TIMEOUT");
                }
            }

            if (this._errors != null)
            {
                string message = string.Empty;

                bool thr = false;
                message += "PARSER EXCEPTION:<br>\n";
                foreach (SorentoLib.ParserError.Error error in this._errors.Errors)
                {
                    if (error.Type == Enums.ParserErrorType.Error)
                    {
                        thr = true;
                    }

                    message += "Line: "+ error.Line + " - "+ error.Code +" - "+ error.Text +"<br>\n";
                }

                if (thr)
                {
                    throw new Exceptions.Parser (message);
                }
            }

            this._output = task.Result;

            //			task.Dispose ();
        }
 public virtual void ReportParseError(ParserError error) {}
示例#4
0
 internal void HandleLexerError(ParserError error, string message)
 {
     _styleSheet.Errors.Add(new StylesheetParseError(error, message, _lexer.Stream.Line, _lexer.Stream.Column));
 }
示例#5
0
 public static Parser <T> Where <T>(this Parser <T> self, Func <T, bool> pred) =>
 inp =>
 self(inp).Match(
     EmptyOK: (x, rem, msg) => pred(x) ? EmptyOK(x, rem, msg) : EmptyError <T>(ParserError.SysUnexpect(inp.Pos, $"\"{x}\"")),
     EmptyError: msg => EmptyError <T>(msg),
     ConsumedOK: (x, rem, msg) => pred(x) ? ConsumedOK(x, rem, msg) : EmptyError <T>(ParserError.SysUnexpect(inp.Pos, $"\"{x}\"")),
     ConsumedError: msg => ConsumedError <T>(msg));
示例#6
0
 public void OnError(ParserError err) {
     Errors++;
     Console.WriteLine("Error at line {0} column {1}: {2}", err.Location.LineIndex + 1, err.Location.CharacterIndex + 1, err.Message);
     CodeGenerator.OnError(err);
 }
	// Methods
	public int Add(ParserError value) {}
示例#8
0
        public static async Task <int> Main()
        {
            try
            {
                var commandLineParser = new CommandLineParser <int, int>();
                commandLineParser.AddVerb(new UpdateVerb(), ExecuteUpdateAsync);
                commandLineParser.AddVerb(new AwaitPublishVerb(), ExecuteAwaitPublishAsync);
                commandLineParser.AddVerb(new PruneLocalSourceVerb(), v => Result.Error(ParserError.From(-1)), builder =>
                {
                    builder.AddVerb(new AllVerb(), ExecutePruneAllAsync);
                    //// builder.AddVerb(new NewestPrereleasesPruneModeVerb(), ExecutePruneNewestPrereleasesAsync);
                });
                commandLineParser.AddVerb(new DeleteVerb(), ExecuteDeleteAsync);
                var result = await commandLineParser.ParseAsync(Environment.CommandLine, 1);

                if (!result)
                {
                    result.WriteToConsole();
                }

                return(result.GetExitCode());
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return(-1);
            }
        }
示例#9
0
        public void SyntaxError(IRecognizer recognizer, IToken offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e)
        {
            ParserError error = new ParserError(msg, new SourceLocation(line, charPositionInLine + 1));

            _parserErrors.Add(error);
        }
        public override Practitioner FromXml(XElement element)
        {
            if (element == null)
            {
                return(null);
            }

            var practitioner = new Practitioner
            {
                Id   = Guid.NewGuid().ToString(),
                Meta = new Meta
                {
                    Profile = new List <string>
                    {
                        "http://hl7.org/fhir/us/core/StructureDefinition/us-core-practitioner"
                    }
                }
            };

            var role = new PractitionerRole()
            {
                Id           = Guid.NewGuid().ToString(),
                Practitioner = new ResourceReference($"{practitioner.TypeName}/{practitioner.Id}")
            };

            var location = new Location
            {
                Id = Guid.NewGuid().ToString()
            };

            foreach (var child in element.Elements())
            {
                switch (child.Name.LocalName)
                {
                case "id":
                    var id = FromXml(new IdentifierParser(), child);
                    if (id != null)
                    {
                        practitioner.Identifier.Add(id);
                    }
                    break;

                case "code":
                    var code = FromXml(new CodeableConceptParser(), child);
                    if (code != null)
                    {
                        role.Specialty.Add(code);
                    }
                    break;

                case "addr":
                    location.Address = FromXml(new AddressParser(), child);
                    break;

                case "telecom":
                    var telecom = FromXml(new ContactPointParser(), child);
                    if (telecom != null)
                    {
                        location.Telecom.Add(telecom);
                    }
                    break;

                case "assignedPerson":
                case "informationRecipient":
                    var name = FromXml(new HumanNameParser(), child.CdaElement("name"));
                    if (name != null)
                    {
                        practitioner.Name.Add(name);
                    }
                    break;

                case "receivedOrganization":
                    break;
                }
            }

            if (!practitioner.Identifier.Any())
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have identifier", ParseErrorLevel.Error));
            }

            if (!practitioner.Name.Any())
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have name", ParseErrorLevel.Warning));
            }

            var existingPractitioner = Bundle?.FirstOrDefault <Practitioner>(p => p.Identifier.IsExactly(practitioner.Identifier));

            if (existingPractitioner != null)
            {
                practitioner = existingPractitioner;
            }
            else
            {
                Bundle?.AddResourceEntry(practitioner);
            }

            role.Practitioner = practitioner.GetResourceReference();

            if (location.Address != null || location.Telecom.Any())
            {
                var existingLocation = Bundle?.FirstOrDefault <Location>(l =>
                                                                         l.Address.IsExactly(location.Address) && l.Telecom.IsExactly(location.Telecom));

                if (existingLocation != null)
                {
                    location = existingLocation;
                }
                else
                {
                    Bundle?.AddResourceEntry(location);
                }

                role.Location.Add(location.GetResourceReference());
            }

            var existingRole = Bundle?.FirstOrDefault <PractitionerRole>(pr =>
                                                                         pr.Location.IsExactly(role.Location) &&
                                                                         pr.Specialty.IsExactly(role.Specialty) &&
                                                                         pr.Practitioner.IsExactly(role.Practitioner));

            if (existingRole == null && (role.Location.Any() || role.Specialty.Any()))
            {
                Bundle?.AddResourceEntry(role);
            }

            return(practitioner);
        }
示例#11
0
        public override Patient FromXml(XElement element)
        {
            if (element == null)
            {
                return(null);
            }

            var patient = new Patient
            {
                Id   = Guid.NewGuid().ToString(),
                Meta = new Meta
                {
                    Profile = new List <string>
                    {
                        "http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient"
                    }
                }
            };

            Bundle?.AddResourceEntry(patient);

            foreach (var child in element.Elements())
            {
                if (child.Name.LocalName == "id")
                {
                    var id = FromXml(new IdentifierParser(), child);

                    if (id != null)
                    {
                        patient.Identifier.Add(id);
                    }
                }
                else if (child.Name.LocalName == "addr")
                {
                    var addr = FromXml(new AddressParser(), child);

                    if (addr != null)
                    {
                        patient.Address.Add(addr);
                    }
                }
                else if (child.Name.LocalName == "telecom")
                {
                    var contactPoint = FromXml(new ContactPointParser(), child);

                    if (contactPoint != null)
                    {
                        patient.Telecom.Add(contactPoint);
                    }
                }
                else if (child.Name.LocalName == "patient")
                {
                    ParsePatient(patient, child);
                }
                else if (child.Name.LocalName == "providerOrganization")
                {
                    var org = FromXml(new OrganizationParser(Bundle), child);
                    if (org != null && Bundle != null)
                    {
                        patient.ManagingOrganization = new ResourceReference($"{org.TypeName}/{org.Id}");
                    }
                }
            }

            if (!patient.Identifier.Any())
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have id element", ParseErrorLevel.Error));
            }

            if (!patient.Name.Any())
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have name element", ParseErrorLevel.Error));
            }

            if (patient.Gender == null)
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have administrativeGenderCode element",
                                                        ParseErrorLevel.Error));
            }

            return(patient);
        }
示例#12
0
        private static ValidationResult Error(Token token, string message)
        {
            var error = new ParserError(message, token.Line, token.Column);

            return(ValidationResult.Error(error));
        }
        public override RelatedPerson FromXml(XElement element)
        {
            if (element == null)
            {
                return(null);
            }

            var relatedPerson = new RelatedPerson
            {
                Id = Guid.NewGuid().ToString()
            };

            var classCode = element.Attribute("classCode")?.Value;

            if (!string.IsNullOrEmpty(classCode))
            {
                relatedPerson.Relationship = new CodeableConcept
                {
                    Coding = new List <Coding>
                    {
                        new Coding("urn:oid:2.16.840.1.113883.1.11.19563", classCode)
                    }
                }
            }
            ;

            foreach (var child in element.Elements())
            {
                switch (child.Name.LocalName)
                {
                case "code":
                    relatedPerson.Relationship = FromXml(new CodeableConceptParser(), child);
                    break;

                case "addr":
                    var addr = FromXml(new AddressParser(), child);
                    if (addr != null)
                    {
                        relatedPerson.Address.Add(addr);
                    }
                    break;

                case "telecom":
                    var contactPoint = FromXml(new ContactPointParser(), child);
                    if (contactPoint != null)
                    {
                        relatedPerson.Telecom.Add(contactPoint);
                    }
                    break;

                case "guardianPerson":
                case "relatedPerson":
                case "associatedPerson":
                    var name = FromXml(new HumanNameParser(), child.CdaElement("name"));
                    if (name != null)
                    {
                        relatedPerson.Name.Add(name);
                    }
                    break;
                }
            }

            if (!relatedPerson.Name.Any())
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have name element",
                                                        ParseErrorLevel.Warning));
            }

            var existingPerson = Bundle?.FirstOrDefault <RelatedPerson>(p => p.Name.IsExactly(relatedPerson.Name));

            if (existingPerson != null)
            {
                return(existingPerson);
            }

            Bundle?.AddResourceEntry(relatedPerson);

            return(relatedPerson);
        }
    }
示例#14
0
 protected virtual void RaiseParserError(string msg, Exception ex) => ParserError?.Invoke(this, new TwitterItemParserErrorEventArgs(msg, ex));
 public RegularExpressionParserException(ParserError errCode, int nErrorStart = -1, int nErrorLength = -1, string sFormattedString = "")
 {
     ErrorCode = errCode;
     ErrorStart = -1;
     ErrorLength = -1;
     FormattedString = sFormattedString;
 }
示例#16
0
文件: CnmFile.cs 项目: iraychen/toxy
        public void ErrorHandler(ParserError err, string comment)
        {
            if (_errorsBuffer == null)
                _errorsBuffer = new StringBuilder();

            _errorsBuffer.AppendLine(string.Format("{0}: {1}", err, comment));
        }
示例#17
0
    // Method to report exception, this is called when external exceptions are caught in the parser.
    protected void ProcessException(Exception ex) {
        // Ignore the errors if in that mode.
        if (IgnoreParseErrors) {
            return;
        }

        // Rethrow as innerexception if in that mode or it is a compile exception.
        if (ThrowOnFirstParseError || ex is HttpCompileException) {
            if (ex is HttpParseException)
                throw ex;
            throw new HttpParseException(ex.Message, ex);
        }

        // If it is already a parser exception remember the location corresponding to 
        // the original error.
        ParserError parseError;

        HttpParseException hpe = ex as HttpParseException;
        if (hpe != null) {
            parseError = new ParserError(hpe.Message, hpe.VirtualPath, hpe.Line);
        }
        else {
            parseError = new ParserError(ex.Message, CurrentVirtualPath, _lineNumber);
        }

        // Remember the original exception.
        parseError.Exception = ex;

        ParserErrors.Add(parseError);

        // If there is a CBM callback, inform it of the error only if the HttpParseException comes
        // from the current virtualpath. Since if the exception is thrown from parsing another file,
        // it would have been reported already.
        if (hpe == null || CurrentVirtualPath.Equals(hpe.VirtualPathObject)) {
            BuildManager.ReportParseError(parseError);
        }
    }
示例#18
0
 public override void ReportParseError(ParserError error)
 {
     DumpError(error.VirtualPath, error.Line, false, "ASPPARSE", error.ErrorText);
 }
	public ParserErrorCollection(ParserError[] value) {}
示例#20
0
        private static Parser <A> MakeParser <A>(IEnumerable <Operator <A> > ops, Parser <A> term)
        {
            var empty2 = ImmutableList.Empty <Parser <Func <A, A> > >();
            var empty3 = ImmutableList.Empty <Parser <Func <A, A, A> > >();

            return(ops.Foldr(
                       SplitOp,
                       Tuple.Create(empty3, empty3, empty3, empty2, empty2)
                       )
                   .Apply((rassoc, lassoc, nassoc, prefix, postfix) =>
            {
                var rassocOp = Prim.Choice(rassoc);
                var lassocOp = Prim.Choice(lassoc);
                var nassocOp = Prim.Choice(nassoc);
                var prefixOp = Prim.Choice(prefix).Fail("");
                var postfixOp = Prim.Choice(postfix).Fail("");

                Func <string, Choice <Func <A, A, A> >, Parser <A> > ambiguous = (string assoc, Choice <Func <A, A, A> > op) =>
                                                                                 Prim.Try <A>(
                    (from o in op
                     from fail in
                     Prim.Failure <A>(
                         ParserError.Create("ambiguous use of a " + assoc + " associative operator",
                                            new ParserChar(' ').Cons()
                                            ))
                     select fail)
                    );


                var ambiguousRight = ambiguous("right", rassocOp);
                var ambiguousLeft = ambiguous("left", lassocOp);
                var ambiguousNon = ambiguous("non", nassocOp);

                var postfixP = postfixOp | Prim.Return <Func <A, A> >(a => a);
                var prefixP = prefixOp | Prim.Return <Func <A, A> >(a => a);

                Parser <A> termP = from pre in prefixP
                                   from x in term
                                   from post in postfixP
                                   select(post(pre(x)));

                Func <A, Parser <A> > rassocP1 = null;

                Func <A, Parser <A> > rassocP = x => (from f in rassocOp
                                                      from y in
                                                      (from z in termP
                                                       from rz in rassocP1(z)
                                                       select rz)
                                                      select f(x, y))
                                                | ambiguousLeft
                                                | ambiguousNon;

                rassocP1 = x => rassocP(x) | Prim.Return(x);

                Func <A, Parser <A> > lassocP1 = null;

                Func <A, Parser <A> > lassocP = x => (from f in lassocOp
                                                      from y in termP
                                                      from l in lassocP1(f(x, y))
                                                      select l)
                                                | ambiguousRight;

                lassocP1 = x => (from l in lassocP(x)
                                 select l)
                           | Prim.Return(x);

                Func <A, Parser <A> > nassocP = x => (from f in nassocOp
                                                      from y in termP
                                                      from r in ambiguousRight
                                                      | ambiguousLeft
                                                      | ambiguousNon
                                                      | Prim.Return(f(x, y))
                                                      select r);

                return from x in termP
                from r in (rassocP(x) | lassocP(x) | nassocP(x) | Prim.Return(x)).Fail("operator")
                select r;
            }
                          ));
        }
	public void AddRange(ParserError[] value) {}
示例#22
0
 public JsonParserException(ParserError error, int position) : base($"Error Reading JSON data: '{error}' at position: '{position}'.")
 {
     Error    = error;
     Position = position;
 }
        public override Organization FromXml(XElement element)
        {
            if (element == null)
            {
                return(null);
            }

            var org = new Organization
            {
                Id   = Guid.NewGuid().ToString(),
                Meta = new Meta
                {
                    Profile = new List <string>
                    {
                        "http://hl7.org/fhir/us/core/StructureDefinition/us-core-organization"
                    }
                },
                Active = true
            };

            foreach (var child in element.Elements())
            {
                if (child.Name.LocalName == "id")
                {
                    var id = new IdentifierParser().FromXml(child, Errors);

                    if (id != null)
                    {
                        org.Identifier.Add(id);
                    }
                }
                else if (child.Name.LocalName == "name")
                {
                    org.Name = child.Value;
                }
                else if (child.Name.LocalName == "telecom")
                {
                    var telecom = new ContactPointParser().FromXml(child, Errors);

                    if (telecom != null)
                    {
                        org.Telecom.Add(telecom);
                    }
                }
                else if (child.Name.LocalName == "addr")
                {
                    var addr = new AddressParser().FromXml(child, Errors);

                    if (addr != null)
                    {
                        org.Address.Add(addr);
                    }
                }
            }

            if (!org.Identifier.Any())
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have id element", ParseErrorLevel.Error));
            }

            if (string.IsNullOrEmpty(org.Name))
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have name element", ParseErrorLevel.Error));
            }

            if (!org.Telecom.Any())
            {
                Errors.Add(
                    ParserError.CreateParseError(element, "does NOT have telecom element", ParseErrorLevel.Error));
            }

            if (!org.Address.Any())
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have addr element", ParseErrorLevel.Error));
            }

            var existingOrg = Bundle?.FirstOrDefault <Organization>(p => p.Identifier.IsExactly(org.Identifier));

            if (existingOrg == null)
            {
                Bundle?.AddResourceEntry(org);
            }
            else
            {
                org = existingOrg;
            }

            return(org);
        }
示例#24
0
 public JsonParserException(ParserError error, ValueType type, int position) : base(
         $"Error Reading JSON data for type '{type}': '{error}' at position: '{position}'.")
 {
     Type = type;
 }
        public override FhirDateTime FromXml(XElement element)
        {
            if (element == null)
            {
                return(null);
            }

            var timeString = element.Attribute("value")?.Value;

            if (timeString == null)
            {
                var nullFlavor = element.Attribute("nullFlavor")?.Value;

                if (nullFlavor != null)
                {
                    Errors.Add(ParserError.CreateParseError(element, "has nullFlavor " + nullFlavor,
                                                            ParseErrorLevel.Warning));
                }
                else
                {
                    Errors.Add(ParserError.CreateParseError(element, "does NOT have value attribute",
                                                            ParseErrorLevel.Error));
                }

                return(null);
            }

            if (timeString.Length < 4)
            {
                Errors.Add(ParserError.CreateParseError(element, "has invalid value " + timeString,
                                                        ParseErrorLevel.Warning));
                return(null);
            }

            var sb = new StringBuilder();

            var timeZoneIndex = timeString.IndexOfAny(new[] { '-', '+' });

            if (timeZoneIndex == -1)
            {
                timeZoneIndex = timeString.Length;
            }

            for (var i = 0; i < timeZoneIndex; i++)
            {
                if (i == 4 || i == 6)
                {
                    sb.Append("-");
                }
                else if (i == 8)
                {
                    sb.Append("T");
                }
                else if (i == 10 || i == 12)
                {
                    sb.Append(":");
                }

                sb.Append(timeString[i]);
            }

            if (timeZoneIndex == 10)
            {
                sb.Append(":00:00");
            }
            else if (timeZoneIndex == 12)
            {
                sb.Append(":00");
            }

            for (var i = timeZoneIndex; i < timeString.Length; i++)
            {
                if (i == timeZoneIndex + 3)
                {
                    sb.Append(":");
                }
                sb.Append(timeString[i]);
            }

            return(new FhirDateTime {
                Value = sb.ToString()
            });


            //    var format = string.Empty;

            //var timeZoneIndex = timeString.IndexOfAny(new char[] { '-', '+' });

            //if (timeZoneIndex == -1)
            //    timeZoneIndex = timeString.Length;

            //switch (timeZoneIndex)
            //{
            //    case 4:
            //        format = "yyyy";
            //        break;
            //    case 6:
            //        format = "yyyyMM";
            //        break;
            //    case 8:
            //        format = "yyyyMMdd";
            //        break;
            //    case 10:
            //        format = "yyyyMMddHH";
            //        break;
            //    case 12:
            //        format = "yyyyMMddHHmm";
            //        break;
            //    case 14:
            //        format = "yyyyMMddHHmmss";
            //        break;
            //    case 19:
            //        format = "yyyyMMddHHmmss.ffff";
            //        break;
            //}


            //if (timeZoneIndex == timeString.Length - 3)
            //    format += "zz";
            //else if (timeZoneIndex == timeString.Length - 5)
            //{
            //    format += "zzz";
            //    timeString = timeString.Insert(timeString.Length - 2, ":");
            //}

            //DateTime datetime = DateTime.ParseExact(timeString, format, null).ToUniversalTime();

            //return new FhirDateTime(datetime);
        }
示例#26
0
        /// <summary>
        /// Parses the given data, which should be 1 or more lines, multiple
        /// calls can be made with multiple lines.
        /// Events are triggered upon reading a line, or on an error.
        /// If TagCollection and XrefTagCollection haven't been set
        /// prior to calling default IndexedKeyCollection objects will be
        /// used.  To support replacing XRefs you need to set XrefTagCollection
        /// to an instance of XRefIndexedKeyCollection before calling.
        /// </summary>
        /// <param name="data">Data to parse, expected to be unicode.</param>
        /// <returns>The last error encountered.</returns>
        public GedcomErrorState GedcomParse(string data)
        {
            ErrorState = GedcomErrorState.NoError;

            int i = 0;

            int len = data.Length;

            // Tags are always the same, data.Substring was allocating lots
            // of memory, instead use a special collection which matches via
            // array index, e.g   tagCollection[str, index, length] to avoid
            // the extra allocations, and caches the resulting string for
            // use again without having to substring
            if (TagCollection == null)
            {
                TagCollection = new IndexedKeyCollection();
            }

            // same for Xrefs
            if (XrefCollection == null)
            {
                XrefCollection = new IndexedKeyCollection();
            }

            while (i < len)
            {
                int temp = i;

                switch (State)
                {
                case GedcomState.Level:
                    // eat up leading white space
                    while (temp < len && char.IsWhiteSpace(data[temp]))
                    {
                        temp++;
                    }

                    bool hadLevel = false;
                    int  lvl      = 0;
                    while (temp < len && IsDigit(data[temp]))
                    {
                        hadLevel = true;
                        lvl     *= 10;
                        lvl     += data[temp++] - '0';
                    }

                    // possible we had data after eating white space
                    // but that it wasn't a digit
                    if (!hadLevel)
                    {
                        if (ApplyConcContOnNewLineHack &&
                            (previousTag == "CONC" || previousTag == "CONT"))
                        {
                            Level = previousLevel;
                            Tag   = "CONC";
                            State = GedcomState.LineValue;
                        }
                        else
                        {
                            ErrorState = GedcomErrorState.LevelExpected;
                        }
                    }
                    else if (temp == i)
                    {
                        if (!char.IsWhiteSpace(data[i]))
                        {
                            ErrorState = GedcomErrorState.LevelExpected;
                        }
                        else
                        {
                            i++;
                        }
                    }
                    else
                    {
                        Level = lvl;

                        if (Level > MaxLevel)
                        {
                            ErrorState = GedcomErrorState.LevelInvalid;
                            Level      = -1;
                        }
                        else
                        {
                            i = temp;
                        }
                    }

                    // move to next state if we have a level
                    // and we are still in a level state (may not be
                    // if we have some hacks active)
                    if (Level != -1 && State == GedcomState.Level)
                    {
                        if (IsDelim(data[i]))
                        {
                            i++;
                            if (IgnoreInvalidDelim)
                            {
                                while (i < len && IsDelim(data[i]))
                                {
                                    i++;
                                }

                                State = GedcomState.XrefID;
                            }
                            else if (IsDelim(data[i]))
                            {
                                ErrorState = GedcomErrorState.InvalidDelim;
                            }
                            else
                            {
                                State = GedcomState.XrefID;
                            }
                        }
                        else
                        {
                            ErrorState = GedcomErrorState.LevelMissingDelim;
                        }
                    }

                    break;

                case GedcomState.XrefID:

                    // no optional xref id just move to next state
                    // otherwise extract pointer
                    if (IsXrefID(data, temp))
                    {
                        // bypass first @
                        i++;
                        temp = i;

                        while (temp < len && data[temp] != '@')
                        {
                            temp++;
                        }

                        if ((temp - i) > MaxXRefLength)
                        {
                            ErrorState = GedcomErrorState.XrefIDTooLong;
                        }
                        else
                        {
                            XrefID = XrefCollection[data, i, temp - i];

                            i = temp + 1;

                            if (IsDelim(data[i]))
                            {
                                i++;
                                if (IgnoreInvalidDelim)
                                {
                                    while (i < len && IsDelim(data[i]))
                                    {
                                        i++;
                                    }

                                    State = GedcomState.Tag;
                                }
                                else if (IsDelim(data[i]))
                                {
                                    ErrorState = GedcomErrorState.InvalidDelim;
                                }
                                else
                                {
                                    State = GedcomState.Tag;
                                }
                            }
                            else
                            {
                                ErrorState = GedcomErrorState.XrefIDMissingDelim;
                            }
                        }
                    }
                    else
                    {
                        State = GedcomState.Tag;
                    }

                    break;

                case GedcomState.Tag:
                    while (temp < len &&
                           (IsAlphaNum(data[temp]) ||
                            (AllowHyphenOrUnderscoreInTag &&
                             (data[temp] == '-' || data[temp] == '_'))))
                    {
                        temp++;
                    }

                    if (temp == i)
                    {
                        ErrorState = GedcomErrorState.TagExpected;
                    }
                    else
                    {
                        Tag = TagCollection[data, i, temp - i];

                        i = temp;
                    }

                    if (Tag != string.Empty)
                    {
                        if (Tag == "TRLR" && i == len)
                        {
                            FoundTag();
                        }
                        else
                        {
                            if (i < len && IsDelim(data[i]))
                            {
                                i++;

                                State = GedcomState.LineValue;
                            }

                            // not else if so we can handle tags with a trailing space but no line value
                            if (i == len || IsTerminator(data[i]))
                            {
                                FoundTag();

                                while (i < len && IsTerminator(data[i]))
                                {
                                    i++;
                                }
                            }
                            else if (State != GedcomState.LineValue && !IgnoreMissingTerms)
                            {
                                ErrorState = GedcomErrorState.TagMissingDelimOrTerm;
                            }
                        }
                    }

                    break;

                case GedcomState.LineValue:
                    if (IsPointer(data, temp))
                    {
                        // bypass first @
                        i++;
                        temp = i;

                        while (temp < len && data[temp] != '@')
                        {
                            temp++;
                        }

                        if ((temp - i) > 0)
                        {
                            LineValue     = XrefCollection[data, i, temp - i];
                            i             = temp + 1;
                            LineValueType = GedcomLineValueType.PointerType;
                        }

                        // GEDCOM only allows a single XREF for a pointer
                        // Genopro ignores this and puts a comma separated
                        // list of XREFs in the mess it pretends is GEDCOM.
                        // This causes us to get stuck in the LineValue state
                        // (this could of cause happen with anything after the
                        //  pointer)
                        if (i < len)
                        {
                            // we will allow white space, but nothing else
                            while (i < len && IsDelim(data[i]))
                            {
                                i++;
                            }

                            if (i < len && !IsTerminator(data[i]))
                            {
                                ErrorState = GedcomErrorState.LineValueInvalid;
                            }
                        }
                    }
                    else
                    {
                        while (ErrorState == GedcomErrorState.NoError && LineValue == string.Empty)
                        {
                            if (temp < len && IsAnyChar(data, temp))
                            {
                                temp++;
                            }
                            else if (temp < len && IsEscape(data, temp))
                            {
                                // bypass @#
                                temp += 2;

                                while (temp < len && data[temp] != '@')
                                {
                                    temp++;
                                }

                                temp++;
                            }

                            // hack for presidents.ged, email address
                            // is used in PHON on line 13 with a single @
                            // this isn't valid GEDCOM
                            // Should be escaped as @@ but handle it anyway
                            // Same thing occurs in user supplied file TOUT200801_unicode.ged
                            // with RELA @INDI:BAPM
                            else if (temp < len && data[temp] == '@')
                            {
                                temp++;
                            }
                            else if (temp != i)
                            {
                                if ((temp < len) && !IsTerminator(data[temp]))
                                {
                                    ErrorState = GedcomErrorState.LineValueInvalid;
                                }
                                else
                                {
                                    temp = Math.Min(temp, len);
                                    string dup = data.Substring(i, temp - i);

                                    // unescape @@
                                    LineValue = dup.Replace("@@", "@");

                                    LineValueType = GedcomLineValueType.DataType;
                                }

                                i = temp;
                            }

                            // TODO: no line value, but have hit the terminator
                            // what should this be allowed for?
                            // Family Tree Maker outputs emtpy CONT (and CONC?)
                            else if (Tag == "CONT" || Tag == "CONC")
                            {
                                LineValue = " ";
                            }
                            else
                            {
                                // hit a terminator
                                break;
                            }
                        }
                    }

                    if (ErrorState == GedcomErrorState.NoError)
                    {
                        // can't use FoundTag here, may not want to reset
                        previousLevel = Level;
                        previousTag   = Tag;

                        if (TagFound != null)
                        {
                            TagFound(this, EventArgs.Empty);
                        }

                        if (i == len || IsTerminator(data[i]))
                        {
                            while (i < len && IsTerminator(data[i]))
                            {
                                i++;
                            }

                            // reset states
                            ResetParseState(false);
                        }
                        else if (!IgnoreMissingTerms)
                        {
                            ErrorState = GedcomErrorState.LineValueMissingTerm;
                        }
                    }

                    break;
                }

                if (ErrorState != GedcomErrorState.NoError)
                {
                    ParserError?.Invoke(this, EventArgs.Empty);
                    break;
                }
            }

            // reset parse status for more input
            ResetParseState(false);

            return(ErrorState);
        }
 private ValidationResult(ParserError parserError) : this() => ParserError = parserError;
	public bool Contains(ParserError value) {}
 public virtual void ReportParseError(ParserError error)
 {
 }
	public void CopyTo(ParserError[] array, int index) {}
 internal static void ReportParseError(ParserError parseError) {
     // If there is a CBM callback, inform it of the error
     if (BuildManager.CBMCallback != null) {
         _parseErrorReported = true;
         BuildManager.CBMCallback.ReportParseError(parseError);
     }
 }
	public int IndexOf(ParserError value) {}
示例#33
0
    // Method to report parser errors.
    protected void ProcessError(string message) {
        // Ignore the errors if in that mode.
        if (IgnoreParseErrors) {
            return;
        }

        // Rethrow as innerexception if in that mode.
        if (ThrowOnFirstParseError) {
            throw new HttpException(message);
        }

        // otherwise add to the error collection with proper info.
        ParserError parseError = new ParserError(message, CurrentVirtualPath, _lineNumber);
        ParserErrors.Add(parseError);

        // If there is a CBM callback, inform it of the error
        BuildManager.ReportParseError(parseError);
    }
	public void Insert(int index, ParserError value) {}
	public void Remove(ParserError value) {}
示例#36
0
 public JsonDocument(ParserError error)
 {
     this.Error = error;
 }